path
stringlengths 14
112
| content
stringlengths 0
6.32M
| size
int64 0
6.32M
| max_lines
int64 1
100k
| repo_name
stringclasses 2
values | autogenerated
bool 1
class |
---|---|---|---|---|---|
cosmopolitan/third_party/tidy/message.c | /* clang-format off */
/* message.c -- General Message Writing Routines
(c) 1998-2017 (W3C) MIT, ERCIM, Keio University, University of
Toronto, HTACG
See tidy.h for the copyright notice.
*/
#include "third_party/tidy/message.h"
#include "third_party/tidy/messageobj.h"
#include "third_party/tidy/tidy-int.h"
#include "third_party/tidy/lexer.h"
#include "third_party/tidy/streamio.h"
#include "third_party/tidy/tmbstr.h"
#include "third_party/tidy/utf8.h"
#include "libc/assert.h"
#include "libc/limits.h"
#include "third_party/tidy/version.inc"
/*********************************************************************
* Release Information
*********************************************************************/
ctmbstr TY_(ReleaseDate)(void)
{
return TY_(release_date);
}
ctmbstr TY_(tidyLibraryVersion)(void)
{
return TY_(library_version);
}
/*********************************************************************
* General Message Utility Functions
*********************************************************************/
/* Returns the given node's tag as a string. */
static char* TagToString(Node* tag, char* buf, size_t count)
{
*buf = 0;
if (tag)
{
if (TY_(nodeIsElement)(tag))
TY_(tmbsnprintf)(buf, count, "<%s>", tag->element);
else if (tag->type == EndTag)
TY_(tmbsnprintf)(buf, count, "</%s>", tag->element);
else if (tag->type == DocTypeTag)
TY_(tmbsnprintf)(buf, count, "<!DOCTYPE>");
else if (tag->type == TextNode)
TY_(tmbsnprintf)(buf, count, "%s", "STRING_PLAIN_TEXT");
else if (tag->type == XmlDecl)
TY_(tmbsnprintf)(buf, count, "%s", "STRING_XML_DECLARATION");
else if (tag->element)
TY_(tmbsnprintf)(buf, count, "%s", tag->element);
}
return buf + TY_(tmbstrlen)(buf);
}
/* Convert an integer to a string. */
static void NtoS(int n, tmbstr str)
{
tmbchar buf[40];
int i;
for (i = 0;; ++i)
{
buf[i] = (tmbchar)( (n % 10) + '0' );
n = n / 10;
if (n == 0)
break;
}
n = i;
while (i >= 0)
{
str[n-i] = buf[i];
--i;
}
str[n+1] = '\0';
}
/* Get an HTML version string */
static ctmbstr HTMLVersion( TidyDocImpl* doc )
{
uint versionEmitted = doc->lexer->versionEmitted;
uint declared = doc->lexer->doctype;
uint version = versionEmitted == 0 ? declared : versionEmitted;
ctmbstr result = TY_(HTMLVersionNameFromCode)(version, 0);
if (!result)
result = tidyLocalizedString(STRING_HTML_PROPRIETARY);
return result;
}
/*********************************************************************
* Message Writing Functions
* These functions provide final, formatted output to the output sink.
*********************************************************************/
/* Writes messages to the output sink unless they are suppressed by one of the
** message callback filters, or suppressed by the configuration settings.
** Report messages are messages that are included in the "error table," and
** dialogue messages are any other output that Tidy traditionally emits.
*/
static void messageOut( TidyMessageImpl *message )
{
TidyDocImpl *doc;
Bool go = yes;
if ( !message )
return;
doc = message->tidyDoc;
/* The filter has had a chance to suppress *any* message from output. */
go = message->allowMessage;
/* Update the count of each report type. */
switch ( message->level )
{
case TidyInfo:
doc->infoMessages++;
break;
case TidyWarning:
doc->warnings++;
break;
case TidyConfig:
doc->optionErrors++;
break;
case TidyAccess:
doc->accessErrors++;
break;
case TidyError:
doc->errors++;
break;
case TidyBadDocument:
doc->docErrors++;
break;
case TidyFatal:
/* Ack! */
break;
default:
break;
}
/* Suppress report messages if they've been muted. */
go = go & !message->muted;
/* Suppress report messages if we've already reached the reporting limit. */
if ( message->level <= TidyFatal )
{
go = go & ( doc->errors < cfg(doc, TidyShowErrors) );
}
/* Let TidyQuiet silence a lot of things. */
if ( cfgBool( doc, TidyQuiet ) == yes )
{
go = go && message->code != STRING_DOCTYPE_GIVEN;
go = go && message->code != STRING_CONTENT_LOOKS;
go = go && message->code != STRING_NO_SYSID;
go = go && message->level != TidyDialogueInfo;
go = go && message->level != TidyConfig;
go = go && message->level != TidyInfo;
go = go && !(message->level >= TidyDialogueSummary &&
message->code != STRING_NEEDS_INTERVENTION);
}
/* Let !TidyShowInfo silence some things. */
if ( cfgBool( doc, TidyShowInfo ) == no )
{
go = go && message->level != TidyInfo;
/* Temporary; TidyShowInfo shouldn't affect TidyDialogueInfo, but
right now such messages are hidden until we granularize the
output controls. */
go = go && message->level != TidyDialogueInfo;
}
/* Let !TidyShowWarnings silence some things. */
if ( cfgBool( doc, TidyShowWarnings ) == no )
{
go = go && message->level != TidyWarning;
}
/* Output the message if applicable. */
if ( go )
{
TidyOutputSink *outp = &doc->errout->sink;
ctmbstr cp;
byte b = '\0';
for ( cp = message->messageOutput; *cp; ++cp )
{
b = (*cp & 0xff);
if (b == (byte)'\n')
TY_(WriteChar)( b, doc->errout ); /* for EOL translation */
else
outp->putByte( outp->sinkData, b ); /* #383 - no encoding */
}
/* Always add a trailing newline. Reports require this, and dialogue
messages will be better spaced out without having to fill the
language file with superfluous newlines. */
TY_(WriteChar)( '\n', doc->errout );
}
TY_(tidyMessageRelease)(message);
}
/*********************************************************************
* Report Formatting
* In order to provide a single, predictable reporting system, Tidy
* provides an extensible messaging system that provides most of the
* basic requirements for most reports, while permitting simple
* implementation of new reports in a flexible manner. By adding
* additional formatters, new messages can be added easily while
* maintaining Tidy's internal organization.
*********************************************************************/
/* Functions of this type will create new instances of TidyMessage specific to
** the type of report being emitted. Many messages share the same formatter for
** messages, but new ones can be written as required. Please have a look at
** the existing formatters in order to determine if an existing signature is
** compatible with the report you wish to output before adding a new formatter.
** In particular, if an existing formatter provides most of the local variables
** required to populate your format string, try to use it.
*/
typedef TidyMessageImpl*(messageFormatter)(TidyDocImpl* doc, Node *element, Node *node, uint code, uint level, va_list args);
/* Forward declarations of messageFormatter functions. */
static messageFormatter formatAccessReport;
static messageFormatter formatAttributeReport;
static messageFormatter formatEncodingReport;
static messageFormatter formatStandard;
static messageFormatter formatStandardDynamic;
/* This structure ties together for each report Code the default
** TidyReportLevel, the Formatter to be used to construct the message, and the
** next code to output, if applicable. Assuming an existing formatter can,
** this it makes it simple to output new reports, or to change report level by
** modifying this array.
*/
static struct _dispatchTable {
uint code; /**< The message code. */
TidyReportLevel level; /**< The default TidyReportLevel of the message. */
messageFormatter *handler; /**< The formatter for the report. */
uint next; /**< If multiple codes should be displayed, which is next? */
} dispatchTable[] = {
{ ADDED_MISSING_CHARSET, TidyInfo, formatStandard },
{ ANCHOR_NOT_UNIQUE, TidyWarning, formatAttributeReport },
{ ANCHOR_DUPLICATED, TidyWarning, formatAttributeReport },
{ APOS_UNDEFINED, TidyWarning, formatStandard },
{ ATTR_VALUE_NOT_LCASE, TidyWarning, formatAttributeReport },
{ ATTRIBUTE_VALUE_REPLACED, TidyInfo, formatAttributeReport },
{ ATTRIBUTE_IS_NOT_ALLOWED, TidyWarning, formatAttributeReport },
{ BACKSLASH_IN_URI, TidyWarning, formatAttributeReport },
{ BAD_ATTRIBUTE_VALUE_REPLACED, TidyWarning, formatAttributeReport },
{ BAD_ATTRIBUTE_VALUE, TidyWarning, formatAttributeReport },
{ BAD_CDATA_CONTENT, TidyWarning, formatStandard },
{ BAD_SUMMARY_HTML5, TidyWarning, formatStandard },
{ BAD_SURROGATE_LEAD, TidyWarning, formatStandard },
{ BAD_SURROGATE_PAIR, TidyWarning, formatStandard },
{ BAD_SURROGATE_TAIL, TidyWarning, formatStandard },
{ CANT_BE_NESTED, TidyWarning, formatStandard },
{ COERCE_TO_ENDTAG, TidyWarning, formatStandard },
{ CONTENT_AFTER_BODY, TidyWarning, formatStandard },
{ CUSTOM_TAG_DETECTED, TidyInfo, formatStandard },
{ DISCARDING_UNEXPECTED, 0, formatStandardDynamic },
{ DOCTYPE_AFTER_TAGS, TidyWarning, formatStandard },
{ DUPLICATE_FRAMESET, TidyError, formatStandard },
{ ELEMENT_NOT_EMPTY, TidyWarning, formatStandard },
{ ELEMENT_VERS_MISMATCH_ERROR, TidyError, formatStandard },
{ ELEMENT_VERS_MISMATCH_WARN, TidyWarning, formatStandard },
{ ENCODING_MISMATCH, TidyWarning, formatEncodingReport },
{ ESCAPED_ILLEGAL_URI, TidyWarning, formatAttributeReport },
{ FILE_CANT_OPEN, TidyBadDocument, formatStandard },
{ FILE_CANT_OPEN_CFG, TidyBadDocument, formatStandard },
{ FILE_NOT_FILE, TidyBadDocument, formatStandard },
{ FIXED_BACKSLASH, TidyWarning, formatAttributeReport },
{ FOUND_STYLE_IN_BODY, TidyWarning, formatStandard },
{ ID_NAME_MISMATCH, TidyWarning, formatAttributeReport },
{ ILLEGAL_NESTING, TidyWarning, formatStandard },
{ ILLEGAL_URI_CODEPOINT, TidyWarning, formatAttributeReport },
{ ILLEGAL_URI_REFERENCE, TidyWarning, formatAttributeReport },
{ INSERTING_AUTO_ATTRIBUTE, TidyWarning, formatAttributeReport },
{ INSERTING_TAG, TidyWarning, formatStandard },
{ INVALID_ATTRIBUTE, TidyWarning, formatAttributeReport },
{ INVALID_NCR, TidyWarning, formatEncodingReport },
{ INVALID_SGML_CHARS, TidyWarning, formatEncodingReport },
{ INVALID_UTF8, TidyWarning, formatEncodingReport },
{ INVALID_UTF16, TidyWarning, formatEncodingReport },
{ INVALID_XML_ID, TidyWarning, formatAttributeReport },
{ JOINING_ATTRIBUTE, TidyWarning, formatAttributeReport },
{ MALFORMED_COMMENT, TidyInfo, formatStandard },
{ MALFORMED_COMMENT_EOS, TidyError, formatStandard },
{ MALFORMED_COMMENT_DROPPING, TidyWarning, formatStandard },
{ MALFORMED_COMMENT_WARN, TidyWarning, formatStandard },
{ MALFORMED_DOCTYPE, TidyWarning, formatStandard },
{ MISMATCHED_ATTRIBUTE_ERROR, TidyError, formatAttributeReport },
{ MISMATCHED_ATTRIBUTE_WARN, TidyWarning, formatAttributeReport },
{ MISSING_ATTR_VALUE, TidyWarning, formatAttributeReport },
{ MISSING_ATTRIBUTE, TidyWarning, formatStandard },
{ MISSING_DOCTYPE, TidyWarning, formatStandard },
{ MISSING_ENDTAG_BEFORE, TidyWarning, formatStandard },
{ MISSING_ENDTAG_FOR, TidyWarning, formatStandard },
{ MISSING_ENDTAG_OPTIONAL, TidyInfo, formatStandard },
{ MISSING_IMAGEMAP, TidyWarning, formatAttributeReport },
{ MISSING_QUOTEMARK, TidyWarning, formatAttributeReport },
{ MISSING_QUOTEMARK_OPEN, TidyInfo, formatAttributeReport },
{ MISSING_SEMICOLON_NCR, TidyWarning, formatStandard },
{ MISSING_SEMICOLON, TidyWarning, formatStandard },
{ MISSING_STARTTAG, TidyWarning, formatStandard },
{ MISSING_TITLE_ELEMENT, TidyWarning, formatStandard },
{ MOVED_STYLE_TO_HEAD, TidyWarning, formatStandard },
{ NESTED_EMPHASIS, TidyWarning, formatStandard },
{ NESTED_QUOTATION, TidyWarning, formatStandard },
{ NEWLINE_IN_URI, TidyWarning, formatAttributeReport },
{ NOFRAMES_CONTENT, TidyWarning, formatStandard },
{ NON_MATCHING_ENDTAG, TidyWarning, formatStandard },
{ OBSOLETE_ELEMENT, TidyWarning, formatStandard },
{ OPTION_REMOVED, TidyConfig, formatStandard },
{ OPTION_REMOVED_APPLIED, TidyConfig, formatStandard },
{ OPTION_REMOVED_UNAPPLIED, TidyConfig, formatStandard },
{ PREVIOUS_LOCATION, TidyInfo, formatStandard },
{ PROPRIETARY_ATTR_VALUE, TidyWarning, formatAttributeReport },
{ PROPRIETARY_ATTRIBUTE, TidyWarning, formatAttributeReport },
{ PROPRIETARY_ELEMENT, TidyWarning, formatStandard },
{ REMOVED_HTML5, TidyWarning, formatStandard },
{ REPEATED_ATTRIBUTE, TidyWarning, formatAttributeReport },
{ REPLACING_ELEMENT, TidyWarning, formatStandard },
{ REPLACING_UNEX_ELEMENT, TidyWarning, formatStandard },
{ SPACE_PRECEDING_XMLDECL, TidyWarning, formatStandard },
{ STRING_ARGUMENT_BAD, TidyConfig, formatStandard },
{ STRING_CONTENT_LOOKS, TidyInfo, formatStandard }, /* reportMarkupVersion() */
{ STRING_DOCTYPE_GIVEN, TidyInfo, formatStandard }, /* reportMarkupVersion() */
{ STRING_MISSING_MALFORMED, TidyConfig, formatStandard },
{ STRING_MUTING_TYPE, TidyInfo, formatStandard },
{ STRING_NO_SYSID, TidyInfo, formatStandard }, /* reportMarkupVersion() */
{ STRING_UNKNOWN_OPTION, TidyConfig, formatStandard },
{ SUSPECTED_MISSING_QUOTE, TidyWarning, formatStandard },
{ TAG_NOT_ALLOWED_IN, TidyWarning, formatStandard, PREVIOUS_LOCATION },
{ TOO_MANY_ELEMENTS_IN, TidyWarning, formatStandard, PREVIOUS_LOCATION },
{ TOO_MANY_ELEMENTS, TidyWarning, formatStandard },
{ TRIM_EMPTY_ELEMENT, TidyWarning, formatStandard },
{ UNESCAPED_AMPERSAND, TidyWarning, formatStandard },
{ UNEXPECTED_END_OF_FILE_ATTR, TidyWarning, formatAttributeReport },
{ UNEXPECTED_END_OF_FILE, TidyWarning, formatStandard },
{ UNEXPECTED_ENDTAG_IN, TidyError, formatStandard },
{ UNEXPECTED_ENDTAG, TidyWarning, formatStandard },
{ UNEXPECTED_ENDTAG_ERR, TidyError, formatStandard },
{ UNEXPECTED_EQUALSIGN, TidyWarning, formatAttributeReport },
{ UNEXPECTED_GT, TidyWarning, formatAttributeReport },
{ UNEXPECTED_QUOTEMARK, TidyWarning, formatAttributeReport },
{ UNKNOWN_ELEMENT_LOOKS_CUSTOM, TidyError, formatStandard },
{ UNKNOWN_ELEMENT, TidyError, formatStandard },
{ UNKNOWN_ENTITY, TidyWarning, formatStandard },
{ USING_BR_INPLACE_OF, TidyWarning, formatStandard },
{ VENDOR_SPECIFIC_CHARS, TidyWarning, formatEncodingReport },
{ WHITE_IN_URI, TidyWarning, formatAttributeReport },
{ XML_DECLARATION_DETECTED, TidyWarning, formatStandard },
{ XML_ID_SYNTAX, TidyWarning, formatAttributeReport },
{ BLANK_TITLE_ELEMENT, TidyWarning, formatStandard },
{ APPLET_MISSING_ALT, TidyAccess, formatAccessReport },
{ AREA_MISSING_ALT, TidyAccess, formatAccessReport },
{ ASCII_REQUIRES_DESCRIPTION, TidyAccess, formatAccessReport },
{ ASSOCIATE_LABELS_EXPLICITLY, TidyAccess, formatAccessReport },
{ ASSOCIATE_LABELS_EXPLICITLY_FOR, TidyAccess, formatAccessReport },
{ ASSOCIATE_LABELS_EXPLICITLY_ID, TidyAccess, formatAccessReport },
{ AUDIO_MISSING_TEXT_AIFF, TidyAccess, formatAccessReport },
{ AUDIO_MISSING_TEXT_AU, TidyAccess, formatAccessReport },
{ AUDIO_MISSING_TEXT_RA, TidyAccess, formatAccessReport },
{ AUDIO_MISSING_TEXT_RM, TidyAccess, formatAccessReport },
{ AUDIO_MISSING_TEXT_SND, TidyAccess, formatAccessReport },
{ AUDIO_MISSING_TEXT_WAV, TidyAccess, formatAccessReport },
{ COLOR_CONTRAST_ACTIVE_LINK, TidyAccess, formatAccessReport },
{ COLOR_CONTRAST_LINK, TidyAccess, formatAccessReport },
{ COLOR_CONTRAST_TEXT, TidyAccess, formatAccessReport },
{ COLOR_CONTRAST_VISITED_LINK, TidyAccess, formatAccessReport },
{ DATA_TABLE_MISSING_HEADERS, TidyAccess, formatAccessReport },
{ DATA_TABLE_MISSING_HEADERS_COLUMN, TidyAccess, formatAccessReport },
{ DATA_TABLE_MISSING_HEADERS_ROW, TidyAccess, formatAccessReport },
{ DATA_TABLE_REQUIRE_MARKUP_COLUMN_HEADERS, TidyAccess, formatAccessReport },
{ DATA_TABLE_REQUIRE_MARKUP_ROW_HEADERS, TidyAccess, formatAccessReport },
{ DOCTYPE_MISSING, TidyAccess, formatAccessReport },
{ ENSURE_PROGRAMMATIC_OBJECTS_ACCESSIBLE_APPLET, TidyAccess, formatAccessReport },
{ ENSURE_PROGRAMMATIC_OBJECTS_ACCESSIBLE_EMBED, TidyAccess, formatAccessReport },
{ ENSURE_PROGRAMMATIC_OBJECTS_ACCESSIBLE_OBJECT, TidyAccess, formatAccessReport },
{ ENSURE_PROGRAMMATIC_OBJECTS_ACCESSIBLE_SCRIPT, TidyAccess, formatAccessReport },
{ FRAME_MISSING_LONGDESC, TidyAccess, formatAccessReport },
{ FRAME_MISSING_NOFRAMES, TidyAccess, formatAccessReport },
{ FRAME_MISSING_TITLE, TidyAccess, formatAccessReport },
{ FRAME_SRC_INVALID, TidyAccess, formatAccessReport },
{ FRAME_TITLE_INVALID_NULL, TidyAccess, formatAccessReport },
{ FRAME_TITLE_INVALID_SPACES, TidyAccess, formatAccessReport },
{ HEADER_USED_FORMAT_TEXT, TidyAccess, formatAccessReport },
{ HEADERS_IMPROPERLY_NESTED, TidyAccess, formatAccessReport },
{ IMAGE_MAP_SERVER_SIDE_REQUIRES_CONVERSION, TidyAccess, formatAccessReport },
{ IMG_ALT_SUSPICIOUS_FILE_SIZE, TidyAccess, formatAccessReport },
{ IMG_ALT_SUSPICIOUS_FILENAME, TidyAccess, formatAccessReport },
{ IMG_ALT_SUSPICIOUS_PLACEHOLDER, TidyAccess, formatAccessReport },
{ IMG_ALT_SUSPICIOUS_TOO_LONG, TidyAccess, formatAccessReport },
{ IMG_BUTTON_MISSING_ALT, TidyAccess, formatAccessReport },
{ IMG_MAP_CLIENT_MISSING_TEXT_LINKS, TidyAccess, formatAccessReport },
{ IMG_MAP_SERVER_REQUIRES_TEXT_LINKS, TidyAccess, formatAccessReport },
{ IMG_MISSING_ALT, TidyAccess, formatAccessReport },
{ IMG_MISSING_DLINK, TidyAccess, formatAccessReport },
{ IMG_MISSING_LONGDESC, TidyAccess, formatAccessReport },
{ IMG_MISSING_LONGDESC_DLINK, TidyAccess, formatAccessReport },
{ INFORMATION_NOT_CONVEYED_APPLET, TidyAccess, formatAccessReport },
{ INFORMATION_NOT_CONVEYED_IMAGE, TidyAccess, formatAccessReport },
{ INFORMATION_NOT_CONVEYED_INPUT, TidyAccess, formatAccessReport },
{ INFORMATION_NOT_CONVEYED_OBJECT, TidyAccess, formatAccessReport },
{ INFORMATION_NOT_CONVEYED_SCRIPT, TidyAccess, formatAccessReport },
{ LANGUAGE_INVALID, TidyAccess, formatAccessReport },
{ LANGUAGE_NOT_IDENTIFIED, TidyAccess, formatAccessReport },
{ LAYOUT_TABLE_INVALID_MARKUP, TidyAccess, formatAccessReport },
{ LAYOUT_TABLES_LINEARIZE_PROPERLY, TidyAccess, formatAccessReport },
{ LINK_TEXT_MISSING, TidyAccess, formatAccessReport },
{ LINK_TEXT_NOT_MEANINGFUL, TidyAccess, formatAccessReport },
{ LINK_TEXT_NOT_MEANINGFUL_CLICK_HERE, TidyAccess, formatAccessReport },
{ LINK_TEXT_TOO_LONG, TidyAccess, formatAccessReport },
{ LIST_USAGE_INVALID_LI, TidyAccess, formatAccessReport },
{ LIST_USAGE_INVALID_OL, TidyAccess, formatAccessReport },
{ LIST_USAGE_INVALID_UL, TidyAccess, formatAccessReport },
{ METADATA_MISSING, TidyAccess, formatAccessReport },
{ METADATA_MISSING_REDIRECT_AUTOREFRESH, TidyAccess, formatAccessReport },
{ MULTIMEDIA_REQUIRES_TEXT, TidyAccess, formatAccessReport },
{ NEW_WINDOWS_REQUIRE_WARNING_BLANK, TidyAccess, formatAccessReport },
{ NEW_WINDOWS_REQUIRE_WARNING_NEW, TidyAccess, formatAccessReport },
{ NOFRAMES_INVALID_CONTENT, TidyAccess, formatAccessReport },
{ NOFRAMES_INVALID_LINK, TidyAccess, formatAccessReport },
{ NOFRAMES_INVALID_NO_VALUE, TidyAccess, formatAccessReport },
{ OBJECT_MISSING_ALT, TidyAccess, formatAccessReport },
{ POTENTIAL_HEADER_BOLD, TidyAccess, formatAccessReport },
{ POTENTIAL_HEADER_ITALICS, TidyAccess, formatAccessReport },
{ POTENTIAL_HEADER_UNDERLINE, TidyAccess, formatAccessReport },
{ PROGRAMMATIC_OBJECTS_REQUIRE_TESTING_APPLET, TidyAccess, formatAccessReport },
{ PROGRAMMATIC_OBJECTS_REQUIRE_TESTING_EMBED, TidyAccess, formatAccessReport },
{ PROGRAMMATIC_OBJECTS_REQUIRE_TESTING_OBJECT, TidyAccess, formatAccessReport },
{ PROGRAMMATIC_OBJECTS_REQUIRE_TESTING_SCRIPT, TidyAccess, formatAccessReport },
{ REMOVE_AUTO_REDIRECT, TidyAccess, formatAccessReport },
{ REMOVE_AUTO_REFRESH, TidyAccess, formatAccessReport },
{ REMOVE_BLINK_MARQUEE, TidyAccess, formatAccessReport },
{ REMOVE_FLICKER_ANIMATED_GIF, TidyAccess, formatAccessReport },
{ REMOVE_FLICKER_APPLET, TidyAccess, formatAccessReport },
{ REMOVE_FLICKER_EMBED, TidyAccess, formatAccessReport },
{ REMOVE_FLICKER_OBJECT, TidyAccess, formatAccessReport },
{ REMOVE_FLICKER_SCRIPT, TidyAccess, formatAccessReport },
{ REPLACE_DEPRECATED_HTML_APPLET, TidyAccess, formatAccessReport },
{ REPLACE_DEPRECATED_HTML_BASEFONT, TidyAccess, formatAccessReport },
{ REPLACE_DEPRECATED_HTML_CENTER, TidyAccess, formatAccessReport },
{ REPLACE_DEPRECATED_HTML_DIR, TidyAccess, formatAccessReport },
{ REPLACE_DEPRECATED_HTML_FONT, TidyAccess, formatAccessReport },
{ REPLACE_DEPRECATED_HTML_ISINDEX, TidyAccess, formatAccessReport },
{ REPLACE_DEPRECATED_HTML_MENU, TidyAccess, formatAccessReport },
{ REPLACE_DEPRECATED_HTML_S, TidyAccess, formatAccessReport },
{ REPLACE_DEPRECATED_HTML_STRIKE, TidyAccess, formatAccessReport },
{ REPLACE_DEPRECATED_HTML_U, TidyAccess, formatAccessReport },
{ SCRIPT_MISSING_NOSCRIPT, TidyAccess, formatAccessReport },
{ SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_CLICK, TidyAccess, formatAccessReport },
{ SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_MOUSE_DOWN, TidyAccess, formatAccessReport },
{ SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_MOUSE_MOVE, TidyAccess, formatAccessReport },
{ SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_MOUSE_OUT, TidyAccess, formatAccessReport },
{ SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_MOUSE_OVER, TidyAccess, formatAccessReport },
{ SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_MOUSE_UP, TidyAccess, formatAccessReport },
{ SKIPOVER_ASCII_ART, TidyAccess, formatAccessReport },
{ STYLE_SHEET_CONTROL_PRESENTATION, TidyAccess, formatAccessReport },
{ STYLESHEETS_REQUIRE_TESTING_LINK, TidyAccess, formatAccessReport },
{ STYLESHEETS_REQUIRE_TESTING_STYLE_ATTR, TidyAccess, formatAccessReport },
{ STYLESHEETS_REQUIRE_TESTING_STYLE_ELEMENT, TidyAccess, formatAccessReport },
{ TABLE_MAY_REQUIRE_HEADER_ABBR, TidyAccess, formatAccessReport },
{ TABLE_MAY_REQUIRE_HEADER_ABBR_NULL, TidyAccess, formatAccessReport },
{ TABLE_MAY_REQUIRE_HEADER_ABBR_SPACES, TidyAccess, formatAccessReport },
{ TABLE_MISSING_CAPTION, TidyAccess, formatAccessReport },
{ TABLE_MISSING_SUMMARY, TidyAccess, formatAccessReport },
{ TABLE_SUMMARY_INVALID_NULL, TidyAccess, formatAccessReport },
{ TABLE_SUMMARY_INVALID_PLACEHOLDER, TidyAccess, formatAccessReport },
{ TABLE_SUMMARY_INVALID_SPACES, TidyAccess, formatAccessReport },
{ TEXT_EQUIVALENTS_REQUIRE_UPDATING_APPLET, TidyAccess, formatAccessReport },
{ TEXT_EQUIVALENTS_REQUIRE_UPDATING_OBJECT, TidyAccess, formatAccessReport },
{ TEXT_EQUIVALENTS_REQUIRE_UPDATING_SCRIPT, TidyAccess, formatAccessReport },
{ 0, 0, NULL }
};
/*********************************************************************
* Message Formatting
* These individual message formatters populate messages with the
* correct, pertinent data.
*********************************************************************/
/* Provides formatting for the Attribute-related reports. This formatter
** should be reserved for messages generated by Tidy's accessibility module,
** even if the signature matches some unrelated report that you wish to
** generate.
*/
TidyMessageImpl *formatAccessReport(TidyDocImpl* doc, Node *element, Node *node, uint code, uint level, va_list args)
{
doc->badAccess |= BA_WAI;
/* Currently *all* cases are handled in the default, but maintain this
structure for possible future cases. */
switch (code)
{
default:
return TY_(tidyMessageCreateWithNode)(doc, node, code, level );
}
return NULL;
}
/* Provides formatting for the Attribute-related reports. This formatter
** provides local variables that are used principally in the formats used for
** the attribute related reports.
*/
TidyMessageImpl *formatAttributeReport(TidyDocImpl* doc, Node *element, Node *node, uint code, uint level, va_list args)
{
AttVal *av = NULL;
char const *name = "NULL";
char const *value = "NULL";
char tagdesc[64];
TagToString(node, tagdesc, sizeof(tagdesc));
if ( ( av = va_arg(args, AttVal*) ) )
{
if (av->attribute)
name = av->attribute;
if (av->value)
value = av->value;
}
switch (code)
{
case MISSING_QUOTEMARK_OPEN:
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, name );
case BACKSLASH_IN_URI:
case ESCAPED_ILLEGAL_URI:
case FIXED_BACKSLASH:
case ID_NAME_MISMATCH:
case ILLEGAL_URI_CODEPOINT:
case ILLEGAL_URI_REFERENCE:
case INVALID_XML_ID:
case MISSING_IMAGEMAP:
case MISSING_QUOTEMARK:
case NEWLINE_IN_URI:
case UNEXPECTED_EQUALSIGN:
case UNEXPECTED_GT:
case UNEXPECTED_QUOTEMARK:
case WHITE_IN_URI:
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, tagdesc );
case ATTRIBUTE_IS_NOT_ALLOWED:
case JOINING_ATTRIBUTE:
case MISSING_ATTR_VALUE:
case PROPRIETARY_ATTRIBUTE:
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, tagdesc, name );
case ATTRIBUTE_VALUE_REPLACED:
case BAD_ATTRIBUTE_VALUE:
case BAD_ATTRIBUTE_VALUE_REPLACED:
case INSERTING_AUTO_ATTRIBUTE:
case INVALID_ATTRIBUTE:
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, tagdesc, name, value );
case MISMATCHED_ATTRIBUTE_ERROR:
case MISMATCHED_ATTRIBUTE_WARN:
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, tagdesc, name, HTMLVersion(doc));
case ANCHOR_NOT_UNIQUE:
case ANCHOR_DUPLICATED:
case ATTR_VALUE_NOT_LCASE:
case PROPRIETARY_ATTR_VALUE:
case XML_ID_SYNTAX:
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, tagdesc, value );
case REPEATED_ATTRIBUTE:
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, tagdesc, value, name );
case UNEXPECTED_END_OF_FILE_ATTR:
/* on end of file adjust reported position to end of input */
doc->lexer->lines = doc->docIn->curline;
doc->lexer->columns = doc->docIn->curcol;
return TY_(tidyMessageCreateWithLexer)(doc, code, level, tagdesc );
}
return NULL;
}
/* Provides report formatting *and* additional status settings for Tidy's
** encoding reports. Provides the local variables typically used for this type
** of report.
** @todo: These status changes probably SHOULD be made in the calling code;
** however these states are captured to generate future output, which may be
** useful here in the long run.
*/
TidyMessageImpl *formatEncodingReport(TidyDocImpl* doc, Node *element, Node *node, uint code, uint level, va_list args)
{
char buf[ 32 ] = {'\0'};
uint c = va_arg( args, uint );
Bool discarded = va_arg( args, Bool );
ctmbstr action = tidyLocalizedString(discarded ? STRING_DISCARDING : STRING_REPLACING);
switch (code)
{
case INVALID_NCR:
NtoS(c, buf);
doc->badChars |= BC_INVALID_NCR;
break;
case INVALID_SGML_CHARS:
NtoS(c, buf);
doc->badChars |= BC_INVALID_SGML_CHARS;
break;
case INVALID_UTF8:
TY_(tmbsnprintf)(buf, sizeof(buf), "U+%04X", c);
doc->badChars |= BC_INVALID_UTF8;
break;
case INVALID_UTF16:
TY_(tmbsnprintf)(buf, sizeof(buf), "U+%04X", c);
doc->badChars |= BC_INVALID_UTF16;
break;
case VENDOR_SPECIFIC_CHARS:
NtoS(c, buf);
doc->badChars |= BC_VENDOR_SPECIFIC_CHARS;
break;
case ENCODING_MISMATCH:
doc->badChars |= BC_ENCODING_MISMATCH;
return TY_(tidyMessageCreateWithLexer)(doc,
code,
level,
TY_(CharEncodingName)(doc->docIn->encoding),
TY_(CharEncodingName)(c));
break;
}
return TY_(tidyMessageCreateWithLexer)(doc, code, level, action, buf );
}
/* Provides general formatting for the majority of Tidy's reports. Because most
** reports use the same basic data derived from the element and node, this
** formatter covers the vast majority of Tidy's report messages. Note that this
** formatter guarantees the values of TidyReportLevel in the dispatchTable[].
** Some of the cases in this formatter start new contexts from the va_list
** when the required data is simple. For complex local variable needs, it may
** be preferred to write a new formatter.
*/
TidyMessageImpl *formatStandard(TidyDocImpl* doc, Node *element, Node *node, uint code, uint level, va_list args)
{
char nodedesc[ 256 ] = {0};
char elemdesc[ 256 ] = {0};
Node* rpt = ( element ? element : node );
TagToString(node, nodedesc, sizeof(nodedesc));
if ( element )
TagToString(element, elemdesc, sizeof(elemdesc));
switch ( code )
{
case CUSTOM_TAG_DETECTED:
{
ctmbstr tagtype;
switch ( cfg( doc, TidyUseCustomTags ) )
{
case TidyCustomBlocklevel:
tagtype = tidyLocalizedString( TIDYCUSTOMBLOCKLEVEL_STRING );
break;
case TidyCustomEmpty:
tagtype = tidyLocalizedString( TIDYCUSTOMEMPTY_STRING );
break;
case TidyCustomInline:
tagtype = tidyLocalizedString( TIDYCUSTOMINLINE_STRING );
break;
case TidyCustomPre:
default:
tagtype = tidyLocalizedString( TIDYCUSTOMPRE_STRING );
break;
}
return TY_(tidyMessageCreateWithNode)(doc, element, code, level, elemdesc, tagtype );
}
case STRING_NO_SYSID:
return TY_(tidyMessageCreate)( doc, code, level );
case FILE_CANT_OPEN:
case FILE_CANT_OPEN_CFG:
case FILE_NOT_FILE:
case STRING_CONTENT_LOOKS:
case STRING_DOCTYPE_GIVEN:
case STRING_MISSING_MALFORMED:
case STRING_MUTING_TYPE:
{
ctmbstr str;
if ( (str = va_arg( args, ctmbstr)) )
return TY_(tidyMessageCreate)( doc, code, level, str );
} break;
case APOS_UNDEFINED:
case MISSING_SEMICOLON_NCR:
case MISSING_SEMICOLON:
case UNESCAPED_AMPERSAND:
case UNKNOWN_ENTITY:
{
ctmbstr entityname;
if ( !(entityname = va_arg( args, ctmbstr)) )
{
entityname = "NULL";
}
return TY_(tidyMessageCreateWithLexer)(doc, code, level, entityname);
}
case MISSING_ATTRIBUTE:
{
ctmbstr name;
if ( (name = va_arg( args, ctmbstr)) )
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, nodedesc, name );
} break;
case STRING_UNKNOWN_OPTION:
case OPTION_REMOVED:
{
ctmbstr str;
if ( (str = va_arg( args, ctmbstr)) )
return TY_(tidyMessageCreateWithLexer)(doc, code, level, str);
} break;
case OPTION_REMOVED_UNAPPLIED:
case STRING_ARGUMENT_BAD:
{
ctmbstr s1 = va_arg( args, ctmbstr );
ctmbstr s2 = va_arg( args, ctmbstr );
return TY_(tidyMessageCreateWithLexer)(doc, code, level, s1, s2);
}
case OPTION_REMOVED_APPLIED:
{
ctmbstr s1 = va_arg( args, ctmbstr );
ctmbstr s2 = va_arg( args, ctmbstr );
ctmbstr s3 = va_arg( args, ctmbstr );
return TY_(tidyMessageCreateWithLexer)(doc, code, level, s1, s2, s3);
}
case BAD_SURROGATE_LEAD:
case BAD_SURROGATE_PAIR:
case BAD_SURROGATE_TAIL:
{
uint c1 = va_arg( args, uint );
uint c2 = va_arg( args, uint );
return TY_(tidyMessageCreateWithLexer)(doc, code, level, c1, c2);
}
case SPACE_PRECEDING_XMLDECL:
/* @TODO: Should this be a TidyInfo "silent" fix? */
return TY_(tidyMessageCreateWithNode)(doc, node, code, level );
case CANT_BE_NESTED:
case NOFRAMES_CONTENT:
case USING_BR_INPLACE_OF:
/* Can we use `rpt` here? No; `element` has a value in every case. */
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, nodedesc );
case ELEMENT_VERS_MISMATCH_ERROR:
case ELEMENT_VERS_MISMATCH_WARN:
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, nodedesc, HTMLVersion(doc) );
case TAG_NOT_ALLOWED_IN:
/* Can we use `rpt` here? No; `element` has a value in every case. */
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, nodedesc, element ? element->element : NULL );
case INSERTING_TAG:
case MISSING_STARTTAG:
case TOO_MANY_ELEMENTS:
case UNEXPECTED_ENDTAG:
case UNEXPECTED_ENDTAG_ERR: /* generated by XML docs */
/* Can we use `rpt` here? No; `element` has a value in every case. */
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, node->element );
case UNEXPECTED_ENDTAG_IN:
/* Can we use `rpt` here? No; `element` has a value in every case. */
return TY_(tidyMessageCreateWithNode)(doc, node, code, level, node->element, element ? element->element : NULL );
case BAD_CDATA_CONTENT:
case CONTENT_AFTER_BODY:
case DOCTYPE_AFTER_TAGS:
case DUPLICATE_FRAMESET:
case MALFORMED_COMMENT:
case MALFORMED_COMMENT_DROPPING:
case MALFORMED_COMMENT_EOS:
case MALFORMED_COMMENT_WARN:
case MALFORMED_DOCTYPE:
case MISSING_DOCTYPE:
case MISSING_TITLE_ELEMENT:
case NESTED_QUOTATION:
case SUSPECTED_MISSING_QUOTE:
case XML_DECLARATION_DETECTED:
case BLANK_TITLE_ELEMENT:
return TY_(tidyMessageCreateWithNode)(doc, rpt, code, level );
case ELEMENT_NOT_EMPTY:
case FOUND_STYLE_IN_BODY:
case ILLEGAL_NESTING:
case MOVED_STYLE_TO_HEAD:
case TRIM_EMPTY_ELEMENT:
case UNEXPECTED_END_OF_FILE:
return TY_(tidyMessageCreateWithNode)(doc, rpt, code, level, elemdesc );
case OBSOLETE_ELEMENT:
case REPLACING_ELEMENT:
case REPLACING_UNEX_ELEMENT:
return TY_(tidyMessageCreateWithNode)(doc, rpt, code, level, elemdesc, nodedesc );
case ADDED_MISSING_CHARSET:
case BAD_SUMMARY_HTML5:
case NESTED_EMPHASIS:
case PROPRIETARY_ELEMENT:
case REMOVED_HTML5:
case UNKNOWN_ELEMENT:
case UNKNOWN_ELEMENT_LOOKS_CUSTOM:
return TY_(tidyMessageCreateWithNode)(doc, rpt, code, level, nodedesc );
case MISSING_ENDTAG_FOR:
case MISSING_ENDTAG_OPTIONAL:
case PREVIOUS_LOCATION:
return TY_(tidyMessageCreateWithNode)(doc, rpt, code, level, element? element->element : NULL );
case MISSING_ENDTAG_BEFORE:
return TY_(tidyMessageCreateWithNode)(doc, rpt, code, level, element? element->element : NULL, nodedesc );
case COERCE_TO_ENDTAG:
case NON_MATCHING_ENDTAG:
return TY_(tidyMessageCreateWithNode)(doc, rpt, code, level, node->element, node->element );
case TOO_MANY_ELEMENTS_IN:
return TY_(tidyMessageCreateWithNode)(doc, rpt, code, level, node->element, element ? element->element : NULL);
}
return NULL;
}
/* Provides general formatting as formatStandard, except TidyReportLevel is set
** dynamically for these items as it cannot be predicted except at runtime.
*/
TidyMessageImpl *formatStandardDynamic(TidyDocImpl* doc, Node *element, Node *node, uint code, uint level, va_list args)
{
char nodedesc[ 256 ] = {0};
TagToString(node, nodedesc, sizeof(nodedesc));
switch (code)
{
case DISCARDING_UNEXPECTED:
/* Force error if in a bad form, or Issue #166 - repeated <main> element. */
/* Can we use `rpt` here? No; `element` has a value in every case. */
return TY_(tidyMessageCreateWithNode)(doc, node, code, doc->badForm ? TidyError : TidyWarning, nodedesc );
break;
}
return NULL;
}
/*********************************************************************
* High Level Message Writing Functions
* When adding new reports to LibTidy, preference should be given
* to one of the existing, general purpose message writing functions
* above, if possible, otherwise try to use one of these, or as a
* last resort add a new one in this section.
*********************************************************************/
/* This function performs the heavy lifting for TY_(Report)(). Critically we
** can accept the va_list needed for recursion.
*/
static void vReport(TidyDocImpl* doc, Node *element, Node *node, uint code, va_list args)
{
int i = 0;
va_list args_copy;
while ( dispatchTable[i].code != 0 )
{
if ( dispatchTable[i].code == code )
{
TidyMessageImpl *message;
messageFormatter *handler = dispatchTable[i].handler;
TidyReportLevel level = dispatchTable[i].level;
va_copy(args_copy, args);
message = handler( doc, element, node, code, level, args_copy );
va_end(args_copy);
messageOut( message );
if ( dispatchTable[i].next )
{
va_copy(args_copy, args);
vReport(doc, element, node, dispatchTable[i].next, args_copy);
va_end(args_copy);
}
break;
}
i++;
}
}
/* This single Report output function uses the correct formatter with all
** possible, relevant data that can be reported. The only real drawbacks are
** having to pass NULL when some of the values aren't used, and the lack of
** type safety by using the variable arguments. To counter this some convenience
** report output functions exist, too. Any new reports you wish to create must
** be able to use this function signature, although convenience functions should
** be added to abstract the full function signature and to preserve type safety.
*/
void TY_(Report)(TidyDocImpl* doc, Node *element, Node *node, uint code, ...)
{
va_list args;
va_start(args, code);
vReport(doc, element, node, code, args);
va_end(args);
}
/*********************************************************************
* Convenience Reporting Functions
* Functions that don't require the full signature of TY_(Report),
* and help protect type safety by avoiding variable arguments in the
* rest of Tidy's code.
*********************************************************************/
void TY_(ReportAccessError)( TidyDocImpl* doc, Node* node, uint code )
{
TY_(Report)( doc, NULL, node, code );
}
void TY_(ReportAttrError)(TidyDocImpl* doc, Node *node, AttVal *av, uint code)
{
TY_(Report)( doc, NULL, node, code, av );
}
void TY_(ReportBadArgument)( TidyDocImpl* doc, ctmbstr option )
{
assert( option != NULL );
TY_(Report)( doc, NULL, NULL, STRING_MISSING_MALFORMED, option );
}
void TY_(ReportEntityError)( TidyDocImpl* doc, uint code, ctmbstr entity, int ARG_UNUSED(c) )
{
/* Note that the report formatter currently doesn't use argument c */
TY_(Report)( doc, NULL, NULL, code, entity, c );
}
void TY_(ReportFileError)( TidyDocImpl* doc, ctmbstr file, uint code )
{
TY_(Report)( doc, NULL, NULL, code, file );
}
void TY_(ReportEncodingError)(TidyDocImpl* doc, uint code, uint c, Bool discarded)
{
TY_(Report)( doc, NULL, NULL, code, c, discarded );
}
void TY_(ReportEncodingWarning)(TidyDocImpl* doc, uint code, uint encoding)
{
/* va_list in formatter expects trailing `no` argument */
TY_(Report)( doc, NULL, NULL, code, encoding, no );
}
void TY_(ReportMissingAttr)( TidyDocImpl* doc, Node* node, ctmbstr name )
{
TY_(Report)( doc, NULL, node, MISSING_ATTRIBUTE, name );
}
void TY_(ReportSurrogateError)(TidyDocImpl* doc, uint code, uint c1, uint c2)
{
TY_(Report)( doc, NULL, NULL, code, c1,c2 );
}
void TY_(ReportUnknownOption)( TidyDocImpl* doc, ctmbstr option )
{
/* lexer is not defined when this is called */
TY_(Report)( doc, NULL, NULL, STRING_UNKNOWN_OPTION, option );
}
/*********************************************************************
* Dialogue Output Functions
* As for issuing reports, Tidy manages all dialogue output from a
* single source in order to manage message categories in a simple
* an consistent manner.
*********************************************************************/
/* This structure ties together for each dialogue Code the default
** TidyReportLevel. This it makes it simple to output new dialogue
** messages, or to change report level by modifying this array.
*/
static struct _dialogueDispatchTable {
uint code; /**< The message code. */
TidyReportLevel level; /**< The default TidyReportLevel of the message. */
} dialogueDispatchTable[] = {
{ STRING_HELLO_ACCESS, TidyDialogueInfo }, /* AccessibilityChecks() */
{ TEXT_GENERAL_INFO, TidyDialogueInfo }, /* tidyGeneralInfo() */
{ TEXT_GENERAL_INFO_PLEA, TidyDialogueInfo }, /* tidyGeneralInfo() */
{ STRING_NEEDS_INTERVENTION, TidyDialogueSummary }, /* tidyDocRunDiagnostics() */
{ STRING_ERROR_COUNT, TidyDialogueSummary }, /* ReportNumWarnings() */
{ STRING_NO_ERRORS, TidyDialogueSummary }, /* ReportNumWarnings() */
{ STRING_NOT_ALL_SHOWN, TidyDialogueSummary }, /* ReportNumWarnings() */
{ FOOTNOTE_TRIM_EMPTY_ELEMENT, TidyDialogueFootnote },
{ TEXT_ACCESS_ADVICE1, TidyDialogueFootnote }, /* errorSummary() */
{ TEXT_ACCESS_ADVICE2, TidyDialogueFootnote },
{ TEXT_BAD_FORM, TidyDialogueFootnote },
{ TEXT_BAD_MAIN, TidyDialogueFootnote },
{ TEXT_HTML_T_ALGORITHM, TidyDialogueFootnote },
{ TEXT_INVALID_URI, TidyDialogueFootnote },
{ TEXT_INVALID_UTF8, TidyDialogueFootnote },
{ TEXT_INVALID_UTF16, TidyDialogueFootnote },
{ TEXT_M_IMAGE_ALT, TidyDialogueFootnote },
{ TEXT_M_IMAGE_MAP, TidyDialogueFootnote },
{ TEXT_M_LINK_ALT, TidyDialogueFootnote },
{ TEXT_M_SUMMARY, TidyDialogueFootnote },
{ TEXT_SGML_CHARS, TidyDialogueFootnote },
{ TEXT_USING_BODY, TidyDialogueFootnote },
{ TEXT_USING_FONT, TidyDialogueFootnote },
{ TEXT_USING_FRAMES, TidyDialogueFootnote },
{ TEXT_USING_LAYER, TidyDialogueFootnote },
{ TEXT_USING_NOBR, TidyDialogueFootnote },
{ TEXT_USING_SPACER, TidyDialogueFootnote },
{ TEXT_VENDOR_CHARS, TidyDialogueFootnote },
{ 0, 0 }
};
/* This message formatter for dialogue messages should be capable of formatting
** every message, because they're not all that complex and there aren't that
** many.
*/
static TidyMessageImpl *formatDialogue( TidyDocImpl* doc, uint code, TidyReportLevel level, va_list args )
{
switch (code)
{
case TEXT_SGML_CHARS:
case TEXT_VENDOR_CHARS:
{
ctmbstr str = va_arg(args, ctmbstr);
return TY_(tidyMessageCreate)( doc, code, level, str );
}
case STRING_ERROR_COUNT:
case STRING_NOT_ALL_SHOWN:
return TY_(tidyMessageCreate)( doc, code, level,
doc->warnings, "STRING_ERROR_COUNT_WARNING",
doc->errors, "STRING_ERROR_COUNT_ERROR" );
case FOOTNOTE_TRIM_EMPTY_ELEMENT:
case STRING_HELLO_ACCESS:
case STRING_NEEDS_INTERVENTION:
case STRING_NO_ERRORS:
case TEXT_ACCESS_ADVICE1:
case TEXT_ACCESS_ADVICE2:
case TEXT_BAD_FORM:
case TEXT_BAD_MAIN:
case TEXT_GENERAL_INFO:
case TEXT_GENERAL_INFO_PLEA:
case TEXT_HTML_T_ALGORITHM:
case TEXT_INVALID_URI:
case TEXT_INVALID_UTF8:
case TEXT_INVALID_UTF16:
case TEXT_M_IMAGE_ALT:
case TEXT_M_IMAGE_MAP:
case TEXT_M_LINK_ALT:
case TEXT_M_SUMMARY:
case TEXT_USING_BODY:
case TEXT_USING_FONT:
case TEXT_USING_FRAMES:
case TEXT_USING_LAYER:
case TEXT_USING_NOBR:
case TEXT_USING_SPACER:
default:
return TY_(tidyMessageCreate)( doc, code, level );
}
return NULL;
}
/* This single Dialogue output function determines the correct message level
** and formats the message with the appropriate formatter, and then outputs it.
** This one dialogue function should be sufficient for every use case.
*/
void TY_(Dialogue)(TidyDocImpl* doc, uint code, ...)
{
int i = 0;
va_list args;
while ( dialogueDispatchTable[i].code != 0 )
{
if ( dialogueDispatchTable[i].code == code )
{
TidyMessageImpl *message;
TidyReportLevel level = dialogueDispatchTable[i].level;
va_start(args, code);
message = formatDialogue( doc, code, level, args );
va_end(args);
messageOut( message );
break;
}
i++;
}
}
/*********************************************************************
* Output Dialogue Information
* In addition to reports that are added to the table, Tidy emits
* various dialogue type information. Most of these are specific to
* exact circumstances, although `TY_(Dialogue)` should be used
* instead of adding a new function, if possible.
*********************************************************************/
/* Outputs the footnotes and other dialogue information after document cleanup
** is complete. LibTidy users might consider capturing these individually in
** the message callback rather than capturing this entire buffer.
** Called by tidyErrorSummary(), in console.
** @todo: This name is a bit misleading and should probably be renamed to
** indicate its focus on printing footnotes.
*/
void TY_(ErrorSummary)( TidyDocImpl* doc )
{
ctmbstr encnam = tidyLocalizedString(STRING_SPECIFIED);
int charenc = cfg( doc, TidyCharEncoding );
if ( charenc == WIN1252 )
encnam = "Windows-1252";
else if ( charenc == MACROMAN )
encnam = "MacRoman";
else if ( charenc == IBM858 )
encnam = "ibm858";
else if ( charenc == LATIN0 )
encnam = "latin0";
/* adjust badAccess to that it is 0 if frames are ok */
if ( doc->badAccess & (BA_USING_FRAMES | BA_USING_NOFRAMES) )
{
if (!((doc->badAccess & BA_USING_FRAMES) && !(doc->badAccess & BA_USING_NOFRAMES)))
{
doc->badAccess &= ~(BA_USING_FRAMES | BA_USING_NOFRAMES);
}
}
if (doc->badChars)
{
if (doc->badChars & BC_VENDOR_SPECIFIC_CHARS)
TY_(Dialogue)( doc, TEXT_VENDOR_CHARS, encnam );
if ((doc->badChars & BC_INVALID_SGML_CHARS) || (doc->badChars & BC_INVALID_NCR))
TY_(Dialogue)( doc, TEXT_SGML_CHARS, encnam );
if (doc->badChars & BC_INVALID_UTF8)
TY_(Dialogue)( doc, TEXT_INVALID_UTF8 );
if (doc->badChars & BC_INVALID_UTF16)
TY_(Dialogue)( doc, TEXT_INVALID_UTF16 );
if (doc->badChars & BC_INVALID_URI)
TY_(Dialogue)( doc, TEXT_INVALID_URI );
}
if (doc->badForm)
{
if (doc->badForm & flg_BadForm) /* Issue #166 - changed to BIT flag to support other errors */
TY_(Dialogue)( doc, TEXT_BAD_FORM );
if (doc->badForm & flg_BadMain) /* Issue #166 - repeated <main> element */
TY_(Dialogue)( doc, TEXT_BAD_MAIN );
}
if (doc->badAccess)
{
/* Tidy "classic" accessibility tests */
if ( cfg(doc, TidyAccessibilityCheckLevel) == 0 )
{
if (doc->badAccess & BA_MISSING_SUMMARY)
TY_(Dialogue)( doc, TEXT_M_SUMMARY );
if (doc->badAccess & BA_MISSING_IMAGE_ALT)
TY_(Dialogue)( doc, TEXT_M_IMAGE_ALT );
if (doc->badAccess & BA_MISSING_IMAGE_MAP)
TY_(Dialogue)( doc, TEXT_M_IMAGE_MAP );
if (doc->badAccess & BA_MISSING_LINK_ALT)
TY_(Dialogue)( doc, TEXT_M_LINK_ALT );
if ((doc->badAccess & BA_USING_FRAMES) && !(doc->badAccess & BA_USING_NOFRAMES))
TY_(Dialogue)( doc, TEXT_USING_FRAMES );
}
if ( cfg(doc, TidyAccessibilityCheckLevel) > 0 )
TY_(Dialogue)( doc, TEXT_ACCESS_ADVICE2 );
else
TY_(Dialogue)( doc, TEXT_ACCESS_ADVICE1 );
}
if (doc->badLayout)
{
if (doc->badLayout & USING_LAYER)
TY_(Dialogue)( doc, TEXT_USING_LAYER );
if (doc->badLayout & USING_SPACER)
TY_(Dialogue)( doc, TEXT_USING_SPACER );
if (doc->badLayout & USING_FONT)
TY_(Dialogue)( doc, TEXT_USING_FONT );
if (doc->badLayout & USING_NOBR)
TY_(Dialogue)( doc, TEXT_USING_NOBR );
if (doc->badLayout & USING_BODY)
TY_(Dialogue)( doc, TEXT_USING_BODY );
}
if (doc->footnotes)
{
if (doc->footnotes & FN_TRIM_EMPTY_ELEMENT)
TY_(Dialogue)( doc, FOOTNOTE_TRIM_EMPTY_ELEMENT );
}
}
/* Outputs document HTML version and version-related information.
** Called by tidyRunDiagnostics(), from console.
** Called by tidyDocReportDoctype(), currently unused.
*/
void TY_(ReportMarkupVersion)( TidyDocImpl* doc )
{
if ( doc->givenDoctype )
TY_(Report)( doc, NULL, NULL, STRING_DOCTYPE_GIVEN, doc->givenDoctype );
if ( ! cfgBool(doc, TidyXmlTags) )
{
Bool isXhtml = doc->lexer->isvoyager;
uint apparentVers = TY_(ApparentVersion)( doc );
ctmbstr vers = TY_(HTMLVersionNameFromCode)( apparentVers, isXhtml );
if ( !vers )
vers = tidyLocalizedString(STRING_HTML_PROPRIETARY);
TY_(Report)( doc, NULL, NULL, STRING_CONTENT_LOOKS, vers );
/* Warn about missing system identifier (SI) in emitted doctype */
if ( TY_(WarnMissingSIInEmittedDocType)( doc ) )
TY_(Report)( doc, NULL, NULL, STRING_NO_SYSID );
}
}
/* Reports the number of warnings and errors found in the document.
** Called by tidyRunDiagnostics(), from console.
*/
void TY_(ReportNumWarnings)( TidyDocImpl* doc )
{
if ( doc->warnings > 0 || doc->errors > 0 )
{
if ( doc->errors > cfg(doc, TidyShowErrors) || !cfgBool(doc, TidyShowWarnings) )
{
TY_(Dialogue)( doc, STRING_NOT_ALL_SHOWN );
}
else
{
TY_(Dialogue)( doc, STRING_ERROR_COUNT );
}
}
else
{
TY_(Dialogue)( doc, STRING_NO_ERRORS );
}
}
/*********************************************************************
* Message Muting
*********************************************************************/
void TY_(FreeMutedMessageList)( TidyDocImpl* doc )
{
TidyMutedMessages *list = &(doc->muted);
if ( list->list )
TidyFree( doc->allocator, list->list );
}
void TY_(DefineMutedMessage)(TidyDocImpl* doc, const TidyOptionImpl* opt, ctmbstr name)
{
enum { capacity = 10 };
TidyMutedMessages *list = &(doc->muted);
tidyStrings message = TY_(tidyErrorCodeFromKey)( name );
if ( message <= REPORT_MESSAGE_FIRST || message >= REPORT_MESSAGE_LAST)
{
TY_(Report)( doc, NULL, NULL, STRING_ARGUMENT_BAD, opt->name, name );
return;
}
if ( !list->list )
{
list->list = TidyAlloc(doc->allocator, sizeof(tidyStrings) * capacity );
list->list[0] = 0;
list->capacity = capacity;
list->count = 0;
}
if ( list->count >= list->capacity )
{
list->capacity = list->capacity * 2;
list->list = TidyRealloc(doc->allocator, list->list, sizeof(tidyStrings) * list->capacity + 1 );
}
list->list[list->count] = message;
list->count++;
list->list[list->count] = 0;
/* Must come *after* adding to the list, in case it's muted, too. */
TY_(Report)( doc, NULL, NULL, STRING_MUTING_TYPE, name );
}
TidyIterator TY_(getMutedMessageList)( TidyDocImpl* doc )
{
TidyMutedMessages *list = &(doc->muted);
size_t result = list->count > 0 ? 1 : 0;
return (TidyIterator) result;
}
ctmbstr TY_(getNextMutedMessage)( TidyDocImpl* doc, TidyIterator* iter )
{
TidyMutedMessages *list = &(doc->muted);
size_t index;
ctmbstr result = NULL;
assert( iter != NULL );
index = (size_t)*iter;
if ( index > 0 && index <= list->count )
{
result = TY_(tidyErrorCodeAsKey)(list->list[index-1]);
index++;
}
*iter = (TidyIterator) ( index <= list->count ? index : (size_t)0 );
return result;
}
/*********************************************************************
* Key Discovery
*********************************************************************/
/*********************************************************************
* LibTidy users may want to to enable their own localization lookup
* lookup methods. Because Tidy's errors codes are enums, the actual
* values can change over time. This table will the LibTidy users
* always have a static value available for use.
*
* For macro documentation, refer to the comments in `tidyenum.h`.
*********************************************************************/
typedef struct tidyStringsKeyItem {
ctmbstr key;
int value;
} tidyStringsKeyItem;
static const tidyStringsKeyItem tidyStringsKeys[] = {
FOREACH_TIDYCONFIGCATEGORY(MAKE_STRUCT)
FOREACH_MSG_MISC(MAKE_STRUCT)
FOREACH_FOOTNOTE_MSG(MAKE_STRUCT)
FOREACH_DIALOG_MSG(MAKE_STRUCT)
FOREACH_REPORT_MSG(MAKE_STRUCT)
FOREACH_ACCESS_MSG(MAKE_STRUCT)
#if SUPPORT_CONSOLE_APP
FOREACH_MSG_CONSOLE(MAKE_STRUCT)
#endif
{ "TIDYSTRINGS_FIRST", TIDYSTRINGS_FIRST },
{ "TIDYSTRINGS_LAST", TIDYSTRINGS_LAST },
{ NULL, 0 },
};
/**
* Given an error code, return the string associated with it.
*/
ctmbstr TY_(tidyErrorCodeAsKey)(uint code)
{
uint i = 0;
while (tidyStringsKeys[i].key) {
if ( tidyStringsKeys[i].value == code )
return tidyStringsKeys[i].key;
i++;
}
return "UNDEFINED";
}
/**
* Given an error code string, return its uint.
*/
uint TY_(tidyErrorCodeFromKey)(ctmbstr code)
{
uint i = 0;
while (tidyStringsKeys[i].key) {
if ( strcmp(tidyStringsKeys[i].key, code) == 0 )
return tidyStringsKeys[i].value;
i++;
}
return UINT_MAX;
}
/**
* Determines the number of error codes used by Tidy.
*/
static const uint tidyErrorCodeListSize()
{
static uint array_size = 0;
if ( array_size == 0 )
{
while ( tidyStringsKeys[array_size].key ) {
array_size++;
}
}
return array_size;
}
/**
* Initializes the TidyIterator to point to the first item
* in Tidy's list of error codes. Individual items must be
* retrieved with getNextErrorCode();
*/
TidyIterator TY_(getErrorCodeList)()
{
return (TidyIterator)(size_t)1;
}
/**
* Returns the next error code.
*/
uint TY_(getNextErrorCode)( TidyIterator* iter )
{
const tidyStringsKeyItem *item = NULL;
size_t itemIndex;
assert( iter != NULL );
itemIndex = (size_t)*iter;
if ( itemIndex > 0 && itemIndex <= tidyErrorCodeListSize() )
{
item = &tidyStringsKeys[itemIndex - 1];
itemIndex++;
}
*iter = (TidyIterator)( itemIndex <= tidyErrorCodeListSize() ? itemIndex : (size_t)0 );
return item ? item->value : 0;
}
/*********************************************************************
* Documentation of configuration options
*
* Although most of the strings now come from the language module,
* generating the documentation by the console application requires a
* series of cross-references that are generated in this messaging
* module.
*********************************************************************/
#if SUPPORT_CONSOLE_APP
/* Cross-references definitions.
* Note that each list must be terminated with `TidyUnknownOption`.
*/
static const TidyOptionId TidyAsciiCharsLinks[] = { TidyMakeClean, TidyUnknownOption };
static const TidyOptionId TidyBlockTagsLinks[] = { TidyEmptyTags, TidyInlineTags, TidyPreTags, TidyUseCustomTags, TidyUnknownOption };
static const TidyOptionId TidyCharEncodingLinks[] = { TidyInCharEncoding, TidyOutCharEncoding, TidyUnknownOption };
static const TidyOptionId TidyDuplicateAttrsLinks[] = { TidyJoinClasses, TidyJoinStyles, TidyUnknownOption };
static const TidyOptionId TidyEmacsLinks[] = { TidyShowFilename, TidyUnknownOption };
static const TidyOptionId TidyEmptyTagsLinks[] = { TidyBlockTags, TidyInlineTags, TidyPreTags, TidyUseCustomTags, TidyUnknownOption };
static const TidyOptionId TidyErrFileLinks[] = { TidyOutFile, TidyUnknownOption };
static const TidyOptionId TidyInCharEncodingLinks[] = { TidyCharEncoding, TidyUnknownOption };
static const TidyOptionId TidyIndentContentLinks[] = { TidyIndentSpaces, TidyUnknownOption };
static const TidyOptionId TidyIndentSpacesLinks[] = { TidyIndentContent, TidyUnknownOption };
static const TidyOptionId TidyInlineTagsLinks[] = { TidyBlockTags, TidyEmptyTags, TidyPreTags, TidyUseCustomTags, TidyUnknownOption };
static const TidyOptionId TidyMergeDivsLinks[] = { TidyMakeClean, TidyMergeSpans, TidyUnknownOption };
static const TidyOptionId TidyMergeSpansLinks[] = { TidyMakeClean, TidyMergeDivs, TidyUnknownOption };
static const TidyOptionId TidyMuteLinks[] = { TidyMuteShow, TidyUnknownOption };
static const TidyOptionId TidyMuteShowLinks[] = { TidyMuteReports, TidyUnknownOption };
static const TidyOptionId TidyNumEntitiesLinks[] = { TidyDoctype, TidyPreserveEntities, TidyUnknownOption };
static const TidyOptionId TidyOutCharEncodingLinks[] = { TidyCharEncoding, TidyUnknownOption };
static const TidyOptionId TidyOutFileLinks[] = { TidyErrFile, TidyUnknownOption };
static const TidyOptionId TidyPreTagsLinks[] = { TidyBlockTags, TidyEmptyTags, TidyInlineTags, TidyUseCustomTags, TidyUnknownOption };
static const TidyOptionId TidyShowFilenameLinks[] = { TidyEmacs, TidyUnknownOption };
static const TidyOptionId TidySortAttributesLinks[] = { TidyPriorityAttributes, TidyUnknownOption };
static const TidyOptionId TidyUseCustomTagsLinks[] = { TidyBlockTags, TidyEmptyTags, TidyInlineTags, TidyPreTags, TidyUnknownOption };
static const TidyOptionId TidyWrapAttValsLinks[] = { TidyWrapScriptlets, TidyLiteralAttribs, TidyUnknownOption };
static const TidyOptionId TidyWrapScriptletsLinks[] = { TidyWrapAttVals, TidyUnknownOption };
static const TidyOptionId TidyXmlDeclLinks[] = { TidyCharEncoding, TidyOutCharEncoding, TidyUnknownOption };
/* Cross-reference assignments.
* We can't build a complex array at compile time and we're not counting on
* any type of initialization, so this two-stage building process is required.
*/
static const TidyOptionDoc docs_xrefs[] =
{
{ TidyAsciiChars, TidyAsciiCharsLinks },
{ TidyBlockTags, TidyBlockTagsLinks },
{ TidyCharEncoding, TidyCharEncodingLinks },
{ TidyDuplicateAttrs, TidyDuplicateAttrsLinks },
{ TidyEmacs, TidyEmacsLinks },
{ TidyEmptyTags, TidyEmptyTagsLinks },
{ TidyErrFile, TidyErrFileLinks },
{ TidyInCharEncoding, TidyInCharEncodingLinks },
{ TidyIndentContent, TidyIndentContentLinks },
{ TidyIndentSpaces, TidyIndentSpacesLinks },
{ TidyInlineTags, TidyInlineTagsLinks },
{ TidyMergeDivs, TidyMergeDivsLinks },
{ TidyMergeSpans, TidyMergeSpansLinks },
{ TidyMuteShow, TidyMuteShowLinks },
{ TidyNumEntities, TidyNumEntitiesLinks },
{ TidyOutCharEncoding, TidyOutCharEncodingLinks },
{ TidyOutFile, TidyOutFileLinks },
{ TidyPreTags, TidyPreTagsLinks },
{ TidyShowFilename, TidyShowFilenameLinks },
{ TidySortAttributes, TidySortAttributesLinks },
{ TidyMuteReports, TidyMuteLinks },
{ TidyUseCustomTags, TidyUseCustomTagsLinks },
{ TidyWrapAttVals, TidyWrapAttValsLinks },
{ TidyWrapScriptlets, TidyWrapScriptletsLinks },
{ TidyXmlDecl, TidyXmlDeclLinks },
{ N_TIDY_OPTIONS }
};
/* Cross-reference retrieval. */
const TidyOptionDoc* TY_(OptGetDocDesc)( TidyOptionId optId )
{
uint i = 0;
while( docs_xrefs[i].opt != N_TIDY_OPTIONS )
{
if ( docs_xrefs[i].opt == optId )
return &docs_xrefs[i];
++i;
}
return NULL;
}
#endif /* SUPPORT_CONSOLE_APP */
/*
* local variables:
* mode: c
* indent-tabs-mode: nil
* c-basic-offset: 4
* end:
*/
| 66,972 | 1,612 | jart/cosmopolitan | false |
cosmopolitan/third_party/tidy/tags.c | /* clang-format off */
/* tags.c
* Recognize HTML tags.
*
* Copyright (c) 1998-2017 World Wide Web Consortium (Massachusetts
* Institute of Technology, European Research Consortium for Informatics
* and Mathematics, Keio University) and HTACG.
*
* See tidy.h for the copyright notice.
*/
#include "third_party/tidy/tidy-int.h"
#include "third_party/tidy/message.h"
#include "third_party/tidy/tmbstr.h"
#include "third_party/tidy/sprtf.h"
/* Attribute checking methods */
static CheckAttribs CheckIMG;
static CheckAttribs CheckLINK;
static CheckAttribs CheckAREA;
static CheckAttribs CheckTABLE;
static CheckAttribs CheckCaption;
static CheckAttribs CheckHTML;
#define VERS_ELEM_A (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_ABBR (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_ACRONYM (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|xxxx|xxxx)
#define VERS_ELEM_ADDRESS (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_APPLET (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_AREA (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_B (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_BASE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_BASEFONT (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_BDO (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_BIG (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|xxxx|xxxx)
#define VERS_ELEM_BLOCKQUOTE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_BODY (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_BR (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_BUTTON (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_CAPTION (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_CENTER (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_CITE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_CODE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_COL (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_COLGROUP (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_DD (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_DEL (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_DFN (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_DIR (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_DIV (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_DL (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_DT (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_EM (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_FIELDSET (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_FONT (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_FORM (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_FRAME (xxxx|xxxx|xxxx|xxxx|xxxx|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_FRAMESET (xxxx|xxxx|xxxx|xxxx|xxxx|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_H1 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_H2 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_H3 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_H4 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_H5 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_H6 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_HEAD (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_HR (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_HTML (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_I (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_IFRAME (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_IMG (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_INPUT (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_INS (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_ISINDEX (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_KBD (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_LABEL (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_LEGEND (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_LI (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_LINK (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_LISTING (HT20|HT32|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_MAP (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_MATHML (xxxx|xxxx|xxxx|H41T|X10T|xxxx|H41F|X10F|xxxx|H41S|X10S|XH11|xxxx|HT50|XH50) /* [i_a]2 */
#define VERS_ELEM_MENU (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_META (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_NEXTID (HT20|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_NOFRAMES (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_NOSCRIPT (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_OBJECT (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_OL (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_OPTGROUP (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_OPTION (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_P (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_PARAM (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_PICTURE (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_PLAINTEXT (HT20|HT32|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_PRE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_Q (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_RB (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx|xxxx|xxxx)
#define VERS_ELEM_RBC (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx|xxxx|xxxx)
#define VERS_ELEM_RP (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_RT (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_RTC (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx|xxxx|xxxx)
#define VERS_ELEM_RUBY (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_S (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_SAMP (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_SCRIPT (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_SELECT (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_SMALL (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_SPAN (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_STRIKE (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_STRONG (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_STYLE (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_SUB (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_SUP (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_SVG (xxxx|xxxx|xxxx|H41T|X10T|xxxx|H41F|X10F|xxxx|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_TABLE (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_TBODY (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_TD (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_TEXTAREA (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_TFOOT (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_TH (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_THEAD (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|HT50|XH50)
#define VERS_ELEM_TITLE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_TR (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_TT (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx|xxxx|xxxx)
#define VERS_ELEM_U (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_UL (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_VAR (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10|HT50|XH50)
#define VERS_ELEM_XMP (HT20|HT32|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_ARTICLE (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_ASIDE (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_AUDIO (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_BDI (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_CANVAS (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_COMMAND (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_DATALIST (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_DATA (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_DETAILS (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_DIALOG (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_EMBED (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_FIGCAPTION (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_FIGURE (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_FOOTER (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_HEADER (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_HGROUP (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_KEYGEN (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_MAIN (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_MARK (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_MENUITEM (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_METER (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_NAV (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_OUTPUT (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_PROGRESS (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_SECTION (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_SLOT (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_SOURCE (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_SUMMARY (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_TEMPLATE (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_TIME (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_TRACK (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_VIDEO (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
#define VERS_ELEM_WBR (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|HT50|XH50)
/*\
* Issue #167 & #169 & #232
* Tidy defaults to HTML5 mode
* but allow this table to be ADJUSTED if NOT HTML5
* was static const Dict tag_defs[] =
\*/
static TIDY_THREAD_LOCAL Dict tag_defs[] =
{
{ TidyTag_UNKNOWN, "unknown!", VERS_UNKNOWN, NULL, (0), NULL, NULL },
/* W3C defined elements */
{ TidyTag_A, "a", VERS_ELEM_A, &TY_(W3CAttrsFor_A)[0], (CM_INLINE|CM_BLOCK|CM_MIXED), TY_(ParseBlock), NULL }, /* Issue #167 & #169 - default HTML5 */
{ TidyTag_ABBR, "abbr", VERS_ELEM_ABBR, &TY_(W3CAttrsFor_ABBR)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_ACRONYM, "acronym", VERS_ELEM_ACRONYM, &TY_(W3CAttrsFor_ACRONYM)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_ADDRESS, "address", VERS_ELEM_ADDRESS, &TY_(W3CAttrsFor_ADDRESS)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_APPLET, "applet", VERS_ELEM_APPLET, &TY_(W3CAttrsFor_APPLET)[0], (CM_OBJECT|CM_IMG|CM_INLINE|CM_PARAM), TY_(ParseBlock), NULL },
{ TidyTag_AREA, "area", VERS_ELEM_AREA, &TY_(W3CAttrsFor_AREA)[0], (CM_BLOCK|CM_EMPTY|CM_VOID), TY_(ParseEmpty), CheckAREA },
{ TidyTag_B, "b", VERS_ELEM_B, &TY_(W3CAttrsFor_B)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_BASE, "base", VERS_ELEM_BASE, &TY_(W3CAttrsFor_BASE)[0], (CM_HEAD|CM_EMPTY|CM_VOID), TY_(ParseEmpty), NULL },
{ TidyTag_BASEFONT, "basefont", VERS_ELEM_BASEFONT, &TY_(W3CAttrsFor_BASEFONT)[0], (CM_INLINE|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_BDO, "bdo", VERS_ELEM_BDO, &TY_(W3CAttrsFor_BDO)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_BIG, "big", VERS_ELEM_BIG, &TY_(W3CAttrsFor_BIG)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_BLOCKQUOTE, "blockquote", VERS_ELEM_BLOCKQUOTE, &TY_(W3CAttrsFor_BLOCKQUOTE)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_BODY, "body", VERS_ELEM_BODY, &TY_(W3CAttrsFor_BODY)[0], (CM_HTML|CM_OPT|CM_OMITST), TY_(ParseBody), NULL },
{ TidyTag_BR, "br", VERS_ELEM_BR, &TY_(W3CAttrsFor_BR)[0], (CM_INLINE|CM_EMPTY|CM_VOID), TY_(ParseEmpty), NULL },
{ TidyTag_BUTTON, "button", VERS_ELEM_BUTTON, &TY_(W3CAttrsFor_BUTTON)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_CAPTION, "caption", VERS_ELEM_CAPTION, &TY_(W3CAttrsFor_CAPTION)[0], (CM_TABLE), TY_(ParseBlock), CheckCaption },
{ TidyTag_CENTER, "center", VERS_ELEM_CENTER, &TY_(W3CAttrsFor_CENTER)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_CITE, "cite", VERS_ELEM_CITE, &TY_(W3CAttrsFor_CITE)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_CODE, "code", VERS_ELEM_CODE, &TY_(W3CAttrsFor_CODE)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_COL, "col", VERS_ELEM_COL, &TY_(W3CAttrsFor_COL)[0], (CM_TABLE|CM_EMPTY|CM_VOID), TY_(ParseEmpty), NULL },
{ TidyTag_COLGROUP, "colgroup", VERS_ELEM_COLGROUP, &TY_(W3CAttrsFor_COLGROUP)[0], (CM_TABLE|CM_OPT), TY_(ParseColGroup), NULL },
{ TidyTag_DD, "dd", VERS_ELEM_DD, &TY_(W3CAttrsFor_DD)[0], (CM_DEFLIST|CM_OPT|CM_NO_INDENT), TY_(ParseBlock), NULL },
{ TidyTag_DEL, "del", VERS_ELEM_DEL, &TY_(W3CAttrsFor_DEL)[0], (CM_INLINE|CM_BLOCK|CM_MIXED), TY_(ParseInline), NULL },
{ TidyTag_DFN, "dfn", VERS_ELEM_DFN, &TY_(W3CAttrsFor_DFN)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_DIR, "dir", VERS_ELEM_DIR, &TY_(W3CAttrsFor_DIR)[0], (CM_BLOCK|CM_OBSOLETE), TY_(ParseList), NULL },
{ TidyTag_DIV, "div", VERS_ELEM_DIV, &TY_(W3CAttrsFor_DIV)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_DL, "dl", VERS_ELEM_DL, &TY_(W3CAttrsFor_DL)[0], (CM_BLOCK), TY_(ParseDefList), NULL },
{ TidyTag_DT, "dt", VERS_ELEM_DT, &TY_(W3CAttrsFor_DT)[0], (CM_DEFLIST|CM_OPT|CM_NO_INDENT), TY_(ParseInline), NULL },
{ TidyTag_EM, "em", VERS_ELEM_EM, &TY_(W3CAttrsFor_EM)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_FIELDSET, "fieldset", VERS_ELEM_FIELDSET, &TY_(W3CAttrsFor_FIELDSET)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_FONT, "font", VERS_ELEM_FONT, &TY_(W3CAttrsFor_FONT)[0], (CM_INLINE), TY_(ParseInline), NULL },
/* HTML5 Form Elements has several new elements and attributes - datalist keygen output */
{ TidyTag_FORM, "form", VERS_ELEM_FORM, &TY_(W3CAttrsFor_FORM)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_FRAME, "frame", VERS_ELEM_FRAME, &TY_(W3CAttrsFor_FRAME)[0], (CM_FRAMES|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_FRAMESET, "frameset", VERS_ELEM_FRAMESET, &TY_(W3CAttrsFor_FRAMESET)[0], (CM_HTML|CM_FRAMES), TY_(ParseFrameSet), NULL },
{ TidyTag_H1, "h1", VERS_ELEM_H1, &TY_(W3CAttrsFor_H1)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_H2, "h2", VERS_ELEM_H2, &TY_(W3CAttrsFor_H2)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_H3, "h3", VERS_ELEM_H3, &TY_(W3CAttrsFor_H3)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_H4, "h4", VERS_ELEM_H4, &TY_(W3CAttrsFor_H4)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_H5, "h5", VERS_ELEM_H5, &TY_(W3CAttrsFor_H5)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_H6, "h6", VERS_ELEM_H6, &TY_(W3CAttrsFor_H6)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_HEAD, "head", VERS_ELEM_HEAD, &TY_(W3CAttrsFor_HEAD)[0], (CM_HTML|CM_OPT|CM_OMITST), TY_(ParseHead), NULL },
{ TidyTag_HR, "hr", VERS_ELEM_HR, &TY_(W3CAttrsFor_HR)[0], (CM_BLOCK|CM_EMPTY|CM_VOID), TY_(ParseEmpty), NULL },
{ TidyTag_HTML, "html", VERS_ELEM_HTML, &TY_(W3CAttrsFor_HTML)[0], (CM_HTML|CM_OPT|CM_OMITST), TY_(ParseHTML), CheckHTML },
{ TidyTag_I, "i", VERS_ELEM_I, &TY_(W3CAttrsFor_I)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_IFRAME, "iframe", VERS_ELEM_IFRAME, &TY_(W3CAttrsFor_IFRAME)[0], (CM_INLINE), TY_(ParseBlock), NULL },
{ TidyTag_IMG, "img", VERS_ELEM_IMG, &TY_(W3CAttrsFor_IMG)[0], (CM_INLINE|CM_IMG|CM_EMPTY|CM_VOID), TY_(ParseEmpty), CheckIMG },
{ TidyTag_INPUT, "input", VERS_ELEM_INPUT, &TY_(W3CAttrsFor_INPUT)[0], (CM_INLINE|CM_IMG|CM_EMPTY|CM_VOID), TY_(ParseEmpty), NULL },
{ TidyTag_INS, "ins", VERS_ELEM_INS, &TY_(W3CAttrsFor_INS)[0], (CM_INLINE|CM_BLOCK|CM_MIXED), TY_(ParseInline), NULL },
{ TidyTag_ISINDEX, "isindex", VERS_ELEM_ISINDEX, &TY_(W3CAttrsFor_ISINDEX)[0], (CM_BLOCK|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_KBD, "kbd", VERS_ELEM_KBD, &TY_(W3CAttrsFor_KBD)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_LABEL, "label", VERS_ELEM_LABEL, &TY_(W3CAttrsFor_LABEL)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_LEGEND, "legend", VERS_ELEM_LEGEND, &TY_(W3CAttrsFor_LEGEND)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_LI, "li", VERS_ELEM_LI, &TY_(W3CAttrsFor_LI)[0], (CM_LIST|CM_OPT|CM_NO_INDENT), TY_(ParseBlock), NULL },
{ TidyTag_LINK, "link", VERS_ELEM_LINK, &TY_(W3CAttrsFor_LINK)[0], (CM_HEAD|CM_BLOCK|CM_EMPTY|CM_VOID), TY_(ParseEmpty), CheckLINK },
{ TidyTag_LISTING, "listing", VERS_ELEM_LISTING, &TY_(W3CAttrsFor_LISTING)[0], (CM_BLOCK|CM_OBSOLETE), TY_(ParsePre), NULL },
{ TidyTag_MAP, "map", VERS_ELEM_MAP, &TY_(W3CAttrsFor_MAP)[0], (CM_INLINE), TY_(ParseBlock), NULL },
{ TidyTag_MATHML, "math", VERS_ELEM_MATHML, &TY_(W3CAttrsFor_MATHML)[0], (CM_INLINE|CM_BLOCK|CM_MIXED), TY_(ParseNamespace),NULL }, /* [i_a]2 */
/* { TidyTag_MENU, "menu", VERS_ELEM_MENU, &TY_(W3CAttrsFor_MENU)[0], (CM_BLOCK|CM_OBSOLETE), TY_(ParseList), NULL }, */
{ TidyTag_META, "meta", VERS_ELEM_META, &TY_(W3CAttrsFor_META)[0], (CM_HEAD|CM_BLOCK|CM_EMPTY|CM_VOID), TY_(ParseEmpty), NULL },
{ TidyTag_NOFRAMES, "noframes", VERS_ELEM_NOFRAMES, &TY_(W3CAttrsFor_NOFRAMES)[0], (CM_BLOCK|CM_FRAMES), TY_(ParseNoFrames), NULL },
{ TidyTag_NOSCRIPT, "noscript", VERS_ELEM_NOSCRIPT, &TY_(W3CAttrsFor_NOSCRIPT)[0], (CM_HEAD|CM_BLOCK|CM_INLINE|CM_MIXED), TY_(ParseBlock), NULL },
{ TidyTag_OBJECT, "object", VERS_ELEM_OBJECT, &TY_(W3CAttrsFor_OBJECT)[0], (CM_OBJECT|CM_IMG|CM_INLINE|CM_PARAM), TY_(ParseBlock), NULL },
{ TidyTag_OL, "ol", VERS_ELEM_OL, &TY_(W3CAttrsFor_OL)[0], (CM_BLOCK), TY_(ParseList), NULL },
{ TidyTag_OPTGROUP, "optgroup", VERS_ELEM_OPTGROUP, &TY_(W3CAttrsFor_OPTGROUP)[0], (CM_FIELD|CM_OPT), TY_(ParseOptGroup), NULL },
{ TidyTag_OPTION, "option", VERS_ELEM_OPTION, &TY_(W3CAttrsFor_OPTION)[0], (CM_FIELD|CM_OPT), TY_(ParseText), NULL },
{ TidyTag_P, "p", VERS_ELEM_P, &TY_(W3CAttrsFor_P)[0], (CM_BLOCK|CM_OPT), TY_(ParseInline), NULL },
{ TidyTag_PARAM, "param", VERS_ELEM_PARAM, &TY_(W3CAttrsFor_PARAM)[0], (CM_INLINE|CM_EMPTY|CM_VOID), TY_(ParseEmpty), NULL },
{ TidyTag_PICTURE, "picture", VERS_ELEM_PICTURE, &TY_(W3CAttrsFor_PICTURE)[0], (CM_INLINE), TY_(ParseInline), NULL }, /* Issue #151 html5 */
{ TidyTag_PLAINTEXT, "plaintext", VERS_ELEM_PLAINTEXT, &TY_(W3CAttrsFor_PLAINTEXT)[0], (CM_BLOCK|CM_OBSOLETE), TY_(ParsePre), NULL },
{ TidyTag_PRE, "pre", VERS_ELEM_PRE, &TY_(W3CAttrsFor_PRE)[0], (CM_BLOCK), TY_(ParsePre), NULL },
{ TidyTag_Q, "q", VERS_ELEM_Q, &TY_(W3CAttrsFor_Q)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RB, "rb", VERS_ELEM_RB, &TY_(W3CAttrsFor_RB)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RBC, "rbc", VERS_ELEM_RBC, &TY_(W3CAttrsFor_RBC)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RP, "rp", VERS_ELEM_RP, &TY_(W3CAttrsFor_RP)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RT, "rt", VERS_ELEM_RT, &TY_(W3CAttrsFor_RT)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RTC, "rtc", VERS_ELEM_RTC, &TY_(W3CAttrsFor_RTC)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RUBY, "ruby", VERS_ELEM_RUBY, &TY_(W3CAttrsFor_RUBY)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_S, "s", VERS_ELEM_S, &TY_(W3CAttrsFor_S)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_SAMP, "samp", VERS_ELEM_SAMP, &TY_(W3CAttrsFor_SAMP)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_SCRIPT, "script", VERS_ELEM_SCRIPT, &TY_(W3CAttrsFor_SCRIPT)[0], (CM_HEAD|CM_MIXED|CM_BLOCK|CM_INLINE), TY_(ParseScript), NULL },
{ TidyTag_SELECT, "select", VERS_ELEM_SELECT, &TY_(W3CAttrsFor_SELECT)[0], (CM_INLINE|CM_FIELD), TY_(ParseSelect), NULL },
{ TidyTag_SMALL, "small", VERS_ELEM_SMALL, &TY_(W3CAttrsFor_SMALL)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_SPAN, "span", VERS_ELEM_SPAN, &TY_(W3CAttrsFor_SPAN)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_STRIKE, "strike", VERS_ELEM_STRIKE, &TY_(W3CAttrsFor_STRIKE)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_STRONG, "strong", VERS_ELEM_STRONG, &TY_(W3CAttrsFor_STRONG)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_STYLE, "style", VERS_ELEM_STYLE, &TY_(W3CAttrsFor_STYLE)[0], (CM_HEAD|CM_BLOCK), TY_(ParseScript), NULL },
{ TidyTag_SUB, "sub", VERS_ELEM_SUB, &TY_(W3CAttrsFor_SUB)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_SUP, "sup", VERS_ELEM_SUP, &TY_(W3CAttrsFor_SUP)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_SVG, "svg", VERS_ELEM_SVG, &TY_(W3CAttrsFor_SVG)[0], (CM_INLINE|CM_BLOCK|CM_MIXED), TY_(ParseNamespace),NULL },
{ TidyTag_TABLE, "table", VERS_ELEM_TABLE, &TY_(W3CAttrsFor_TABLE)[0], (CM_BLOCK), TY_(ParseTableTag), CheckTABLE },
{ TidyTag_TBODY, "tbody", VERS_ELEM_TBODY, &TY_(W3CAttrsFor_TBODY)[0], (CM_TABLE|CM_ROWGRP|CM_OPT), TY_(ParseRowGroup), NULL },
{ TidyTag_TD, "td", VERS_ELEM_TD, &TY_(W3CAttrsFor_TD)[0], (CM_ROW|CM_OPT|CM_NO_INDENT), TY_(ParseBlock), NULL },
{ TidyTag_TEXTAREA, "textarea", VERS_ELEM_TEXTAREA, &TY_(W3CAttrsFor_TEXTAREA)[0], (CM_INLINE|CM_FIELD), TY_(ParseText), NULL },
{ TidyTag_TFOOT, "tfoot", VERS_ELEM_TFOOT, &TY_(W3CAttrsFor_TFOOT)[0], (CM_TABLE|CM_ROWGRP|CM_OPT), TY_(ParseRowGroup), NULL },
{ TidyTag_TH, "th", VERS_ELEM_TH, &TY_(W3CAttrsFor_TH)[0], (CM_ROW|CM_OPT|CM_NO_INDENT), TY_(ParseBlock), NULL },
{ TidyTag_THEAD, "thead", VERS_ELEM_THEAD, &TY_(W3CAttrsFor_THEAD)[0], (CM_TABLE|CM_ROWGRP|CM_OPT), TY_(ParseRowGroup), NULL },
{ TidyTag_TITLE, "title", VERS_ELEM_TITLE, &TY_(W3CAttrsFor_TITLE)[0], (CM_HEAD), TY_(ParseTitle), NULL },
{ TidyTag_TR, "tr", VERS_ELEM_TR, &TY_(W3CAttrsFor_TR)[0], (CM_TABLE|CM_OPT), TY_(ParseRow), NULL },
{ TidyTag_TT, "tt", VERS_ELEM_TT, &TY_(W3CAttrsFor_TT)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_U, "u", VERS_ELEM_U, &TY_(W3CAttrsFor_U)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_UL, "ul", VERS_ELEM_UL, &TY_(W3CAttrsFor_UL)[0], (CM_BLOCK), TY_(ParseList), NULL },
{ TidyTag_VAR, "var", VERS_ELEM_VAR, &TY_(W3CAttrsFor_VAR)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_XMP, "xmp", VERS_ELEM_XMP, &TY_(W3CAttrsFor_XMP)[0], (CM_BLOCK|CM_OBSOLETE), TY_(ParsePre), NULL },
{ TidyTag_NEXTID, "nextid", VERS_ELEM_NEXTID, &TY_(W3CAttrsFor_NEXTID)[0], (CM_HEAD|CM_EMPTY), TY_(ParseEmpty), NULL },
/* proprietary elements */
{ TidyTag_ALIGN, "align", VERS_NETSCAPE, NULL, (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_BGSOUND, "bgsound", VERS_MICROSOFT, NULL, (CM_HEAD|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_BLINK, "blink", VERS_PROPRIETARY, NULL, (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_COMMENT, "comment", VERS_MICROSOFT, NULL, (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_ILAYER, "ilayer", VERS_NETSCAPE, NULL, (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_LAYER, "layer", VERS_NETSCAPE, NULL, (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_MARQUEE, "marquee", VERS_MICROSOFT, NULL, (CM_INLINE|CM_OPT), TY_(ParseInline), NULL },
{ TidyTag_MULTICOL, "multicol", VERS_NETSCAPE, NULL, (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_NOBR, "nobr", VERS_PROPRIETARY, NULL, (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_NOEMBED, "noembed", VERS_NETSCAPE, NULL, (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_NOLAYER, "nolayer", VERS_NETSCAPE, NULL, (CM_BLOCK|CM_INLINE|CM_MIXED), TY_(ParseBlock), NULL },
{ TidyTag_NOSAVE, "nosave", VERS_NETSCAPE, NULL, (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_SERVER, "server", VERS_NETSCAPE, NULL, (CM_HEAD|CM_MIXED|CM_BLOCK|CM_INLINE), TY_(ParseScript), NULL },
{ TidyTag_SERVLET, "servlet", VERS_SUN, NULL, (CM_OBJECT|CM_IMG|CM_INLINE|CM_PARAM), TY_(ParseBlock), NULL },
{ TidyTag_SPACER, "spacer", VERS_NETSCAPE, NULL, (CM_INLINE|CM_EMPTY), TY_(ParseEmpty), NULL },
/* HTML5 */
{ TidyTag_ARTICLE, "article", VERS_ELEM_ARTICLE, &TY_(W3CAttrsFor_ARTICLE)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_ASIDE, "aside", VERS_ELEM_ASIDE, &TY_(W3CAttrsFor_ASIDE)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_AUDIO, "audio", VERS_ELEM_AUDIO, &TY_(W3CAttrsFor_AUDIO)[0], (CM_BLOCK|CM_INLINE), TY_(ParseBlock), NULL },
{ TidyTag_BDI, "bdi", VERS_ELEM_BDI, &TY_(W3CAttrsFor_BDI)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_CANVAS, "canvas", VERS_ELEM_CANVAS, &TY_(W3CAttrsFor_CANVAS)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_COMMAND, "command", VERS_ELEM_COMMAND, &TY_(W3CAttrsFor_COMMAND)[0], (CM_HEAD|CM_INLINE|CM_EMPTY|CM_VOID), TY_(ParseEmpty), NULL },
{ TidyTag_DATALIST, "datalist", VERS_ELEM_DATALIST, &TY_(W3CAttrsFor_DATALIST)[0], (CM_INLINE|CM_FIELD), TY_(ParseDatalist), NULL },
/* { TidyTag_DATALIST, "datalist", VERS_ELEM_DATALIST, &TY_(W3CAttrsFor_DATALIST)[0], (CM_FIELD), TY_(ParseInline), NULL },*/
{ TidyTag_DATA, "data", VERS_ELEM_DATA, &TY_(W3CAttrsFor_DATA)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_DETAILS, "details", VERS_ELEM_DETAILS, &TY_(W3CAttrsFor_DETAILS)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_DIALOG, "dialog", VERS_ELEM_DIALOG, &TY_(W3CAttrsFor_DIALOG)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_EMBED, "embed", VERS_ELEM_EMBED, &TY_(W3CAttrsFor_EMBED)[0], (CM_INLINE|CM_IMG|CM_EMPTY|CM_VOID), TY_(ParseEmpty), NULL },
{ TidyTag_FIGCAPTION, "figcaption", VERS_ELEM_FIGCAPTION, &TY_(W3CAttrsFor_FIGCAPTION)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_FIGURE, "figure", VERS_ELEM_FIGURE, &TY_(W3CAttrsFor_FIGURE)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_FOOTER, "footer", VERS_ELEM_FOOTER, &TY_(W3CAttrsFor_FOOTER)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_HEADER, "header", VERS_ELEM_HEADER, &TY_(W3CAttrsFor_HEADER)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_HGROUP, "hgroup", VERS_ELEM_HGROUP, &TY_(W3CAttrsFor_HGROUP)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_KEYGEN, "keygen", VERS_ELEM_KEYGEN, &TY_(W3CAttrsFor_KEYGEN)[0], (CM_INLINE|CM_EMPTY|CM_VOID), TY_(ParseEmpty), NULL },
{ TidyTag_MAIN, "main", VERS_ELEM_MAIN, &TY_(W3CAttrsFor_MAIN)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_MARK, "mark", VERS_ELEM_MARK, &TY_(W3CAttrsFor_MARK)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_MENU, "menu", VERS_ELEM_MENU, &TY_(W3CAttrsFor_MENU)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_MENUITEM, "menuitem", VERS_ELEM_MENUITEM, &TY_(W3CAttrsFor_MENUITEM)[0], (CM_INLINE|CM_BLOCK|CM_MIXED), TY_(ParseInline), NULL },
{ TidyTag_METER, "meter", VERS_ELEM_METER, &TY_(W3CAttrsFor_METER)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_NAV, "nav", VERS_ELEM_NAV, &TY_(W3CAttrsFor_NAV)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_OUTPUT, "output", VERS_ELEM_OUTPUT, &TY_(W3CAttrsFor_OUTPUT)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_PROGRESS, "progress", VERS_ELEM_PROGRESS, &TY_(W3CAttrsFor_PROGRESS)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_SECTION, "section", VERS_ELEM_SECTION, &TY_(W3CAttrsFor_SECTION)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_SLOT, "slot", VERS_ELEM_SLOT, &TY_(W3CAttrsFor_SLOT)[0], (CM_BLOCK|CM_INLINE|CM_MIXED), TY_(ParseBlock), NULL },
{ TidyTag_SOURCE, "source", VERS_ELEM_SOURCE, &TY_(W3CAttrsFor_SOURCE)[0], (CM_BLOCK|CM_INLINE|CM_EMPTY|CM_VOID), TY_(ParseBlock), NULL },
{ TidyTag_SUMMARY, "summary", VERS_ELEM_SUMMARY, &TY_(W3CAttrsFor_SUMMARY)[0], (CM_BLOCK), TY_(ParseBlock), NULL }, /* Is. #895 */
{ TidyTag_TEMPLATE, "template", VERS_ELEM_TEMPLATE, &TY_(W3CAttrsFor_TEMPLATE)[0], (CM_BLOCK|CM_HEAD), TY_(ParseBlock), NULL },
{ TidyTag_TIME, "time", VERS_ELEM_TIME, &TY_(W3CAttrsFor_TIME)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_TRACK, "track", VERS_ELEM_TRACK, &TY_(W3CAttrsFor_TRACK)[0], (CM_BLOCK|CM_EMPTY|CM_VOID), TY_(ParseBlock), NULL },
{ TidyTag_VIDEO, "video", VERS_ELEM_VIDEO, &TY_(W3CAttrsFor_VIDEO)[0], (CM_BLOCK|CM_INLINE), TY_(ParseBlock), NULL },
{ TidyTag_WBR, "wbr", VERS_ELEM_WBR, &TY_(W3CAttrsFor_WBR)[0], (CM_INLINE|CM_EMPTY|CM_VOID), TY_(ParseEmpty), NULL },
/* this must be the final entry */
{ (TidyTagId)0, NULL, 0, NULL, (0), NULL, NULL }
};
static uint tagsHash(ctmbstr s)
{
uint hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31*hashval;
return hashval % ELEMENT_HASH_SIZE;
}
static const Dict *tagsInstall(TidyDocImpl* doc, TidyTagImpl* tags, const Dict* old)
{
DictHash *np;
uint hashval;
if (old)
{
np = (DictHash *)TidyDocAlloc(doc, sizeof(*np));
np->tag = old;
hashval = tagsHash(old->name);
np->next = tags->hashtab[hashval];
tags->hashtab[hashval] = np;
}
return old;
}
static void tagsRemoveFromHash( TidyDocImpl* doc, TidyTagImpl* tags, ctmbstr s )
{
uint h = tagsHash(s);
DictHash *p, *prev = NULL;
for (p = tags->hashtab[h]; p && p->tag; p = p->next)
{
if (TY_(tmbstrcmp)(s, p->tag->name) == 0)
{
DictHash* next = p->next;
if ( prev )
prev->next = next;
else
tags->hashtab[h] = next;
TidyDocFree(doc, p);
return;
}
prev = p;
}
}
static void tagsEmptyHash( TidyDocImpl* doc, TidyTagImpl* tags )
{
uint i;
DictHash *prev, *next;
for (i = 0; i < ELEMENT_HASH_SIZE; ++i)
{
prev = NULL;
next = tags->hashtab[i];
while(next)
{
prev = next->next;
TidyDocFree(doc, next);
next = prev;
}
tags->hashtab[i] = NULL;
}
}
static const Dict* tagsLookup( TidyDocImpl* doc, TidyTagImpl* tags, ctmbstr s )
{
const Dict *np;
const DictHash* p;
if (!s)
return NULL;
/* this breaks if declared elements get changed between two */
/* parser runs since Tidy would use the cached version rather */
/* than the new one. */
/* However, as FreeDeclaredTags() correctly cleans the hash */
/* this should not be true anymore. */
for (p = tags->hashtab[tagsHash(s)]; p && p->tag; p = p->next)
if (TY_(tmbstrcmp)(s, p->tag->name) == 0)
return p->tag;
for (np = tag_defs + 1; np < tag_defs + N_TIDY_TAGS; ++np)
if (TY_(tmbstrcmp)(s, np->name) == 0)
return tagsInstall(doc, tags, np);
for (np = tags->declared_tag_list; np; np = np->next)
if (TY_(tmbstrcmp)(s, np->name) == 0)
return tagsInstall(doc, tags, np);
return NULL;
}
static Dict* NewDict( TidyDocImpl* doc, ctmbstr name )
{
Dict *np = (Dict*) TidyDocAlloc( doc, sizeof(Dict) );
np->id = TidyTag_UNKNOWN;
np->name = name ? TY_(tmbstrdup)( doc->allocator, name ) : NULL;
np->versions = VERS_UNKNOWN;
np->attrvers = NULL;
np->model = CM_UNKNOWN;
np->parser = 0;
np->chkattrs = 0;
np->next = NULL;
return np;
}
static void FreeDict( TidyDocImpl* doc, Dict *d )
{
if ( d )
TidyDocFree( doc, d->name );
TidyDocFree( doc, d );
}
static void declare( TidyDocImpl* doc, TidyTagImpl* tags,
ctmbstr name, uint versions, uint model,
Parser *parser, CheckAttribs *chkattrs )
{
if ( name )
{
Dict* np = (Dict*) tagsLookup( doc, tags, name );
if ( np == NULL )
{
np = NewDict( doc, name );
np->next = tags->declared_tag_list;
tags->declared_tag_list = np;
}
/* Make sure we are not over-writing predefined tags */
if ( np->id == TidyTag_UNKNOWN )
{
np->versions = versions;
np->model |= model;
np->parser = parser;
np->chkattrs = chkattrs;
np->attrvers = NULL;
}
}
}
/* Coordinates Config update and Tags data */
void TY_(DeclareUserTag)( TidyDocImpl* doc, const TidyOptionImpl* opt, ctmbstr name )
{
UserTagType tagType;
switch ( opt->id )
{
case TidyInlineTags: tagType = tagtype_inline; break;
case TidyBlockTags: tagType = tagtype_block; break;
case TidyEmptyTags: tagType = tagtype_empty; break;
case TidyPreTags: tagType = tagtype_pre; break;
case TidyCustomTags:
{
switch (cfg( doc, TidyUseCustomTags ))
{
case TidyCustomBlocklevel: tagType = tagtype_block; break;
case TidyCustomEmpty: tagType = tagtype_empty; break;
case TidyCustomInline: tagType = tagtype_inline; break;
case TidyCustomPre: tagType = tagtype_pre; break;
default: TY_(ReportUnknownOption)( doc, opt->name ); return;
}
} break;
default:
TY_(ReportUnknownOption)( doc, opt->name );
return;
}
TY_(DefineTag)( doc, tagType, name );
}
#if defined(ENABLE_DEBUG_LOG)
void ListElementsPerVersion( uint vers, Bool has )
{
uint val, cnt, total, wrap = 10;
const Dict *np = tag_defs + 1;
const Dict *end = tag_defs + N_TIDY_TAGS;
cnt = 0;
total = 0;
for ( ; np < end; np++) {
val = (np->versions & vers);
if (has) {
if (val) {
SPRTF("%s ",np->name);
cnt++;
total++;
}
} else {
if (!val) {
SPRTF("%s ",np->name);
cnt++;
total++;
}
}
if (cnt == wrap) {
SPRTF("\n");
cnt = 0;
}
}
if (cnt)
SPRTF("\n");
SPRTF("Listed total %u tags that %s version %u\n", total,
(has ? "have" : "do not have"),
vers );
}
void show_not_html5(void)
{
SPRTF("List tags that do not have version HTML5 (HT50|XH50)\n"),
ListElementsPerVersion( VERS_HTML5, no );
}
void show_have_html5(void)
{
ListElementsPerVersion( VERS_HTML5, yes );
}
#endif /* defined(ENABLE_DEBUG_LOG) */
/* public interface for finding tag by name */
Bool TY_(FindTag)( TidyDocImpl* doc, Node *node )
{
const Dict *np = NULL;
if ( cfgBool(doc, TidyXmlTags) )
{
node->tag = doc->tags.xml_tags;
return yes;
}
if ( node->element && (np = tagsLookup(doc, &doc->tags, node->element)) )
{
node->tag = np;
return yes;
}
/* Add autonomous custom tag. This can be done in both HTML5 mode and
earlier, although if it's earlier we will complain about it elsewhere. */
if ( TY_(nodeIsAutonomousCustomTag)( doc, node) )
{
const TidyOptionImpl* opt = TY_(getOption)( TidyCustomTags );
TY_(DeclareUserTag)( doc, opt, node->element );
node->tag = tagsLookup(doc, &doc->tags, node->element);
/* Output a message the first time we encounter an autonomous custom
tag. This applies despite the HTML5 mode. */
TY_(Report)(doc, node, node, CUSTOM_TAG_DETECTED);
return yes;
}
return no;
}
const Dict* TY_(LookupTagDef)( TidyTagId tid )
{
const Dict *np;
for (np = tag_defs + 1; np < tag_defs + N_TIDY_TAGS; ++np )
if (np->id == tid)
return np;
return NULL;
}
Parser* TY_(FindParser)( TidyDocImpl* doc, Node *node )
{
const Dict* np = tagsLookup( doc, &doc->tags, node->element );
if ( np )
return np->parser;
return NULL;
}
void TY_(DefineTag)( TidyDocImpl* doc, UserTagType tagType, ctmbstr name )
{
Parser* parser = 0;
uint cm = CM_UNKNOWN;
uint vers = VERS_PROPRIETARY;
switch (tagType)
{
case tagtype_empty:
cm = CM_EMPTY|CM_NO_INDENT|CM_NEW;
parser = TY_(ParseBlock);
break;
case tagtype_inline:
cm = CM_INLINE|CM_NO_INDENT|CM_NEW;
parser = TY_(ParseInline);
break;
case tagtype_block:
cm = CM_BLOCK|CM_NO_INDENT|CM_NEW;
parser = TY_(ParseBlock);
break;
case tagtype_pre:
cm = CM_BLOCK|CM_NO_INDENT|CM_NEW;
parser = TY_(ParsePre);
break;
case tagtype_null:
break;
}
if ( cm && parser )
declare( doc, &doc->tags, name, vers, cm, parser, 0 );
}
TidyIterator TY_(GetDeclaredTagList)( TidyDocImpl* doc )
{
return (TidyIterator) doc->tags.declared_tag_list;
}
ctmbstr TY_(GetNextDeclaredTag)( TidyDocImpl* ARG_UNUSED(doc),
UserTagType tagType, TidyIterator* iter )
{
ctmbstr name = NULL;
Dict* curr;
for ( curr = (Dict*) *iter; name == NULL && curr != NULL; curr = curr->next )
{
switch ( tagType )
{
case tagtype_empty:
if ( (curr->model & CM_EMPTY) != 0 )
name = curr->name;
break;
case tagtype_inline:
if ( (curr->model & CM_INLINE) != 0 )
name = curr->name;
break;
case tagtype_block:
if ( (curr->model & CM_BLOCK) != 0 &&
curr->parser == TY_(ParseBlock) )
name = curr->name;
break;
case tagtype_pre:
if ( (curr->model & CM_BLOCK) != 0 &&
curr->parser == TY_(ParsePre) )
name = curr->name;
break;
case tagtype_null:
break;
}
}
*iter = (TidyIterator) curr;
return name;
}
void TY_(InitTags)( TidyDocImpl* doc )
{
Dict* xml;
TidyTagImpl* tags = &doc->tags;
TidyClearMemory( tags, sizeof(TidyTagImpl) );
/* create dummy entry for all xml tags */
xml = NewDict( doc, NULL );
xml->versions = VERS_XML;
xml->model = CM_BLOCK;
xml->parser = 0;
xml->chkattrs = 0;
xml->attrvers = NULL;
tags->xml_tags = xml;
}
/* By default, zap all of them. But allow
** an single type to be specified.
*/
void TY_(FreeDeclaredTags)( TidyDocImpl* doc, UserTagType tagType )
{
TidyTagImpl* tags = &doc->tags;
Dict *curr, *next = NULL, *prev = NULL;
for ( curr=tags->declared_tag_list; curr; curr = next )
{
Bool deleteIt = yes;
next = curr->next;
switch ( tagType )
{
case tagtype_empty:
deleteIt = ( curr->model & CM_EMPTY ) != 0;
break;
case tagtype_inline:
deleteIt = ( curr->model & CM_INLINE ) != 0;
break;
case tagtype_block:
deleteIt = ( (curr->model & CM_BLOCK) != 0 &&
curr->parser == TY_(ParseBlock) );
break;
case tagtype_pre:
deleteIt = ( (curr->model & CM_BLOCK) != 0 &&
curr->parser == TY_(ParsePre) );
break;
case tagtype_null:
break;
}
if ( deleteIt )
{
tagsRemoveFromHash( doc, &doc->tags, curr->name );
FreeDict( doc, curr );
if ( prev )
prev->next = next;
else
tags->declared_tag_list = next;
}
else
prev = curr;
}
}
/*\
* Issue #167 & #169
* Tidy defaults to HTML5 mode
* If the <!DOCTYPE ...> is found to NOT be HTML5,
* then adjust tags to HTML4 mode
*
* NOTE: For each change added to here, there must
* be a RESET added in TY_(ResetTags) below!
\*/
void TY_(AdjustTags)( TidyDocImpl *doc )
{
Dict *np = (Dict *)TY_(LookupTagDef)( TidyTag_A );
TidyTagImpl* tags = &doc->tags;
if (np)
{
np->parser = TY_(ParseInline);
np->model = CM_INLINE;
}
/*\
* Issue #196
* TidyTag_CAPTION allows %flow; in HTML5,
* but only %inline; in HTML4
\*/
np = (Dict *)TY_(LookupTagDef)( TidyTag_CAPTION );
if (np)
{
np->parser = TY_(ParseInline);
}
/*\
* Issue #232
* TidyTag_OBJECT not in head in HTML5,
* but still allowed in HTML4
\*/
np = (Dict *)TY_(LookupTagDef)( TidyTag_OBJECT );
if (np)
{
np->model |= CM_HEAD; /* add back allowed in head */
}
/*\
* Issue #461
* TidyTag_BUTTON is a block in HTML4,
* whereas it is inline in HTML5
\*/
np = (Dict *)TY_(LookupTagDef)(TidyTag_BUTTON);
if (np)
{
np->parser = TY_(ParseBlock);
}
tagsEmptyHash(doc, tags); /* not sure this is really required, but to be sure */
doc->HTML5Mode = no; /* set *NOT* HTML5 mode */
}
Bool TY_(IsHTML5Mode)( TidyDocImpl *doc )
{
return doc->HTML5Mode;
}
/*\
* Issue #285
* Reset the table to default HTML5 mode.
* For every change made in the above AdjustTags,
* the equivalent reset must be added here.
\*/
void TY_(ResetTags)( TidyDocImpl *doc )
{
Dict *np = (Dict *)TY_(LookupTagDef)( TidyTag_A );
TidyTagImpl* tags = &doc->tags;
if (np)
{
np->parser = TY_(ParseBlock);
np->model = (CM_INLINE|CM_BLOCK|CM_MIXED);
}
np = (Dict *)TY_(LookupTagDef)( TidyTag_CAPTION );
if (np)
{
np->parser = TY_(ParseBlock);
}
np = (Dict *)TY_(LookupTagDef)( TidyTag_OBJECT );
if (np)
{
np->model = (CM_OBJECT|CM_IMG|CM_INLINE|CM_PARAM); /* reset */
}
/*\
* Issue #461
* TidyTag_BUTTON reset to inline in HTML5
\*/
np = (Dict *)TY_(LookupTagDef)(TidyTag_BUTTON);
if (np)
{
np->parser = TY_(ParseInline);
}
tagsEmptyHash( doc, tags ); /* not sure this is really required, but to be sure */
doc->HTML5Mode = yes; /* set HTML5 mode */
}
void TY_(FreeTags)( TidyDocImpl* doc )
{
TidyTagImpl* tags = &doc->tags;
tagsEmptyHash( doc, tags );
TY_(FreeDeclaredTags)( doc, tagtype_null );
FreeDict( doc, tags->xml_tags );
/* get rid of dangling tag references */
TidyClearMemory( tags, sizeof(TidyTagImpl) );
}
/* default method for checking an element's attributes */
void TY_(CheckAttributes)( TidyDocImpl* doc, Node *node )
{
AttVal *next, *attval = node->attributes;
while (attval)
{
next = attval->next;
TY_(CheckAttribute)( doc, node, attval );
attval = next;
}
}
/* methods for checking attributes for specific elements */
void CheckIMG( TidyDocImpl* doc, Node *node )
{
Bool HasAlt = TY_(AttrGetById)(node, TidyAttr_ALT) != NULL;
Bool HasSrc = TY_(AttrGetById)(node, TidyAttr_SRC) != NULL;
Bool HasUseMap = TY_(AttrGetById)(node, TidyAttr_USEMAP) != NULL;
Bool HasIsMap = TY_(AttrGetById)(node, TidyAttr_ISMAP) != NULL;
Bool HasDataFld = TY_(AttrGetById)(node, TidyAttr_DATAFLD) != NULL;
TY_(CheckAttributes)(doc, node);
if ( !HasAlt )
{
ctmbstr alttext = cfgStr(doc, TidyAltText);
if ( ( cfg(doc, TidyAccessibilityCheckLevel) == 0 ) && ( !alttext ) )
{
doc->badAccess |= BA_MISSING_IMAGE_ALT;
TY_(ReportMissingAttr)( doc, node, "alt" );
}
if ( alttext ) {
AttVal *attval = TY_(AddAttribute)( doc, node, "alt", alttext );
TY_(ReportAttrError)( doc, node, attval, INSERTING_AUTO_ATTRIBUTE);
}
}
if ( !HasSrc && !HasDataFld )
TY_(ReportMissingAttr)( doc, node, "src" );
if ( cfg(doc, TidyAccessibilityCheckLevel) == 0 )
{
if ( HasIsMap && !HasUseMap )
{
TY_(ReportAttrError)( doc, node, NULL, MISSING_IMAGEMAP);
doc->badAccess |= BA_MISSING_IMAGE_MAP;
}
}
}
void CheckCaption(TidyDocImpl* doc, Node *node)
{
AttVal *attval;
TY_(CheckAttributes)(doc, node);
attval = TY_(AttrGetById)(node, TidyAttr_ALIGN);
if (!AttrHasValue(attval))
return;
if (AttrValueIs(attval, "left") || AttrValueIs(attval, "right"))
TY_(ConstrainVersion)(doc, VERS_HTML40_LOOSE);
else if (AttrValueIs(attval, "top") || AttrValueIs(attval, "bottom"))
TY_(ConstrainVersion)(doc, ~(VERS_HTML20|VERS_HTML32));
else
TY_(ReportAttrError)(doc, node, attval, BAD_ATTRIBUTE_VALUE);
}
void CheckHTML( TidyDocImpl* doc, Node *node )
{
TY_(CheckAttributes)(doc, node);
}
void CheckAREA( TidyDocImpl* doc, Node *node )
{
Bool HasAlt = TY_(AttrGetById)(node, TidyAttr_ALT) != NULL;
Bool HasHref = TY_(AttrGetById)(node, TidyAttr_HREF) != NULL;
Bool HasNohref = TY_(AttrGetById)(node, TidyAttr_NOHREF) != NULL;
TY_(CheckAttributes)(doc, node);
if ( !HasAlt )
{
if ( cfg(doc, TidyAccessibilityCheckLevel) == 0 )
{
doc->badAccess |= BA_MISSING_LINK_ALT;
TY_(ReportMissingAttr)( doc, node, "alt" );
}
}
if ( !HasHref && !HasNohref )
TY_(ReportMissingAttr)( doc, node, "href" );
}
void CheckTABLE( TidyDocImpl* doc, Node *node )
{
AttVal* attval;
Bool HasSummary = (TY_(AttrGetById)(node, TidyAttr_SUMMARY) != NULL) ? yes : no;
uint vers = TY_(HTMLVersion)(doc); /* Issue #377 - Also applies to XHTML5 */
Bool isHTML5 = ((vers == HT50)||(vers == XH50)) ? yes : no;
TY_(CheckAttributes)(doc, node);
/* Issue #210 - a missing summary attribute is bad accessibility, no matter
what HTML version is involved; a document without is valid
EXCEPT for HTML5, when to have a summary is wrong */
if (cfg(doc, TidyAccessibilityCheckLevel) == 0)
{
if (HasSummary && isHTML5)
{
/* #210 - has summary, and is HTML5, then report obsolete */
TY_(Report)(doc, node, node, BAD_SUMMARY_HTML5);
}
else if (!HasSummary && !isHTML5)
{
/* #210 - No summary, and NOT HTML5, then report as before */
doc->badAccess |= BA_MISSING_SUMMARY;
TY_(ReportMissingAttr)( doc, node, "summary");
}
}
/* convert <table border> to <table border="1"> */
if ( cfgBool(doc, TidyXmlOut) && (attval = TY_(AttrGetById)(node, TidyAttr_BORDER)) )
{
if (attval->value == NULL)
attval->value = TY_(tmbstrdup)(doc->allocator, "1");
}
}
/* report missing href attribute; report missing rel attribute */
void CheckLINK( TidyDocImpl* doc, Node *node )
{
Bool HasHref = TY_(AttrGetById)(node, TidyAttr_HREF) != NULL;
Bool HasRel = TY_(AttrGetById)(node, TidyAttr_REL) != NULL;
Bool HasItemprop = TY_(AttrGetById)(node, TidyAttr_ITEMPROP) != NULL;
if (!HasHref)
{
TY_(ReportMissingAttr)( doc, node, "href" );
}
if (!HasItemprop && !HasRel)
{
TY_(ReportMissingAttr)( doc, node, "rel" );
}
}
Bool TY_(nodeIsText)( Node* node )
{
return ( node && node->type == TextNode );
}
Bool TY_(nodeHasText)( TidyDocImpl* doc, Node* node )
{
if ( doc && node )
{
uint ix;
Lexer* lexer = doc->lexer;
for ( ix = node->start; ix < node->end; ++ix )
{
/* whitespace */
if ( !TY_(IsWhite)( lexer->lexbuf[ix] ) )
return yes;
}
}
return no;
}
Bool TY_(nodeIsElement)( Node* node )
{
return ( node &&
(node->type == StartTag || node->type == StartEndTag) );
}
Bool TY_(elementIsAutonomousCustomFormat)( ctmbstr element )
{
if ( element )
{
const char *ptr = strchr(element, '-');
/* Tag must contain hyphen not in first character. */
if ( ptr && (ptr - element > 0) )
{
return yes;
}
}
return no;
}
Bool TY_(nodeIsAutonomousCustomFormat)( Node* node )
{
if ( node->element )
return TY_(elementIsAutonomousCustomFormat)( node->element );
return no;
}
Bool TY_(nodeIsAutonomousCustomTag)( TidyDocImpl* doc, Node* node )
{
return TY_(nodeIsAutonomousCustomFormat)( node )
&& ( cfg( doc, TidyUseCustomTags ) != TidyCustomNo );
}
/* True if any of the bits requested are set.
*/
Bool TY_(nodeHasCM)( Node* node, uint contentModel )
{
return ( node && node->tag &&
(node->tag->model & contentModel) != 0 );
}
Bool TY_(nodeCMIsBlock)( Node* node )
{
return TY_(nodeHasCM)( node, CM_BLOCK );
}
Bool TY_(nodeCMIsInline)( Node* node )
{
return TY_(nodeHasCM)( node, CM_INLINE );
}
Bool TY_(nodeCMIsEmpty)( Node* node )
{
return TY_(nodeHasCM)( node, CM_EMPTY );
}
Bool TY_(nodeIsHeader)( Node* node )
{
TidyTagId tid = TagId( node );
return ( tid && (
tid == TidyTag_H1 ||
tid == TidyTag_H2 ||
tid == TidyTag_H3 ||
tid == TidyTag_H4 ||
tid == TidyTag_H5 ||
tid == TidyTag_H6 ));
}
uint TY_(nodeHeaderLevel)( Node* node )
{
TidyTagId tid = TagId( node );
switch ( tid )
{
case TidyTag_H1:
return 1;
case TidyTag_H2:
return 2;
case TidyTag_H3:
return 3;
case TidyTag_H4:
return 4;
case TidyTag_H5:
return 5;
case TidyTag_H6:
return 6;
default:
{
/* fall through */
}
}
return 0;
}
/* [i_a] generic node tree traversal; see also <tidy-int.h> */
NodeTraversalSignal TY_(TraverseNodeTree)(TidyDocImpl* doc, Node* node, NodeTraversalCallBack *cb, void *propagate )
{
while (node)
{
NodeTraversalSignal s = (*cb)(doc, node, propagate);
if (node->content && (s == ContinueTraversal || s == SkipSiblings))
{
s = TY_(TraverseNodeTree)(doc, node->content, cb, propagate);
}
switch (s)
{
case ExitTraversal:
return ExitTraversal;
case VisitParent:
node = node->parent;
continue;
case SkipSiblings:
case SkipChildrenAndSiblings:
return ContinueTraversal;
default:
node = node->next;
break;
}
}
return ContinueTraversal;
}
/*
* local variables:
* mode: c
* indent-tabs-mode: nil
* c-basic-offset: 4
* end:
*/
| 64,879 | 1,190 | jart/cosmopolitan | false |
cosmopolitan/third_party/tidy/tagask.c | /* clang-format off */
/* tagask.c -- Interrogate node type
(c) 1998-2006 (W3C) MIT, ERCIM, Keio University
See tidy.h for the copyright notice.
*/
#include "third_party/tidy/tidy-int.h"
#include "third_party/tidy/tags.h"
#include "third_party/tidy/tidy.h"
Bool tidyNodeIsText( TidyNode tnod )
{ return TY_(nodeIsText)( tidyNodeToImpl(tnod) );
}
Bool tidyNodeCMIsBlock( TidyNode tnod ); /* not exported yet */
Bool tidyNodeCMIsBlock( TidyNode tnod )
{ return TY_(nodeCMIsBlock)( tidyNodeToImpl(tnod) );
}
Bool tidyNodeCMIsInline( TidyNode tnod ); /* not exported yet */
Bool tidyNodeCMIsInline( TidyNode tnod )
{ return TY_(nodeCMIsInline)( tidyNodeToImpl(tnod) );
}
Bool tidyNodeCMIsEmpty( TidyNode tnod ); /* not exported yet */
Bool tidyNodeCMIsEmpty( TidyNode tnod )
{ return TY_(nodeCMIsEmpty)( tidyNodeToImpl(tnod) );
}
Bool tidyNodeIsHeader( TidyNode tnod )
{ return TY_(nodeIsHeader)( tidyNodeToImpl(tnod) );
}
/*
* local variables:
* mode: c
* indent-tabs-mode: nil
* c-basic-offset: 4
* end:
*/
| 1,021 | 40 | jart/cosmopolitan | false |
cosmopolitan/third_party/tidy/tidyplatform.h | #ifndef __TIDY_PLATFORM_H__
#define __TIDY_PLATFORM_H__
COSMOPOLITAN_C_START_
#define LINUX_OS
#define PLATFORM_NAME "Cosmopolitan"
#define TIDY_CONFIG_FILE "/zip/.tidyrc"
#define TIDY_USER_CONFIG_FILE "~/.tidyrc"
#define SUPPORT_LOCALIZATIONS 0
#define SUPPORT_CONSOLE_APP 1
#define FILENAMES_CASE_SENSITIVE 1
#define PRESERVE_FILE_TIMES 1
#define HAS_FUTIME 0
#define UTIME_NEEDS_CLOSED_FILE 1
#define HAS_VSNPRINTF 1
#define SUPPORT_POSIX_MAPPED_FILES 1
#define TIDY_EXPORT
#define TIDY_STRUCT
#define TIDY_THREAD_LOCAL
#define TIDY_INDENTATION_LIMIT 50
#define TIDY_CALL
/* #define SUPPORT_GETPWNAM */
#if defined(__GNUC__) || defined(__INTEL_COMPILER)
#define ARG_UNUSED(x) x __attribute__((__unused__))
#define FUNC_UNUSED __attribute__((__unused__))
#else
#define ARG_UNUSED(x) x
#define FUNC_UNUSED
#endif
typedef unsigned int uint;
typedef unsigned long ulong;
typedef unsigned char byte;
typedef uint tchar; /* single, full character */
typedef char tmbchar; /* single, possibly partial character */
typedef enum { no, yes } Bool;
typedef tmbchar* tmbstr; /* pointer to buffer of possibly partial chars */
typedef const tmbchar* ctmbstr; /* Ditto, but const */
#define NULLSTR (tmbstr) ""
#define TMBSTR_DEFINED
/* Opaque data structure.
* Cast to implementation type struct within lib.
* This will reduce inter-dependencies/conflicts w/ application code.
*/
#if 1
#define opaque_type(typenam) \
struct _##typenam { \
int _opaque; \
}; \
typedef struct _##typenam const* typenam
#else
#define opaque_type(typenam) typedef const void* typenam
#endif
/* Opaque data structure used to pass back
** and forth to keep current position in a
** list or other collection.
*/
opaque_type(TidyIterator);
COSMOPOLITAN_C_END_
#endif /* __TIDY_PLATFORM_H__ */
| 1,907 | 66 | jart/cosmopolitan | false |
cosmopolitan/third_party/tidy/tidybuffio.h | #ifndef __TIDY_BUFFIO_H__
#define __TIDY_BUFFIO_H__
/* clang-format off */
/**************************************************************************//**
* @file
* Treat buffer as a stream that Tidy can use for I/O operations. It offers
* the ability for the buffer to grow as bytes are added, and keeps track
* of current read and write points.
*
* @author
* HTACG, et al (consult git log)
*
* @copyright
* Copyright (c) 1998-2017 World Wide Web Consortium (Massachusetts
* Institute of Technology, European Research Consortium for Informatics
* and Mathematics, Keio University).
* @copyright
* See tidy.h for license.
*
* @date
* Consult git log.
******************************************************************************/
#include "third_party/tidy/tidyplatform.h"
#include "third_party/tidy/tidy.h"
#ifdef __cplusplus
extern "C" {
#endif
/** A TidyBuffer is chunk of memory that can be used for multiple I/O purposes
** within Tidy.
** @ingroup IO
*/
TIDY_STRUCT
struct _TidyBuffer
{
TidyAllocator* allocator; /**< Memory allocator */
byte* bp; /**< Pointer to bytes */
uint size; /**< Number of bytes currently in use */
uint allocated; /**< Number of bytes allocated */
uint next; /**< Offset of current input position */
};
/** Initialize data structure using the default allocator */
void tidyBufInit( TidyBuffer* buf );
/** Initialize data structure using the given custom allocator */
void tidyBufInitWithAllocator( TidyBuffer* buf, TidyAllocator* allocator );
/** Free current buffer, allocate given amount, reset input pointer,
use the default allocator */
void tidyBufAlloc( TidyBuffer* buf, uint allocSize );
/** Free current buffer, allocate given amount, reset input pointer,
use the given custom allocator */
void tidyBufAllocWithAllocator( TidyBuffer* buf,
TidyAllocator* allocator,
uint allocSize );
/** Expand buffer to given size.
** Chunk size is minimum growth. Pass 0 for default of 256 bytes.
*/
void tidyBufCheckAlloc( TidyBuffer* buf,
uint allocSize, uint chunkSize );
/** Free current contents and zero out */
void tidyBufFree( TidyBuffer* buf );
/** Set buffer bytes to 0 */
void tidyBufClear( TidyBuffer* buf );
/** Attach to existing buffer */
void tidyBufAttach( TidyBuffer* buf, byte* bp, uint size );
/** Detach from buffer. Caller must free. */
void tidyBufDetach( TidyBuffer* buf );
/** Append bytes to buffer. Expand if necessary. */
void tidyBufAppend( TidyBuffer* buf, void* vp, uint size );
/** Append one byte to buffer. Expand if necessary. */
void tidyBufPutByte( TidyBuffer* buf, byte bv );
/** Get byte from end of buffer */
int tidyBufPopByte( TidyBuffer* buf );
/** Get byte from front of buffer. Increment input offset. */
int tidyBufGetByte( TidyBuffer* buf );
/** At end of buffer? */
Bool tidyBufEndOfInput( TidyBuffer* buf );
/** Put a byte back into the buffer. Decrement input offset. */
void tidyBufUngetByte( TidyBuffer* buf, byte bv );
/**************
TIDY
**************/
/* Forward declarations
*/
/** Initialize a buffer input source */
void tidyInitInputBuffer( TidyInputSource* inp, TidyBuffer* buf );
/** Initialize a buffer output sink */
void tidyInitOutputBuffer( TidyOutputSink* outp, TidyBuffer* buf );
#ifdef __cplusplus
}
#endif
#endif /* __TIDY_BUFFIO_H__ */
/*
* local variables:
* mode: c
* indent-tabs-mode: nil
* c-basic-offset: 4
* end:
*/
| 3,655 | 126 | jart/cosmopolitan | false |
cosmopolitan/third_party/tidy/config.h | #ifndef __CONFIG_H__
#define __CONFIG_H__
/* clang-format off */
/**************************************************************************//**
* @file
* Read configuration files and manage configuration properties.
*
* Config files associate a property name with a value.
*
* // comments can start at the beginning of a line
* # comments can start at the beginning of a line
* name: short values fit onto one line
* name: a really long value that
* continues on the next line
*
* Property names are case insensitive and should be less than 60 characters
* in length, and must start at the beginning of the line, as whitespace at
* the start of a line signifies a line continuation.
*
* @author HTACG, et al (consult git log)
*
* @copyright
* Copyright (c) 1998-2017 World Wide Web Consortium (Massachusetts
* Institute of Technology, European Research Consortium for Informatics
* and Mathematics, Keio University) and HTACG.
* @par
* All Rights Reserved.
* @par
* See `tidy.h` for the complete license.
*
* @date Additional updates: consult git log
*
******************************************************************************/
#include "third_party/tidy/forward.h"
#include "third_party/tidy/tidy.h"
#include "third_party/tidy/streamio.h"
/** @addtogroup internal_api */
/** @{ */
/***************************************************************************//**
** @defgroup configuration_options Configuration Options
**
** This module organizes all of Tidy's configuration options, including
** picklist management, option setting and retrieval, option file utilities,
** and so on.
**
** @{
******************************************************************************/
/** Determines the maximum number of items in an option's picklist. PickLists
** may have up to 16 items. For some reason, this limit has been hard-coded
** into Tidy for some time. Feel free to increase this as needed.
*/
#define TIDY_PL_SIZE 16
/** Structs of this type contain information needed in order to present
** picklists, relate picklist entries to public enum values, and parse
** strings that are accepted in order to assign the value.
*/
typedef struct PickListItem {
ctmbstr label; /**< PickList label for this item. */
const int value; /**< The option value represented by this label. */
ctmbstr inputs[10]; /**< String values that can select this value. */
} PickListItem;
/** An array of PickListItems, fixed in size for in-code declarations.
** Arrays must be populated in 0 to 10 order, as the option value is assigned
** based on this index and *not* on the structures' value field. It remains
** a best practice, however, to assign a public enum value with the proper
** index value.
*/
typedef const PickListItem PickListItems[TIDY_PL_SIZE];
struct _tidy_option; /* forward */
/** The TidyOptionImpl type implements the `_tidy_option` structure.
*/
typedef struct _tidy_option TidyOptionImpl;
/** This typedef describes a function that is used for parsing the input
** given for a particular Tidy option.
*/
typedef Bool (ParseProperty)( TidyDocImpl* doc, const TidyOptionImpl* opt );
/** This structure defines the internal representation of a Tidy option.
*/
struct _tidy_option
{
TidyOptionId id; /**< The unique identifier for this option. */
TidyConfigCategory category; /**< The category of the option. */
ctmbstr name; /**< The name of the option. */
TidyOptionType type; /**< The date type for the option. */
ulong dflt; /**< Default value for TidyInteger and TidyBoolean */
ParseProperty* parser; /**< Function to parse input; read-only if NULL. */
PickListItems* pickList; /**< The picklist of possible values for this option. */
ctmbstr pdflt; /**< Default value for TidyString. */
};
/** Stored option values can be one of two internal types.
*/
typedef union
{
ulong v; /**< Value for TidyInteger and TidyBoolean */
char *p; /**< Value for TidyString */
} TidyOptionValue;
/** This type is used to define a structure for keeping track of the values
** for each option.
*/
typedef struct _tidy_config
{
TidyOptionValue value[ N_TIDY_OPTIONS + 1 ]; /**< Current config values. */
TidyOptionValue snapshot[ N_TIDY_OPTIONS + 1 ]; /**< Snapshot of values to be restored later. */
uint defined_tags; /**< Tracks user-defined tags. */
uint c; /**< Current char in input stream for reading options. */
StreamIn* cfgIn; /**< Current input source for reading options.*/
} TidyConfigImpl;
/** Used to build a table of documentation cross-references.
*/
typedef struct {
TidyOptionId opt; /**< Identifier. */
TidyOptionId const *links; /**< Cross references. Last element must be 'TidyUnknownOption'. */
} TidyOptionDoc;
/** Given an option name, return an instance of an option.
** @param optnam The option name to retrieve.
** @returns The instance of the requested option.
*/
const TidyOptionImpl* TY_(lookupOption)( ctmbstr optnam );
/** Given an option ID, return an instance of an option.
** @param optId The option ID to retrieve.
** @returns The instance of the requested option.
*/
const TidyOptionImpl* TY_(getOption)( TidyOptionId optId );
/** Given an option ID, indicates whether or not the option is a list.
** @param optId The option ID to check.
** @returns Returns yes if the option value is a list.
*/
const Bool TY_(getOptionIsList)( TidyOptionId optId );
/** Initiates an iterator to cycle through all of the available options.
** @param doc The Tidy document to get options.
** @returns An iterator token to be used with TY_(getNextOption)().
*/
TidyIterator TY_(getOptionList)( TidyDocImpl* doc );
/** Gets the next option provided by the iterator.
** @param doc The Tidy document to get options.
** @param iter The iterator token initialized by TY_(getOptionList)().
** @returns The instance of the next option.
*/
const TidyOptionImpl* TY_(getNextOption)( TidyDocImpl* doc, TidyIterator* iter );
/** Initiates an iterator to cycle through all of the available picklist
** possibilities.
** @param option An instance of an option for which to iterate a picklist.
** @returns An iterator token to be used with TY_(getNextOptionPick)().
*/
TidyIterator TY_(getOptionPickList)( const TidyOptionImpl* option );
/** Gets the next picklist possibility provided by the iterator.
** @param option The instance of the option for which to iterate a picklist.
** @param iter The iterator token initialized by TY_(getOptionPickList)().
** @returns The next picklist entry.
*/
ctmbstr TY_(getNextOptionPick)( const TidyOptionImpl* option, TidyIterator* iter );
#if SUPPORT_CONSOLE_APP
/** Returns the cross-reference information structure for optID, which is
** used for generating documentation.
** @param optId The option ID to get cross-reference information for.
** @returns Cross reference information.
*/
const TidyOptionDoc* TY_(OptGetDocDesc)( TidyOptionId optId );
#endif /* SUPPORT_CONSOLE_APP */
/** Initialize the configuration for the given Tidy document.
** @param doc The Tidy document.
*/
void TY_(InitConfig)( TidyDocImpl* doc );
/** Frees the configuration memory for the given Tidy document.
** @param doc The Tidy document.
*/
void TY_(FreeConfig)( TidyDocImpl* doc );
/** Gets the picklist label for a given value.
** @param optId the option id having a picklist to check.
** @param pick the picklist item to retrieve.
** @returns The label for the pick.
*/
ctmbstr TY_(GetPickListLabelForPick)( TidyOptionId optId, uint pick );
/** Sets the integer value for the given option Id.
** @param doc The Tidy document.
** @param optId The option ID to set.
** @param val The value to set.
** @returns Success or failure.
*/
Bool TY_(SetOptionInt)( TidyDocImpl* doc, TidyOptionId optId, ulong val );
/** Sets the bool value for the given option Id.
** @param doc The Tidy document.
** @param optId The option ID to set.
** @param val The value to set.
** @returns Success or failure.
*/
Bool TY_(SetOptionBool)( TidyDocImpl* doc, TidyOptionId optId, Bool val );
/** Resets the given option to its default value.
** @param doc The Tidy document.
** @param optId The option ID to set.
** @returns Success or failure.
*/
Bool TY_(ResetOptionToDefault)( TidyDocImpl* doc, TidyOptionId optId );
/** Resets all options in the document to their default values.
** @param doc The Tidy document.
*/
void TY_(ResetConfigToDefault)( TidyDocImpl* doc );
/** Stores a snapshot of all of the configuration values that can be
** restored later.
** @param doc The Tidy document.
*/
void TY_(TakeConfigSnapshot)( TidyDocImpl* doc );
/** Restores all of the configuration values to their snapshotted values.
** @param doc The Tidy document.
*/
void TY_(ResetConfigToSnapshot)( TidyDocImpl* doc );
/** Copies the configuration from one document to another.
** @param docTo The destination Tidy document.
** @param docFrom The source Tidy document.
*/
void TY_(CopyConfig)( TidyDocImpl* docTo, TidyDocImpl* docFrom );
/** Attempts to parse the given config file into the document.
** @param doc The Tidy document.
** @param cfgfil The file to load.
** @returns a file system error code.
*/
int TY_(ParseConfigFile)( TidyDocImpl* doc, ctmbstr cfgfil );
/** Attempts to parse the given config file into the document, using
** the provided encoding.
** @param doc The Tidy document.
** @param cfgfil The file to load.
** @param charenc The name of the encoding to use for reading the file.
** @returns a file system error code.
*/
int TY_(ParseConfigFileEnc)( TidyDocImpl* doc,
ctmbstr cfgfil, ctmbstr charenc );
/** Saves the current configuration for options not having default values
** into the specified file.
** @param doc The Tidy document.
** @param cfgfil The file to save.
** @returns a file system error code.
*/
int TY_(SaveConfigFile)( TidyDocImpl* doc, ctmbstr cfgfil );
/** Writes the current configuration for options not having default values
** into the specified sink.
** @param doc The Tidy document.
** @param sink The sink to save into.
** @returns a file system error code.
*/
int TY_(SaveConfigSink)( TidyDocImpl* doc, TidyOutputSink* sink );
/** Attempts to parse the provided value for the given option name. Returns
** false if unknown option, missing parameter, or the option doesn't
** use the parameter.
** @param doc The Tidy document.
** @param optnam The name of the option to be set.
** @param optVal The string value to attempt to parse.
** @returns Success or failure.
*/
Bool TY_(ParseConfigOption)( TidyDocImpl* doc, ctmbstr optnam, ctmbstr optVal );
/** Attempts to parse the provided value for the given option id. Returns
** false if unknown option, missing parameter, or the option doesn't
** use the parameter.
** @param doc The Tidy document.
** @param optId The ID of the option to be set.
** @param optVal The string value to attempt to parse.
** @returns Success or failure.
*/
Bool TY_(ParseConfigValue)( TidyDocImpl* doc, TidyOptionId optId, ctmbstr optVal );
/** Ensure that char encodings are self consistent.
** @param doc The Tidy document to adjust.
** @param encoding The encoding being applied.
** @returns A bool indicating success or failure.
*/
Bool TY_(AdjustCharEncoding)( TidyDocImpl* doc, int encoding );
/** Ensure that the configuration options are self consistent.
** THIS PROCESS IS DESTRUCTIVE TO THE USER STATE. It examines
** certain user-specified options and changes other options
** as a result. This means that documented API functions such
** as tidyOptGetValue() won't return the user-set values after
** this is used. As a result, *don't* just use this function
** at every opportunity, but only where needed, which is ONLY
** prior to parsing a stream, and again prior to saving a
** stream (because we reset after parsing.)
** @param doc The Tidy document to adjust.
*/
void TY_(AdjustConfig)( TidyDocImpl* doc );
/** Indicates whether or not the current configuration is completely default.
** @param doc The Tidy document.
** @returns The result.
*/
Bool TY_(ConfigDiffThanDefault)( TidyDocImpl* doc );
/** Indicates whether or not the current configuration is different from the
** stored snapshot.
** @param doc The Tidy document.
** @returns The result.
*/
Bool TY_(ConfigDiffThanSnapshot)( TidyDocImpl* doc );
/** Returns the character encoding ID for the given character encoding
** string.
** @param doc The Tidy document.
** @param charenc The name of the character encoding.
** @returns The Id of the character encoding.
*/
int TY_(CharEncodingId)( TidyDocImpl* doc, ctmbstr charenc );
/** Returns the full name of the encoding for the given ID.
** @param encoding The Id of the encoding.
** @returns The name of the character encoding.
*/
ctmbstr TY_(CharEncodingName)( int encoding );
/** Returns the Tidy command line option name of the encoding for the given ID.
** @param encoding The Id of the encoding.
** @returns The Tidy command line option representing the encoding.
*/
ctmbstr TY_(CharEncodingOptName)( int encoding );
/** Coordinates Config update and list data.
** @param doc The Tidy document.
** @param opt The option the list item is intended for.
** @param name The name of the new list item.
*/
void TY_(DeclareListItem)( TidyDocImpl* doc, const TidyOptionImpl* opt, ctmbstr name );
#ifdef _DEBUG
/* Debug lookup functions will be type-safe and assert option type match */
ulong TY_(_cfgGet)( TidyDocImpl* doc, TidyOptionId optId );
Bool TY_(_cfgGetBool)( TidyDocImpl* doc, TidyOptionId optId );
TidyTriState TY_(_cfgGetAutoBool)( TidyDocImpl* doc, TidyOptionId optId );
ctmbstr TY_(_cfgGetString)( TidyDocImpl* doc, TidyOptionId optId );
#define cfg(doc, id) TY_(_cfgGet)( (doc), (id) )
#define cfgBool(doc, id) TY_(_cfgGetBool)( (doc), (id) )
#define cfgAutoBool(doc, id) TY_(_cfgGetAutoBool)( (doc), (id) )
#define cfgStr(doc, id) TY_(_cfgGetString)( (doc), (id) )
#else
/* Release build macros for speed */
/** Access the raw, non-string uint value of the given option ID. */
#define cfg(doc, id) ((doc)->config.value[ (id) ].v)
/** Access the Bool value of the given option ID. */
#define cfgBool(doc, id) ((Bool) cfg(doc, id))
/** Access the TidyTriState value of the given option ID. */
#define cfgAutoBool(doc, id) ((TidyTriState) cfg(doc, id))
/** Access the string value of the given option ID. */
#define cfgStr(doc, id) ((ctmbstr) (doc)->config.value[ (id) ].p)
#endif /* _DEBUG */
/** @} configuration_options group */
/** @} internal_api addtogroup */
#endif /* __CONFIG_H__ */
| 15,057 | 435 | jart/cosmopolitan | false |
cosmopolitan/third_party/tidy/parser.c | /* clang-format off */
/* parser.c -- HTML Parser
(c) 1998-2007 (W3C) MIT, ERCIM, Keio University
See tidy.h for the copyright notice.
*/
#include "third_party/tidy/tidy-int.h"
#include "third_party/tidy/lexer.h"
#include "third_party/tidy/parser.h"
#include "third_party/tidy/message.h"
#include "third_party/tidy/clean.h"
#include "third_party/tidy/tags.h"
#include "third_party/tidy/tmbstr.h"
#include "libc/assert.h"
#include "third_party/tidy/sprtf.h"
/****************************************************************************//*
** MARK: - Configuration Options
***************************************************************************/
/**
* Issue #72 - Need to know to avoid error-reporting - no warning only if
* --show-body-only yes.
* Issue #132 - Likewise avoid warning if showing body only.
*/
#define showingBodyOnly(doc) (cfgAutoBool(doc,TidyBodyOnly) == TidyYesState) ? yes : no
/****************************************************************************//*
** MARK: - Forward Declarations
***************************************************************************/
static Node* ParseXMLElement(TidyDocImpl* doc, Node *element, GetTokenMode mode);
/****************************************************************************//*
** MARK: - Node Operations
***************************************************************************/
/**
* Generalised search for duplicate elements.
* Issue #166 - repeated <main> element.
*/
static Bool findNodeWithId( Node *node, TidyTagId tid )
{
Node *content;
while (node)
{
if (TagIsId(node,tid))
return yes;
/*\
* Issue #459 - Under certain circumstances, with many node this use of
* 'for (content = node->content; content; content = content->content)'
* would produce a **forever** circle, or at least a very extended loop...
* It is sufficient to test the content, if it exists,
* to quickly iterate all nodes. Now all nodes are tested only once.
\*/
content = node->content;
if (content)
{
if ( findNodeWithId(content,tid) )
return yes;
}
node = node->next;
}
return no;
}
/**
* Perform a global search for an element.
* Issue #166 - repeated <main> element
*/
static Bool findNodeById( TidyDocImpl* doc, TidyTagId tid )
{
Node *node = (doc ? doc->root.content : NULL);
return findNodeWithId( node,tid );
}
/**
* Inserts node into element at an appropriate location based
* on the type of node being inserted.
*/
static Bool InsertMisc(Node *element, Node *node)
{
if (node->type == CommentTag ||
node->type == ProcInsTag ||
node->type == CDATATag ||
node->type == SectionTag ||
node->type == AspTag ||
node->type == JsteTag ||
node->type == PhpTag )
{
TY_(InsertNodeAtEnd)(element, node);
return yes;
}
if ( node->type == XmlDecl )
{
Node* root = element;
while ( root && root->parent )
root = root->parent;
if ( root && !(root->content && root->content->type == XmlDecl))
{
TY_(InsertNodeAtStart)( root, node );
return yes;
}
}
/* Declared empty tags seem to be slipping through
** the cracks. This is an experiment to figure out
** a decent place to pick them up.
*/
if ( node->tag &&
TY_(nodeIsElement)(node) &&
TY_(nodeCMIsEmpty)(node) && TagId(node) == TidyTag_UNKNOWN &&
(node->tag->versions & VERS_PROPRIETARY) != 0 )
{
TY_(InsertNodeAtEnd)(element, node);
return yes;
}
return no;
}
/**
* Insert "node" into markup tree in place of "element"
* which is moved to become the child of the node
*/
static void InsertNodeAsParent(Node *element, Node *node)
{
node->content = element;
node->last = element;
node->parent = element->parent;
element->parent = node;
if (node->parent->content == element)
node->parent->content = node;
if (node->parent->last == element)
node->parent->last = node;
node->prev = element->prev;
element->prev = NULL;
if (node->prev)
node->prev->next = node;
node->next = element->next;
element->next = NULL;
if (node->next)
node->next->prev = node;
}
/**
* Unexpected content in table row is moved to just before the table in
* in accordance with Netscape and IE. This code assumes that node hasn't
* been inserted into the row.
*/
static void MoveBeforeTable( TidyDocImpl* ARG_UNUSED(doc), Node *row,
Node *node )
{
Node *table;
/* first find the table element */
for (table = row->parent; table; table = table->parent)
{
if ( nodeIsTABLE(table) )
{
TY_(InsertNodeBeforeElement)( table, node );
return;
}
}
/* No table element */
TY_(InsertNodeBeforeElement)( row->parent, node );
}
/**
* Moves given node to end of body element.
*/
static void MoveNodeToBody( TidyDocImpl* doc, Node* node )
{
Node* body = TY_(FindBody)( doc );
if ( body )
{
TY_(RemoveNode)( node );
TY_(InsertNodeAtEnd)( body, node );
}
}
/**
* Move node to the head, where element is used as starting
* point in hunt for head. Normally called during parsing.
*/
static void MoveToHead( TidyDocImpl* doc, Node *element, Node *node )
{
Node *head = NULL;
TY_(RemoveNode)( node ); /* make sure that node is isolated */
if ( TY_(nodeIsElement)(node) )
{
TY_(Report)(doc, element, node, TAG_NOT_ALLOWED_IN );
head = TY_(FindHEAD)(doc);
assert(head != NULL);
TY_(InsertNodeAtEnd)(head, node);
if ( node->tag->parser )
{
/* Only one of the existing test cases as of 2021-08-14 invoke
MoveToHead, and it doesn't go deeper than one level. The
parser() call is supposed to return a node if additional
parsing is needed. Keep this in mind if we start to get bug
reports.
*/
Parser* parser = node->tag->parser;
parser( doc, node, IgnoreWhitespace );
}
}
else
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node );
}
}
/***************************************************************************//*
** MARK: - Decision Making
***************************************************************************/
/**
* Indicates whether or not element can be pruned based on content,
* user settings, etc.
*/
static Bool CanPrune( TidyDocImpl* doc, Node *element )
{
if ( !cfgBool(doc, TidyDropEmptyElems) )
return no;
if ( TY_(nodeIsText)(element) )
return yes;
if ( element->content )
return no;
if ( element->tag == NULL )
return no;
if ( element->tag->model & CM_BLOCK && element->attributes != NULL )
return no;
if ( nodeIsA(element) && element->attributes != NULL )
return no;
if ( nodeIsP(element) && !cfgBool(doc, TidyDropEmptyParas) )
return no;
if ( element->tag->model & CM_ROW )
return no;
if ( element->tag->model & CM_EMPTY )
return no;
if ( nodeIsAPPLET(element) )
return no;
if ( nodeIsOBJECT(element) )
return no;
if ( nodeIsSCRIPT(element) && attrGetSRC(element) )
return no;
if ( nodeIsTITLE(element) )
return no;
/* #433359 - fix by Randy Waki 12 Mar 01 */
if ( nodeIsIFRAME(element) )
return no;
/* fix for bug 770297 */
if (nodeIsTEXTAREA(element))
return no;
/* fix for ISSUE #7 https://github.com/w3c/tidy-html5/issues/7 */
if (nodeIsCANVAS(element))
return no;
if (nodeIsPROGRESS(element))
return no;
if ( attrGetID(element) || attrGetNAME(element) )
return no;
/* fix for bug 695408; a better fix would look for unknown and */
/* known proprietary attributes that make the element significant */
if (attrGetDATAFLD(element))
return no;
/* fix for bug 723772, don't trim new-...-tags */
if (element->tag->id == TidyTag_UNKNOWN)
return no;
if (nodeIsBODY(element))
return no;
if (nodeIsCOLGROUP(element))
return no;
/* HTML5 - do NOT drop empty option if it has attributes */
if ( nodeIsOPTION(element) && element->attributes != NULL )
return no;
/* fix for #103 - don't drop empty dd tags lest document not validate */
if (nodeIsDD(element))
return no;
return yes;
}
/**
* Indicates whether or not node is a descendant of a tag of the given tid.
*/
static Bool DescendantOf( Node *element, TidyTagId tid )
{
Node *parent;
for ( parent = element->parent;
parent != NULL;
parent = parent->parent )
{
if ( TagIsId(parent, tid) )
return yes;
}
return no;
}
/**
* Indicates whether or not node is a descendant of a pre tag.
*/
static Bool IsPreDescendant(Node* node)
{
Node *parent = node->parent;
while (parent)
{
if (parent->tag && parent->tag->parser == TY_(ParsePre))
return yes;
parent = parent->parent;
}
return no;
}
/**
* Indicates whether or not the only content model for the given node
* is CM_INLINE.
*/
static Bool nodeCMIsOnlyInline( Node* node )
{
return TY_(nodeHasCM)( node, CM_INLINE ) && !TY_(nodeHasCM)( node, CM_BLOCK );
}
/**
* Indicates whether or not the content of the given node is acceptable
* content for pre elements
*/
static Bool PreContent( TidyDocImpl* ARG_UNUSED(doc), Node* node )
{
/* p is coerced to br's, Text OK too */
if ( nodeIsP(node) || TY_(nodeIsText)(node) )
return yes;
if ( node->tag == NULL ||
nodeIsPARAM(node) ||
!TY_(nodeHasCM)(node, CM_INLINE|CM_NEW) )
return no;
return yes;
}
/**
* Indicates whether or not leading whitespace should be cleaned.
*/
static Bool CleanLeadingWhitespace(TidyDocImpl* ARG_UNUSED(doc), Node* node)
{
if (!TY_(nodeIsText)(node))
return no;
if (node->parent->type == DocTypeTag)
return no;
if (IsPreDescendant(node))
return no;
if (node->parent->tag && node->parent->tag->parser == TY_(ParseScript))
return no;
/* #523, prevent blank spaces after script if the next item is script.
* This is actually more generalized as, if the preceding element is
* a body level script, then indicate that we want to clean leading
* whitespace.
*/
if ( node->prev && nodeIsSCRIPT(node->prev) && nodeIsBODY(node->prev->parent) )
return yes;
/* <p>...<br> <em>...</em>...</p> */
if (nodeIsBR(node->prev))
return yes;
/* <p> ...</p> */
if (node->prev == NULL && !TY_(nodeHasCM)(node->parent, CM_INLINE))
return yes;
/* <h4>...</h4> <em>...</em> */
if (node->prev && !TY_(nodeHasCM)(node->prev, CM_INLINE) &&
TY_(nodeIsElement)(node->prev))
return yes;
/* <p><span> ...</span></p> */
if (!node->prev && !node->parent->prev && !TY_(nodeHasCM)(node->parent->parent, CM_INLINE))
return yes;
return no;
}
/**
* Indicates whether or not trailing whitespace should be cleaned.
*/
static Bool CleanTrailingWhitespace(TidyDocImpl* doc, Node* node)
{
Node* next;
if (!TY_(nodeIsText)(node))
return no;
if (node->parent->type == DocTypeTag)
return no;
if (IsPreDescendant(node))
return no;
if (node->parent->tag && node->parent->tag->parser == TY_(ParseScript))
return no;
/* #523, prevent blank spaces after script if the next item is script.
* This is actually more generalized as, if the next element is
* a body level script, then indicate that we want to clean trailing
* whitespace.
*/
if ( node->next && nodeIsSCRIPT(node->next) && nodeIsBODY(node->next->parent) )
return yes;
next = node->next;
/* <p>... </p> */
if (!next && !TY_(nodeHasCM)(node->parent, CM_INLINE))
return yes;
/* <div><small>... </small><h3>...</h3></div> */
if (!next && node->parent->next && !TY_(nodeHasCM)(node->parent->next, CM_INLINE))
return yes;
if (!next)
return no;
if (nodeIsBR(next))
return yes;
if (TY_(nodeHasCM)(next, CM_INLINE))
return no;
/* <a href='/'>...</a> <p>...</p> */
if (next->type == StartTag)
return yes;
/* <strong>...</strong> <hr /> */
if (next->type == StartEndTag)
return yes;
/* evil adjacent text nodes, Tidy should not generate these :-( */
if (TY_(nodeIsText)(next) && next->start < next->end
&& TY_(IsWhite)(doc->lexer->lexbuf[next->start]))
return yes;
return no;
}
/***************************************************************************//*
** MARK: - Information Accumulation
***************************************************************************/
/**
* Errors in positioning of form start or end tags
* generally require human intervention to fix.
* Issue #166 - repeated <main> element also uses this flag
* to indicate duplicates, discarded.
*/
static void BadForm( TidyDocImpl* doc )
{
doc->badForm |= flg_BadForm;
}
/***************************************************************************//*
** MARK: - Fixes and Touchup
***************************************************************************/
/**
* Adds style information as a class in the document or a property
* of the node to prevent indentation of inferred UL tags.
*/
static void AddClassNoIndent( TidyDocImpl* doc, Node *node )
{
ctmbstr sprop =
"padding-left: 2ex; margin-left: 0ex"
"; margin-top: 0ex; margin-bottom: 0ex";
if ( !cfgBool(doc, TidyDecorateInferredUL) )
return;
if ( cfgBool(doc, TidyMakeClean) )
TY_(AddStyleAsClass)( doc, node, sprop );
else
TY_(AddStyleProperty)( doc, node, sprop );
}
/**
* Cleans whitespace from text nodes, and drops such nodes if emptied
* completely as a result.
*/
static void CleanSpaces(TidyDocImpl* doc, Node* node)
{
Stack *stack = TY_(newStack)(doc, 16);
Node *next;
while (node)
{
next = node->next;
if (TY_(nodeIsText)(node) && CleanLeadingWhitespace(doc, node))
while (node->start < node->end && TY_(IsWhite)(doc->lexer->lexbuf[node->start]))
++(node->start);
if (TY_(nodeIsText)(node) && CleanTrailingWhitespace(doc, node))
while (node->end > node->start && TY_(IsWhite)(doc->lexer->lexbuf[node->end - 1]))
--(node->end);
if (TY_(nodeIsText)(node) && !(node->start < node->end))
{
TY_(RemoveNode)(node);
TY_(FreeNode)(doc, node);
node = next ? next : TY_(pop)(stack);
continue;
}
if (node->content)
{
TY_(push)(stack, next);
node = node->content;
continue;
}
node = next ? next : TY_(pop)(stack);
}
TY_(freeStack)(stack);
}
/**
* If a table row is empty then insert an empty cell. This practice is
* consistent with browser behavior and avoids potential problems with
* row spanning cells.
*/
static void FixEmptyRow(TidyDocImpl* doc, Node *row)
{
Node *cell;
if (row->content == NULL)
{
cell = TY_(InferredTag)(doc, TidyTag_TD);
TY_(InsertNodeAtEnd)(row, cell);
TY_(Report)(doc, row, cell, MISSING_STARTTAG);
}
}
/**
* The doctype has been found after other tags,
* and needs moving to before the html element
*/
static void InsertDocType( TidyDocImpl* doc, Node *element, Node *doctype )
{
Node* existing = TY_(FindDocType)( doc );
if ( existing )
{
TY_(Report)(doc, element, doctype, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, doctype );
}
else
{
TY_(Report)(doc, element, doctype, DOCTYPE_AFTER_TAGS );
while ( !nodeIsHTML(element) )
element = element->parent;
TY_(InsertNodeBeforeElement)( element, doctype );
}
}
/**
* This maps
* <p>hello<em> world</em>
* to
* <p>hello <em>world</em>
*
* Trims initial space, by moving it before the
* start tag, or if this element is the first in
* parent's content, then by discarding the space
*/
static void TrimInitialSpace( TidyDocImpl* doc, Node *element, Node *text )
{
Lexer* lexer = doc->lexer;
Node *prev, *node;
if ( TY_(nodeIsText)(text) &&
lexer->lexbuf[text->start] == ' ' &&
text->start < text->end )
{
if ( (element->tag->model & CM_INLINE) &&
!(element->tag->model & CM_FIELD) )
{
prev = element->prev;
if (TY_(nodeIsText)(prev))
{
if (prev->end == 0 || lexer->lexbuf[prev->end - 1] != ' ')
lexer->lexbuf[(prev->end)++] = ' ';
++(element->start);
}
else /* create new node */
{
node = TY_(NewNode)(lexer->allocator, lexer);
node->start = (element->start)++;
node->end = element->start;
lexer->lexbuf[node->start] = ' ';
TY_(InsertNodeBeforeElement)(element ,node);
DEBUG_LOG(SPRTF("TrimInitialSpace: Created text node, inserted before <%s>\n",
(element->element ? element->element : "unknown")));
}
}
/* discard the space in current node */
++(text->start);
}
}
/**
* This maps
* <em>hello </em><strong>world</strong>
* to
* <em>hello</em> <strong>world</strong>
*
* If last child of element is a text node
* then trim trailing white space character
* moving it to after element's end tag.
*/
static void TrimTrailingSpace( TidyDocImpl* doc, Node *element, Node *last )
{
Lexer* lexer = doc->lexer;
byte c;
if (TY_(nodeIsText)(last))
{
if (last->end > last->start)
{
c = (byte) lexer->lexbuf[ last->end - 1 ];
if ( c == ' ' )
{
last->end -= 1;
if ( (element->tag->model & CM_INLINE) &&
!(element->tag->model & CM_FIELD) )
lexer->insertspace = yes;
}
}
}
}
/**
* Move initial and trailing space out.
* This routine maps:
* hello<em> world</em>
* to
* hello <em>world</em>
* and
* <em>hello </em><strong>world</strong>
* to
* <em>hello</em> <strong>world</strong>
*/
static void TrimSpaces( TidyDocImpl* doc, Node *element)
{
Node* text = element->content;
if (nodeIsPRE(element) || IsPreDescendant(element))
return;
if (TY_(nodeIsText)(text))
TrimInitialSpace(doc, element, text);
text = element->last;
if (TY_(nodeIsText)(text))
TrimTrailingSpace(doc, element, text);
}
/***************************************************************************//*
** MARK: - Parsers Support
***************************************************************************/
/**
* Structure used by FindDescendant_cb.
*/
struct MatchingDescendantData
{
Node *found_node;
Bool *passed_marker_node;
/* input: */
TidyTagId matching_tagId;
Node *node_to_find;
Node *marker_node;
};
/**
* The main engine for FindMatchingDescendant.
*/
static NodeTraversalSignal FindDescendant_cb(TidyDocImpl* ARG_UNUSED(doc), Node* node, void *propagate)
{
struct MatchingDescendantData *cb_data = (struct MatchingDescendantData *)propagate;
if (TagId(node) == cb_data->matching_tagId)
{
/* make sure we match up 'unknown' tags exactly! */
if (cb_data->matching_tagId != TidyTag_UNKNOWN ||
(node->element != NULL &&
cb_data->node_to_find != NULL &&
cb_data->node_to_find->element != NULL &&
0 == TY_(tmbstrcmp)(cb_data->node_to_find->element, node->element)))
{
cb_data->found_node = node;
return ExitTraversal;
}
}
if (cb_data->passed_marker_node && node == cb_data->marker_node)
*cb_data->passed_marker_node = yes;
return VisitParent;
}
/**
* Search the parent chain (from `parent` upwards up to the root) for a node
* matching the given 'node'.
*
* When the search passes beyond the `marker_node` (which is assumed to sit
* in the parent chain), this will be flagged by setting the boolean
* referenced by `is_parent_of_marker` to `yes`.
*
* 'is_parent_of_marker' and 'marker_node' are optional parameters and may
* be NULL.
*/
static Node *FindMatchingDescendant( Node *parent, Node *node, Node *marker_node, Bool *is_parent_of_marker )
{
struct MatchingDescendantData cb_data = { 0 };
cb_data.matching_tagId = TagId(node);
cb_data.node_to_find = node;
cb_data.marker_node = marker_node;
assert(node);
if (is_parent_of_marker)
*is_parent_of_marker = no;
TY_(TraverseNodeTree)(NULL, parent, FindDescendant_cb, &cb_data);
return cb_data.found_node;
}
/**
* Finds the last list item for the given list, providing it in the
* in-out parameter. Returns yes or no if the item was the last list
* item.
*/
static Bool FindLastLI( Node *list, Node **lastli )
{
Node *node;
*lastli = NULL;
for ( node = list->content; node ; node = node->next )
if ( nodeIsLI(node) && node->type == StartTag )
*lastli=node;
return *lastli ? yes:no;
}
/***************************************************************************//*
** MARK: - Parser Stack
***************************************************************************/
/**
* Allocates and initializes the parser's stack.
*/
void TY_(InitParserStack)( TidyDocImpl* doc )
{
enum { default_size = 32 };
TidyParserMemory *content = (TidyParserMemory *) TidyAlloc( doc->allocator, sizeof(TidyParserMemory) * default_size );
doc->stack.content = content;
doc->stack.size = default_size;
doc->stack.top = -1;
}
/**
* Frees the parser's stack when done.
*/
void TY_(FreeParserStack)( TidyDocImpl* doc )
{
TidyFree( doc->allocator, doc->stack.content );
doc->stack.content = NULL;
doc->stack.size = 0;
doc->stack.top = -1;
}
/**
* Increase the stack size.
*/
static void growParserStack( TidyDocImpl* doc )
{
TidyParserMemory *content;
content = (TidyParserMemory *) TidyAlloc( doc->allocator, sizeof(TidyParserMemory) * doc->stack.size * 2 );
memcpy( content, doc->stack.content, sizeof(TidyParserMemory) * (doc->stack.top + 1) );
TidyFree(doc->allocator, doc->stack.content);
doc->stack.content = content;
doc->stack.size = doc->stack.size * 2;
}
/**
* Indicates whether or not the stack is empty.
*/
Bool TY_(isEmptyParserStack)( TidyDocImpl* doc )
{
return doc->stack.top < 0;
}
/**
* Peek at the parser memory.
*/
TidyParserMemory TY_(peekMemory)( TidyDocImpl* doc )
{
return doc->stack.content[doc->stack.top];
}
/**
* Peek at the parser memory "identity" field. This is just a convenience
* to avoid having to create a new struct instance in the caller.
*/
Parser* TY_(peekMemoryIdentity)( TidyDocImpl* doc )
{
return doc->stack.content[doc->stack.top].identity;
}
/**
* Peek at the parser memory "mode" field. This is just a convenience
* to avoid having to create a new struct instance in the caller.
*/
GetTokenMode TY_(peekMemoryMode)( TidyDocImpl* doc )
{
return doc->stack.content[doc->stack.top].mode;
}
/**
* Pop out a parser memory.
*/
TidyParserMemory TY_(popMemory)( TidyDocImpl* doc )
{
if ( !TY_(isEmptyParserStack)( doc ) )
{
TidyParserMemory data = doc->stack.content[doc->stack.top];
DEBUG_LOG(SPRTF("\n"
"<--POP original: %s @ %p\n"
" reentry: %s @ %p\n"
" stack depth: %lu @ %p\n"
" mode: %u\n"
" register 1: %i\n"
" register 2: %i\n\n",
data.original_node ? data.original_node->element : "none", data.original_node,
data.reentry_node ? data.reentry_node->element : "none", data.reentry_node,
doc->stack.top, &doc->stack.content[doc->stack.top],
data.mode,
data.register_1,
data.register_2
));
doc->stack.top = doc->stack.top - 1;
return data;
}
TidyParserMemory blank = { NULL };
return blank;
}
/**
* Push the parser memory to the stack.
*/
void TY_(pushMemory)( TidyDocImpl* doc, TidyParserMemory data )
{
if ( doc->stack.top == doc->stack.size - 1 )
growParserStack( doc );
doc->stack.top++;
doc->stack.content[doc->stack.top] = data;
DEBUG_LOG(SPRTF("\n"
"-->PUSH original: %s @ %p\n"
" reentry: %s @ %p\n"
" stack depth: %lu @ %p\n"
" mode: %u\n"
" register 1: %i\n"
" register 2: %i\n\n",
data.original_node ? data.original_node->element : "none", data.original_node,
data.reentry_node ? data.reentry_node->element : "none", data.reentry_node,
doc->stack.top, &doc->stack.content[doc->stack.top],
data.mode,
data.register_1,
data.register_2
));
}
/***************************************************************************//*
** MARK: Convenience Logging Macros
***************************************************************************/
#if defined(ENABLE_DEBUG_LOG)
# define DEBUG_LOG_COUNTERS \
static int depth_parser = 0;\
static int count_parser = 0;\
int old_mode = IgnoreWhitespace;
# define DEBUG_LOG_GET_OLD_MODE old_mode = mode;
# define DEBUG_LOG_REENTER_WITH_NODE(NODE) SPRTF("\n>>>Re-Enter %s-%u with '%s', +++mode: %u, depth: %d, cnt: %d\n", __FUNCTION__, __LINE__, NODE->element, mode, ++depth_parser, ++count_parser);
# define DEBUG_LOG_ENTER_WITH_NODE(NODE) SPRTF("\n>>>Enter %s-%u with '%s', +++mode: %u, depth: %d, cnt: %d\n", __FUNCTION__, __LINE__, NODE->element, mode, ++depth_parser, ++count_parser);
# define DEBUG_LOG_CHANGE_MODE SPRTF("+++%s-%u Changing mode to %u (was %u)\n", __FUNCTION__, __LINE__, mode, old_mode);
# define DEBUG_LOG_GOT_TOKEN(NODE) SPRTF("---%s-%u got token '%s' with mode '%u'.\n", __FUNCTION__, __LINE__, NODE ? NODE->element : NULL, mode);
# define DEBUG_LOG_EXIT_WITH_NODE(NODE) SPRTF("<<<Exit %s-%u with a node to parse: '%s', depth: %d\n", __FUNCTION__, __LINE__, NODE->element, depth_parser--);
# define DEBUG_LOG_EXIT SPRTF("<<<Exit %s-%u, depth: %d\n", __FUNCTION__, __LINE__, depth_parser--);
#else
# define DEBUG_LOG_COUNTERS
# define DEBUG_LOG_GET_OLD_MODE
# define DEBUG_LOG_REENTER_WITH_NODE(NODE)
# define DEBUG_LOG_ENTER_WITH_NODE(NODE)
# define DEBUG_LOG_CHANGE_MODE
# define DEBUG_LOG_GOT_TOKEN(NODE)
# define DEBUG_LOG_EXIT_WITH_NODE(NODE)
# define DEBUG_LOG_EXIT
#endif
/***************************************************************************//*
** MARK: - Parser Search and Instantiation
***************************************************************************/
/**
* Retrieves the correct parser for the given node, accounting for various
* conditions, and readies the lexer for parsing that node.
*/
static Parser* GetParserForNode( TidyDocImpl* doc, Node *node )
{
Lexer* lexer = doc->lexer;
if ( cfgBool( doc, TidyXmlTags ) )
return ParseXMLElement;
/* [i_a]2 prevent crash for active content (php, asp) docs */
if (!node || node->tag == NULL)
return NULL;
/*
Fix by GLP 2000-12-21. Need to reset insertspace if this is both
a non-inline and empty tag (base, link, meta, isindex, hr, area).
*/
if (node->tag->model & CM_EMPTY)
{
lexer->waswhite = no;
if (node->tag->parser == NULL)
return NULL;
}
else if (!(node->tag->model & CM_INLINE))
lexer->insertspace = no;
if (node->tag->parser == NULL)
return NULL;
if (node->type == StartEndTag)
return NULL;
/* [i_a]2 added this - not sure why - CHECKME: */
lexer->parent = node;
return (node->tag->parser);
}
/**
* This parser controller initiates the parsing process with the document's
* root starting with the provided node, which should be the HTML node after
* the pre-HTML stuff is handled at a higher level.
*
* This controller is responsible for calling each of the individual parsers,
* based on the tokens it pulls from the lexer, or the tokens passed back via
* the parserMemory stack from each of the parsers. Having a main, central
* looping dispatcher in this fashion allows the prevention of recursion.
*/
void ParseHTMLWithNode( TidyDocImpl* doc, Node* node )
{
GetTokenMode mode = IgnoreWhitespace;
Parser* parser = GetParserForNode( doc, node );
Bool something_to_do = yes;
/*
This main loop is only extinguished when all of the parser tokens are
consumed. Ideally, EVERY parser will return nodes to this loop for
dispatch to the appropriate parser, but some of the recursive parsers
still consume some tokens on their own.
*/
while (something_to_do)
{
node = parser ? parser( doc, node, mode ) : NULL;
/*
We have a node, so anything deferred was already pushed to the stack
to be dealt with later.
*/
if ( node )
{
parser = GetParserForNode( doc, node );
continue;
}
/*
We weren't given a node, which means this particular leaf is bottomed
out. We'll re-enter the parsers using information from the stack.
*/
if ( !TY_(isEmptyParserStack)(doc))
{
parser = TY_(peekMemoryIdentity)(doc);
if (parser)
{
continue;
}
else
{
/* No parser means we're only passing back a parsing mode. */
mode = TY_(peekMemoryMode)( doc );
TY_(popMemory)( doc );
}
}
/*
At this point, there's nothing being returned from parsers, and
nothing on the stack, so we can draw a new node from the lexer.
*/
node = TY_(GetToken)( doc, mode );
DEBUG_LOG_GOT_TOKEN(node);
if (node)
parser = GetParserForNode( doc, node );
else
something_to_do = no;
}
}
/***************************************************************************//*
** MARK: - Parsers
***************************************************************************/
/** MARK: TY_(ParseBlock)
* `element` is a node created by the lexer upon seeing the start tag, or
* by the parser when the start tag is inferred
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseBlock)( TidyDocImpl* doc, Node *element, GetTokenMode mode )
{
Lexer* lexer = doc->lexer;
Node *node = NULL;
Bool checkstack = yes;
uint istackbase = 0;
DEBUG_LOG_COUNTERS;
if ( element == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, because the loop overwrites this immediately. */
DEBUG_LOG_REENTER_WITH_NODE(node);
element = memory.original_node;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.reentry_mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(element);
if ( element->tag->model & CM_EMPTY )
{
DEBUG_LOG_EXIT;
return NULL;
}
if ( nodeIsDIV(element) && nodeIsDL(element->parent) && TY_(IsHTML5Mode)(doc) )
{
DEBUG_LOG_EXIT;
return TY_(ParseDefList)(doc, element, mode); /* @warning: possible recursion! */
}
if ( nodeIsFORM(element) && DescendantOf(element, TidyTag_FORM) )
{
TY_(Report)(doc, element, NULL, ILLEGAL_NESTING );
}
/*
InlineDup() asks the lexer to insert inline emphasis tags
currently pushed on the istack, but take care to avoid
propagating inline emphasis inside OBJECT or APPLET.
For these elements a fresh inline stack context is created
and disposed of upon reaching the end of the element.
They thus behave like table cells in this respect.
*/
if (element->tag->model & CM_OBJECT)
{
istackbase = lexer->istackbase;
lexer->istackbase = lexer->istacksize;
}
if (!(element->tag->model & CM_MIXED))
{
TY_(InlineDup)( doc, NULL );
}
/*\
* Issue #212 - If it is likely that it may be necessary
* to move a leading space into a text node before this
* element, then keep the mode MixedContent to keep any
* leading space
\*/
if ( !(element->tag->model & CM_INLINE) ||
(element->tag->model & CM_FIELD ) )
{
DEBUG_LOG_GET_OLD_MODE;
mode = IgnoreWhitespace;
DEBUG_LOG_CHANGE_MODE;
}
else if (mode == IgnoreWhitespace)
{
/* Issue #212 - Further fix in case ParseBlock() is called with 'IgnoreWhitespace'
when such a leading space may need to be inserted before this element to
preserve the browser view */
DEBUG_LOG_GET_OLD_MODE;
mode = MixedContent;
DEBUG_LOG_CHANGE_MODE;
}
} /* Re-Entering */
/*
Main Loop
*/
while ((node = TY_(GetToken)(doc, mode /*MixedContent*/)) != NULL)
{
DEBUG_LOG_GOT_TOKEN(node);
/* end tag for this element */
if (node->type == EndTag && node->tag &&
(node->tag == element->tag || element->was == node->tag))
{
TY_(FreeNode)( doc, node );
if (element->tag->model & CM_OBJECT)
{
/* pop inline stack */
while (lexer->istacksize > lexer->istackbase)
TY_(PopInline)( doc, NULL );
lexer->istackbase = istackbase;
}
element->closed = yes;
TrimSpaces( doc, element );
DEBUG_LOG_EXIT;
return NULL;
}
if ( nodeIsHTML(node) || nodeIsHEAD(node) || nodeIsBODY(node) )
{
if ( TY_(nodeIsElement)(node) )
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node );
continue;
}
if (node->type == EndTag)
{
if (node->tag == NULL)
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node );
continue;
}
else if ( nodeIsBR(node) )
{
node->type = StartTag;
}
else if ( nodeIsP(node) )
{
/* Cannot have a block inside a paragraph, so no checking
for an ancestor is necessary -- but we _can_ have
paragraphs inside a block, so change it to an implicit
empty paragraph, to be dealt with according to the user's
options
*/
node->type = StartEndTag;
node->implicit = yes;
}
else if (DescendantOf( element, node->tag->id ))
{
/*
if this is the end tag for an ancestor element
then infer end tag for this element
*/
TY_(UngetToken)( doc );
break;
}
else
{
/* special case </tr> etc. for stuff moved in front of table */
if ( lexer->exiled
&& (TY_(nodeHasCM)(node, CM_TABLE) || nodeIsTABLE(node)) )
{
TY_(UngetToken)( doc );
TrimSpaces( doc, element );
DEBUG_LOG_EXIT;
return NULL;
}
}
}
/* mixed content model permits text */
if (TY_(nodeIsText)(node))
{
if ( checkstack )
{
checkstack = no;
if (!(element->tag->model & CM_MIXED))
{
if ( TY_(InlineDup)(doc, node) > 0 )
continue;
}
}
TY_(InsertNodeAtEnd)(element, node);
DEBUG_LOG_GET_OLD_MODE
mode = MixedContent;
DEBUG_LOG_CHANGE_MODE;
/*
HTML4 strict doesn't allow mixed content for
elements with %block; as their content model
*/
/*
But only body, map, blockquote, form and
noscript have content model %block;
*/
if ( nodeIsBODY(element) ||
nodeIsMAP(element) ||
nodeIsBLOCKQUOTE(element) ||
nodeIsFORM(element) ||
nodeIsNOSCRIPT(element) )
TY_(ConstrainVersion)( doc, ~VERS_HTML40_STRICT );
continue;
}
if ( InsertMisc(element, node) )
continue;
/* allow PARAM elements? */
if ( nodeIsPARAM(node) )
{
if ( TY_(nodeHasCM)(element, CM_PARAM) && TY_(nodeIsElement)(node) )
{
TY_(InsertNodeAtEnd)(element, node);
continue;
}
/* otherwise discard it */
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node );
continue;
}
/* allow AREA elements? */
if ( nodeIsAREA(node) )
{
if ( nodeIsMAP(element) && TY_(nodeIsElement)(node) )
{
TY_(InsertNodeAtEnd)(element, node);
continue;
}
/* otherwise discard it */
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node );
continue;
}
/* ignore unknown start/end tags */
if ( node->tag == NULL )
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node );
continue;
}
/*
Allow CM_INLINE elements here.
Allow CM_BLOCK elements here unless
lexer->excludeBlocks is yes.
LI and DD are special cased.
Otherwise infer end tag for this element.
*/
if ( !TY_(nodeHasCM)(node, CM_INLINE) )
{
if ( !TY_(nodeIsElement)(node) )
{
if ( nodeIsFORM(node) )
BadForm( doc );
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node );
continue;
}
/* #427671 - Fix by Randy Waki - 10 Aug 00 */
/*
If an LI contains an illegal FRAME, FRAMESET, OPTGROUP, or OPTION
start tag, discard the start tag and let the subsequent content get
parsed as content of the enclosing LI. This seems to mimic IE and
Netscape, and avoids an infinite loop: without this check,
ParseBlock (which is parsing the LI's content) and ParseList (which
is parsing the LI's parent's content) repeatedly defer to each
other to parse the illegal start tag, each time inferring a missing
</li> or <li> respectively.
NOTE: This check is a bit fragile. It specifically checks for the
four tags that happen to weave their way through the current series
of tests performed by ParseBlock and ParseList to trigger the
infinite loop.
*/
if ( nodeIsLI(element) )
{
if ( nodeIsFRAME(node) ||
nodeIsFRAMESET(node) ||
nodeIsOPTGROUP(node) ||
nodeIsOPTION(node) )
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node ); /* DSR - 27Apr02 avoid memory leak */
continue;
}
}
if ( nodeIsTD(element) || nodeIsTH(element) )
{
/* if parent is a table cell, avoid inferring the end of the cell */
if ( TY_(nodeHasCM)(node, CM_HEAD) )
{
MoveToHead( doc, element, node );
continue;
}
if ( TY_(nodeHasCM)(node, CM_LIST) )
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_UL);
AddClassNoIndent(doc, node);
lexer->excludeBlocks = yes;
}
else if ( TY_(nodeHasCM)(node, CM_DEFLIST) )
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_DL);
lexer->excludeBlocks = yes;
}
/* infer end of current table cell */
if ( !TY_(nodeHasCM)(node, CM_BLOCK) )
{
TY_(UngetToken)( doc );
TrimSpaces( doc, element );
DEBUG_LOG_EXIT;
return NULL;
}
}
else if ( TY_(nodeHasCM)(node, CM_BLOCK) )
{
if ( lexer->excludeBlocks )
{
if ( !TY_(nodeHasCM)(element, CM_OPT) )
TY_(Report)(doc, element, node, MISSING_ENDTAG_BEFORE );
TY_(UngetToken)( doc );
if ( TY_(nodeHasCM)(element, CM_OBJECT) )
lexer->istackbase = istackbase;
TrimSpaces( doc, element );
DEBUG_LOG_EXIT;
return NULL;
}
}
else if ( ! nodeIsTEMPLATE( element ) )/* things like list items */
{
if (node->tag->model & CM_HEAD)
{
MoveToHead( doc, element, node );
continue;
}
/*
special case where a form start tag
occurs in a tr and is followed by td or th
*/
if ( nodeIsFORM(element) &&
nodeIsTD(element->parent) &&
element->parent->implicit )
{
if ( nodeIsTD(node) )
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node );
continue;
}
if ( nodeIsTH(node) )
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node );
node = element->parent;
TidyDocFree(doc, node->element);
node->element = TY_(tmbstrdup)(doc->allocator, "th");
node->tag = TY_(LookupTagDef)( TidyTag_TH );
continue;
}
}
if ( !TY_(nodeHasCM)(element, CM_OPT) && !element->implicit )
TY_(Report)(doc, element, node, MISSING_ENDTAG_BEFORE );
/* #521, warn on missing optional end-tags if not omitting them. */
if ( cfgBool( doc, TidyOmitOptionalTags ) == no && TY_(nodeHasCM)(element, CM_OPT) )
TY_(Report)(doc, element, node, MISSING_ENDTAG_OPTIONAL );
TY_(UngetToken)( doc );
if ( TY_(nodeHasCM)(node, CM_LIST) )
{
if ( element->parent && element->parent->tag &&
element->parent->tag->parser == TY_(ParseList) )
{
TrimSpaces( doc, element );
DEBUG_LOG_EXIT;
return NULL;
}
node = TY_(InferredTag)(doc, TidyTag_UL);
AddClassNoIndent(doc, node);
}
else if ( TY_(nodeHasCM)(node, CM_DEFLIST) )
{
if ( nodeIsDL(element->parent) )
{
TrimSpaces( doc, element );
DEBUG_LOG_EXIT;
return NULL;
}
node = TY_(InferredTag)(doc, TidyTag_DL);
}
else if ( TY_(nodeHasCM)(node, CM_TABLE) || TY_(nodeHasCM)(node, CM_ROW) )
{
/* http://tidy.sf.net/issue/1316307 */
/* In exiled mode, return so table processing can
continue. */
if (lexer->exiled)
{
DEBUG_LOG_EXIT;
return NULL;
}
node = TY_(InferredTag)(doc, TidyTag_TABLE);
}
else if ( TY_(nodeHasCM)(element, CM_OBJECT) )
{
/* pop inline stack */
while ( lexer->istacksize > lexer->istackbase )
TY_(PopInline)( doc, NULL );
lexer->istackbase = istackbase;
TrimSpaces( doc, element );
DEBUG_LOG_EXIT;
return NULL;
}
else
{
TrimSpaces( doc, element );
DEBUG_LOG_EXIT;
return NULL;
}
}
}
/*\
* Issue #307 - an <A> tag to ends any open <A> element
* Like #427827 - fixed by Randy Waki and Bjoern Hoehrmann 23 Aug 00
* in ParseInline(), fix copied HERE to ParseBlock()
* href: http://www.w3.org/TR/html-markup/a.html
* The interactive element a must not appear as a descendant of the a element.
\*/
if ( nodeIsA(node) && !node->implicit &&
(nodeIsA(element) || DescendantOf(element, TidyTag_A)) )
{
if (node->type != EndTag && node->attributes == NULL
&& cfgBool(doc, TidyCoerceEndTags) )
{
node->type = EndTag;
TY_(Report)(doc, element, node, COERCE_TO_ENDTAG);
TY_(UngetToken)( doc );
continue;
}
if (nodeIsA(element))
{
TY_(Report)(doc, element, node, MISSING_ENDTAG_BEFORE);
TY_(UngetToken)( doc );
}
else
{
/* Issue #597 - if we not 'UngetToken' then it is being discarded.
Add message, and 'FreeNode' - thanks @ralfjunker */
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)(doc, node);
}
if (!(mode & Preformatted))
TrimSpaces(doc, element);
DEBUG_LOG_EXIT;
return NULL;
}
/* parse known element */
if (TY_(nodeIsElement)(node))
{
if (node->tag->model & CM_INLINE)
{
if (checkstack && !node->implicit)
{
checkstack = no;
if (!(element->tag->model & CM_MIXED)) /* #431731 - fix by Randy Waki 25 Dec 00 */
{
if ( TY_(InlineDup)(doc, node) > 0 )
continue;
}
}
DEBUG_LOG_GET_OLD_MODE;
mode = MixedContent;
DEBUG_LOG_CHANGE_MODE;
}
else
{
checkstack = yes;
DEBUG_LOG_GET_OLD_MODE;
mode = IgnoreWhitespace;
DEBUG_LOG_CHANGE_MODE;
}
/* trim white space before <br> */
if ( nodeIsBR(node) )
TrimSpaces( doc, element );
TY_(InsertNodeAtEnd)(element, node);
if (node->implicit)
TY_(Report)(doc, element, node, INSERTING_TAG );
/* Issue #212 - WHY is this hard coded to 'IgnoreWhitespace' while an
effort has been made above to set a 'MixedContent' mode in some cases?
WHY IS THE 'mode' VARIABLE NOT USED HERE???? */
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseBlock);
memory.reentry_node = node;
memory.reentry_mode = mode;
memory.original_node = element;
TY_(pushMemory)(doc, memory);
DEBUG_LOG_EXIT_WITH_NODE(node);
}
return node;
}
/* discard unexpected tags */
if (node->type == EndTag)
TY_(PopInline)( doc, node ); /* if inline end tag */
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node );
continue;
}
if (!(element->tag->model & CM_OPT))
TY_(Report)(doc, element, node, MISSING_ENDTAG_FOR);
if (element->tag->model & CM_OBJECT)
{
/* pop inline stack */
while ( lexer->istacksize > lexer->istackbase )
TY_(PopInline)( doc, NULL );
lexer->istackbase = istackbase;
}
TrimSpaces( doc, element );
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseBody)
* Parses the `body` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseBody)( TidyDocImpl* doc, Node *body, GetTokenMode mode )
{
Lexer* lexer = doc->lexer;
Node *node = NULL;
Bool checkstack = no;
Bool iswhitenode = no;
DEBUG_LOG_COUNTERS;
mode = IgnoreWhitespace;
checkstack = yes;
/*
If we're re-entering, then we need to setup from a previous state,
instead of starting fresh. We can pull what we need from the document's
stack.
*/
if ( body == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
body = memory.original_node;
checkstack = memory.register_1;
iswhitenode = memory.register_2;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(body);
TY_(BumpObject)( doc, body->parent );
}
while ((node = TY_(GetToken)(doc, mode)) != NULL)
{
DEBUG_LOG_GOT_TOKEN(node);
/* find and discard multiple <body> elements */
if (node->tag == body->tag && node->type == StartTag)
{
TY_(Report)(doc, body, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)(doc, node);
continue;
}
/* #538536 Extra endtags not detected */
if ( nodeIsHTML(node) )
{
if (TY_(nodeIsElement)(node) || lexer->seenEndHtml)
TY_(Report)(doc, body, node, DISCARDING_UNEXPECTED);
else
lexer->seenEndHtml = 1;
TY_(FreeNode)( doc, node);
continue;
}
if ( lexer->seenEndBody &&
( node->type == StartTag ||
node->type == EndTag ||
node->type == StartEndTag ) )
{
TY_(Report)(doc, body, node, CONTENT_AFTER_BODY );
}
if ( node->tag == body->tag && node->type == EndTag )
{
body->closed = yes;
TrimSpaces(doc, body);
TY_(FreeNode)( doc, node);
lexer->seenEndBody = 1;
DEBUG_LOG_GET_OLD_MODE;
mode = IgnoreWhitespace;
DEBUG_LOG_CHANGE_MODE;
if ( nodeIsNOFRAMES(body->parent) )
break;
continue;
}
if ( nodeIsNOFRAMES(node) )
{
if (node->type == StartTag)
{
TidyParserMemory memory = {0};
TY_(InsertNodeAtEnd)(body, node);
memory.identity = TY_(ParseBody);
memory.original_node = body;
memory.reentry_node = node;
memory.register_1 = checkstack;
memory.register_2 = iswhitenode;
memory.mode = mode;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
if (node->type == EndTag && nodeIsNOFRAMES(body->parent) )
{
TrimSpaces(doc, body);
TY_(UngetToken)( doc );
break;
}
}
if ( (nodeIsFRAME(node) || nodeIsFRAMESET(node))
&& nodeIsNOFRAMES(body->parent) )
{
TrimSpaces(doc, body);
TY_(UngetToken)( doc );
break;
}
iswhitenode = no;
if ( TY_(nodeIsText)(node) &&
node->end <= node->start + 1 &&
lexer->lexbuf[node->start] == ' ' )
iswhitenode = yes;
/* deal with comments etc. */
if (InsertMisc(body, node))
continue;
/* mixed content model permits text */
if (TY_(nodeIsText)(node))
{
if (iswhitenode && mode == IgnoreWhitespace)
{
TY_(FreeNode)( doc, node);
continue;
}
/* HTML 2 and HTML4 strict don't allow text here */
TY_(ConstrainVersion)(doc, ~(VERS_HTML40_STRICT | VERS_HTML20));
if (checkstack)
{
checkstack = no;
if ( TY_(InlineDup)(doc, node) > 0 )
continue;
}
TY_(InsertNodeAtEnd)(body, node);
DEBUG_LOG_GET_OLD_MODE;
mode = MixedContent;
DEBUG_LOG_CHANGE_MODE;
continue;
}
if (node->type == DocTypeTag)
{
InsertDocType(doc, body, node);
continue;
}
/* discard unknown and PARAM tags */
if ( node->tag == NULL || nodeIsPARAM(node) )
{
TY_(Report)(doc, body, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/*
Netscape allows LI and DD directly in BODY
We infer UL or DL respectively and use this
Bool to exclude block-level elements so as
to match Netscape's observed behaviour.
*/
lexer->excludeBlocks = no;
if ((( nodeIsINPUT(node) ||
(!TY_(nodeHasCM)(node, CM_BLOCK) && !TY_(nodeHasCM)(node, CM_INLINE))
) && !TY_(IsHTML5Mode)(doc)) || nodeIsLI(node) )
{
/* avoid this error message being issued twice */
if (!(node->tag->model & CM_HEAD))
TY_(Report)(doc, body, node, TAG_NOT_ALLOWED_IN);
if (node->tag->model & CM_HTML)
{
/* copy body attributes if current body was inferred */
if ( nodeIsBODY(node) && body->implicit
&& body->attributes == NULL )
{
body->attributes = node->attributes;
node->attributes = NULL;
}
TY_(FreeNode)( doc, node);
continue;
}
if (node->tag->model & CM_HEAD)
{
MoveToHead(doc, body, node);
continue;
}
if (node->tag->model & CM_LIST)
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_UL);
AddClassNoIndent(doc, node);
lexer->excludeBlocks = yes;
}
else if (node->tag->model & CM_DEFLIST)
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_DL);
lexer->excludeBlocks = yes;
}
else if (node->tag->model & (CM_TABLE | CM_ROWGRP | CM_ROW))
{
/* http://tidy.sf.net/issue/2855621 */
if (node->type != EndTag) {
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_TABLE);
}
lexer->excludeBlocks = yes;
}
else if ( nodeIsINPUT(node) )
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_FORM);
lexer->excludeBlocks = yes;
}
else
{
if ( !TY_(nodeHasCM)(node, CM_ROW | CM_FIELD) )
{
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
/* ignore </td> </th> <option> etc. */
TY_(FreeNode)( doc, node );
continue;
}
}
if (node->type == EndTag)
{
if ( nodeIsBR(node) )
{
node->type = StartTag;
}
else if ( nodeIsP(node) )
{
node->type = StartEndTag;
node->implicit = yes;
}
else if ( TY_(nodeHasCM)(node, CM_INLINE) )
TY_(PopInline)( doc, node );
}
if (TY_(nodeIsElement)(node))
{
if (nodeIsMAIN(node))
{
/*\ Issue #166 - repeated <main> element
* How to efficiently search for a previous main element?
\*/
if ( findNodeById(doc, TidyTag_MAIN) )
{
doc->badForm |= flg_BadMain; /* this is an ERROR in format */
TY_(Report)(doc, body, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
}
/* Issue #20 - merging from Ger Hobbelt fork put back CM_MIXED, which had been
removed to fix this issue - reverting to fix 880221e
*/
if ( TY_(nodeHasCM)(node, CM_INLINE) )
{
/* HTML4 strict doesn't allow inline content here */
/* but HTML2 does allow img elements as children of body */
if ( nodeIsIMG(node) )
TY_(ConstrainVersion)(doc, ~VERS_HTML40_STRICT);
else
TY_(ConstrainVersion)(doc, ~(VERS_HTML40_STRICT|VERS_HTML20));
if (checkstack && !node->implicit)
{
checkstack = no;
if ( TY_(InlineDup)(doc, node) > 0 )
continue;
}
DEBUG_LOG_GET_OLD_MODE;
mode = MixedContent;
DEBUG_LOG_CHANGE_MODE;
}
else
{
checkstack = yes;
DEBUG_LOG_GET_OLD_MODE;
mode = IgnoreWhitespace;
DEBUG_LOG_CHANGE_MODE;
}
if (node->implicit)
{
TY_(Report)(doc, body, node, INSERTING_TAG);
}
TY_(InsertNodeAtEnd)(body, node);
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseBody);
memory.original_node = body;
memory.reentry_node = node;
memory.register_1 = checkstack;
memory.register_2 = iswhitenode;
memory.mode = mode;
TY_(pushMemory)( doc, memory );
}
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
/* discard unexpected tags */
TY_(Report)(doc, body, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
}
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseColGroup)
* Parses the `colgroup` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseColGroup)( TidyDocImpl* doc, Node *colgroup, GetTokenMode ARG_UNUSED(mode) )
{
Node *node, *parent;
DEBUG_LOG_COUNTERS;
/*
If we're re-entering, then we need to setup from a previous state,
instead of starting fresh. We can pull what we need from the document's
stack.
*/
if ( colgroup == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
colgroup = memory.original_node;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(colgroup);
if (colgroup->tag->model & CM_EMPTY)
return NULL;
}
while ((node = TY_(GetToken)(doc, IgnoreWhitespace)) != NULL)
{
DEBUG_LOG_GOT_TOKEN(node);
if (node->tag == colgroup->tag && node->type == EndTag)
{
TY_(FreeNode)( doc, node);
colgroup->closed = yes;
return NULL;
}
/*
if this is the end tag for an ancestor element
then infer end tag for this element
*/
if (node->type == EndTag)
{
if ( nodeIsFORM(node) )
{
BadForm( doc );
TY_(Report)(doc, colgroup, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
for ( parent = colgroup->parent;
parent != NULL;
parent = parent->parent )
{
if (node->tag == parent->tag)
{
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
}
}
if (TY_(nodeIsText)(node))
{
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
/* deal with comments etc. */
if (InsertMisc(colgroup, node))
continue;
/* discard unknown tags */
if (node->tag == NULL)
{
TY_(Report)(doc, colgroup, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if ( !nodeIsCOL(node) )
{
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
if (node->type == EndTag)
{
TY_(Report)(doc, colgroup, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* node should be <COL> */
TY_(InsertNodeAtEnd)(colgroup, node);
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseColGroup);
memory.original_node = colgroup;
memory.reentry_node = node;
memory.mode = mode;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
}
DEBUG_LOG_EXIT;
return node;
}
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseDatalist)
* Parses the `datalist` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseDatalist)( TidyDocImpl* doc, Node *field, GetTokenMode ARG_UNUSED(mode) )
{
Lexer* lexer = doc->lexer;
Node *node;
DEBUG_LOG_COUNTERS;
if ( field == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
field = memory.original_node;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(field);
}
lexer->insert = NULL; /* defer implicit inline start tags */
while ((node = TY_(GetToken)(doc, IgnoreWhitespace)) != NULL)
{
if (node->tag == field->tag && node->type == EndTag)
{
TY_(FreeNode)( doc, node);
field->closed = yes;
TrimSpaces(doc, field);
DEBUG_LOG_EXIT;
return NULL;
}
/* deal with comments etc. */
if (InsertMisc(field, node))
continue;
if ( node->type == StartTag &&
( nodeIsOPTION(node) ||
nodeIsOPTGROUP(node) ||
nodeIsDATALIST(node) ||
nodeIsSCRIPT(node))
)
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseDatalist);
memory.original_node = field;
memory.reentry_node = node;
memory.reentry_mode = IgnoreWhitespace;
TY_(InsertNodeAtEnd)(field, node);
TY_(pushMemory)(doc, memory);
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
/* discard unexpected tags */
TY_(Report)(doc, field, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
}
TY_(Report)(doc, field, node, MISSING_ENDTAG_FOR);
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseDefList)
* Parses the `dl` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseDefList)( TidyDocImpl* doc, Node *list, GetTokenMode mode )
{
Lexer* lexer = doc->lexer;
Node *node = NULL;
Node *parent = NULL;
DEBUG_LOG_COUNTERS;
enum parserState {
STATE_INITIAL, /* This is the initial state for every parser. */
STATE_POST_NODEISCENTER, /* To-do after re-entering after checks. */
STATE_COMPLETE, /* Done with the switch. */
} state = STATE_INITIAL;
if ( list == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
list = memory.original_node;
state = memory.reentry_state;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(list);
}
if (list->tag->model & CM_EMPTY)
return NULL;
lexer->insert = NULL; /* defer implicit inline start tags */
while ( state != STATE_COMPLETE )
{
if ( state == STATE_INITIAL )
node = TY_(GetToken)( doc, IgnoreWhitespace);
switch ( state)
{
case STATE_INITIAL:
{
if ( node == NULL)
{
state = STATE_COMPLETE;
continue;
}
if (node->tag == list->tag && node->type == EndTag)
{
TY_(FreeNode)( doc, node);
list->closed = yes;
DEBUG_LOG_EXIT;
return NULL;
}
/* deal with comments etc. */
if (InsertMisc(list, node))
continue;
if (TY_(nodeIsText)(node))
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_DT);
TY_(Report)(doc, list, node, MISSING_STARTTAG);
}
if (node->tag == NULL)
{
TY_(Report)(doc, list, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/*
if this is the end tag for an ancestor element
then infer end tag for this element
*/
if (node->type == EndTag)
{
Bool discardIt = no;
if ( nodeIsFORM(node) )
{
BadForm( doc );
TY_(Report)(doc, list, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node );
continue;
}
for (parent = list->parent;
parent != NULL; parent = parent->parent)
{
/* Do not match across BODY to avoid infinite loop
between ParseBody and this parser,
See http://tidy.sf.net/bug/1098012. */
if (nodeIsBODY(parent))
{
discardIt = yes;
break;
}
if (node->tag == parent->tag)
{
TY_(Report)(doc, list, node, MISSING_ENDTAG_BEFORE);
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
}
if (discardIt)
{
TY_(Report)(doc, list, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
}
/* center in a dt or a dl breaks the dl list in two */
if ( nodeIsCENTER(node) )
{
if (list->content)
TY_(InsertNodeAfterElement)(list, node);
else /* trim empty dl list */
{
TY_(InsertNodeBeforeElement)(list, node);
}
/* #426885 - fix by Glenn Carroll 19 Apr 00, and
Gary Dechaines 11 Aug 00 */
/* ParseTag can destroy node, if it finds that
* this <center> is followed immediately by </center>.
* It's awkward but necessary to determine if this
* has happened.
*/
parent = node->parent;
/* and parse contents of center */
lexer->excludeBlocks = no;
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseDefList);
memory.original_node = list;
memory.reentry_node = node;
memory.reentry_state = STATE_POST_NODEISCENTER;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
}
if ( !( nodeIsDT(node) || nodeIsDD(node) || ( nodeIsDIV(node) && TY_(IsHTML5Mode)(doc) ) ) )
{
TY_(UngetToken)( doc );
if (!(node->tag->model & (CM_BLOCK | CM_INLINE)))
{
TY_(Report)(doc, list, node, TAG_NOT_ALLOWED_IN);
DEBUG_LOG_EXIT;
return NULL;
}
/* if DD appeared directly in BODY then exclude blocks */
if (!(node->tag->model & CM_INLINE) && lexer->excludeBlocks)
{
DEBUG_LOG_EXIT;
return NULL;
}
node = TY_(InferredTag)(doc, TidyTag_DD);
TY_(Report)(doc, list, node, MISSING_STARTTAG);
}
if (node->type == EndTag)
{
TY_(Report)(doc, list, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* node should be <DT> or <DD> or <DIV>*/
TY_(InsertNodeAtEnd)(list, node);
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseDefList);
memory.original_node = list;
memory.reentry_node = node;
memory.reentry_state = STATE_INITIAL;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT;
return node;
}
} break;
case STATE_POST_NODEISCENTER:
{
lexer->excludeBlocks = yes;
/* now create a new dl element,
* unless node has been blown away because the
* center was empty, as above.
*/
if (parent && parent->last == node)
{
list = TY_(InferredTag)(doc, TidyTag_DL);
TY_(InsertNodeAfterElement)(node, list);
}
state = STATE_INITIAL;
continue;
} break;
default:
break;
} /* switch */
} /* while */
TY_(Report)(doc, list, node, MISSING_ENDTAG_FOR);
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseEmpty)
* Parse empty element nodes.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseEmpty)( TidyDocImpl* doc, Node *element, GetTokenMode mode )
{
Lexer* lexer = doc->lexer;
if ( lexer->isvoyager )
{
Node *node = TY_(GetToken)( doc, mode);
if ( node )
{
if ( !(node->type == EndTag && node->tag == element->tag) )
{
/* TY_(Report)(doc, element, node, ELEMENT_NOT_EMPTY); */
TY_(UngetToken)( doc );
}
else
{
TY_(FreeNode)( doc, node );
}
}
}
return NULL;
}
/** MARK: TY_(ParseFrameSet)
* Parses the `frameset` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseFrameSet)( TidyDocImpl* doc, Node *frameset, GetTokenMode ARG_UNUSED(mode) )
{
Lexer* lexer = doc->lexer;
Node *node;
DEBUG_LOG_COUNTERS;
/*
If we're re-entering, then we need to setup from a previous state,
instead of starting fresh. We can pull what we need from the document's
stack.
*/
if ( frameset == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, because we replace it entering the loop. */
DEBUG_LOG_REENTER_WITH_NODE(node);
frameset = memory.original_node;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(frameset);
if ( cfg(doc, TidyAccessibilityCheckLevel) == 0 )
{
doc->badAccess |= BA_USING_FRAMES;
}
}
while ((node = TY_(GetToken)(doc, IgnoreWhitespace)) != NULL)
{
if (node->tag == frameset->tag && node->type == EndTag)
{
TY_(FreeNode)( doc, node);
frameset->closed = yes;
TrimSpaces(doc, frameset);
DEBUG_LOG_EXIT;
return NULL;
}
/* deal with comments etc. */
if (InsertMisc(frameset, node))
continue;
if (node->tag == NULL)
{
TY_(Report)(doc, frameset, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if (TY_(nodeIsElement)(node))
{
if (node->tag && node->tag->model & CM_HEAD)
{
MoveToHead(doc, frameset, node);
continue;
}
}
if ( nodeIsBODY(node) )
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_NOFRAMES);
TY_(Report)(doc, frameset, node, INSERTING_TAG);
}
if (node->type == StartTag && (node->tag && node->tag->model & CM_FRAMES))
{
TY_(InsertNodeAtEnd)(frameset, node);
lexer->excludeBlocks = no;
/*
* We don't really have to do anything when re-entering, except
* setting up the state when we left. No post-processing means
* this stays simple.
*/
TidyParserMemory memory = {0};
memory.identity = TY_(ParseFrameSet);
memory.original_node = frameset;
memory.reentry_node = node;
memory.mode = MixedContent;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
else if (node->type == StartEndTag && (node->tag && node->tag->model & CM_FRAMES))
{
TY_(InsertNodeAtEnd)(frameset, node);
continue;
}
/* discard unexpected tags */
/* WAI [6.5.1.4] link is being discarded outside of NOFRAME */
if ( nodeIsA(node) )
doc->badAccess |= BA_INVALID_LINK_NOFRAMES;
TY_(Report)(doc, frameset, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
}
TY_(Report)(doc, frameset, node, MISSING_ENDTAG_FOR);
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseHead)
* Parses the `head` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseHead)( TidyDocImpl* doc, Node *head, GetTokenMode ARG_UNUSED(mode) )
{
Lexer* lexer = doc->lexer;
Node *node;
int HasTitle = 0;
int HasBase = 0;
DEBUG_LOG_COUNTERS;
if ( head == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
head = memory.original_node;
HasTitle = memory.register_1;
HasBase = memory.register_2;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(head);
}
while ((node = TY_(GetToken)(doc, IgnoreWhitespace)) != NULL)
{
if (node->tag == head->tag && node->type == EndTag)
{
TY_(FreeNode)( doc, node);
head->closed = yes;
break;
}
/* find and discard multiple <head> elements */
/* find and discard <html> in <head> elements */
if ((node->tag == head->tag || nodeIsHTML(node)) && node->type == StartTag)
{
TY_(Report)(doc, head, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)(doc, node);
continue;
}
if (TY_(nodeIsText)(node))
{
/*\ Issue #132 - avoid warning for missing body tag,
* if configured to --omit-otpional-tags yes
* Issue #314 - and if --show-body-only
\*/
if (!cfgBool( doc, TidyOmitOptionalTags ) &&
!showingBodyOnly(doc) )
{
TY_(Report)(doc, head, node, TAG_NOT_ALLOWED_IN);
}
TY_(UngetToken)( doc );
break;
}
if (node->type == ProcInsTag && node->element &&
TY_(tmbstrcmp)(node->element, "xml-stylesheet") == 0)
{
TY_(Report)(doc, head, node, TAG_NOT_ALLOWED_IN);
TY_(InsertNodeBeforeElement)(TY_(FindHTML)(doc), node);
continue;
}
/* deal with comments etc. */
if (InsertMisc(head, node))
continue;
if (node->type == DocTypeTag)
{
InsertDocType(doc, head, node);
continue;
}
/* discard unknown tags */
if (node->tag == NULL)
{
TY_(Report)(doc, head, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/*
if it doesn't belong in the head then
treat as implicit end of head and deal
with as part of the body
*/
if (!(node->tag->model & CM_HEAD))
{
/* #545067 Implicit closing of head broken - warn only for XHTML input */
if ( lexer->isvoyager )
TY_(Report)(doc, head, node, TAG_NOT_ALLOWED_IN );
TY_(UngetToken)( doc );
break;
}
if (TY_(nodeIsElement)(node))
{
if ( nodeIsTITLE(node) )
{
++HasTitle;
if (HasTitle > 1)
TY_(Report)(doc, head, node,
head ?
TOO_MANY_ELEMENTS_IN : TOO_MANY_ELEMENTS);
}
else if ( nodeIsBASE(node) )
{
++HasBase;
if (HasBase > 1)
TY_(Report)(doc, head, node,
head ?
TOO_MANY_ELEMENTS_IN : TOO_MANY_ELEMENTS);
}
TY_(InsertNodeAtEnd)(head, node);
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseHead);
memory.original_node = head;
memory.reentry_node = node;
memory.register_1 = HasTitle;
memory.register_2 = HasBase;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
}
/* discard unexpected text nodes and end tags */
TY_(Report)(doc, head, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
}
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseHTML)
* Parses the `html` tag. At this point, other root-level stuff (doctype,
* comments) are already set up, and here we handle all of the complexities
* of things such as frameset documents, etc.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseHTML)( TidyDocImpl *doc, Node *html, GetTokenMode mode )
{
Node *node = NULL;
Node *head = NULL;
Node *frameset = NULL;
Node *noframes = NULL;
DEBUG_LOG_COUNTERS;
enum parserState {
STATE_INITIAL, /* This is the initial state for every parser. */
STATE_COMPLETE, /* Complete! */
STATE_PRE_BODY, /* In this state, we'll consider frames vs. body. */
STATE_PARSE_BODY, /* In this state, we can parse the body. */
STATE_PARSE_HEAD, /* In this state, we will setup head for parsing. */
STATE_PARSE_HEAD_REENTER, /* Resume here after parsing head. */
STATE_PARSE_NOFRAMES, /* In this state, we can parse noframes content. */
STATE_PARSE_NOFRAMES_REENTER, /* In this state, we can restore more state. */
STATE_PARSE_FRAMESET, /* In this state, we will parse frameset content. */
STATE_PARSE_FRAMESET_REENTER, /* We need to cleanup some things after parsing frameset. */
} state = STATE_INITIAL;
TY_(SetOptionBool)( doc, TidyXmlTags, no );
if ( html == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node;
DEBUG_LOG_REENTER_WITH_NODE(node);
html = memory.original_node;
state = memory.reentry_state;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.reentry_mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(html);
}
/*
This main loop pulls tokens from the lexer until we're out of tokens,
or until there's no more work to do.
*/
while ( state != STATE_COMPLETE )
{
if ( state == STATE_INITIAL || state == STATE_PRE_BODY )
{
node = TY_(GetToken)( doc, IgnoreWhitespace );
DEBUG_LOG_GOT_TOKEN(node);
}
switch ( state )
{
/**************************************************************
This case is all about finding a head tag and dealing with
cases were we don't, so that we can move on to parsing a head
tag.
**************************************************************/
case STATE_INITIAL:
{
/*
The only way we can possibly be here is if the lexer
had nothing to give us. Thus we'll create our own
head, and set the signal to start parsing it.
*/
if (node == NULL)
{
node = TY_(InferredTag)(doc, TidyTag_HEAD);
state = STATE_PARSE_HEAD;
continue;
}
/* We found exactly what we expected: head. */
if ( nodeIsHEAD(node) )
{
state = STATE_PARSE_HEAD;
continue;
}
/* We did not expect to find an html closing tag here! */
if (html && (node->tag == html->tag) && (node->type == EndTag))
{
TY_(Report)(doc, html, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* Find and discard multiple <html> elements. */
if (html && (node->tag == html->tag) && (node->type == StartTag))
{
TY_(Report)(doc, html, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)(doc, node);
continue;
}
/* Deal with comments, etc. */
if (InsertMisc(html, node))
continue;
/*
At this point, we didn't find a head tag, so put the
token back and create our own head tag, so we can
move on.
*/
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_HEAD);
state = STATE_PARSE_HEAD;
continue;
} break;
/**************************************************************
This case determines whether we're dealing with body or
frameset + noframes, and sets things up accordingly.
**************************************************************/
case STATE_PRE_BODY:
{
if (node == NULL )
{
if (frameset == NULL) /* Implied body. */
{
node = TY_(InferredTag)(doc, TidyTag_BODY);
state = STATE_PARSE_BODY;
} else {
state = STATE_COMPLETE;
}
continue;
}
/* Robustly handle html tags. */
if (node->tag == html->tag)
{
if (node->type != StartTag && frameset == NULL)
TY_(Report)(doc, html, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* Deal with comments, etc. */
if (InsertMisc(html, node))
continue;
/* If frameset document, coerce <body> to <noframes> */
if ( nodeIsBODY(node) )
{
if (node->type != StartTag)
{
TY_(Report)(doc, html, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if ( cfg(doc, TidyAccessibilityCheckLevel) == 0 )
{
if (frameset != NULL)
{
TY_(UngetToken)( doc );
if (noframes == NULL)
{
noframes = TY_(InferredTag)(doc, TidyTag_NOFRAMES);
TY_(InsertNodeAtEnd)(frameset, noframes);
TY_(Report)(doc, html, noframes, INSERTING_TAG);
}
else
{
if (noframes->type == StartEndTag)
noframes->type = StartTag;
}
state = STATE_PARSE_NOFRAMES;
continue;
}
}
TY_(ConstrainVersion)(doc, ~VERS_FRAMESET);
state = STATE_PARSE_BODY;
continue;
}
/* Flag an error if we see more than one frameset. */
if ( nodeIsFRAMESET(node) )
{
if (node->type != StartTag)
{
TY_(Report)(doc, html, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if (frameset != NULL)
TY_(Report)(doc, html, node, DUPLICATE_FRAMESET);
else
frameset = node;
state = STATE_PARSE_FRAMESET;
continue;
}
/* If not a frameset document coerce <noframes> to <body>. */
if ( nodeIsNOFRAMES(node) )
{
if (node->type != StartTag)
{
TY_(Report)(doc, html, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if (frameset == NULL)
{
TY_(Report)(doc, html, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
node = TY_(InferredTag)(doc, TidyTag_BODY);
state = STATE_PARSE_BODY;
continue;
}
if (noframes == NULL)
{
noframes = node;
TY_(InsertNodeAtEnd)(frameset, noframes);
state = STATE_PARSE_NOFRAMES;
}
else
{
TY_(FreeNode)( doc, node);
}
continue;
}
/* Deal with some other element that we're not expecting. */
if (TY_(nodeIsElement)(node))
{
if (node->tag && node->tag->model & CM_HEAD)
{
MoveToHead(doc, html, node);
continue;
}
/* Discard illegal frame element following a frameset. */
if ( frameset != NULL && nodeIsFRAME(node) )
{
TY_(Report)(doc, html, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)(doc, node);
continue;
}
}
TY_(UngetToken)( doc );
/* Insert other content into noframes element. */
if (frameset)
{
if (noframes == NULL)
{
noframes = TY_(InferredTag)(doc, TidyTag_NOFRAMES);
TY_(InsertNodeAtEnd)(frameset, noframes);
}
else
{
TY_(Report)(doc, html, node, NOFRAMES_CONTENT);
if (noframes->type == StartEndTag)
noframes->type = StartTag;
}
TY_(ConstrainVersion)(doc, VERS_FRAMESET);
state = STATE_PARSE_NOFRAMES;
continue;
}
node = TY_(InferredTag)(doc, TidyTag_BODY);
/* Issue #132 - disable inserting BODY tag warning
BUT only if NOT --show-body-only yes */
if (!showingBodyOnly(doc))
TY_(Report)(doc, html, node, INSERTING_TAG );
TY_(ConstrainVersion)(doc, ~VERS_FRAMESET);
state = STATE_PARSE_BODY;
continue;
} break;
/**************************************************************
In this case, we're ready to parse the head, and move on to
look for the body or body alternative.
**************************************************************/
case STATE_PARSE_HEAD:
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseHTML);
memory.mode = mode;
memory.original_node = html;
memory.reentry_node = node;
memory.reentry_mode = mode;
memory.reentry_state = STATE_PARSE_HEAD_REENTER;
TY_(InsertNodeAtEnd)(html, node);
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
} break;
case STATE_PARSE_HEAD_REENTER:
{
head = node;
state = STATE_PRE_BODY;
} break;
/**************************************************************
In this case, we can finally parse a body.
**************************************************************/
case STATE_PARSE_BODY:
{
TidyParserMemory memory = {0};
memory.identity = NULL; /* we don't need to reenter */
memory.mode = mode;
memory.original_node = html;
memory.reentry_node = NULL;
memory.reentry_mode = mode;
memory.reentry_state = STATE_COMPLETE;
TY_(InsertNodeAtEnd)(html, node);
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
} break;
/**************************************************************
In this case, we will parse noframes. If necessary, the
node is already inserted in the proper spot.
**************************************************************/
case STATE_PARSE_NOFRAMES:
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseHTML);
memory.mode = mode;
memory.original_node = html;
memory.reentry_node = frameset;
memory.reentry_mode = mode;
memory.reentry_state = STATE_PARSE_NOFRAMES_REENTER;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return noframes;
} break;
case STATE_PARSE_NOFRAMES_REENTER:
{
frameset = node;
state = STATE_PRE_BODY;
} break;
/**************************************************************
In this case, we parse the frameset, and look for noframes
content to merge later if necessary.
**************************************************************/
case STATE_PARSE_FRAMESET:
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseHTML);
memory.mode = mode;
memory.original_node = html;
memory.reentry_node = frameset;
memory.reentry_mode = mode;
memory.reentry_state = STATE_PARSE_FRAMESET_REENTER;
TY_(InsertNodeAtEnd)(html, node);
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
} break;
case (STATE_PARSE_FRAMESET_REENTER):
{
frameset = node;
/*
See if it includes a noframes element so that
we can merge subsequent noframes elements.
*/
for (node = frameset->content; node; node = node->next)
{
if ( nodeIsNOFRAMES(node) )
noframes = node;
}
state = STATE_PRE_BODY;
} break;
/**************************************************************
We really shouldn't get here, but if we do, finish nicely.
**************************************************************/
default:
{
state = STATE_COMPLETE;
}
} /* switch */
} /* while */
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseInline)
* Parse inline element nodes.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseInline)( TidyDocImpl *doc, Node *element, GetTokenMode mode )
{
Lexer* lexer = doc->lexer;
Node *node = NULL;
Node *parent = NULL;
DEBUG_LOG_COUNTERS;
if ( element == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
element = memory.original_node;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.reentry_mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(element);
if (element->tag->model & CM_EMPTY)
{
DEBUG_LOG_EXIT;
return NULL;
}
/*
ParseInline is used for some block level elements like H1 to H6
For such elements we need to insert inline emphasis tags currently
on the inline stack. For Inline elements, we normally push them
onto the inline stack provided they aren't implicit or OBJECT/APPLET.
This test is carried out in PushInline and PopInline, see istack.c
InlineDup(...) is not called for elements with a CM_MIXED (inline and
block) content model, e.g. <del> or <ins>, otherwise constructs like
<p>111<a name='foo'>222<del>333</del>444</a>555</p>
<p>111<span>222<del>333</del>444</span>555</p>
<p>111<em>222<del>333</del>444</em>555</p>
will get corrupted.
*/
if ((TY_(nodeHasCM)(element, CM_BLOCK) || nodeIsDT(element)) &&
!TY_(nodeHasCM)(element, CM_MIXED))
TY_(InlineDup)(doc, NULL);
else if (TY_(nodeHasCM)(element, CM_INLINE))
TY_(PushInline)(doc, element);
if ( nodeIsNOBR(element) )
doc->badLayout |= USING_NOBR;
else if ( nodeIsFONT(element) )
doc->badLayout |= USING_FONT;
/* Inline elements may or may not be within a preformatted element */
if (mode != Preformatted)
{
DEBUG_LOG_GET_OLD_MODE;
mode = MixedContent;
DEBUG_LOG_CHANGE_MODE;
}
}
while ((node = TY_(GetToken)(doc, mode)) != NULL)
{
/* end tag for current element */
if (node->tag == element->tag && node->type == EndTag)
{
if (element->tag->model & CM_INLINE)
TY_(PopInline)( doc, node );
TY_(FreeNode)( doc, node );
if (!(mode & Preformatted))
TrimSpaces(doc, element);
/*
if a font element wraps an anchor and nothing else
then move the font element inside the anchor since
otherwise it won't alter the anchor text color
*/
if ( nodeIsFONT(element) &&
element->content && element->content == element->last )
{
Node *child = element->content;
if ( nodeIsA(child) )
{
child->parent = element->parent;
child->next = element->next;
child->prev = element->prev;
element->next = NULL;
element->prev = NULL;
element->parent = child;
element->content = child->content;
element->last = child->last;
child->content = element;
TY_(FixNodeLinks)(child);
TY_(FixNodeLinks)(element);
}
}
element->closed = yes;
TrimSpaces( doc, element );
DEBUG_LOG_EXIT;
return NULL;
}
/* <u>...<u> map 2nd <u> to </u> if 1st is explicit */
/* (see additional conditions below) */
/* otherwise emphasis nesting is probably unintentional */
/* big, small, sub, sup have cumulative effect to leave them alone */
if ( node->type == StartTag
&& node->tag == element->tag
&& TY_(IsPushed)( doc, node )
&& !node->implicit
&& !element->implicit
&& node->tag && (node->tag->model & CM_INLINE)
&& !nodeIsA(node)
&& !nodeIsFONT(node)
&& !nodeIsBIG(node)
&& !nodeIsSMALL(node)
&& !nodeIsSUB(node)
&& !nodeIsSUP(node)
&& !nodeIsQ(node)
&& !nodeIsSPAN(node)
&& cfgBool(doc, TidyCoerceEndTags)
)
{
/* proceeds only if "node" does not have any attribute and
follows a text node not finishing with a space */
if (element->content != NULL && node->attributes == NULL
&& TY_(nodeIsText)(element->last)
&& !TY_(TextNodeEndWithSpace)(doc->lexer, element->last) )
{
TY_(Report)(doc, element, node, COERCE_TO_ENDTAG);
node->type = EndTag;
TY_(UngetToken)(doc);
continue;
}
if (node->attributes == NULL || element->attributes == NULL)
TY_(Report)(doc, element, node, NESTED_EMPHASIS);
}
else if ( TY_(IsPushed)(doc, node) && node->type == StartTag &&
nodeIsQ(node) )
{
/*\
* Issue #215 - such nested quotes are NOT a problem if HTML5, so
* only issue this warning if NOT HTML5 mode.
\*/
if (TY_(HTMLVersion)(doc) != HT50)
{
TY_(Report)(doc, element, node, NESTED_QUOTATION);
}
}
if ( TY_(nodeIsText)(node) )
{
/* only called for 1st child */
if ( element->content == NULL && !(mode & Preformatted) )
TrimSpaces( doc, element );
if ( node->start >= node->end )
{
TY_(FreeNode)( doc, node );
continue;
}
TY_(InsertNodeAtEnd)(element, node);
continue;
}
/* mixed content model so allow text */
if (InsertMisc(element, node))
continue;
/* deal with HTML tags */
if ( nodeIsHTML(node) )
{
if ( TY_(nodeIsElement)(node) )
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node );
continue;
}
/* otherwise infer end of inline element */
TY_(UngetToken)( doc );
if (!(mode & Preformatted))
TrimSpaces(doc, element);
DEBUG_LOG_EXIT;
return NULL;
}
/* within <dt> or <pre> map <p> to <br> */
if ( nodeIsP(node) &&
node->type == StartTag &&
( (mode & Preformatted) ||
nodeIsDT(element) ||
DescendantOf(element, TidyTag_DT )
)
)
{
node->tag = TY_(LookupTagDef)( TidyTag_BR );
TidyDocFree(doc, node->element);
node->element = TY_(tmbstrdup)(doc->allocator, "br");
TrimSpaces(doc, element);
TY_(InsertNodeAtEnd)(element, node);
continue;
}
/* <p> allowed within <address> in HTML 4.01 Transitional */
if ( nodeIsP(node) &&
node->type == StartTag &&
nodeIsADDRESS(element) )
{
TY_(ConstrainVersion)( doc, ~VERS_HTML40_STRICT );
TY_(InsertNodeAtEnd)(element, node);
(*node->tag->parser)( doc, node, mode );
continue;
}
/* ignore unknown and PARAM tags */
if ( node->tag == NULL || nodeIsPARAM(node) )
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node );
continue;
}
if ( nodeIsBR(node) && node->type == EndTag )
node->type = StartTag;
if ( node->type == EndTag )
{
/* coerce </br> to <br> */
if ( nodeIsBR(node) )
node->type = StartTag;
else if ( nodeIsP(node) )
{
/* coerce unmatched </p> to <br><br> */
if ( !DescendantOf(element, TidyTag_P) )
{
TY_(CoerceNode)(doc, node, TidyTag_BR, no, no);
TrimSpaces( doc, element );
TY_(InsertNodeAtEnd)( element, node );
node = TY_(InferredTag)(doc, TidyTag_BR);
TY_(InsertNodeAtEnd)( element, node ); /* todo: check this */
continue;
}
}
else if ( TY_(nodeHasCM)(node, CM_INLINE)
&& !nodeIsA(node)
&& !TY_(nodeHasCM)(node, CM_OBJECT)
&& TY_(nodeHasCM)(element, CM_INLINE) )
{
/* allow any inline end tag to end current element */
/* http://tidy.sf.net/issue/1426419 */
/* but, like the browser, retain an earlier inline element.
This is implemented by setting the lexer into a mode
where it gets tokens from the inline stack rather than
from the input stream. Check if the scenerio fits. */
if ( !nodeIsA(element)
&& (node->tag != element->tag)
&& TY_(IsPushed)( doc, node )
&& TY_(IsPushed)( doc, element ) )
{
/* we have something like
<b>bold <i>bold and italic</b> italics</i> */
if ( TY_(SwitchInline)( doc, element, node ) )
{
TY_(Report)(doc, element, node, NON_MATCHING_ENDTAG);
TY_(UngetToken)( doc ); /* put this back */
TY_(InlineDup1)( doc, NULL, element ); /* dupe the <i>, after </b> */
if (!(mode & Preformatted))
TrimSpaces( doc, element );
DEBUG_LOG_EXIT;
return NULL; /* close <i>, but will re-open it, after </b> */
}
}
TY_(PopInline)( doc, element );
if ( !nodeIsA(element) )
{
if ( nodeIsA(node) && node->tag != element->tag )
{
TY_(Report)(doc, element, node, MISSING_ENDTAG_BEFORE );
TY_(UngetToken)( doc );
}
else
{
TY_(Report)(doc, element, node, NON_MATCHING_ENDTAG);
TY_(FreeNode)( doc, node);
}
if (!(mode & Preformatted))
TrimSpaces(doc, element);
DEBUG_LOG_EXIT;
return NULL;
}
/* if parent is <a> then discard unexpected inline end tag */
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
} /* special case </tr> etc. for stuff moved in front of table */
else if ( lexer->exiled
&& (TY_(nodeHasCM)(node, CM_TABLE) || nodeIsTABLE(node)) )
{
TY_(UngetToken)( doc );
TrimSpaces(doc, element);
DEBUG_LOG_EXIT;
return NULL;
}
}
/* allow any header tag to end current header */
if ( TY_(nodeHasCM)(node, CM_HEADING) && TY_(nodeHasCM)(element, CM_HEADING) )
{
if ( node->tag == element->tag )
{
TY_(Report)(doc, element, node, NON_MATCHING_ENDTAG );
TY_(FreeNode)( doc, node);
}
else
{
TY_(Report)(doc, element, node, MISSING_ENDTAG_BEFORE );
TY_(UngetToken)( doc );
}
if (!(mode & Preformatted))
TrimSpaces(doc, element);
DEBUG_LOG_EXIT;
return NULL;
}
/*
an <A> tag to ends any open <A> element
but <A href=...> is mapped to </A><A href=...>
*/
/* #427827 - fix by Randy Waki and Bjoern Hoehrmann 23 Aug 00 */
/* if (node->tag == doc->tags.tag_a && !node->implicit && TY_(IsPushed)(doc, node)) */
if ( nodeIsA(node) && !node->implicit &&
(nodeIsA(element) || DescendantOf(element, TidyTag_A)) )
{
/* coerce <a> to </a> unless it has some attributes */
/* #427827 - fix by Randy Waki and Bjoern Hoehrmann 23 Aug 00 */
/* other fixes by Dave Raggett */
/* if (node->attributes == NULL) */
if (node->type != EndTag && node->attributes == NULL
&& cfgBool(doc, TidyCoerceEndTags) )
{
node->type = EndTag;
TY_(Report)(doc, element, node, COERCE_TO_ENDTAG);
/* TY_(PopInline)( doc, node ); */
TY_(UngetToken)( doc );
continue;
}
TY_(UngetToken)( doc );
TY_(Report)(doc, element, node, MISSING_ENDTAG_BEFORE);
/* TY_(PopInline)( doc, element ); */
if (!(mode & Preformatted))
TrimSpaces(doc, element);
DEBUG_LOG_EXIT;
return NULL;
}
if (element->tag->model & CM_HEADING)
{
if ( nodeIsCENTER(node) || nodeIsDIV(node) )
{
if (!TY_(nodeIsElement)(node))
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
TY_(Report)(doc, element, node, TAG_NOT_ALLOWED_IN);
/* insert center as parent if heading is empty */
if (element->content == NULL)
{
InsertNodeAsParent(element, node);
continue;
}
/* split heading and make center parent of 2nd part */
TY_(InsertNodeAfterElement)(element, node);
if (!(mode & Preformatted))
TrimSpaces(doc, element);
element = TY_(CloneNode)( doc, element );
TY_(InsertNodeAtEnd)(node, element);
continue;
}
if ( nodeIsHR(node) )
{
if ( !TY_(nodeIsElement)(node) )
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
TY_(Report)(doc, element, node, TAG_NOT_ALLOWED_IN);
/* insert hr before heading if heading is empty */
if (element->content == NULL)
{
TY_(InsertNodeBeforeElement)(element, node);
continue;
}
/* split heading and insert hr before 2nd part */
TY_(InsertNodeAfterElement)(element, node);
if (!(mode & Preformatted))
TrimSpaces(doc, element);
element = TY_(CloneNode)( doc, element );
TY_(InsertNodeAfterElement)(node, element);
continue;
}
}
if ( nodeIsDT(element) )
{
if ( nodeIsHR(node) )
{
Node *dd;
if ( !TY_(nodeIsElement)(node) )
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
TY_(Report)(doc, element, node, TAG_NOT_ALLOWED_IN);
dd = TY_(InferredTag)(doc, TidyTag_DD);
/* insert hr within dd before dt if dt is empty */
if (element->content == NULL)
{
TY_(InsertNodeBeforeElement)(element, dd);
TY_(InsertNodeAtEnd)(dd, node);
continue;
}
/* split dt and insert hr within dd before 2nd part */
TY_(InsertNodeAfterElement)(element, dd);
TY_(InsertNodeAtEnd)(dd, node);
if (!(mode & Preformatted))
TrimSpaces(doc, element);
element = TY_(CloneNode)( doc, element );
TY_(InsertNodeAfterElement)(dd, element);
continue;
}
}
/*
if this is the end tag for an ancestor element
then infer end tag for this element
*/
if (node->type == EndTag)
{
for (parent = element->parent;
parent != NULL; parent = parent->parent)
{
if (node->tag == parent->tag)
{
if (!(element->tag->model & CM_OPT) && !element->implicit)
TY_(Report)(doc, element, node, MISSING_ENDTAG_BEFORE);
if( TY_(IsPushedLast)( doc, element, node ) )
TY_(PopInline)( doc, element );
TY_(UngetToken)( doc );
if (!(mode & Preformatted))
TrimSpaces(doc, element);
DEBUG_LOG_EXIT;
return NULL;
}
}
}
/*\
* block level tags end this element
* Issue #333 - There seems an exception if the element is a 'span',
* and the node just collected is a 'meta'. The 'meta' can not have
* CM_INLINE added, nor can the 'span' have CM_MIXED added without
* big consequences.
* There may be other exceptions to be added...
\*/
if (!(node->tag->model & CM_INLINE) &&
!(element->tag->model & CM_MIXED) &&
!(nodeIsSPAN(element) && nodeIsMETA(node)) )
{
if ( !TY_(nodeIsElement)(node) )
{
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* HTML5 */
if (nodeIsDATALIST(element)) {
TY_(ConstrainVersion)( doc, ~VERS_HTML5 );
} else
if (!(element->tag->model & CM_OPT))
TY_(Report)(doc, element, node, MISSING_ENDTAG_BEFORE);
if (node->tag->model & CM_HEAD && !(node->tag->model & CM_BLOCK))
{
MoveToHead(doc, element, node);
continue;
}
/*
prevent anchors from propagating into block tags
except for headings h1 to h6
*/
if ( nodeIsA(element) )
{
if (node->tag && !(node->tag->model & CM_HEADING))
TY_(PopInline)( doc, element );
else if (!(element->content))
{
TY_(DiscardElement)( doc, element );
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
}
TY_(UngetToken)( doc );
if (!(mode & Preformatted))
TrimSpaces(doc, element);
DEBUG_LOG_EXIT;
return NULL;
}
/* parse inline element */
if (TY_(nodeIsElement)(node))
{
if (node->implicit)
TY_(Report)(doc, element, node, INSERTING_TAG);
/* trim white space before <br> */
if ( nodeIsBR(node) )
TrimSpaces(doc, element);
TY_(InsertNodeAtEnd)(element, node);
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseInline);
memory.original_node = element;
memory.reentry_node = node;
memory.mode = mode;
memory.reentry_mode = mode;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
}
/* discard unexpected tags */
TY_(Report)(doc, element, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node );
continue;
}
if (!(element->tag->model & CM_OPT))
TY_(Report)(doc, element, node, MISSING_ENDTAG_FOR);
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseList)
* Parses list tags.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseList)( TidyDocImpl* doc, Node *list, GetTokenMode ARG_UNUSED(mode) )
{
Lexer* lexer = doc->lexer;
Node *node = NULL;
Node *parent = NULL;
Node *lastli = NULL;;
Bool wasblock = no;
Bool nodeisOL = nodeIsOL(list);
DEBUG_LOG_COUNTERS;
if ( list == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
list = memory.original_node;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(list);
if (list->tag->model & CM_EMPTY)
{
DEBUG_LOG_EXIT;
return NULL;
}
}
lexer->insert = NULL; /* defer implicit inline start tags */
while ((node = TY_(GetToken)( doc, IgnoreWhitespace)) != NULL)
{
Bool foundLI = no;
if (node->tag == list->tag && node->type == EndTag)
{
TY_(FreeNode)( doc, node);
list->closed = yes;
DEBUG_LOG_EXIT;
return NULL;
}
/* deal with comments etc. */
if (InsertMisc(list, node))
continue;
if (node->type != TextNode && node->tag == NULL)
{
TY_(Report)(doc, list, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if (lexer && (node->type == TextNode))
{
uint ch, ix = node->start;
/* Issue #572 - Skip whitespace. */
while (ix < node->end && (ch = (lexer->lexbuf[ix] & 0xff))
&& (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'))
++ix;
if (ix >= node->end)
{
/* Issue #572 - Discard if ALL whitespace. */
TY_(FreeNode)(doc, node);
continue;
}
}
/*
if this is the end tag for an ancestor element
then infer end tag for this element
*/
if (node->type == EndTag)
{
if ( nodeIsFORM(node) )
{
BadForm( doc );
TY_(Report)(doc, list, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node );
continue;
}
if (TY_(nodeHasCM)(node,CM_INLINE))
{
TY_(Report)(doc, list, node, DISCARDING_UNEXPECTED);
TY_(PopInline)( doc, node );
TY_(FreeNode)( doc, node);
continue;
}
for ( parent = list->parent;
parent != NULL; parent = parent->parent )
{
/* Do not match across BODY to avoid infinite loop
between ParseBody and this parser,
See http://tidy.sf.net/bug/1053626. */
if (nodeIsBODY(parent))
break;
if (node->tag == parent->tag)
{
TY_(Report)(doc, list, node, MISSING_ENDTAG_BEFORE);
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
}
TY_(Report)(doc, list, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if ( !nodeIsLI(node) && nodeisOL )
{
/* Issue #572 - A <ol><li> can have nested <ol> elements */
foundLI = FindLastLI(list, &lastli); /* find last <li> */
}
if ( nodeIsLI(node) || (TY_(IsHTML5Mode)(doc) && !foundLI) )
{
/* node is <LI> OR
Issue #396 - A <ul> can have Zero or more <li> elements
*/
TY_(InsertNodeAtEnd)(list,node);
}
else
{
TY_(UngetToken)( doc );
if (TY_(nodeHasCM)(node,CM_BLOCK) && lexer->excludeBlocks)
{
TY_(Report)(doc, list, node, MISSING_ENDTAG_BEFORE);
DEBUG_LOG_EXIT;
return NULL;
}
/* http://tidy.sf.net/issue/1316307 */
/* In exiled mode, return so table processing can continue. */
else if ( lexer->exiled
&& (TY_(nodeHasCM)(node, CM_TABLE|CM_ROWGRP|CM_ROW)
|| nodeIsTABLE(node)) )
{
DEBUG_LOG_EXIT;
return NULL;
}
/* http://tidy.sf.net/issue/836462
If "list" is an unordered list, insert the next tag within
the last <li> to preserve the numbering to match the visual
rendering of most browsers. */
if ( nodeIsOL(list) && FindLastLI(list, &lastli) )
{
/* Create a node for error reporting */
node = TY_(InferredTag)(doc, TidyTag_LI);
TY_(Report)(doc, list, node, MISSING_STARTTAG );
TY_(FreeNode)( doc, node);
node = lastli;
}
else
{
/* Add an inferred <li> */
wasblock = TY_(nodeHasCM)(node,CM_BLOCK);
node = TY_(InferredTag)(doc, TidyTag_LI);
/* Add "display: inline" to avoid a blank line after <li> with
Internet Explorer. See http://tidy.sf.net/issue/836462 */
TY_(AddStyleProperty)( doc, node,
wasblock
? "list-style: none; display: inline"
: "list-style: none"
);
TY_(Report)(doc, list, node, MISSING_STARTTAG );
TY_(InsertNodeAtEnd)(list,node);
}
}
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseList);
memory.original_node = list;
memory.reentry_node = node;
memory.mode = IgnoreWhitespace;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
}
TY_(Report)(doc, list, node, MISSING_ENDTAG_FOR);
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseNamespace)
* Act as a generic XML (sub)tree parser: collect each node and add it
* to the DOM, without any further validation. It's useful for tags that
* have XML-like content, such as `svg` and `math`.
*
* @note Perhaps this is poorly named, as we're not parsing the namespace
* of a particular tag, but a tag with XML-like content.
*
* @todo Add schema- or other-hierarchy-definition-based validation
* of the subtree here.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseNamespace)( TidyDocImpl* doc, Node *basenode, GetTokenMode mode )
{
Lexer* lexer = doc->lexer;
Node *node;
Node *parent = basenode;
uint istackbase;
AttVal* av; /* #130 MathML attr and entity fix! */
/* a la <table>: defer popping elements off the inline stack */
TY_(DeferDup)( doc );
istackbase = lexer->istackbase;
lexer->istackbase = lexer->istacksize;
mode = OtherNamespace; /* Preformatted; IgnoreWhitespace; */
while ((node = TY_(GetToken)(doc, mode)) != NULL)
{
/*
fix check to skip action in InsertMisc for regular/empty
nodes, which we don't want here...
The way we do it here is by checking and processing everything
and only what remains goes into InsertMisc()
*/
/* is this a close tag? And does it match the current parent node? */
if (node->type == EndTag)
{
/*
to prevent end tags flowing from one 'alternate namespace' we
check this in two phases: first we check if the tag is a
descendant of the current node, and when it is, we check whether
it is the end tag for a node /within/ or /outside/ the basenode.
*/
Bool outside;
Node *mp = FindMatchingDescendant(parent, node, basenode, &outside);
if (mp != NULL)
{
/*
when mp != parent as we might expect,
infer end tags until we 'hit' the matched
parent or the basenode
*/
Node *n;
for (n = parent;
n != NULL && n != basenode->parent && n != mp;
n = n->parent)
{
/* n->implicit = yes; */
n->closed = yes;
TY_(Report)(doc, n->parent, n, MISSING_ENDTAG_BEFORE);
}
/* Issue #369 - Since 'assert' is DEBUG only, and there are
simple cases where these can be fired, removing them
pending feedback from the original author!
assert(outside == no ? n == mp : 1);
assert(outside == yes ? n == basenode->parent : 1);
=================================================== */
if (outside == no)
{
/* EndTag for a node within the basenode subtree. Roll on... */
if (n)
n->closed = yes;
TY_(FreeNode)(doc, node);
node = n;
parent = node ? node->parent : NULL;
}
else
{
/* EndTag for a node outside the basenode subtree: let the caller handle that. */
TY_(UngetToken)( doc );
node = basenode;
parent = node->parent;
}
/* when we've arrived at the end-node for the base node, it's quitting time */
if (node == basenode)
{
lexer->istackbase = istackbase;
assert(basenode && basenode->closed == yes);
return NULL;
}
}
else
{
/* unmatched close tag: report an error and discard */
/* TY_(Report)(doc, parent, node, NON_MATCHING_ENDTAG); Issue #308 - Seems wrong warning! */
TY_(Report)(doc, parent, node, DISCARDING_UNEXPECTED);
assert(parent);
/* assert(parent->tag != node->tag); Issue #308 - Seems would always be true! */
TY_(FreeNode)( doc, node); /* Issue #308 - Discard unexpected end tag memory */
}
}
else if (node->type == StartTag)
{
/* #130 MathML attr and entity fix!
care if it has attributes, and 'accidently' any of those attributes match known */
for ( av = node->attributes; av; av = av->next )
{
av->dict = 0; /* does something need to be freed? */
}
/* add another child to the current parent */
TY_(InsertNodeAtEnd)(parent, node);
parent = node;
}
else
{
/* #130 MathML attr and entity fix!
care if it has attributes, and 'accidently' any of those attributes match known */
for ( av = node->attributes; av; av = av->next )
{
av->dict = 0; /* does something need to be freed? */
}
TY_(InsertNodeAtEnd)(parent, node);
}
}
TY_(Report)(doc, basenode->parent, basenode, MISSING_ENDTAG_FOR);
return NULL;
}
/** MARK: TY_(ParseNoFrames)
* Parses the `noframes` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseNoFrames)( TidyDocImpl* doc, Node *noframes, GetTokenMode mode )
{
Lexer* lexer = doc->lexer;
Node *node = NULL;
Bool body_seen = no;
DEBUG_LOG_COUNTERS;
enum parserState {
STATE_INITIAL, /* This is the initial state for every parser. */
STATE_POST_NODEISBODY, /* To-do after re-entering after checks. */
STATE_COMPLETE, /* Done with the switch. */
} state = STATE_INITIAL;
/*
If we're re-entering, then we need to setup from a previous state,
instead of starting fresh. We can pull what we need from the document's
stack.
*/
if ( noframes == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, because we replace it entering the loop anyway.*/
DEBUG_LOG_REENTER_WITH_NODE(node);
noframes = memory.original_node;
state = memory.reentry_state;
body_seen = memory.register_1;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(noframes);
if ( cfg(doc, TidyAccessibilityCheckLevel) == 0 )
{
doc->badAccess |= BA_USING_NOFRAMES;
}
}
mode = IgnoreWhitespace;
while ( state != STATE_COMPLETE )
{
if ( state == STATE_INITIAL )
{
node = TY_(GetToken)(doc, mode);
DEBUG_LOG_GOT_TOKEN(node);
}
switch ( state )
{
case STATE_INITIAL:
{
if ( node == NULL )
{
state = STATE_COMPLETE;
continue;
}
if ( node->tag == noframes->tag && node->type == EndTag )
{
TY_(FreeNode)( doc, node);
noframes->closed = yes;
TrimSpaces(doc, noframes);
DEBUG_LOG_EXIT;
return NULL;
}
if ( nodeIsFRAME(node) || nodeIsFRAMESET(node) )
{
TrimSpaces(doc, noframes);
if (node->type == EndTag)
{
TY_(Report)(doc, noframes, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node); /* Throw it away */
}
else
{
TY_(Report)(doc, noframes, node, MISSING_ENDTAG_BEFORE);
TY_(UngetToken)( doc );
}
DEBUG_LOG_EXIT;
return NULL;
}
if ( nodeIsHTML(node) )
{
if (TY_(nodeIsElement)(node))
TY_(Report)(doc, noframes, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* deal with comments etc. */
if (InsertMisc(noframes, node))
continue;
if ( nodeIsBODY(node) && node->type == StartTag )
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseNoFrames);
memory.original_node = noframes;
memory.reentry_node = node;
memory.reentry_state = STATE_POST_NODEISBODY;
memory.register_1 = lexer->seenEndBody;
memory.mode = IgnoreWhitespace;
TY_(InsertNodeAtEnd)(noframes, node);
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
/* implicit body element inferred */
if (TY_(nodeIsText)(node) || (node->tag && node->type != EndTag))
{
Node *body = TY_(FindBody)( doc );
if ( body || lexer->seenEndBody )
{
if ( body == NULL )
{
TY_(Report)(doc, noframes, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if ( TY_(nodeIsText)(node) )
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_P);
TY_(Report)(doc, noframes, node, CONTENT_AFTER_BODY );
}
TY_(InsertNodeAtEnd)( body, node );
}
else
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_BODY);
if ( cfgBool(doc, TidyXmlOut) )
TY_(Report)(doc, noframes, node, INSERTING_TAG);
TY_(InsertNodeAtEnd)( noframes, node );
}
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseNoFrames);
memory.original_node = noframes;
memory.reentry_node = node;
memory.mode = IgnoreWhitespace; /*MixedContent*/
memory.reentry_state = STATE_INITIAL;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
}
/* discard unexpected end tags */
TY_(Report)(doc, noframes, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
} break;
case STATE_POST_NODEISBODY:
{
/* fix for bug http://tidy.sf.net/bug/887259 */
if (body_seen && TY_(FindBody)(doc) != node)
{
TY_(CoerceNode)(doc, node, TidyTag_DIV, no, no);
MoveNodeToBody(doc, node);
}
state = STATE_INITIAL;
continue;
} break;
default:
break;
} /* switch */
} /* while */
TY_(Report)(doc, noframes, node, MISSING_ENDTAG_FOR);
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseOptGroup)
* Parses the `optgroup` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseOptGroup)( TidyDocImpl* doc, Node *field, GetTokenMode ARG_UNUSED(mode) )
{
Lexer* lexer = doc->lexer;
Node *node;
DEBUG_LOG_COUNTERS;
if ( field == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
field = memory.original_node;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(field);
}
lexer->insert = NULL; /* defer implicit inline start tags */
while ((node = TY_(GetToken)(doc, IgnoreWhitespace)) != NULL)
{
if (node->tag == field->tag && node->type == EndTag)
{
TY_(FreeNode)( doc, node);
field->closed = yes;
TrimSpaces(doc, field);
DEBUG_LOG_EXIT;
return NULL;
}
/* deal with comments etc. */
if (InsertMisc(field, node))
continue;
if ( node->type == StartTag &&
(nodeIsOPTION(node) || nodeIsOPTGROUP(node)) )
{
TidyParserMemory memory = {0};
if ( nodeIsOPTGROUP(node) )
TY_(Report)(doc, field, node, CANT_BE_NESTED);
TY_(InsertNodeAtEnd)(field, node);
memory.identity = TY_(ParseOptGroup);
memory.original_node = field;
memory.reentry_node = node;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
/* discard unexpected tags */
TY_(Report)(doc, field, node, DISCARDING_UNEXPECTED );
TY_(FreeNode)( doc, node);
}
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParsePre)
* Parses the `pre` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParsePre)( TidyDocImpl* doc, Node *pre, GetTokenMode ARG_UNUSED(mode) )
{
Node *node = NULL;
DEBUG_LOG_COUNTERS;
enum parserState {
STATE_INITIAL, /* This is the initial state for every parser. */
STATE_RENTRY_ACTION, /* To-do after re-entering after checks. */
STATE_COMPLETE, /* Done with the switch. */
} state = STATE_INITIAL;
if ( pre == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
pre = memory.original_node;
state = memory.reentry_state;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(pre);
if (pre->tag->model & CM_EMPTY)
{
DEBUG_LOG_EXIT;
return NULL;
}
}
TY_(InlineDup)( doc, NULL ); /* tell lexer to insert inlines if needed */
while ( state != STATE_COMPLETE )
{
if ( state == STATE_INITIAL )
node = TY_(GetToken)(doc, Preformatted);
switch ( state )
{
case STATE_INITIAL:
{
if ( node == NULL )
{
state = STATE_COMPLETE;
continue;
}
if ( node->type == EndTag &&
(node->tag == pre->tag || DescendantOf(pre, TagId(node))) )
{
if (nodeIsBODY(node) || nodeIsHTML(node))
{
TY_(Report)(doc, pre, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)(doc, node);
continue;
}
if (node->tag == pre->tag)
{
TY_(FreeNode)(doc, node);
}
else
{
TY_(Report)(doc, pre, node, MISSING_ENDTAG_BEFORE );
TY_(UngetToken)( doc );
}
pre->closed = yes;
TrimSpaces(doc, pre);
DEBUG_LOG_EXIT;
return NULL;
}
if (TY_(nodeIsText)(node))
{
TY_(InsertNodeAtEnd)(pre, node);
continue;
}
/* deal with comments etc. */
if (InsertMisc(pre, node))
continue;
if (node->tag == NULL)
{
TY_(Report)(doc, pre, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)(doc, node);
continue;
}
/* strip unexpected tags */
if ( !PreContent(doc, node) )
{
/* fix for http://tidy.sf.net/bug/772205 */
if (node->type == EndTag)
{
/* http://tidy.sf.net/issue/1590220 */
if ( doc->lexer->exiled
&& (TY_(nodeHasCM)(node, CM_TABLE) || nodeIsTABLE(node)) )
{
TY_(UngetToken)(doc);
TrimSpaces(doc, pre);
DEBUG_LOG_EXIT;
return NULL;
}
TY_(Report)(doc, pre, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)(doc, node);
continue;
}
/* http://tidy.sf.net/issue/1590220 */
else if (TY_(nodeHasCM)(node, CM_TABLE|CM_ROW)
|| nodeIsTABLE(node) )
{
if (!doc->lexer->exiled)
/* No missing close warning if exiled. */
TY_(Report)(doc, pre, node, MISSING_ENDTAG_BEFORE);
TY_(UngetToken)(doc);
DEBUG_LOG_EXIT;
return NULL;
}
/*
This is basically what Tidy 04 August 2000 did and far more accurate
with respect to browser behaivour than the code commented out above.
Tidy could try to propagate the <pre> into each disallowed child where
<pre> is allowed in order to replicate some browsers behaivour, but
there are a lot of exceptions, e.g. Internet Explorer does not propagate
<pre> into table cells while Mozilla does. Opera 6 never propagates
<pre> into blocklevel elements while Opera 7 behaves much like Mozilla.
Tidy behaves thus mostly like Opera 6 except for nested <pre> elements
which are handled like Mozilla takes them (Opera6 closes all <pre> after
the first </pre>).
There are similar issues like replacing <p> in <pre> with <br>, for
example
<pre>...<p>...</pre> (Input)
<pre>...<br>...</pre> (Tidy)
<pre>...<br>...</pre> (Opera 7 and Internet Explorer)
<pre>...<br><br>...</pre> (Opera 6 and Mozilla)
<pre>...<p>...</p>...</pre> (Input)
<pre>...<br>......</pre> (Tidy, BUG!)
<pre>...<br>...<br>...</pre> (Internet Explorer)
<pre>...<br><br>...<br><br>...</pre> (Mozilla, Opera 6)
<pre>...<br>...<br><br>...</pre> (Opera 7)
or something similar, they could also be closing the <pre> and propagate
the <pre> into the newly opened <p>.
Todo: IMG, OBJECT, APPLET, BIG, SMALL, SUB, SUP, FONT, and BASEFONT are
disallowed in <pre>, Tidy neither detects this nor does it perform any
cleanup operation. Tidy should at least issue a warning if it encounters
such constructs.
Todo: discarding </p> is abviously a bug, it should be replaced by <br>.
*/
TY_(InsertNodeAfterElement)(pre, node);
TY_(Report)(doc, pre, node, MISSING_ENDTAG_BEFORE);
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParsePre);
memory.original_node = pre;
memory.reentry_node = node;
memory.reentry_state = STATE_RENTRY_ACTION;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
}
if ( nodeIsP(node) )
{
if (node->type == StartTag)
{
TY_(Report)(doc, pre, node, USING_BR_INPLACE_OF);
/* trim white space before <p> in <pre>*/
TrimSpaces(doc, pre);
/* coerce both <p> and </p> to <br> */
TY_(CoerceNode)(doc, node, TidyTag_BR, no, no);
TY_(FreeAttrs)( doc, node ); /* discard align attribute etc. */
TY_(InsertNodeAtEnd)( pre, node );
}
else
{
TY_(Report)(doc, pre, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
}
continue;
}
if ( TY_(nodeIsElement)(node) )
{
/* trim white space before <br> */
if ( nodeIsBR(node) )
TrimSpaces(doc, pre);
TY_(InsertNodeAtEnd)(pre, node);
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParsePre);
memory.original_node = pre;
memory.reentry_node = node;
memory.reentry_state = STATE_INITIAL;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
}
/* discard unexpected tags */
TY_(Report)(doc, pre, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
} break;
case STATE_RENTRY_ACTION:
{
Node* newnode = TY_(InferredTag)(doc, TidyTag_PRE);
TY_(Report)(doc, pre, newnode, INSERTING_TAG);
pre = newnode;
TY_(InsertNodeAfterElement)(node, pre);
state = STATE_INITIAL;
continue;
} break;
default:
break;
} /* switch */
} /* while */
TY_(Report)(doc, pre, node, MISSING_ENDTAG_FOR);
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseRow)
* Parses the `row` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseRow)( TidyDocImpl* doc, Node *row, GetTokenMode ARG_UNUSED(mode) )
{
Lexer* lexer = doc->lexer;
Node *node = NULL;
Bool exclude_state = no;
DEBUG_LOG_COUNTERS;
enum parserState {
STATE_INITIAL, /* This is the initial state for every parser. */
STATE_POST_NOT_ENDTAG, /* To-do after re-entering after !EndTag checks. */
STATE_POST_TD_TH, /* To-do after re-entering after TD/TH checks. */
STATE_COMPLETE, /* Done with the switch. */
} state = STATE_INITIAL;
if ( row == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
row = memory.original_node;
state = memory.reentry_state;
exclude_state = memory.register_1;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(row);
if (row->tag->model & CM_EMPTY)
return NULL;
}
while ( state != STATE_COMPLETE )
{
if ( state == STATE_INITIAL )
{
node = TY_(GetToken)( doc, IgnoreWhitespace );
DEBUG_LOG_GOT_TOKEN(node);
}
switch (state)
{
case STATE_INITIAL:
{
if ( node == NULL)
{
state = STATE_COMPLETE;
continue;
}
if (node->tag == row->tag)
{
if (node->type == EndTag)
{
TY_(FreeNode)( doc, node);
row->closed = yes;
FixEmptyRow( doc, row);
DEBUG_LOG_EXIT;
return NULL;
}
/* New row start implies end of current row */
TY_(UngetToken)( doc );
FixEmptyRow( doc, row);
DEBUG_LOG_EXIT;
return NULL;
}
/*
if this is the end tag for an ancestor element
then infer end tag for this element
*/
if ( node->type == EndTag )
{
if ( (TY_(nodeHasCM)(node, CM_HTML|CM_TABLE) || nodeIsTABLE(node))
&& DescendantOf(row, TagId(node)) )
{
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
if ( nodeIsFORM(node) || TY_(nodeHasCM)(node, CM_BLOCK|CM_INLINE) )
{
if ( nodeIsFORM(node) )
BadForm( doc );
TY_(Report)(doc, row, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if ( nodeIsTD(node) || nodeIsTH(node) )
{
TY_(Report)(doc, row, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
}
/* deal with comments etc. */
if (InsertMisc(row, node))
continue;
/* discard unknown tags */
if (node->tag == NULL && node->type != TextNode)
{
TY_(Report)(doc, row, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* discard unexpected <table> element */
if ( nodeIsTABLE(node) )
{
TY_(Report)(doc, row, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* THEAD, TFOOT or TBODY */
if ( TY_(nodeHasCM)(node, CM_ROWGRP) )
{
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
if (node->type == EndTag)
{
TY_(Report)(doc, row, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/*
if text or inline or block move before table
if head content move to head
*/
if (node->type != EndTag)
{
if ( nodeIsFORM(node) )
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_TD);
TY_(Report)(doc, row, node, MISSING_STARTTAG);
}
else if ( TY_(nodeIsText)(node)
|| TY_(nodeHasCM)(node, CM_BLOCK | CM_INLINE) )
{
MoveBeforeTable( doc, row, node );
TY_(Report)(doc, row, node, TAG_NOT_ALLOWED_IN);
lexer->exiled = yes;
exclude_state = lexer->excludeBlocks;
lexer->excludeBlocks = no;
if (node->type != TextNode)
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseRow);
memory.original_node = row;
memory.reentry_node = node;
memory.reentry_state = STATE_POST_NOT_ENDTAG;
memory.register_1 = exclude_state;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
lexer->exiled = no;
lexer->excludeBlocks = exclude_state;
continue;
}
else if (node->tag->model & CM_HEAD)
{
TY_(Report)(doc, row, node, TAG_NOT_ALLOWED_IN);
MoveToHead( doc, row, node);
continue;
}
}
if ( !(nodeIsTD(node) || nodeIsTH(node)) )
{
TY_(Report)(doc, row, node, TAG_NOT_ALLOWED_IN);
TY_(FreeNode)( doc, node);
continue;
}
/* node should be <TD> or <TH> */
TY_(InsertNodeAtEnd)(row, node);
exclude_state = lexer->excludeBlocks;
lexer->excludeBlocks = no;
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseRow);
memory.original_node = row;
memory.reentry_node = node;
memory.reentry_state = STATE_POST_TD_TH;
memory.register_1 = exclude_state;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
} break;
case STATE_POST_NOT_ENDTAG:
{
lexer->exiled = no;
lexer->excludeBlocks = exclude_state; /* capture this in stack. */
state = STATE_INITIAL;
continue;
} break;
case STATE_POST_TD_TH:
{
lexer->excludeBlocks = exclude_state; /* capture this in stack. */
/* pop inline stack */
while ( lexer->istacksize > lexer->istackbase )
TY_(PopInline)( doc, NULL );
state = STATE_INITIAL;
continue;
} break;
default:
break;
} /* switch */
} /* while */
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseRowGroup)
* Parses the `rowgroup` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseRowGroup)( TidyDocImpl* doc, Node *rowgroup, GetTokenMode ARG_UNUSED(mode) )
{
Lexer* lexer = doc->lexer;
Node *node = NULL;
Node *parent = NULL;
DEBUG_LOG_COUNTERS;
enum parserState {
STATE_INITIAL, /* This is the initial state for every parser. */
STATE_POST_NOT_TEXTNODE, /* To-do after re-entering after checks. */
STATE_COMPLETE, /* Done with the switch. */
} state = STATE_INITIAL;
if ( rowgroup == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
rowgroup = memory.original_node;
state = memory.reentry_state;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(rowgroup);
if (rowgroup->tag->model & CM_EMPTY)
{
DEBUG_LOG_EXIT;
return NULL;
}
}
while ( state != STATE_COMPLETE )
{
if ( state == STATE_INITIAL )
node = TY_(GetToken)(doc, IgnoreWhitespace);
switch (state)
{
case STATE_INITIAL:
{
TidyParserMemory memory = {0};
if (node == NULL)
{
state = STATE_COMPLETE;
continue;
}
if (node->tag == rowgroup->tag)
{
if (node->type == EndTag)
{
rowgroup->closed = yes;
TY_(FreeNode)( doc, node);
DEBUG_LOG_EXIT;
return NULL;
}
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
/* if </table> infer end tag */
if ( nodeIsTABLE(node) && node->type == EndTag )
{
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
/* deal with comments etc. */
if (InsertMisc(rowgroup, node))
continue;
/* discard unknown tags */
if (node->tag == NULL && node->type != TextNode)
{
TY_(Report)(doc, rowgroup, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/*
if TD or TH then infer <TR>
if text or inline or block move before table
if head content move to head
*/
if (node->type != EndTag)
{
if ( nodeIsTD(node) || nodeIsTH(node) )
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_TR);
TY_(Report)(doc, rowgroup, node, MISSING_STARTTAG);
}
else if ( TY_(nodeIsText)(node)
|| TY_(nodeHasCM)(node, CM_BLOCK|CM_INLINE) )
{
MoveBeforeTable( doc, rowgroup, node );
TY_(Report)(doc, rowgroup, node, TAG_NOT_ALLOWED_IN);
lexer->exiled = yes;
if (node->type != TextNode)
{
memory.identity = TY_(ParseRowGroup);
memory.original_node = rowgroup;
memory.reentry_node = node;
memory.reentry_state = STATE_POST_NOT_TEXTNODE;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
state = STATE_POST_NOT_TEXTNODE;
continue;
}
else if (node->tag->model & CM_HEAD)
{
TY_(Report)(doc, rowgroup, node, TAG_NOT_ALLOWED_IN);
MoveToHead(doc, rowgroup, node);
continue;
}
}
/*
if this is the end tag for ancestor element
then infer end tag for this element
*/
if (node->type == EndTag)
{
if ( nodeIsFORM(node) || TY_(nodeHasCM)(node, CM_BLOCK|CM_INLINE) )
{
if ( nodeIsFORM(node) )
BadForm( doc );
TY_(Report)(doc, rowgroup, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if ( nodeIsTR(node) || nodeIsTD(node) || nodeIsTH(node) )
{
TY_(Report)(doc, rowgroup, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
for ( parent = rowgroup->parent;
parent != NULL;
parent = parent->parent )
{
if (node->tag == parent->tag)
{
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
}
}
/*
if THEAD, TFOOT or TBODY then implied end tag
*/
if (node->tag->model & CM_ROWGRP)
{
if (node->type != EndTag)
{
TY_(UngetToken)( doc );
DEBUG_LOG_EXIT;
return NULL;
}
}
if (node->type == EndTag)
{
TY_(Report)(doc, rowgroup, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if ( !nodeIsTR(node) )
{
node = TY_(InferredTag)(doc, TidyTag_TR);
TY_(Report)(doc, rowgroup, node, MISSING_STARTTAG);
TY_(UngetToken)( doc );
}
/* node should be <TR> */
TY_(InsertNodeAtEnd)(rowgroup, node);
memory.identity = TY_(ParseRowGroup);
memory.original_node = rowgroup;
memory.reentry_node = node;
memory.reentry_state = STATE_INITIAL;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
} break;
case STATE_POST_NOT_TEXTNODE:
{
lexer->exiled = no;
state = STATE_INITIAL;
continue;
} break;
default:
break;
} /* switch */
} /* while */
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseScript)
* Parses the `script` tag.
*
* @todo This isn't quite right for CDATA content as it recognises tags
* within the content and parses them accordingly. This will unfortunately
* screw up scripts which include:
* < + letter
* < + !
* < + ?
* < + / + letter
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseScript)( TidyDocImpl* doc, Node *script, GetTokenMode ARG_UNUSED(mode) )
{
Node *node = NULL;
#if defined(ENABLE_DEBUG_LOG)
static int depth_parser = 0;
static int count_parser = 0;
#endif
DEBUG_LOG_ENTER_WITH_NODE(script);
doc->lexer->parent = script;
node = TY_(GetToken)(doc, CdataContent);
doc->lexer->parent = NULL;
if (node)
{
TY_(InsertNodeAtEnd)(script, node);
}
else
{
/* handle e.g. a document like "<script>" */
TY_(Report)(doc, script, NULL, MISSING_ENDTAG_FOR);
DEBUG_LOG_EXIT;
return NULL;
}
node = TY_(GetToken)(doc, IgnoreWhitespace);
DEBUG_LOG_GOT_TOKEN(node);
if (!(node && node->type == EndTag && node->tag &&
node->tag->id == script->tag->id))
{
TY_(Report)(doc, script, node, MISSING_ENDTAG_FOR);
if (node)
TY_(UngetToken)(doc);
}
else
{
TY_(FreeNode)(doc, node);
}
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseSelect)
* Parses the `select` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseSelect)( TidyDocImpl* doc, Node *field, GetTokenMode ARG_UNUSED(mode) )
{
Lexer* lexer = doc->lexer;
Node *node;
DEBUG_LOG_COUNTERS;
if ( field == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
field = memory.original_node;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(field);
}
lexer->insert = NULL; /* defer implicit inline start tags */
while ((node = TY_(GetToken)(doc, IgnoreWhitespace)) != NULL)
{
if (node->tag == field->tag && node->type == EndTag)
{
TY_(FreeNode)( doc, node);
field->closed = yes;
TrimSpaces(doc, field);
DEBUG_LOG_EXIT;
return NULL;
}
/* deal with comments etc. */
if (InsertMisc(field, node))
continue;
if ( node->type == StartTag &&
( nodeIsOPTION(node) ||
nodeIsOPTGROUP(node) ||
nodeIsDATALIST(node) ||
nodeIsSCRIPT(node))
)
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseSelect);
memory.original_node = field;
memory.reentry_node = node;
TY_(InsertNodeAtEnd)(field, node);
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
/* discard unexpected tags */
TY_(Report)(doc, field, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
}
TY_(Report)(doc, field, node, MISSING_ENDTAG_FOR);
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseTableTag)
* Parses the `table` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseTableTag)( TidyDocImpl* doc, Node *table, GetTokenMode ARG_UNUSED(mode) )
{
Lexer* lexer = doc->lexer;
Node *node, *parent;
uint istackbase;
DEBUG_LOG_COUNTERS;
if ( table == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
DEBUG_LOG_REENTER_WITH_NODE(node);
table = memory.original_node;
lexer->exiled = memory.register_1;
DEBUG_LOG_GET_OLD_MODE;
mode = memory.mode;
DEBUG_LOG_CHANGE_MODE;
}
else
{
DEBUG_LOG_ENTER_WITH_NODE(table);
TY_(DeferDup)( doc );
}
istackbase = lexer->istackbase;
lexer->istackbase = lexer->istacksize;
while ((node = TY_(GetToken)(doc, IgnoreWhitespace)) != NULL)
{
DEBUG_LOG_GOT_TOKEN(node);
if (node->tag == table->tag )
{
if (node->type == EndTag)
{
TY_(FreeNode)(doc, node);
}
else
{
/* Issue #498 - If a <table> in a <table>
* just close the current table, and issue a
* warning. The previous action was to discard
* this second <table>
*/
TY_(UngetToken)(doc);
TY_(Report)(doc, table, node, TAG_NOT_ALLOWED_IN);
}
lexer->istackbase = istackbase;
table->closed = yes;
DEBUG_LOG_EXIT;
return NULL;
}
/* deal with comments etc. */
if (InsertMisc(table, node))
continue;
/* discard unknown tags */
if (node->tag == NULL && node->type != TextNode)
{
TY_(Report)(doc, table, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* if TD or TH or text or inline or block then infer <TR> */
if (node->type != EndTag)
{
if ( nodeIsTD(node) || nodeIsTH(node) || nodeIsTABLE(node) )
{
TY_(UngetToken)( doc );
node = TY_(InferredTag)(doc, TidyTag_TR);
TY_(Report)(doc, table, node, MISSING_STARTTAG);
}
else if ( TY_(nodeIsText)(node) ||TY_(nodeHasCM)(node,CM_BLOCK|CM_INLINE) )
{
TY_(InsertNodeBeforeElement)(table, node);
TY_(Report)(doc, table, node, TAG_NOT_ALLOWED_IN);
lexer->exiled = yes;
if (node->type != TextNode)
{
TidyParserMemory memory = {0};
memory.identity = TY_(ParseTableTag);
memory.original_node = table;
memory.reentry_node = node;
memory.register_1 = no; /* later, lexer->exiled = no */
memory.mode = IgnoreWhitespace;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
lexer->exiled = no;
continue;
}
else if (node->tag->model & CM_HEAD)
{
MoveToHead(doc, table, node);
continue;
}
}
/*
if this is the end tag for an ancestor element
then infer end tag for this element
*/
if (node->type == EndTag)
{
if ( nodeIsFORM(node) )
{
BadForm( doc );
TY_(Report)(doc, table, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* best to discard unexpected block/inline end tags */
if ( TY_(nodeHasCM)(node, CM_TABLE|CM_ROW) ||
TY_(nodeHasCM)(node, CM_BLOCK|CM_INLINE) )
{
TY_(Report)(doc, table, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
for ( parent = table->parent;
parent != NULL;
parent = parent->parent )
{
if (node->tag == parent->tag)
{
TY_(Report)(doc, table, node, MISSING_ENDTAG_BEFORE );
TY_(UngetToken)( doc );
lexer->istackbase = istackbase;
DEBUG_LOG_EXIT;
return NULL;
}
}
}
if (!(node->tag->model & CM_TABLE))
{
TY_(UngetToken)( doc );
TY_(Report)(doc, table, node, TAG_NOT_ALLOWED_IN);
lexer->istackbase = istackbase;
DEBUG_LOG_EXIT;
return NULL;
}
if (TY_(nodeIsElement)(node))
{
TidyParserMemory memory = {0};
TY_(InsertNodeAtEnd)(table, node);
memory.identity = TY_(ParseTableTag);
memory.original_node = table;
memory.reentry_node = node;
memory.register_1 = lexer->exiled;
TY_(pushMemory)( doc, memory );
DEBUG_LOG_EXIT_WITH_NODE(node);
return node;
}
/* discard unexpected text nodes and end tags */
TY_(Report)(doc, table, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
}
TY_(Report)(doc, table, node, MISSING_ENDTAG_FOR);
lexer->istackbase = istackbase;
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseText)
* Parses the `option` and `textarea` tags.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseText)( TidyDocImpl* doc, Node *field, GetTokenMode mode )
{
Lexer* lexer = doc->lexer;
Node *node;
DEBUG_LOG_COUNTERS;
DEBUG_LOG_ENTER_WITH_NODE(field);
lexer->insert = NULL; /* defer implicit inline start tags */
DEBUG_LOG_GET_OLD_MODE;
if ( nodeIsTEXTAREA(field) )
mode = Preformatted;
else
mode = MixedContent; /* kludge for font tags */
DEBUG_LOG_CHANGE_MODE;
while ((node = TY_(GetToken)(doc, mode)) != NULL)
{
if (node->tag == field->tag && node->type == EndTag)
{
TY_(FreeNode)( doc, node);
field->closed = yes;
TrimSpaces(doc, field);
DEBUG_LOG_EXIT;
return NULL;
}
/* deal with comments etc. */
if (InsertMisc(field, node))
continue;
if (TY_(nodeIsText)(node))
{
/* only called for 1st child */
if (field->content == NULL && !(mode & Preformatted))
TrimSpaces(doc, field);
if (node->start >= node->end)
{
TY_(FreeNode)( doc, node);
continue;
}
TY_(InsertNodeAtEnd)(field, node);
continue;
}
/* for textarea should all cases of < and & be escaped? */
/* discard inline tags e.g. font */
if ( node->tag
&& node->tag->model & CM_INLINE
&& !(node->tag->model & CM_FIELD)) /* #487283 - fix by Lee Passey 25 Jan 02 */
{
TY_(Report)(doc, field, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* terminate element on other tags */
if (!(field->tag->model & CM_OPT))
TY_(Report)(doc, field, node, MISSING_ENDTAG_BEFORE);
TY_(UngetToken)( doc );
TrimSpaces(doc, field);
DEBUG_LOG_EXIT;
return NULL;
}
if (!(field->tag->model & CM_OPT))
TY_(Report)(doc, field, node, MISSING_ENDTAG_FOR);
DEBUG_LOG_EXIT;
return NULL;
}
/** MARK: TY_(ParseTitle)
* Parses the `title` tag.
*
* This is a non-recursing parser. It uses the document's parser memory stack
* to send subsequent nodes back to the controller for dispatching to parsers.
* This parser is also re-enterable, so that post-processing can occur after
* such dispatching.
*/
Node* TY_(ParseTitle)( TidyDocImpl* doc, Node *title, GetTokenMode ARG_UNUSED(mode) )
{
Node *node;
while ((node = TY_(GetToken)(doc, MixedContent)) != NULL)
{
if (node->tag == title->tag && node->type == StartTag
&& cfgBool(doc, TidyCoerceEndTags) )
{
TY_(Report)(doc, title, node, COERCE_TO_ENDTAG);
node->type = EndTag;
TY_(UngetToken)( doc );
continue;
}
else if (node->tag == title->tag && node->type == EndTag)
{
TY_(FreeNode)( doc, node);
title->closed = yes;
TrimSpaces(doc, title);
return NULL;
}
if (TY_(nodeIsText)(node))
{
/* only called for 1st child */
if (title->content == NULL)
TrimInitialSpace(doc, title, node);
if (node->start >= node->end)
{
TY_(FreeNode)( doc, node);
continue;
}
TY_(InsertNodeAtEnd)(title, node);
continue;
}
/* deal with comments etc. */
if (InsertMisc(title, node))
continue;
/* discard unknown tags */
if (node->tag == NULL)
{
TY_(Report)(doc, title, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
/* pushback unexpected tokens */
TY_(Report)(doc, title, node, MISSING_ENDTAG_BEFORE);
TY_(UngetToken)( doc );
TrimSpaces(doc, title);
return NULL;
}
TY_(Report)(doc, title, node, MISSING_ENDTAG_FOR);
return NULL;
}
/** MARK: ParseXMLElement
* Parses the given XML element.
*/
static Node* ParseXMLElement(TidyDocImpl* doc, Node *element, GetTokenMode mode)
{
Lexer* lexer = doc->lexer;
Node *node;
if ( element == NULL )
{
TidyParserMemory memory = TY_(popMemory)( doc );
element = memory.original_node;
node = memory.reentry_node; /* Throwaway, as main loop overrwrites anyway. */
mode = memory.reentry_mode;
TY_(InsertNodeAtEnd)(element, node); /* The only re-entry action needed. */
}
else
{
/* if node is pre or has xml:space="preserve" then do so */
if ( TY_(XMLPreserveWhiteSpace)(doc, element) )
mode = Preformatted;
/* deal with comments etc. */
InsertMisc( &doc->root, element);
/* we shouldn't have plain text at this point. */
if (TY_(nodeIsText)(element))
{
TY_(Report)(doc, &doc->root, element, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, element);
return NULL;
}
}
while ((node = TY_(GetToken)(doc, mode)) != NULL)
{
if (node->type == EndTag &&
node->element && element->element &&
TY_(tmbstrcmp)(node->element, element->element) == 0)
{
TY_(FreeNode)( doc, node);
element->closed = yes;
break;
}
/* discard unexpected end tags */
if (node->type == EndTag)
{
if (element)
TY_(Report)(doc, element, node, UNEXPECTED_ENDTAG_IN);
else
TY_(Report)(doc, element, node, UNEXPECTED_ENDTAG_ERR);
TY_(FreeNode)( doc, node);
continue;
}
/* parse content on seeing start tag */
if (node->type == StartTag)
{
TidyParserMemory memory = {0};
memory.identity = ParseXMLElement;
memory.original_node = element;
memory.reentry_node = node;
memory.reentry_mode = mode;
TY_(pushMemory)( doc, memory );
return node;
}
TY_(InsertNodeAtEnd)(element, node);
} /* while */
/*
if first child is text then trim initial space and
delete text node if it is empty.
*/
node = element->content;
if (TY_(nodeIsText)(node) && mode != Preformatted)
{
if ( lexer->lexbuf[node->start] == ' ' )
{
node->start++;
if (node->start >= node->end)
TY_(DiscardElement)( doc, node );
}
}
/*
if last child is text then trim final space and
delete the text node if it is empty
*/
node = element->last;
if (TY_(nodeIsText)(node) && mode != Preformatted)
{
if ( lexer->lexbuf[node->end - 1] == ' ' )
{
node->end--;
if (node->start >= node->end)
TY_(DiscardElement)( doc, node );
}
}
return NULL;
}
/***************************************************************************//*
** MARK: - Post-Parse Operations
***************************************************************************/
/**
* Performs checking of all attributes recursively starting at `node`.
*/
static void AttributeChecks(TidyDocImpl* doc, Node* node)
{
Node *next;
while (node)
{
next = node->next;
if (TY_(nodeIsElement)(node))
{
if (node->tag && node->tag->chkattrs) /* [i_a]2 fix crash after adding SVG support with alt/unknown tag subtree insertion there */
node->tag->chkattrs(doc, node);
else
TY_(CheckAttributes)(doc, node);
}
if (node->content)
AttributeChecks(doc, node->content);
assert( next != node ); /* http://tidy.sf.net/issue/1603538 */
node = next;
}
}
/**
* Encloses naked text in certain elements within `p` tags.
*
* <form>, <blockquote>, and <noscript> do not allow #PCDATA in
* HTML 4.01 Strict (%block; model instead of %flow;).
*/
static void EncloseBlockText(TidyDocImpl* doc, Node* node)
{
Node *next;
Node *block;
while (node)
{
next = node->next;
if (node->content)
EncloseBlockText(doc, node->content);
if (!(nodeIsFORM(node) || nodeIsNOSCRIPT(node) ||
nodeIsBLOCKQUOTE(node))
|| !node->content)
{
node = next;
continue;
}
block = node->content;
if ((TY_(nodeIsText)(block) && !TY_(IsBlank)(doc->lexer, block)) ||
(TY_(nodeIsElement)(block) && nodeCMIsOnlyInline(block)))
{
Node* p = TY_(InferredTag)(doc, TidyTag_P);
TY_(InsertNodeBeforeElement)(block, p);
while (block &&
(!TY_(nodeIsElement)(block) || nodeCMIsOnlyInline(block)))
{
Node* tempNext = block->next;
TY_(RemoveNode)(block);
TY_(InsertNodeAtEnd)(p, block);
block = tempNext;
}
TrimSpaces(doc, p);
continue;
}
node = next;
}
}
/**
* Encloses all naked body text within `p` tags.
*/
static void EncloseBodyText(TidyDocImpl* doc)
{
Node* node;
Node* body = TY_(FindBody)(doc);
if (!body)
return;
node = body->content;
while (node)
{
if ((TY_(nodeIsText)(node) && !TY_(IsBlank)(doc->lexer, node)) ||
(TY_(nodeIsElement)(node) && nodeCMIsOnlyInline(node)))
{
Node* p = TY_(InferredTag)(doc, TidyTag_P);
TY_(InsertNodeBeforeElement)(node, p);
while (node && (!TY_(nodeIsElement)(node) || nodeCMIsOnlyInline(node)))
{
Node* next = node->next;
TY_(RemoveNode)(node);
TY_(InsertNodeAtEnd)(p, node);
node = next;
}
TrimSpaces(doc, p);
continue;
}
node = node->next;
}
}
/**
* Replaces elements that are obsolete with appropriate substitute tags.
*/
static void ReplaceObsoleteElements(TidyDocImpl* doc, Node* node)
{
Node *next;
while (node)
{
next = node->next;
/* if (nodeIsDIR(node) || nodeIsMENU(node)) */
/* HTML5 - <menu ... > is no longer obsolete */
if (nodeIsDIR(node))
TY_(CoerceNode)(doc, node, TidyTag_UL, yes, yes);
if (nodeIsXMP(node) || nodeIsLISTING(node) ||
(node->tag && node->tag->id == TidyTag_PLAINTEXT))
TY_(CoerceNode)(doc, node, TidyTag_PRE, yes, yes);
if (node->content)
ReplaceObsoleteElements(doc, node->content);
node = next;
}
}
/***************************************************************************//*
** MARK: - Internal API Implementation
***************************************************************************/
/** MARK: TY_(CheckNodeIntegrity)
* Is used to perform a node integrity check after parsing an HTML or XML
* document.
* @note Actual performance of this check can be disabled by defining the
* macro NO_NODE_INTEGRITY_CHECK.
*/
Bool TY_(CheckNodeIntegrity)(Node *node)
{
#ifndef NO_NODE_INTEGRITY_CHECK
Node *child;
if (node->prev)
{
if (node->prev->next != node)
return no;
}
if (node->next)
{
if (node->next == node || node->next->prev != node)
return no;
}
if (node->parent)
{
if (node->prev == NULL && node->parent->content != node)
return no;
if (node->next == NULL && node->parent->last != node)
return no;
}
for (child = node->content; child; child = child->next)
if ( child->parent != node || !TY_(CheckNodeIntegrity)(child) )
return no;
#endif
return yes;
}
/** MARK: TY_(CoerceNode)
* Transforms a given node to another element, for example, from a <p>
* to a <br>.
*/
void TY_(CoerceNode)(TidyDocImpl* doc, Node *node, TidyTagId tid, Bool obsolete, Bool unexpected)
{
const Dict* tag = TY_(LookupTagDef)(tid);
Node* tmp = TY_(InferredTag)(doc, tag->id);
if (obsolete)
TY_(Report)(doc, node, tmp, OBSOLETE_ELEMENT);
else if (unexpected)
TY_(Report)(doc, node, tmp, REPLACING_UNEX_ELEMENT);
else
TY_(Report)(doc, node, tmp, REPLACING_ELEMENT);
TidyDocFree(doc, tmp->element);
TidyDocFree(doc, tmp);
node->was = node->tag;
node->tag = tag;
node->type = StartTag;
node->implicit = yes;
TidyDocFree(doc, node->element);
node->element = TY_(tmbstrdup)(doc->allocator, tag->name);
}
/** MARK: TY_(DiscardElement)
* Remove node from markup tree and discard it.
*/
Node *TY_(DiscardElement)( TidyDocImpl* doc, Node *element )
{
Node *next = NULL;
if (element)
{
next = element->next;
TY_(RemoveNode)(element);
TY_(FreeNode)( doc, element);
}
return next;
}
/** MARK: TY_(DropEmptyElements)
* Trims a tree of empty elements recursively, returning the next node.
*/
Node* TY_(DropEmptyElements)(TidyDocImpl* doc, Node* node)
{
Node* next;
while (node)
{
next = node->next;
if (node->content)
TY_(DropEmptyElements)(doc, node->content);
if (!TY_(nodeIsElement)(node) &&
!(TY_(nodeIsText)(node) && !(node->start < node->end)))
{
node = next;
continue;
}
next = TY_(TrimEmptyElement)(doc, node);
node = next;
}
return node;
}
/** MARK: TY_(InsertNodeAtStart)
* Insert node into markup tree as the first element of content of element.
*/
void TY_(InsertNodeAtStart)(Node *element, Node *node)
{
node->parent = element;
if (element->content == NULL)
element->last = node;
else
element->content->prev = node;
node->next = element->content;
node->prev = NULL;
element->content = node;
}
/** MARK: TY_(InsertNodeAtEnd)
* Insert node into markup tree as the last element of content of element.
*/
void TY_(InsertNodeAtEnd)(Node *element, Node *node)
{
node->parent = element;
node->prev = element ? element->last : NULL;
if (element && element->last != NULL)
element->last->next = node;
else
if (element)
element->content = node;
if (element)
element->last = node;
}
/** MARK: TY_(InsertNodeBeforeElement)
* Insert node into markup tree before element.
*/
void TY_(InsertNodeBeforeElement)(Node *element, Node *node)
{
Node *parent;
parent = element ? element->parent : NULL;
node->parent = parent;
node->next = element;
node->prev = element ? element->prev : NULL;
if (element)
element->prev = node;
if (node->prev)
node->prev->next = node;
if (parent && parent->content == element)
parent->content = node;
}
/** MARK: TY_(InsertNodeAfterElement)
* Insert node into markup tree after element.
*/
void TY_(InsertNodeAfterElement)(Node *element, Node *node)
{
Node *parent;
parent = element->parent;
node->parent = parent;
/* AQ - 13 Jan 2000 fix for parent == NULL */
if (parent != NULL && parent->last == element)
parent->last = node;
else
{
node->next = element->next;
/* AQ - 13 Jan 2000 fix for node->next == NULL */
if (node->next != NULL)
node->next->prev = node;
}
element->next = node;
node->prev = element;
}
/** MARK: TY_(IsBlank)
* Indicates whether or not a text node is blank, meaning that it consists
* of nothing, or a single space.
*/
Bool TY_(IsBlank)(Lexer *lexer, Node *node)
{
Bool isBlank = TY_(nodeIsText)(node);
if ( isBlank )
isBlank = ( node->end == node->start || /* Zero length */
( node->end == node->start+1 /* or one blank. */
&& lexer->lexbuf[node->start] == ' ' ) );
return isBlank;
}
/** MARK: TY_(IsJavaScript)
* Indicates whether or not a node is declared as containing javascript
* code.
*/
Bool TY_(IsJavaScript)(Node *node)
{
Bool result = no;
AttVal *attr;
if (node->attributes == NULL)
return yes;
for (attr = node->attributes; attr; attr = attr->next)
{
if ( (attrIsLANGUAGE(attr) || attrIsTYPE(attr))
&& AttrContains(attr, "javascript") )
{
result = yes;
break;
}
}
return result;
}
/** MARK: TY_(IsNewNode)
* Used to check if a node uses CM_NEW, which determines how attributes
* without values should be printed. This was introduced to deal with
* user-defined tags e.g. ColdFusion.
*/
Bool TY_(IsNewNode)(Node *node)
{
if (node && node->tag)
{
return (node->tag->model & CM_NEW);
}
return yes;
}
/** MARK: TY_(RemoveNode)
* Extract a node and its children from a markup tree
*/
Node *TY_(RemoveNode)(Node *node)
{
if (node->prev)
node->prev->next = node->next;
if (node->next)
node->next->prev = node->prev;
if (node->parent)
{
if (node->parent->content == node)
node->parent->content = node->next;
if (node->parent->last == node)
node->parent->last = node->prev;
}
node->parent = node->prev = node->next = NULL;
return node;
}
/** MARK: TY_(TrimEmptyElement)
* Trims a single, empty element, returning the next node.
*/
Node *TY_(TrimEmptyElement)( TidyDocImpl* doc, Node *element )
{
if ( CanPrune(doc, element) )
{
if (element->type != TextNode)
{
doc->footnotes |= FN_TRIM_EMPTY_ELEMENT;
TY_(Report)(doc, element, NULL, TRIM_EMPTY_ELEMENT);
}
return TY_(DiscardElement)(doc, element);
}
return element->next;
}
/** MARK: TY_(XMLPreserveWhiteSpace)
* Indicates whether or not whitespace is to be preserved in XHTML/XML
* documents.
*/
Bool TY_(XMLPreserveWhiteSpace)( TidyDocImpl* doc, Node *element)
{
AttVal *attribute;
/* search attributes for xml:space */
for (attribute = element->attributes; attribute; attribute = attribute->next)
{
if (attrIsXML_SPACE(attribute))
{
if (AttrValueIs(attribute, "preserve"))
return yes;
return no;
}
}
if (element->element == NULL)
return no;
/* kludge for html docs without explicit xml:space attribute */
if (nodeIsPRE(element) ||
nodeIsSCRIPT(element) ||
nodeIsSTYLE(element) ||
TY_(FindParser)(doc, element) == TY_(ParsePre))
return yes;
/* kludge for XSL docs */
if ( TY_(tmbstrcasecmp)(element->element, "xsl:text") == 0 )
return yes;
return no;
}
/***************************************************************************//*
** MARK: - Internal API Implementation - Main Parsers
***************************************************************************/
/** MARK: TY_(ParseDocument)
* Parses an HTML document after lexing. It begins by properly configuring
* the overall HTML structure, and subsequently processes all remaining
* nodes.
*/
void TY_(ParseDocument)(TidyDocImpl* doc)
{
Node *node, *html, *doctype = NULL;
while ((node = TY_(GetToken)(doc, IgnoreWhitespace)) != NULL)
{
if (node->type == XmlDecl)
{
doc->xmlDetected = yes;
if (TY_(FindXmlDecl)(doc) && doc->root.content)
{
TY_(Report)(doc, &doc->root, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)(doc, node);
continue;
}
if (node->line > 1 || node->column != 1)
{
TY_(Report)(doc, &doc->root, node, SPACE_PRECEDING_XMLDECL);
}
}
/* deal with comments etc. */
if (InsertMisc( &doc->root, node ))
continue;
if (node->type == DocTypeTag)
{
if (doctype == NULL)
{
TY_(InsertNodeAtEnd)( &doc->root, node);
doctype = node;
}
else
{
TY_(Report)(doc, &doc->root, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
}
continue;
}
if (node->type == EndTag)
{
TY_(Report)(doc, &doc->root, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
continue;
}
if (node->type == StartTag && nodeIsHTML(node))
{
AttVal *xmlns = TY_(AttrGetById)(node, TidyAttr_XMLNS);
if (AttrValueIs(xmlns, XHTML_NAMESPACE))
{
Bool htmlOut = cfgBool( doc, TidyHtmlOut );
doc->lexer->isvoyager = yes; /* Unless plain HTML */
TY_(SetOptionBool)( doc, TidyXhtmlOut, !htmlOut ); /* is specified, output*/
TY_(SetOptionBool)( doc, TidyXmlOut, !htmlOut ); /* will be XHTML. */
/* adjust other config options, just as in config.c */
if ( !htmlOut )
{
TY_(SetOptionBool)( doc, TidyUpperCaseTags, no );
TY_(SetOptionInt)( doc, TidyUpperCaseAttrs, no );
}
}
}
if ( node->type != StartTag || !nodeIsHTML(node) )
{
TY_(UngetToken)( doc );
html = TY_(InferredTag)(doc, TidyTag_HTML);
}
else
html = node;
/*\
* #72, avoid MISSING_DOCTYPE if show-body-only.
* #191, also if --doctype omit, that is TidyDoctypeOmit
* #342, adjust tags to html4-- if not 'auto' or 'html5'
\*/
if (!TY_(FindDocType)(doc))
{
ulong dtmode = cfg( doc, TidyDoctypeMode );
if ((dtmode != TidyDoctypeOmit) && !showingBodyOnly(doc))
TY_(Report)(doc, NULL, NULL, MISSING_DOCTYPE);
if ((dtmode != TidyDoctypeAuto) && (dtmode != TidyDoctypeHtml5))
{
/*\
* Issue #342 - if not doctype 'auto', or 'html5'
* then reset mode htm4-- parsing
\*/
TY_(AdjustTags)(doc); /* Dynamically modify the tags table to html4-- mode */
}
}
TY_(InsertNodeAtEnd)( &doc->root, html);
ParseHTMLWithNode( doc, html );
break;
}
/* do this before any more document fixes */
if ( cfg( doc, TidyAccessibilityCheckLevel ) > 0 )
TY_(AccessibilityChecks)( doc );
if (!TY_(FindHTML)(doc))
{
/* a later check should complain if <body> is empty */
html = TY_(InferredTag)(doc, TidyTag_HTML);
TY_(InsertNodeAtEnd)( &doc->root, html);
ParseHTMLWithNode( doc, html );
}
node = TY_(FindTITLE)(doc);
if (!node)
{
Node* head = TY_(FindHEAD)(doc);
/* #72, avoid MISSING_TITLE_ELEMENT if show-body-only (but allow InsertNodeAtEnd to avoid new warning) */
if (!showingBodyOnly(doc))
{
TY_(Report)(doc, head, NULL, MISSING_TITLE_ELEMENT);
}
TY_(InsertNodeAtEnd)(head, TY_(InferredTag)(doc, TidyTag_TITLE));
}
else if (!node->content && !showingBodyOnly(doc))
{
/* Is #839 - warn node is blank in HTML5 */
if (TY_(IsHTML5Mode)(doc))
{
TY_(Report)(doc, node, NULL, BLANK_TITLE_ELEMENT);
}
}
AttributeChecks(doc, &doc->root);
ReplaceObsoleteElements(doc, &doc->root);
TY_(DropEmptyElements)(doc, &doc->root);
CleanSpaces(doc, &doc->root);
if (cfgBool(doc, TidyEncloseBodyText))
EncloseBodyText(doc);
if (cfgBool(doc, TidyEncloseBlockText))
EncloseBlockText(doc, &doc->root);
}
/** MARK: TY_(ParseXMLDocument)
* Parses the document using Tidy's XML parser.
*/
void TY_(ParseXMLDocument)(TidyDocImpl* doc)
{
Node *node, *doctype = NULL;
TY_(SetOptionBool)( doc, TidyXmlTags, yes );
doc->xmlDetected = yes;
while ((node = TY_(GetToken)(doc, IgnoreWhitespace)) != NULL)
{
/* discard unexpected end tags */
if (node->type == EndTag)
{
TY_(Report)(doc, NULL, node, UNEXPECTED_ENDTAG);
TY_(FreeNode)( doc, node);
continue;
}
/* deal with comments etc. */
if (InsertMisc( &doc->root, node))
continue;
if (node->type == DocTypeTag)
{
if (doctype == NULL)
{
TY_(InsertNodeAtEnd)( &doc->root, node);
doctype = node;
}
else
{
TY_(Report)(doc, &doc->root, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
}
continue;
}
if (node->type == StartEndTag)
{
TY_(InsertNodeAtEnd)( &doc->root, node);
continue;
}
/* if start tag then parse element's content */
if (node->type == StartTag)
{
TY_(InsertNodeAtEnd)( &doc->root, node );
ParseHTMLWithNode( doc, node );
continue;
}
TY_(Report)(doc, &doc->root, node, DISCARDING_UNEXPECTED);
TY_(FreeNode)( doc, node);
}
/* ensure presence of initial <?xml version="1.0"?> */
if ( cfgBool(doc, TidyXmlDecl) )
TY_(FixXmlDecl)( doc );
}
| 204,565 | 6,453 | jart/cosmopolitan | false |
cosmopolitan/third_party/tidy/tidyenum.h | #ifndef __TIDYENUM_H__
#define __TIDYENUM_H__
/* clang-format off */
/**************************************************************************//**
* @file
* Separated public enumerations header providing important indentifiers for
* LibTidy and internal users, as well as code-generator macros used to
* generate many of them.
*
* The use of enums simplifies enum re-use in various wrappers, e.g. SWIG,
* generated wrappers, and COM IDL files.
*
* This file also contains macros to generate additional enums for use in
* Tidy's language localizations and/or to access Tidy's strings via the API.
* See detailed information elsewhere in this file's documentation.
*
* @note LibTidy does *not* guarantee the value of any enumeration member,
* including the starting integer value, except where noted. Always use enum
* members rather than their values!
*
* Enums that have starting values have starting values for a good reason,
* mainly to prevent string key overlap.
*
* @author Dave Raggett [[email protected]]
* @author HTACG, et al (consult git log)
*
* @copyright
* Copyright (c) 1998-2017 World Wide Web Consortium (Massachusetts
* Institute of Technology, European Research Consortium for Informatics
* and Mathematics, Keio University).
* @copyright
* See tidy.h for license.
*
* @date Created 2001-05-20 by Charles Reitzel
* @date Updated 2002-07-01 by Charles Reitzel
* @date Further modifications: consult git log.
******************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
/***************************************************************************//**
** @defgroup public_enum_gen Tidy Strings Generation Macros
** @ingroup internal_api
**
** Tidy aims to provide a consistent API for library users, and so we go to
** some lengths to provide a `tidyStrings` enum that consists of the message
** code for every string that Tidy can emit (used internally), and the array
** `tidyStringsKeys[]` containing string representations of each message code.
**
** In order to keep code maintainable and make it simple to add new messages,
** the message code enums and `tidyStringsKeys[]` are generated dynamically
** with preprocessor macros defined below.
**
** Any visible FOREACH_MSG_* macro (including new ones) must be applied to the
** `tidyStrings` enum with the `MAKE_ENUM()` macro in this file, and to the
** `tidyStringsKeys[]` (in `messages.c`) with `MAKE_STRUCT` in this file.
**
** Modern IDE's will dynamically pre-process all of these macros, enabling
** code-completion of these enums and array of structs.
**
** @{
******************************************************************************/
/* MARK: - Code Generation Macros */
/** @name Code Generation Macros
** These macros generate the enums and arrays from the Content Generation
** Macros defined below.
** @{
*/
/** Used to populate the contents of an enumerator, such as `tidyStrings`. */
#define MAKE_ENUM(MESSAGE) MESSAGE,
/** Used to populate the contents of a structure, such as tidyStringsKeys[]. */
#define MAKE_STRUCT(MESSAGE) {#MESSAGE, MESSAGE},
/** @} */
/* MARK: - Content Generation Macros */
/** @name Content Generation Macros
** These macros generate the individual entries in the enums and structs used
** to manage strings in Tidy.
** @{
*/
/** Codes for populating TidyConfigCategory enumeration. */
#define FOREACH_TIDYCONFIGCATEGORY(FN) \
FN(TidyDiagnostics) /**< Diagnostics */ \
FN(TidyDisplay) /**< Affecting screen display */ \
FN(TidyDocumentIO) /**< Pertaining to document I/O */ \
FN(TidyEncoding) /**< Relating to encoding */ \
FN(TidyFileIO) /**< Pertaining to file I/O */ \
FN(TidyMarkupCleanup) /**< Cleanup related options */ \
FN(TidyMarkupEntities) /**< Entity related options */ \
FN(TidyMarkupRepair) /**< Document repair related options */ \
FN(TidyMarkupTeach) /**< Teach tidy new things */ \
FN(TidyMarkupXForm) /**< Transform HTML one way or another */ \
FN(TidyPrettyPrint) /**< Pretty printing options */ \
FN(TidyInternalCategory) /**< Option is internal only. */ \
/** These message codes comprise every possible message that can be output by
** Tidy that are *not* diagnostic style messages, and are *not* console
** application specific messages.
*/
#define FOREACH_MSG_MISC(FN) \
/** line %d column %d */ FN(LINE_COLUMN_STRING) \
/** %s: line %d column %d */ FN(FN_LINE_COLUMN_STRING) \
/** discarding */ FN(STRING_DISCARDING) \
/** error and errors */ FN(STRING_ERROR_COUNT_ERROR) \
/** warning and warnings */ FN(STRING_ERROR_COUNT_WARNING) \
/** Accessibility hello message */ FN(STRING_HELLO_ACCESS) \
/** HTML Proprietary */ FN(STRING_HTML_PROPRIETARY) \
/** plain text */ FN(STRING_PLAIN_TEXT) \
/** replacing */ FN(STRING_REPLACING) \
/** specified */ FN(STRING_SPECIFIED) \
/** XML declaration */ FN(STRING_XML_DECLARATION) \
/** no */ FN(TIDYCUSTOMNO_STRING) \
/** block level */ FN(TIDYCUSTOMBLOCKLEVEL_STRING) \
/** empty */ FN(TIDYCUSTOMEMPTY_STRING) \
/** inline */ FN(TIDYCUSTOMINLINE_STRING) \
/** pre */ FN(TIDYCUSTOMPRE_STRING) \
/** These messages are used to generate additional dialogue style output from
** Tidy when certain conditions exist, and provide more verbose explanations
** than the short report.
*/
#define FOREACH_FOOTNOTE_MSG(FN) \
FN(FOOTNOTE_TRIM_EMPTY_ELEMENT) \
FN(TEXT_ACCESS_ADVICE1) \
FN(TEXT_ACCESS_ADVICE2) \
FN(TEXT_BAD_FORM) \
FN(TEXT_BAD_MAIN) \
FN(TEXT_HTML_T_ALGORITHM) \
FN(TEXT_INVALID_URI) \
FN(TEXT_INVALID_UTF16) \
FN(TEXT_INVALID_UTF8) \
FN(TEXT_M_IMAGE_ALT) \
FN(TEXT_M_IMAGE_MAP) \
FN(TEXT_M_LINK_ALT) \
FN(TEXT_M_SUMMARY) \
FN(TEXT_SGML_CHARS) \
FN(TEXT_USING_BODY) \
FN(TEXT_USING_FONT) \
FN(TEXT_USING_FRAMES) \
FN(TEXT_USING_LAYER) \
FN(TEXT_USING_NOBR) \
FN(TEXT_USING_SPACER) \
FN(TEXT_VENDOR_CHARS) \
FN(TEXT_WINDOWS_CHARS)
/** These messages are used to generate additional dialogue style output from
** Tidy when certain conditions exist, and provide more verbose explanations
** than the short report.
*/
#define FOREACH_DIALOG_MSG(FN) \
/* TidyDialogueSummary */ FN(STRING_ERROR_COUNT) \
/* TidyDialogueSummary */ FN(STRING_NEEDS_INTERVENTION) \
/* TidyDialogueSummary */ FN(STRING_NO_ERRORS) \
/* TidyDialogueSummary */ FN(STRING_NOT_ALL_SHOWN) \
/* TidyDialogueInfo */ FN(TEXT_GENERAL_INFO_PLEA) \
/* TidyDialogueInfo */ FN(TEXT_GENERAL_INFO)
/** These are report messages, i.e., messages that appear in Tidy's table
** of errors and warnings.
*/
#define FOREACH_REPORT_MSG(FN) \
FN(ADDED_MISSING_CHARSET) \
FN(ANCHOR_NOT_UNIQUE) \
FN(ANCHOR_DUPLICATED) \
FN(APOS_UNDEFINED) \
FN(ATTR_VALUE_NOT_LCASE) \
FN(ATTRIBUTE_IS_NOT_ALLOWED) \
FN(ATTRIBUTE_VALUE_REPLACED) \
FN(BACKSLASH_IN_URI) \
FN(BAD_ATTRIBUTE_VALUE_REPLACED) \
FN(BAD_ATTRIBUTE_VALUE) \
FN(BAD_CDATA_CONTENT) \
FN(BAD_SUMMARY_HTML5) \
FN(BAD_SURROGATE_LEAD) \
FN(BAD_SURROGATE_PAIR) \
FN(BAD_SURROGATE_TAIL) \
FN(CANT_BE_NESTED) \
FN(COERCE_TO_ENDTAG) \
FN(CONTENT_AFTER_BODY) \
FN(CUSTOM_TAG_DETECTED) \
FN(DISCARDING_UNEXPECTED) \
FN(DOCTYPE_AFTER_TAGS) \
FN(DUPLICATE_FRAMESET) \
FN(ELEMENT_NOT_EMPTY) \
FN(ELEMENT_VERS_MISMATCH_ERROR) \
FN(ELEMENT_VERS_MISMATCH_WARN) \
FN(ENCODING_MISMATCH) \
FN(ESCAPED_ILLEGAL_URI) \
FN(FILE_CANT_OPEN) \
FN(FILE_CANT_OPEN_CFG) \
FN(FILE_NOT_FILE) \
FN(FIXED_BACKSLASH) \
FN(FOUND_STYLE_IN_BODY) \
FN(ID_NAME_MISMATCH) \
FN(ILLEGAL_NESTING) \
FN(ILLEGAL_URI_CODEPOINT) \
FN(ILLEGAL_URI_REFERENCE) \
FN(INSERTING_AUTO_ATTRIBUTE) \
FN(INSERTING_TAG) \
FN(INVALID_ATTRIBUTE) \
FN(INVALID_NCR) \
FN(INVALID_SGML_CHARS) \
FN(INVALID_UTF8) \
FN(INVALID_UTF16) \
FN(INVALID_XML_ID) \
FN(JOINING_ATTRIBUTE) \
FN(MALFORMED_COMMENT) \
FN(MALFORMED_COMMENT_DROPPING) \
FN(MALFORMED_COMMENT_EOS) \
FN(MALFORMED_COMMENT_WARN) \
FN(MALFORMED_DOCTYPE) \
FN(MISMATCHED_ATTRIBUTE_ERROR) \
FN(MISMATCHED_ATTRIBUTE_WARN) \
FN(MISSING_ATTR_VALUE) \
FN(MISSING_ATTRIBUTE) \
FN(MISSING_DOCTYPE) \
FN(MISSING_ENDTAG_BEFORE) \
FN(MISSING_ENDTAG_FOR) \
FN(MISSING_ENDTAG_OPTIONAL) \
FN(MISSING_IMAGEMAP) \
FN(MISSING_QUOTEMARK) \
FN(MISSING_QUOTEMARK_OPEN) \
FN(MISSING_SEMICOLON_NCR) \
FN(MISSING_SEMICOLON) \
FN(MISSING_STARTTAG) \
FN(MISSING_TITLE_ELEMENT) \
FN(MOVED_STYLE_TO_HEAD) \
FN(NESTED_EMPHASIS) \
FN(NESTED_QUOTATION) \
FN(NEWLINE_IN_URI) \
FN(NOFRAMES_CONTENT) \
FN(NON_MATCHING_ENDTAG) \
FN(OBSOLETE_ELEMENT) \
FN(OPTION_REMOVED) \
FN(OPTION_REMOVED_APPLIED) \
FN(OPTION_REMOVED_UNAPPLIED) \
FN(PREVIOUS_LOCATION) \
FN(PROPRIETARY_ATTR_VALUE) \
FN(PROPRIETARY_ATTRIBUTE) \
FN(PROPRIETARY_ELEMENT) \
FN(REMOVED_HTML5) \
FN(REPEATED_ATTRIBUTE) \
FN(REPLACING_ELEMENT) \
FN(REPLACING_UNEX_ELEMENT) \
FN(SPACE_PRECEDING_XMLDECL) \
FN(STRING_CONTENT_LOOKS) \
FN(STRING_ARGUMENT_BAD) \
FN(STRING_DOCTYPE_GIVEN) \
FN(STRING_MISSING_MALFORMED) \
FN(STRING_MUTING_TYPE) \
FN(STRING_NO_SYSID) \
FN(STRING_UNKNOWN_OPTION) \
FN(SUSPECTED_MISSING_QUOTE) \
FN(TAG_NOT_ALLOWED_IN) \
FN(TOO_MANY_ELEMENTS_IN) \
FN(TOO_MANY_ELEMENTS) \
FN(TRIM_EMPTY_ELEMENT) \
FN(UNESCAPED_AMPERSAND) \
FN(UNEXPECTED_END_OF_FILE_ATTR) \
FN(UNEXPECTED_END_OF_FILE) \
FN(UNEXPECTED_ENDTAG_ERR) \
FN(UNEXPECTED_ENDTAG_IN) \
FN(UNEXPECTED_ENDTAG) \
FN(UNEXPECTED_EQUALSIGN) \
FN(UNEXPECTED_GT) \
FN(UNEXPECTED_QUOTEMARK) \
FN(UNKNOWN_ELEMENT_LOOKS_CUSTOM) \
FN(UNKNOWN_ELEMENT) \
FN(UNKNOWN_ENTITY) \
FN(USING_BR_INPLACE_OF) \
FN(VENDOR_SPECIFIC_CHARS) \
FN(WHITE_IN_URI) \
FN(XML_DECLARATION_DETECTED) \
FN(XML_ID_SYNTAX) \
FN(BLANK_TITLE_ELEMENT)
/** These are report messages added by Tidy's accessibility module.
** Note that commented out items don't have checks for them at this time,
** and it was probably intended that some test would eventually be written.
*/
#define FOREACH_ACCESS_MSG(FN) \
/** [1.1.1.1] */ FN(IMG_MISSING_ALT) \
/** [1.1.1.2] */ FN(IMG_ALT_SUSPICIOUS_FILENAME) \
/** [1.1.1.3] */ FN(IMG_ALT_SUSPICIOUS_FILE_SIZE) \
/** [1.1.1.4] */ FN(IMG_ALT_SUSPICIOUS_PLACEHOLDER) \
/** [1.1.1.10] */ FN(IMG_ALT_SUSPICIOUS_TOO_LONG) \
/** [1.1.1.11] */ /* FN(IMG_MISSING_ALT_BULLET) */ \
/** [1.1.1.12] */ /* FN(IMG_MISSING_ALT_H_RULE) */ \
/** [1.1.2.1] */ FN(IMG_MISSING_LONGDESC_DLINK) \
/** [1.1.2.2] */ FN(IMG_MISSING_DLINK) \
/** [1.1.2.3] */ FN(IMG_MISSING_LONGDESC) \
/** [1.1.2.5] */ /* FN(LONGDESC_NOT_REQUIRED) */ \
/** [1.1.3.1] */ FN(IMG_BUTTON_MISSING_ALT) \
/** [1.1.4.1] */ FN(APPLET_MISSING_ALT) \
/** [1.1.5.1] */ FN(OBJECT_MISSING_ALT) \
/** [1.1.6.1] */ FN(AUDIO_MISSING_TEXT_WAV) \
/** [1.1.6.2] */ FN(AUDIO_MISSING_TEXT_AU) \
/** [1.1.6.3] */ FN(AUDIO_MISSING_TEXT_AIFF) \
/** [1.1.6.4] */ FN(AUDIO_MISSING_TEXT_SND) \
/** [1.1.6.5] */ FN(AUDIO_MISSING_TEXT_RA) \
/** [1.1.6.6] */ FN(AUDIO_MISSING_TEXT_RM) \
/** [1.1.8.1] */ FN(FRAME_MISSING_LONGDESC) \
/** [1.1.9.1] */ FN(AREA_MISSING_ALT) \
/** [1.1.10.1] */ FN(SCRIPT_MISSING_NOSCRIPT) \
/** [1.1.12.1] */ FN(ASCII_REQUIRES_DESCRIPTION) \
/** [1.2.1.1] */ FN(IMG_MAP_SERVER_REQUIRES_TEXT_LINKS) \
/** [1.4.1.1] */ FN(MULTIMEDIA_REQUIRES_TEXT) \
/** [1.5.1.1] */ FN(IMG_MAP_CLIENT_MISSING_TEXT_LINKS) \
/** [2.1.1.1] */ FN(INFORMATION_NOT_CONVEYED_IMAGE) \
/** [2.1.1.2] */ FN(INFORMATION_NOT_CONVEYED_APPLET) \
/** [2.1.1.3] */ FN(INFORMATION_NOT_CONVEYED_OBJECT) \
/** [2.1.1.4] */ FN(INFORMATION_NOT_CONVEYED_SCRIPT) \
/** [2.1.1.5] */ FN(INFORMATION_NOT_CONVEYED_INPUT) \
/** [2.2.1.1] */ FN(COLOR_CONTRAST_TEXT) \
/** [2.2.1.2] */ FN(COLOR_CONTRAST_LINK) \
/** [2.2.1.3] */ FN(COLOR_CONTRAST_ACTIVE_LINK) \
/** [2.2.1.4] */ FN(COLOR_CONTRAST_VISITED_LINK) \
/** [3.2.1.1] */ FN(DOCTYPE_MISSING) \
/** [3.3.1.1] */ FN(STYLE_SHEET_CONTROL_PRESENTATION) \
/** [3.5.1.1] */ FN(HEADERS_IMPROPERLY_NESTED) \
/** [3.5.2.1] */ FN(POTENTIAL_HEADER_BOLD) \
/** [3.5.2.2] */ FN(POTENTIAL_HEADER_ITALICS) \
/** [3.5.2.3] */ FN(POTENTIAL_HEADER_UNDERLINE) \
/** [3.5.3.1] */ FN(HEADER_USED_FORMAT_TEXT) \
/** [3.6.1.1] */ FN(LIST_USAGE_INVALID_UL) \
/** [3.6.1.2] */ FN(LIST_USAGE_INVALID_OL) \
/** [3.6.1.4] */ FN(LIST_USAGE_INVALID_LI) \
/** [4.1.1.1] */ /* FN(INDICATE_CHANGES_IN_LANGUAGE) */ \
/** [4.3.1.1] */ FN(LANGUAGE_NOT_IDENTIFIED) \
/** [4.3.1.1] */ FN(LANGUAGE_INVALID) \
/** [5.1.2.1] */ FN(DATA_TABLE_MISSING_HEADERS) \
/** [5.1.2.2] */ FN(DATA_TABLE_MISSING_HEADERS_COLUMN) \
/** [5.1.2.3] */ FN(DATA_TABLE_MISSING_HEADERS_ROW) \
/** [5.2.1.1] */ FN(DATA_TABLE_REQUIRE_MARKUP_COLUMN_HEADERS) \
/** [5.2.1.2] */ FN(DATA_TABLE_REQUIRE_MARKUP_ROW_HEADERS) \
/** [5.3.1.1] */ FN(LAYOUT_TABLES_LINEARIZE_PROPERLY) \
/** [5.4.1.1] */ FN(LAYOUT_TABLE_INVALID_MARKUP) \
/** [5.5.1.1] */ FN(TABLE_MISSING_SUMMARY) \
/** [5.5.1.2] */ FN(TABLE_SUMMARY_INVALID_NULL) \
/** [5.5.1.3] */ FN(TABLE_SUMMARY_INVALID_SPACES) \
/** [5.5.1.6] */ FN(TABLE_SUMMARY_INVALID_PLACEHOLDER) \
/** [5.5.2.1] */ FN(TABLE_MISSING_CAPTION) \
/** [5.6.1.1] */ FN(TABLE_MAY_REQUIRE_HEADER_ABBR) \
/** [5.6.1.2] */ FN(TABLE_MAY_REQUIRE_HEADER_ABBR_NULL) \
/** [5.6.1.3] */ FN(TABLE_MAY_REQUIRE_HEADER_ABBR_SPACES) \
/** [6.1.1.1] */ FN(STYLESHEETS_REQUIRE_TESTING_LINK) \
/** [6.1.1.2] */ FN(STYLESHEETS_REQUIRE_TESTING_STYLE_ELEMENT) \
/** [6.1.1.3] */ FN(STYLESHEETS_REQUIRE_TESTING_STYLE_ATTR) \
/** [6.2.1.1] */ FN(FRAME_SRC_INVALID) \
/** [6.2.2.1] */ FN(TEXT_EQUIVALENTS_REQUIRE_UPDATING_APPLET) \
/** [6.2.2.2] */ FN(TEXT_EQUIVALENTS_REQUIRE_UPDATING_SCRIPT) \
/** [6.2.2.3] */ FN(TEXT_EQUIVALENTS_REQUIRE_UPDATING_OBJECT) \
/** [6.3.1.1] */ FN(PROGRAMMATIC_OBJECTS_REQUIRE_TESTING_SCRIPT) \
/** [6.3.1.2] */ FN(PROGRAMMATIC_OBJECTS_REQUIRE_TESTING_OBJECT) \
/** [6.3.1.3] */ FN(PROGRAMMATIC_OBJECTS_REQUIRE_TESTING_EMBED) \
/** [6.3.1.4] */ FN(PROGRAMMATIC_OBJECTS_REQUIRE_TESTING_APPLET) \
/** [6.5.1.1] */ FN(FRAME_MISSING_NOFRAMES) \
/** [6.5.1.2] */ FN(NOFRAMES_INVALID_NO_VALUE) \
/** [6.5.1.3] */ FN(NOFRAMES_INVALID_CONTENT) \
/** [6.5.1.4] */ FN(NOFRAMES_INVALID_LINK) \
/** [7.1.1.1] */ FN(REMOVE_FLICKER_SCRIPT) \
/** [7.1.1.2] */ FN(REMOVE_FLICKER_OBJECT) \
/** [7.1.1.3] */ FN(REMOVE_FLICKER_EMBED) \
/** [7.1.1.4] */ FN(REMOVE_FLICKER_APPLET) \
/** [7.1.1.5] */ FN(REMOVE_FLICKER_ANIMATED_GIF) \
/** [7.2.1.1] */ FN(REMOVE_BLINK_MARQUEE) \
/** [7.4.1.1] */ FN(REMOVE_AUTO_REFRESH) \
/** [7.5.1.1] */ FN(REMOVE_AUTO_REDIRECT) \
/** [8.1.1.1] */ FN(ENSURE_PROGRAMMATIC_OBJECTS_ACCESSIBLE_SCRIPT) \
/** [8.1.1.2] */ FN(ENSURE_PROGRAMMATIC_OBJECTS_ACCESSIBLE_OBJECT) \
/** [8.1.1.3] */ FN(ENSURE_PROGRAMMATIC_OBJECTS_ACCESSIBLE_APPLET) \
/** [8.1.1.4] */ FN(ENSURE_PROGRAMMATIC_OBJECTS_ACCESSIBLE_EMBED) \
/** [9.1.1.1] */ FN(IMAGE_MAP_SERVER_SIDE_REQUIRES_CONVERSION) \
/** [9.3.1.1] */ FN(SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_MOUSE_DOWN) \
/** [9.3.1.2] */ FN(SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_MOUSE_UP) \
/** [9.3.1.3] */ FN(SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_CLICK) \
/** [9.3.1.4] */ FN(SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_MOUSE_OVER) \
/** [9.3.1.5] */ FN(SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_MOUSE_OUT) \
/** [9.3.1.6] */ FN(SCRIPT_NOT_KEYBOARD_ACCESSIBLE_ON_MOUSE_MOVE) \
/** [10.1.1.1] */ FN(NEW_WINDOWS_REQUIRE_WARNING_NEW) \
/** [10.1.1.2] */ FN(NEW_WINDOWS_REQUIRE_WARNING_BLANK) \
/** [10.2.1.1] */ /* FN(LABEL_NEEDS_REPOSITIONING_BEFORE_INPUT) */ \
/** [10.2.1.2] */ /* FN(LABEL_NEEDS_REPOSITIONING_AFTER_INPUT) */ \
/** [10.4.1.1] */ /* FN(FORM_CONTROL_REQUIRES_DEFAULT_TEXT) */ \
/** [10.4.1.2] */ /* FN(FORM_CONTROL_DEFAULT_TEXT_INVALID_NULL) */ \
/** [10.4.1.3] */ /* FN(FORM_CONTROL_DEFAULT_TEXT_INVALID_SPACES) */ \
/** [11.2.1.1] */ FN(REPLACE_DEPRECATED_HTML_APPLET) \
/** [11.2.1.2] */ FN(REPLACE_DEPRECATED_HTML_BASEFONT) \
/** [11.2.1.3] */ FN(REPLACE_DEPRECATED_HTML_CENTER) \
/** [11.2.1.4] */ FN(REPLACE_DEPRECATED_HTML_DIR) \
/** [11.2.1.5] */ FN(REPLACE_DEPRECATED_HTML_FONT) \
/** [11.2.1.6] */ FN(REPLACE_DEPRECATED_HTML_ISINDEX) \
/** [11.2.1.7] */ FN(REPLACE_DEPRECATED_HTML_MENU) \
/** [11.2.1.8] */ FN(REPLACE_DEPRECATED_HTML_S) \
/** [11.2.1.9] */ FN(REPLACE_DEPRECATED_HTML_STRIKE) \
/** [11.2.1.10] */ FN(REPLACE_DEPRECATED_HTML_U) \
/** [12.1.1.1] */ FN(FRAME_MISSING_TITLE) \
/** [12.1.1.2] */ FN(FRAME_TITLE_INVALID_NULL) \
/** [12.1.1.3] */ FN(FRAME_TITLE_INVALID_SPACES) \
/** [12.4.1.1] */ FN(ASSOCIATE_LABELS_EXPLICITLY) \
/** [12.4.1.2] */ FN(ASSOCIATE_LABELS_EXPLICITLY_FOR) \
/** [12.4.1.3] */ FN(ASSOCIATE_LABELS_EXPLICITLY_ID) \
/** [13.1.1.1] */ FN(LINK_TEXT_NOT_MEANINGFUL) \
/** [13.1.1.2] */ FN(LINK_TEXT_MISSING) \
/** [13.1.1.3] */ FN(LINK_TEXT_TOO_LONG) \
/** [13.1.1.4] */ FN(LINK_TEXT_NOT_MEANINGFUL_CLICK_HERE) \
/** [13.1.1.5] */ /* FN(LINK_TEXT_NOT_MEANINGFUL_MORE) */ \
/** [13.1.1.6] */ /* FN(LINK_TEXT_NOT_MEANINGFUL_FOLLOW_THIS) */ \
/** [13.2.1.1] */ FN(METADATA_MISSING) \
/** [13.2.1.2] */ /* FN(METADATA_MISSING_LINK) */ \
/** [13.2.1.3] */ FN(METADATA_MISSING_REDIRECT_AUTOREFRESH) \
/** [13.10.1.1] */ FN(SKIPOVER_ASCII_ART)
/** These message codes comprise every message is exclusive to theTidy console
** application. It it possible to build LibTidy without these strings.
*/
#if SUPPORT_CONSOLE_APP
#define FOREACH_MSG_CONSOLE(FN) \
FN(TC_LABEL_COL) \
FN(TC_LABEL_FILE) \
FN(TC_LABEL_LANG) \
FN(TC_LABEL_LEVL) \
FN(TC_LABEL_OPT) \
FN(TC_MAIN_ERROR_LOAD_CONFIG) \
FN(TC_OPT_ACCESS) \
FN(TC_OPT_ASCII) \
FN(TC_OPT_ASHTML) \
FN(TC_OPT_ASXML) \
FN(TC_OPT_BARE) \
FN(TC_OPT_BIG5) \
FN(TC_OPT_CLEAN) \
FN(TC_OPT_CONFIG) \
FN(TC_OPT_ERRORS) \
FN(TC_OPT_FILE) \
FN(TC_OPT_GDOC) \
FN(TC_OPT_HELP) \
FN(TC_OPT_HELPCFG) \
FN(TC_OPT_HELPENV) \
FN(TC_OPT_HELPOPT) \
FN(TC_OPT_IBM858) \
FN(TC_OPT_INDENT) \
FN(TC_OPT_ISO2022) \
FN(TC_OPT_LANGUAGE) \
FN(TC_OPT_LATIN0) \
FN(TC_OPT_LATIN1) \
FN(TC_OPT_MAC) \
FN(TC_OPT_MODIFY) \
FN(TC_OPT_NUMERIC) \
FN(TC_OPT_OMIT) \
FN(TC_OPT_OUTPUT) \
FN(TC_OPT_QUIET) \
FN(TC_OPT_RAW) \
FN(TC_OPT_SHIFTJIS) \
FN(TC_OPT_SHOWCFG) \
FN(TC_OPT_EXP_CFG) \
FN(TC_OPT_EXP_DEF) \
FN(TC_OPT_UPPER) \
FN(TC_OPT_UTF16) \
FN(TC_OPT_UTF16BE) \
FN(TC_OPT_UTF16LE) \
FN(TC_OPT_UTF8) \
FN(TC_OPT_VERSION) \
FN(TC_OPT_WIN1252) \
FN(TC_OPT_WRAP) \
FN(TC_OPT_XML) \
FN(TC_OPT_XMLCFG) \
FN(TC_OPT_XMLSTRG) \
FN(TC_OPT_XMLERRS) \
FN(TC_OPT_XMLOPTS) \
FN(TC_OPT_XMLHELP) \
FN(TC_STRING_CONF_HEADER) \
FN(TC_STRING_CONF_NAME) \
FN(TC_STRING_CONF_TYPE) \
FN(TC_STRING_CONF_VALUE) \
FN(TC_STRING_CONF_NOTE) \
FN(TC_STRING_OPT_NOT_DOCUMENTED) \
FN(TC_STRING_OUT_OF_MEMORY) \
FN(TC_STRING_FATAL_ERROR) \
FN(TC_STRING_FILE_MANIP) \
FN(TC_STRING_LANG_MUST_SPECIFY) \
FN(TC_STRING_LANG_NOT_FOUND) \
FN(TC_STRING_MUST_SPECIFY) \
FN(TC_STRING_PROCESS_DIRECTIVES) \
FN(TC_STRING_CHAR_ENCODING) \
FN(TC_STRING_MISC) \
FN(TC_STRING_XML) \
FN(TC_STRING_UNKNOWN_OPTION) \
FN(TC_STRING_UNKNOWN_OPTION_B) \
FN(TC_STRING_VERS_A) \
FN(TC_STRING_VERS_B) \
FN(TC_TXT_HELP_1) \
FN(TC_TXT_HELP_2A) \
FN(TC_TXT_HELP_2B) \
FN(TC_TXT_HELP_3) \
FN(TC_TXT_HELP_3A) \
FN(TC_TXT_HELP_CONFIG) \
FN(TC_TXT_HELP_CONFIG_NAME) \
FN(TC_TXT_HELP_CONFIG_TYPE) \
FN(TC_TXT_HELP_CONFIG_ALLW) \
FN(TC_TXT_HELP_ENV_1) \
FN(TC_TXT_HELP_ENV_1A) \
FN(TC_TXT_HELP_ENV_1B) \
FN(TC_TXT_HELP_ENV_1C) \
FN(TC_TXT_HELP_LANG_1) \
FN(TC_TXT_HELP_LANG_2) \
FN(TC_TXT_HELP_LANG_3)
#endif /* SUPPORT_CONSOLE_APP */
/** @} */
/** @} end group public_enum_gen */
/* MARK: - Public Enumerations */
/***************************************************************************//**
** @defgroup public_enumerations Public Enumerations
** @ingroup public_api
**
** @copybrief tidyenum.h
******************************************************************************/
/** @addtogroup public_enumerations
** @{ */
/** @name Configuration Options Enumerations
**
** These enumerators are used to define available configuration options and
** their option categories.
**
** @{ */
/** Option IDs are used used to get and/or set configuration option values and
** retrieve their descriptions.
**
** @remark These enum members all have associated localized strings available
** which describe the purpose of the option. These descriptions are
** available via their enum values only.
**
** @sa `config.c:option_defs[]` for internal implementation details; that
** array is where you will implement options defined in this enum; and
** it's important to add a string describing the option to
** `language_en.h`, too.
*/
typedef enum
{
TidyUnknownOption = 0, /**< Unknown option! */
TidyAccessibilityCheckLevel, /**< Accessibility check level */
TidyAltText, /**< Default text for alt attribute */
TidyAnchorAsName, /**< Define anchors as name attributes */
TidyAsciiChars, /**< Convert quotes and dashes to nearest ASCII char */
TidyBlockTags, /**< Declared block tags */
TidyBodyOnly, /**< Output BODY content only */
TidyBreakBeforeBR, /**< Output newline before <br> or not? */
TidyCharEncoding, /**< In/out character encoding */
TidyCoerceEndTags, /**< Coerce end tags from start tags where probably intended */
TidyCSSPrefix, /**< CSS class naming for clean option */
#ifndef DOXYGEN_SHOULD_SKIP_THIS
TidyCustomTags, /**< Internal use ONLY */
#endif
TidyDecorateInferredUL, /**< Mark inferred UL elements with no indent CSS */
TidyDoctype, /**< User specified doctype */
#ifndef DOXYGEN_SHOULD_SKIP_THIS
TidyDoctypeMode, /**< Internal use ONLY */
#endif
TidyDropEmptyElems, /**< Discard empty elements */
TidyDropEmptyParas, /**< Discard empty p elements */
TidyDropPropAttrs, /**< Discard proprietary attributes */
TidyDuplicateAttrs, /**< Keep first or last duplicate attribute */
TidyEmacs, /**< If true, format error output for GNU Emacs */
#ifndef DOXYGEN_SHOULD_SKIP_THIS
TidyEmacsFile, /**< Internal use ONLY */
#endif
TidyEmptyTags, /**< Declared empty tags */
TidyEncloseBlockText, /**< If yes text in blocks is wrapped in P's */
TidyEncloseBodyText, /**< If yes text at body is wrapped in P's */
TidyErrFile, /**< File name to write errors to */
TidyEscapeCdata, /**< Replace <![CDATA[]]> sections with escaped text */
TidyEscapeScripts, /**< Escape items that look like closing tags in script tags */
TidyFixBackslash, /**< Fix URLs by replacing \ with / */
TidyFixComments, /**< Fix comments with adjacent hyphens */
TidyFixUri, /**< Applies URI encoding if necessary */
TidyForceOutput, /**< Output document even if errors were found */
TidyGDocClean, /**< Clean up HTML exported from Google Docs */
TidyHideComments, /**< Hides all (real) comments in output */
TidyHtmlOut, /**< Output plain HTML, even for XHTML input.*/
TidyInCharEncoding, /**< Input character encoding (if different) */
TidyIndentAttributes, /**< Newline+indent before each attribute */
TidyIndentCdata, /**< Indent <!CDATA[ ... ]]> section */
TidyIndentContent, /**< Indent content of appropriate tags */
TidyIndentSpaces, /**< Indentation n spaces/tabs */
TidyInlineTags, /**< Declared inline tags */
TidyJoinClasses, /**< Join multiple class attributes */
TidyJoinStyles, /**< Join multiple style attributes */
TidyKeepFileTimes, /**< If yes last modied time is preserved */
TidyKeepTabs, /**< If yes keep input source tabs */
TidyLiteralAttribs, /**< If true attributes may use newlines */
TidyLogicalEmphasis, /**< Replace i by em and b by strong */
TidyLowerLiterals, /**< Folds known attribute values to lower case */
TidyMakeBare, /**< Replace smart quotes, em dashes, etc with ASCII */
TidyMakeClean, /**< Replace presentational clutter by style rules */
TidyMark, /**< Add meta element indicating tidied doc */
TidyMergeDivs, /**< Merge multiple DIVs */
TidyMergeEmphasis, /**< Merge nested B and I elements */
TidyMergeSpans, /**< Merge multiple SPANs */
TidyMetaCharset, /**< Adds/checks/fixes meta charset in the head, based on document type */
TidyMuteReports, /**< Filter these messages from output. */
TidyMuteShow, /**< Show message ID's in the error table */
TidyNCR, /**< Allow numeric character references */
TidyNewline, /**< Output line ending (default to platform) */
TidyNumEntities, /**< Use numeric entities */
TidyOmitOptionalTags, /**< Suppress optional start tags and end tags */
TidyOutCharEncoding, /**< Output character encoding (if different) */
TidyOutFile, /**< File name to write markup to */
TidyOutputBOM, /**< Output a Byte Order Mark (BOM) for UTF-16 encodings */
TidyPPrintTabs, /**< Indent using tabs instead of spaces */
TidyPreserveEntities, /**< Preserve entities */
TidyPreTags, /**< Declared pre tags */
TidyPriorityAttributes, /**< Attributes to place first in an element */
TidyPunctWrap, /**< consider punctuation and breaking spaces for wrapping */
TidyQuiet, /**< No 'Parsing X', guessed DTD or summary */
TidyQuoteAmpersand, /**< Output naked ampersand as & */
TidyQuoteMarks, /**< Output " marks as " */
TidyQuoteNbsp, /**< Output non-breaking space as entity */
TidyReplaceColor, /**< Replace hex color attribute values with names */
TidyShowErrors, /**< Number of errors to put out */
TidyShowFilename, /**< If true, the input filename is displayed with the error messages */
TidyShowInfo, /**< If true, info-level messages are shown */
TidyShowMarkup, /**< If false, normal output is suppressed */
TidyShowMetaChange, /**< show when meta http-equiv content charset was changed - compatibility */
TidyShowWarnings, /**< However errors are always shown */
TidySkipNested, /**< Skip nested tags in script and style CDATA */
TidySortAttributes, /**< Sort attributes */
TidyStrictTagsAttr, /**< Ensure tags and attributes match output HTML version */
TidyStyleTags, /**< Move style to head */
TidyTabSize, /**< Expand tabs to n spaces */
TidyUpperCaseAttrs, /**< Output attributes in upper not lower case */
TidyUpperCaseTags, /**< Output tags in upper not lower case */
TidyUseCustomTags, /**< Enable Tidy to use autonomous custom tags */
TidyVertSpace, /**< degree to which markup is spread out vertically */
TidyWarnPropAttrs, /**< Warns on proprietary attributes */
TidyWord2000, /**< Draconian cleaning for Word2000 */
TidyWrapAsp, /**< Wrap within ASP pseudo elements */
TidyWrapAttVals, /**< Wrap within attribute values */
TidyWrapJste, /**< Wrap within JSTE pseudo elements */
TidyWrapLen, /**< Wrap margin */
TidyWrapPhp, /**< Wrap consecutive PHP pseudo elements */
TidyWrapScriptlets, /**< Wrap within JavaScript string literals */
TidyWrapSection, /**< Wrap within <![ ... ]> section tags */
TidyWriteBack, /**< If true then output tidied markup */
TidyXhtmlOut, /**< Output extensible HTML */
TidyXmlDecl, /**< Add <?xml?> for XML docs */
TidyXmlOut, /**< Create output as XML */
TidyXmlPIs, /**< If set to yes PIs must end with ?> */
TidyXmlSpace, /**< If set to yes adds xml:space attr as needed */
TidyXmlTags, /**< Treat input as XML */
N_TIDY_OPTIONS /**< Must be last */
} TidyOptionId;
/** Categories of Tidy configuration options, which are used mostly by user
** interfaces to sort Tidy options into related groups.
**
** @remark These enum members all have associated localized strings available
** suitable for use as a category label, and are available with either
** the enum value, or a string version of the name.
**
** @sa `config.c:option_defs[]` for internal implementation details.
*/
typedef enum
{
TidyUnknownCategory = 300, /**< Unknown Category! */
FOREACH_TIDYCONFIGCATEGORY(MAKE_ENUM)
} TidyConfigCategory;
/** A Tidy configuration option can have one of these data types. */
typedef enum
{
TidyString, /**< String */
TidyInteger, /**< Integer or enumeration */
TidyBoolean /**< Boolean */
} TidyOptionType;
/** @}
** @name Configuration Options Pick List and Parser Enumerations
**
** These enums define enumerated states for the configuration options that
** take values that are not simple yes/no, strings, or simple integers.
**
** @{ */
/** AutoBool values used by ParseBool, ParseTriState, ParseIndent, ParseBOM
** @remark This enum's starting value is guaranteed to remain stable.
*/
typedef enum
{
TidyNoState = 0, /**< maps to 'no' */
TidyYesState, /**< maps to 'yes' */
TidyAutoState /**< Automatic */
} TidyTriState;
/** Values used by ParseUseCustomTags, which describes how Autonomous Custom
** tags (ACT's) found by Tidy are treated.
**
** @remark These enum members all have associated localized strings available
** for internal LibTidy use, and also have public string keys in the
** form MEMBER_STRING, e.g., TIDYCUSTOMBLOCKLEVEL_STRING
**
** @remark This enum's starting value is guaranteed to remain stable.
*/
typedef enum
{
TidyCustomNo = 0, /**< Do not allow autonomous custom tags */
TidyCustomBlocklevel, /**< ACT's treated as blocklevel */
TidyCustomEmpty, /**< ACT's treated as empty tags */
TidyCustomInline, /**< ACT's treated as inline tags */
TidyCustomPre /**< ACT's treated as pre tags */
} TidyUseCustomTagsState;
/** TidyNewline option values to control output line endings.
** @remark This enum's starting value is guaranteed to remain stable.
*/
typedef enum
{
TidyLF = 0, /**< Use Unix style: LF */
TidyCRLF, /**< Use DOS/Windows style: CR+LF */
TidyCR /**< Use Macintosh style: CR */
} TidyLineEnding;
/** TidyEncodingOptions option values specify the input and/or output encoding.
** @remark This enum's starting value is guaranteed to remain stable.
*/
typedef enum
{
TidyEncRaw = 0,
TidyEncAscii,
TidyEncLatin0,
TidyEncLatin1,
TidyEncUtf8,
#ifndef NO_NATIVE_ISO2022_SUPPORT
TidyEncIso2022,
#endif
TidyEncMac,
TidyEncWin1252,
TidyEncIbm858,
TidyEncUtf16le,
TidyEncUtf16be,
TidyEncUtf16,
TidyEncBig5,
TidyEncShiftjis
} TidyEncodingOptions;
/** Mode controlling treatment of doctype
** @remark This enum's starting value is guaranteed to remain stable.
*/
typedef enum
{
TidyDoctypeHtml5 = 0, /**< <!DOCTYPE html> */
TidyDoctypeOmit, /**< Omit DOCTYPE altogether */
TidyDoctypeAuto, /**< Keep DOCTYPE in input. Set version to content */
TidyDoctypeStrict, /**< Convert document to HTML 4 strict content model */
TidyDoctypeLoose, /**< Convert document to HTML 4 transitional content model */
TidyDoctypeUser /**< Set DOCTYPE FPI explicitly */
} TidyDoctypeModes;
/** Mode controlling treatment of duplicate Attributes
** @remark This enum's starting value is guaranteed to remain stable.
*/
typedef enum
{
TidyKeepFirst = 0, /**< Keep the first instance of an attribute */
TidyKeepLast /**< Keep the last instance of an attribute */
} TidyDupAttrModes;
/** Mode controlling treatment of sorting attributes
** @remark This enum's starting value is guaranteed to remain stable.
*/
typedef enum
{
TidySortAttrNone = 0, /**< Don't sort attributes */
TidySortAttrAlpha /**< Sort attributes alphabetically */
} TidyAttrSortStrategy;
/** Mode controlling capitalization of things, such as attributes.
** @remark This enum's starting value is guaranteed to remain stable.
*/
typedef enum
{
TidyUppercaseNo = 0, /**< Don't uppercase. */
TidyUppercaseYes, /**< Do uppercase. */
TidyUppercasePreserve /**< Preserve case. */
} TidyUppercase;
/** @}
** @name Document Tree
** @{
*/
/** Node types
*/
typedef enum
{
TidyNode_Root, /**< Root */
TidyNode_DocType, /**< DOCTYPE */
TidyNode_Comment, /**< Comment */
TidyNode_ProcIns, /**< Processing Instruction */
TidyNode_Text, /**< Text */
TidyNode_Start, /**< Start Tag */
TidyNode_End, /**< End Tag */
TidyNode_StartEnd, /**< Start/End (empty) Tag */
TidyNode_CDATA, /**< Unparsed Text */
TidyNode_Section, /**< XML Section */
TidyNode_Asp, /**< ASP Source */
TidyNode_Jste, /**< JSTE Source */
TidyNode_Php, /**< PHP Source */
TidyNode_XmlDecl /**< XML Declaration */
} TidyNodeType;
/** Known HTML element types
*/
typedef enum
{
TidyTag_UNKNOWN, /**< Unknown tag! Must be first */
TidyTag_A, /**< A */
TidyTag_ABBR, /**< ABBR */
TidyTag_ACRONYM, /**< ACRONYM */
TidyTag_ADDRESS, /**< ADDRESS */
TidyTag_ALIGN, /**< ALIGN */
TidyTag_APPLET, /**< APPLET */
TidyTag_AREA, /**< AREA */
TidyTag_B, /**< B */
TidyTag_BASE, /**< BASE */
TidyTag_BASEFONT, /**< BASEFONT */
TidyTag_BDO, /**< BDO */
TidyTag_BGSOUND, /**< BGSOUND */
TidyTag_BIG, /**< BIG */
TidyTag_BLINK, /**< BLINK */
TidyTag_BLOCKQUOTE, /**< BLOCKQUOTE */
TidyTag_BODY, /**< BODY */
TidyTag_BR, /**< BR */
TidyTag_BUTTON, /**< BUTTON */
TidyTag_CAPTION, /**< CAPTION */
TidyTag_CENTER, /**< CENTER */
TidyTag_CITE, /**< CITE */
TidyTag_CODE, /**< CODE */
TidyTag_COL, /**< COL */
TidyTag_COLGROUP, /**< COLGROUP */
TidyTag_COMMENT, /**< COMMENT */
TidyTag_DD, /**< DD */
TidyTag_DEL, /**< DEL */
TidyTag_DFN, /**< DFN */
TidyTag_DIR, /**< DIR */
TidyTag_DIV, /**< DIF */
TidyTag_DL, /**< DL */
TidyTag_DT, /**< DT */
TidyTag_EM, /**< EM */
TidyTag_EMBED, /**< EMBED */
TidyTag_FIELDSET, /**< FIELDSET */
TidyTag_FONT, /**< FONT */
TidyTag_FORM, /**< FORM */
TidyTag_FRAME, /**< FRAME */
TidyTag_FRAMESET, /**< FRAMESET */
TidyTag_H1, /**< H1 */
TidyTag_H2, /**< H2 */
TidyTag_H3, /**< H3 */
TidyTag_H4, /**< H4 */
TidyTag_H5, /**< H5 */
TidyTag_H6, /**< H6 */
TidyTag_HEAD, /**< HEAD */
TidyTag_HR, /**< HR */
TidyTag_HTML, /**< HTML */
TidyTag_I, /**< I */
TidyTag_IFRAME, /**< IFRAME */
TidyTag_ILAYER, /**< ILAYER */
TidyTag_IMG, /**< IMG */
TidyTag_INPUT, /**< INPUT */
TidyTag_INS, /**< INS */
TidyTag_ISINDEX, /**< ISINDEX */
TidyTag_KBD, /**< KBD */
TidyTag_KEYGEN, /**< KEYGEN */
TidyTag_LABEL, /**< LABEL */
TidyTag_LAYER, /**< LAYER */
TidyTag_LEGEND, /**< LEGEND */
TidyTag_LI, /**< LI */
TidyTag_LINK, /**< LINK */
TidyTag_LISTING, /**< LISTING */
TidyTag_MAP, /**< MAP */
TidyTag_MATHML, /**< MATH (HTML5) [i_a]2 MathML embedded in [X]HTML */
TidyTag_MARQUEE, /**< MARQUEE */
TidyTag_MENU, /**< MENU */
TidyTag_META, /**< META */
TidyTag_MULTICOL, /**< MULTICOL */
TidyTag_NOBR, /**< NOBR */
TidyTag_NOEMBED, /**< NOEMBED */
TidyTag_NOFRAMES, /**< NOFRAMES */
TidyTag_NOLAYER, /**< NOLAYER */
TidyTag_NOSAVE, /**< NOSAVE */
TidyTag_NOSCRIPT, /**< NOSCRIPT */
TidyTag_OBJECT, /**< OBJECT */
TidyTag_OL, /**< OL */
TidyTag_OPTGROUP, /**< OPTGROUP */
TidyTag_OPTION, /**< OPTION */
TidyTag_P, /**< P */
TidyTag_PARAM, /**< PARAM */
TidyTag_PICTURE, /**< PICTURE (HTML5) */
TidyTag_PLAINTEXT, /**< PLAINTEXT */
TidyTag_PRE, /**< PRE */
TidyTag_Q, /**< Q */
TidyTag_RB, /**< RB */
TidyTag_RBC, /**< RBC */
TidyTag_RP, /**< RP */
TidyTag_RT, /**< RT */
TidyTag_RTC, /**< RTC */
TidyTag_RUBY, /**< RUBY */
TidyTag_S, /**< S */
TidyTag_SAMP, /**< SAMP */
TidyTag_SCRIPT, /**< SCRIPT */
TidyTag_SELECT, /**< SELECT */
TidyTag_SERVER, /**< SERVER */
TidyTag_SERVLET, /**< SERVLET */
TidyTag_SMALL, /**< SMALL */
TidyTag_SPACER, /**< SPACER */
TidyTag_SPAN, /**< SPAN */
TidyTag_STRIKE, /**< STRIKE */
TidyTag_STRONG, /**< STRONG */
TidyTag_STYLE, /**< STYLE */
TidyTag_SUB, /**< SUB */
TidyTag_SUP, /**< SUP */
TidyTag_SVG, /**< SVG (HTML5) */
TidyTag_TABLE, /**< TABLE */
TidyTag_TBODY, /**< TBODY */
TidyTag_TD, /**< TD */
TidyTag_TEXTAREA, /**< TEXTAREA */
TidyTag_TFOOT, /**< TFOOT */
TidyTag_TH, /**< TH */
TidyTag_THEAD, /**< THEAD */
TidyTag_TITLE, /**< TITLE */
TidyTag_TR, /**< TR */
TidyTag_TT, /**< TT */
TidyTag_U, /**< U */
TidyTag_UL, /**< UL */
TidyTag_VAR, /**< VAR */
TidyTag_WBR, /**< WBR */
TidyTag_XMP, /**< XMP */
TidyTag_NEXTID, /**< NEXTID */
TidyTag_ARTICLE, /**< ARTICLE */
TidyTag_ASIDE, /**< ASIDE */
TidyTag_AUDIO, /**< AUDIO */
TidyTag_BDI, /**< BDI */
TidyTag_CANVAS, /**< CANVAS */
TidyTag_COMMAND, /**< COMMAND */
TidyTag_DATA, /**< DATA */
TidyTag_DATALIST, /**< DATALIST */
TidyTag_DETAILS, /**< DETAILS */
TidyTag_DIALOG, /**< DIALOG */
TidyTag_FIGCAPTION, /**< FIGCAPTION */
TidyTag_FIGURE, /**< FIGURE */
TidyTag_FOOTER, /**< FOOTER */
TidyTag_HEADER, /**< HEADER */
TidyTag_HGROUP, /**< HGROUP */
TidyTag_MAIN, /**< MAIN */
TidyTag_MARK, /**< MARK */
TidyTag_MENUITEM, /**< MENUITEM */
TidyTag_METER, /**< METER */
TidyTag_NAV, /**< NAV */
TidyTag_OUTPUT, /**< OUTPUT */
TidyTag_PROGRESS, /**< PROGRESS */
TidyTag_SECTION, /**< SECTION */
TidyTag_SOURCE, /**< SOURCE */
TidyTag_SUMMARY, /**< SUMMARY */
TidyTag_TEMPLATE, /**< TEMPLATE */
TidyTag_TIME, /**< TIME */
TidyTag_TRACK, /**< TRACK */
TidyTag_VIDEO, /**< VIDEO */
TidyTag_SLOT, /**< SLOT */
N_TIDY_TAGS /**< Must be last */
} TidyTagId;
/** Known HTML attributes
*/
typedef enum
{
TidyAttr_UNKNOWN, /**< UNKNOWN= */
TidyAttr_ABBR, /**< ABBR= */
TidyAttr_ACCEPT, /**< ACCEPT= */
TidyAttr_ACCEPT_CHARSET, /**< ACCEPT_CHARSET= */
TidyAttr_ACCESSKEY, /**< ACCESSKEY= */
TidyAttr_ACTION, /**< ACTION= */
TidyAttr_ADD_DATE, /**< ADD_DATE= */
TidyAttr_ALIGN, /**< ALIGN= */
TidyAttr_ALINK, /**< ALINK= */
TidyAttr_ALLOWFULLSCREEN, /**< ALLOWFULLSCREEN= */
TidyAttr_ALT, /**< ALT= */
TidyAttr_ARCHIVE, /**< ARCHIVE= */
TidyAttr_AXIS, /**< AXIS= */
TidyAttr_BACKGROUND, /**< BACKGROUND= */
TidyAttr_BGCOLOR, /**< BGCOLOR= */
TidyAttr_BGPROPERTIES, /**< BGPROPERTIES= */
TidyAttr_BORDER, /**< BORDER= */
TidyAttr_BORDERCOLOR, /**< BORDERCOLOR= */
TidyAttr_BOTTOMMARGIN, /**< BOTTOMMARGIN= */
TidyAttr_CELLPADDING, /**< CELLPADDING= */
TidyAttr_CELLSPACING, /**< CELLSPACING= */
TidyAttr_CHAR, /**< CHAR= */
TidyAttr_CHAROFF, /**< CHAROFF= */
TidyAttr_CHARSET, /**< CHARSET= */
TidyAttr_CHECKED, /**< CHECKED= */
TidyAttr_CITE, /**< CITE= */
TidyAttr_CLASS, /**< CLASS= */
TidyAttr_CLASSID, /**< CLASSID= */
TidyAttr_CLEAR, /**< CLEAR= */
TidyAttr_CODE, /**< CODE= */
TidyAttr_CODEBASE, /**< CODEBASE= */
TidyAttr_CODETYPE, /**< CODETYPE= */
TidyAttr_COLOR, /**< COLOR= */
TidyAttr_COLS, /**< COLS= */
TidyAttr_COLSPAN, /**< COLSPAN= */
TidyAttr_COMPACT, /**< COMPACT= */
TidyAttr_CONTENT, /**< CONTENT= */
TidyAttr_COORDS, /**< COORDS= */
TidyAttr_DATA, /**< DATA= */
TidyAttr_DATAFLD, /**< DATAFLD= */
TidyAttr_DATAFORMATAS, /**< DATAFORMATAS= */
TidyAttr_DATAPAGESIZE, /**< DATAPAGESIZE= */
TidyAttr_DATASRC, /**< DATASRC= */
TidyAttr_DATETIME, /**< DATETIME= */
TidyAttr_DECLARE, /**< DECLARE= */
TidyAttr_DEFER, /**< DEFER= */
TidyAttr_DIR, /**< DIR= */
TidyAttr_DISABLED, /**< DISABLED= */
TidyAttr_DOWNLOAD, /**< DOWNLOAD= */
TidyAttr_ENCODING, /**< ENCODING= */
TidyAttr_ENCTYPE, /**< ENCTYPE= */
TidyAttr_FACE, /**< FACE= */
TidyAttr_FOR, /**< FOR= */
TidyAttr_FRAME, /**< FRAME= */
TidyAttr_FRAMEBORDER, /**< FRAMEBORDER= */
TidyAttr_FRAMESPACING, /**< FRAMESPACING= */
TidyAttr_GRIDX, /**< GRIDX= */
TidyAttr_GRIDY, /**< GRIDY= */
TidyAttr_HEADERS, /**< HEADERS= */
TidyAttr_HEIGHT, /**< HEIGHT= */
TidyAttr_HREF, /**< HREF= */
TidyAttr_HREFLANG, /**< HREFLANG= */
TidyAttr_HSPACE, /**< HSPACE= */
TidyAttr_HTTP_EQUIV, /**< HTTP_EQUIV= */
TidyAttr_ID, /**< ID= */
TidyAttr_IS, /**< IS= */
TidyAttr_ISMAP, /**< ISMAP= */
TidyAttr_ITEMID, /**< ITEMID= */
TidyAttr_ITEMPROP, /**< ITEMPROP= */
TidyAttr_ITEMREF, /**< ITEMREF= */
TidyAttr_ITEMSCOPE, /**< ITEMSCOPE= */
TidyAttr_ITEMTYPE, /**< ITEMTYPE= */
TidyAttr_LABEL, /**< LABEL= */
TidyAttr_LANG, /**< LANG= */
TidyAttr_LANGUAGE, /**< LANGUAGE= */
TidyAttr_LAST_MODIFIED, /**< LAST_MODIFIED= */
TidyAttr_LAST_VISIT, /**< LAST_VISIT= */
TidyAttr_LEFTMARGIN, /**< LEFTMARGIN= */
TidyAttr_LINK, /**< LINK= */
TidyAttr_LONGDESC, /**< LONGDESC= */
TidyAttr_LOWSRC, /**< LOWSRC= */
TidyAttr_MARGINHEIGHT, /**< MARGINHEIGHT= */
TidyAttr_MARGINWIDTH, /**< MARGINWIDTH= */
TidyAttr_MAXLENGTH, /**< MAXLENGTH= */
TidyAttr_MEDIA, /**< MEDIA= */
TidyAttr_METHOD, /**< METHOD= */
TidyAttr_MULTIPLE, /**< MULTIPLE= */
TidyAttr_NAME, /**< NAME= */
TidyAttr_NOHREF, /**< NOHREF= */
TidyAttr_NORESIZE, /**< NORESIZE= */
TidyAttr_NOSHADE, /**< NOSHADE= */
TidyAttr_NOWRAP, /**< NOWRAP= */
TidyAttr_OBJECT, /**< OBJECT= */
TidyAttr_OnAFTERUPDATE, /**< OnAFTERUPDATE= */
TidyAttr_OnBEFOREUNLOAD, /**< OnBEFOREUNLOAD= */
TidyAttr_OnBEFOREUPDATE, /**< OnBEFOREUPDATE= */
TidyAttr_OnBLUR, /**< OnBLUR= */
TidyAttr_OnCHANGE, /**< OnCHANGE= */
TidyAttr_OnCLICK, /**< OnCLICK= */
TidyAttr_OnDATAAVAILABLE, /**< OnDATAAVAILABLE= */
TidyAttr_OnDATASETCHANGED, /**< OnDATASETCHANGED= */
TidyAttr_OnDATASETCOMPLETE, /**< OnDATASETCOMPLETE= */
TidyAttr_OnDBLCLICK, /**< OnDBLCLICK= */
TidyAttr_OnERRORUPDATE, /**< OnERRORUPDATE= */
TidyAttr_OnFOCUS, /**< OnFOCUS= */
TidyAttr_OnKEYDOWN, /**< OnKEYDOWN= */
TidyAttr_OnKEYPRESS, /**< OnKEYPRESS= */
TidyAttr_OnKEYUP, /**< OnKEYUP= */
TidyAttr_OnLOAD, /**< OnLOAD= */
TidyAttr_OnMOUSEDOWN, /**< OnMOUSEDOWN= */
TidyAttr_OnMOUSEMOVE, /**< OnMOUSEMOVE= */
TidyAttr_OnMOUSEOUT, /**< OnMOUSEOUT= */
TidyAttr_OnMOUSEOVER, /**< OnMOUSEOVER= */
TidyAttr_OnMOUSEUP, /**< OnMOUSEUP= */
TidyAttr_OnRESET, /**< OnRESET= */
TidyAttr_OnROWENTER, /**< OnROWENTER= */
TidyAttr_OnROWEXIT, /**< OnROWEXIT= */
TidyAttr_OnSELECT, /**< OnSELECT= */
TidyAttr_OnSUBMIT, /**< OnSUBMIT= */
TidyAttr_OnUNLOAD, /**< OnUNLOAD= */
TidyAttr_PROFILE, /**< PROFILE= */
TidyAttr_PROMPT, /**< PROMPT= */
TidyAttr_RBSPAN, /**< RBSPAN= */
TidyAttr_READONLY, /**< READONLY= */
TidyAttr_REL, /**< REL= */
TidyAttr_REV, /**< REV= */
TidyAttr_RIGHTMARGIN, /**< RIGHTMARGIN= */
TidyAttr_ROLE, /**< ROLE= */
TidyAttr_ROWS, /**< ROWS= */
TidyAttr_ROWSPAN, /**< ROWSPAN= */
TidyAttr_RULES, /**< RULES= */
TidyAttr_SCHEME, /**< SCHEME= */
TidyAttr_SCOPE, /**< SCOPE= */
TidyAttr_SCROLLING, /**< SCROLLING= */
TidyAttr_SELECTED, /**< SELECTED= */
TidyAttr_SHAPE, /**< SHAPE= */
TidyAttr_SHOWGRID, /**< SHOWGRID= */
TidyAttr_SHOWGRIDX, /**< SHOWGRIDX= */
TidyAttr_SHOWGRIDY, /**< SHOWGRIDY= */
TidyAttr_SIZE, /**< SIZE= */
TidyAttr_SPAN, /**< SPAN= */
TidyAttr_SRC, /**< SRC= */
TidyAttr_SRCSET, /**< SRCSET= (HTML5) */
TidyAttr_STANDBY, /**< STANDBY= */
TidyAttr_START, /**< START= */
TidyAttr_STYLE, /**< STYLE= */
TidyAttr_SUMMARY, /**< SUMMARY= */
TidyAttr_TABINDEX, /**< TABINDEX= */
TidyAttr_TARGET, /**< TARGET= */
TidyAttr_TEXT, /**< TEXT= */
TidyAttr_TITLE, /**< TITLE= */
TidyAttr_TOPMARGIN, /**< TOPMARGIN= */
TidyAttr_TRANSLATE, /**< TRANSLATE= */
TidyAttr_TYPE, /**< TYPE= */
TidyAttr_USEMAP, /**< USEMAP= */
TidyAttr_VALIGN, /**< VALIGN= */
TidyAttr_VALUE, /**< VALUE= */
TidyAttr_VALUETYPE, /**< VALUETYPE= */
TidyAttr_VERSION, /**< VERSION= */
TidyAttr_VLINK, /**< VLINK= */
TidyAttr_VSPACE, /**< VSPACE= */
TidyAttr_WIDTH, /**< WIDTH= */
TidyAttr_WRAP, /**< WRAP= */
TidyAttr_XML_LANG, /**< XML_LANG= */
TidyAttr_XML_SPACE, /**< XML_SPACE= */
TidyAttr_XMLNS, /**< XMLNS= */
TidyAttr_EVENT, /**< EVENT= */
TidyAttr_METHODS, /**< METHODS= */
TidyAttr_N, /**< N= */
TidyAttr_SDAFORM, /**< SDAFORM= */
TidyAttr_SDAPREF, /**< SDAPREF= */
TidyAttr_SDASUFF, /**< SDASUFF= */
TidyAttr_URN, /**< URN= */
TidyAttr_ASYNC, /**< ASYNC= */
TidyAttr_AUTOCOMPLETE, /**< AUTOCOMPLETE= */
TidyAttr_AUTOFOCUS, /**< AUTOFOCUS= */
TidyAttr_AUTOPLAY, /**< AUTOPLAY= */
TidyAttr_CHALLENGE, /**< CHALLENGE= */
TidyAttr_CONTENTEDITABLE, /**< CONTENTEDITABLE= */
TidyAttr_CONTEXTMENU, /**< CONTEXTMENU= */
TidyAttr_CONTROLS, /**< CONTROLS= */
TidyAttr_CROSSORIGIN, /**< CROSSORIGIN= */
TidyAttr_DEFAULT, /**< DEFAULT= */
TidyAttr_DIRNAME, /**< DIRNAME= */
TidyAttr_DRAGGABLE, /**< DRAGGABLE= */
TidyAttr_DROPZONE, /**< DROPZONE= */
TidyAttr_FORM, /**< FORM= */
TidyAttr_FORMACTION, /**< FORMACTION= */
TidyAttr_FORMENCTYPE, /**< FORMENCTYPE= */
TidyAttr_FORMMETHOD, /**< FORMMETHOD= */
TidyAttr_FORMNOVALIDATE, /**< FORMNOVALIDATE= */
TidyAttr_FORMTARGET, /**< FORMTARGET= */
TidyAttr_HIDDEN, /**< HIDDEN= */
TidyAttr_HIGH, /**< HIGH= */
TidyAttr_ICON, /**< ICON= */
TidyAttr_KEYTYPE, /**< KEYTYPE= */
TidyAttr_KIND, /**< KIND= */
TidyAttr_LIST, /**< LIST= */
TidyAttr_LOOP, /**< LOOP= */
TidyAttr_LOW, /**< LOW= */
TidyAttr_MANIFEST, /**< MANIFEST= */
TidyAttr_MAX, /**< MAX= */
TidyAttr_MEDIAGROUP, /**< MEDIAGROUP= */
TidyAttr_MIN, /**< MIN= */
TidyAttr_MUTED, /**< MUTED= */
TidyAttr_NOVALIDATE, /**< NOVALIDATE= */
TidyAttr_OPEN, /**< OPEN= */
TidyAttr_OPTIMUM, /**< OPTIMUM= */
TidyAttr_OnABORT, /**< OnABORT= */
TidyAttr_OnAFTERPRINT, /**< OnAFTERPRINT= */
TidyAttr_OnBEFOREPRINT, /**< OnBEFOREPRINT= */
TidyAttr_OnCANPLAY, /**< OnCANPLAY= */
TidyAttr_OnCANPLAYTHROUGH, /**< OnCANPLAYTHROUGH= */
TidyAttr_OnCONTEXTMENU, /**< OnCONTEXTMENU= */
TidyAttr_OnCUECHANGE, /**< OnCUECHANGE= */
TidyAttr_OnDRAG, /**< OnDRAG= */
TidyAttr_OnDRAGEND, /**< OnDRAGEND= */
TidyAttr_OnDRAGENTER, /**< OnDRAGENTER= */
TidyAttr_OnDRAGLEAVE, /**< OnDRAGLEAVE= */
TidyAttr_OnDRAGOVER, /**< OnDRAGOVER= */
TidyAttr_OnDRAGSTART, /**< OnDRAGSTART= */
TidyAttr_OnDROP, /**< OnDROP= */
TidyAttr_OnDURATIONCHANGE, /**< OnDURATIONCHANGE= */
TidyAttr_OnEMPTIED, /**< OnEMPTIED= */
TidyAttr_OnENDED, /**< OnENDED= */
TidyAttr_OnERROR, /**< OnERROR= */
TidyAttr_OnHASHCHANGE, /**< OnHASHCHANGE= */
TidyAttr_OnINPUT, /**< OnINPUT= */
TidyAttr_OnINVALID, /**< OnINVALID= */
TidyAttr_OnLOADEDDATA, /**< OnLOADEDDATA= */
TidyAttr_OnLOADEDMETADATA, /**< OnLOADEDMETADATA= */
TidyAttr_OnLOADSTART, /**< OnLOADSTART= */
TidyAttr_OnMESSAGE, /**< OnMESSAGE= */
TidyAttr_OnMOUSEWHEEL, /**< OnMOUSEWHEEL= */
TidyAttr_OnOFFLINE, /**< OnOFFLINE= */
TidyAttr_OnONLINE, /**< OnONLINE= */
TidyAttr_OnPAGEHIDE, /**< OnPAGEHIDE= */
TidyAttr_OnPAGESHOW, /**< OnPAGESHOW= */
TidyAttr_OnPAUSE, /**< OnPAUSE= */
TidyAttr_OnPLAY, /**< OnPLAY= */
TidyAttr_OnPLAYING, /**< OnPLAYING= */
TidyAttr_OnPOPSTATE, /**< OnPOPSTATE= */
TidyAttr_OnPROGRESS, /**< OnPROGRESS= */
TidyAttr_OnRATECHANGE, /**< OnRATECHANGE= */
TidyAttr_OnREADYSTATECHANGE, /**< OnREADYSTATECHANGE= */
TidyAttr_OnREDO, /**< OnREDO= */
TidyAttr_OnRESIZE, /**< OnRESIZE= */
TidyAttr_OnSCROLL, /**< OnSCROLL= */
TidyAttr_OnSEEKED, /**< OnSEEKED= */
TidyAttr_OnSEEKING, /**< OnSEEKING= */
TidyAttr_OnSHOW, /**< OnSHOW= */
TidyAttr_OnSTALLED, /**< OnSTALLED= */
TidyAttr_OnSTORAGE, /**< OnSTORAGE= */
TidyAttr_OnSUSPEND, /**< OnSUSPEND= */
TidyAttr_OnTIMEUPDATE, /**< OnTIMEUPDATE= */
TidyAttr_OnUNDO, /**< OnUNDO= */
TidyAttr_OnVOLUMECHANGE, /**< OnVOLUMECHANGE= */
TidyAttr_OnWAITING, /**< OnWAITING= */
TidyAttr_PATTERN, /**< PATTERN= */
TidyAttr_PLACEHOLDER, /**< PLACEHOLDER= */
TidyAttr_PLAYSINLINE, /**< PLAYSINLINE= */
TidyAttr_POSTER, /**< POSTER= */
TidyAttr_PRELOAD, /**< PRELOAD= */
TidyAttr_PUBDATE, /**< PUBDATE= */
TidyAttr_RADIOGROUP, /**< RADIOGROUP= */
TidyAttr_REQUIRED, /**< REQUIRED= */
TidyAttr_REVERSED, /**< REVERSED= */
TidyAttr_SANDBOX, /**< SANDBOX= */
TidyAttr_SCOPED, /**< SCOPED= */
TidyAttr_SEAMLESS, /**< SEAMLESS= */
TidyAttr_SIZES, /**< SIZES= */
TidyAttr_SPELLCHECK, /**< SPELLCHECK= */
TidyAttr_SRCDOC, /**< SRCDOC= */
TidyAttr_SRCLANG, /**< SRCLANG= */
TidyAttr_STEP, /**< STEP= */
TidyAttr_ARIA_ACTIVEDESCENDANT, /**< ARIA_ACTIVEDESCENDANT */
TidyAttr_ARIA_ATOMIC, /**< ARIA_ATOMIC= */
TidyAttr_ARIA_AUTOCOMPLETE, /**< ARIA_AUTOCOMPLETE= */
TidyAttr_ARIA_BUSY, /**< ARIA_BUSY= */
TidyAttr_ARIA_CHECKED, /**< ARIA_CHECKED= */
TidyAttr_ARIA_CONTROLS, /**< ARIA_CONTROLS= */
TidyAttr_ARIA_DESCRIBEDBY, /**< ARIA_DESCRIBEDBY= */
TidyAttr_ARIA_DISABLED, /**< ARIA_DISABLED= */
TidyAttr_ARIA_DROPEFFECT, /**< ARIA_DROPEFFECT= */
TidyAttr_ARIA_EXPANDED, /**< ARIA_EXPANDED= */
TidyAttr_ARIA_FLOWTO, /**< ARIA_FLOWTO= */
TidyAttr_ARIA_GRABBED, /**< ARIA_GRABBED= */
TidyAttr_ARIA_HASPOPUP, /**< ARIA_HASPOPUP= */
TidyAttr_ARIA_HIDDEN, /**< ARIA_HIDDEN= */
TidyAttr_ARIA_INVALID, /**< ARIA_INVALID= */
TidyAttr_ARIA_LABEL, /**< ARIA_LABEL= */
TidyAttr_ARIA_LABELLEDBY, /**< ARIA_LABELLEDBY= */
TidyAttr_ARIA_LEVEL, /**< ARIA_LEVEL= */
TidyAttr_ARIA_LIVE, /**< ARIA_LIVE= */
TidyAttr_ARIA_MULTILINE, /**< ARIA_MULTILINE= */
TidyAttr_ARIA_MULTISELECTABLE, /**< ARIA_MULTISELECTABLE= */
TidyAttr_ARIA_ORIENTATION, /**< ARIA_ORIENTATION= */
TidyAttr_ARIA_OWNS, /**< ARIA_OWNS= */
TidyAttr_ARIA_POSINSET, /**< ARIA_POSINSET= */
TidyAttr_ARIA_PRESSED, /**< ARIA_PRESSED= */
TidyAttr_ARIA_READONLY, /**< ARIA_READONLY= */
TidyAttr_ARIA_RELEVANT, /**< ARIA_RELEVANT= */
TidyAttr_ARIA_REQUIRED, /**< ARIA_REQUIRED= */
TidyAttr_ARIA_SELECTED, /**< ARIA_SELECTED= */
TidyAttr_ARIA_SETSIZE, /**< ARIA_SETSIZE= */
TidyAttr_ARIA_SORT, /**< ARIA_SORT= */
TidyAttr_ARIA_VALUEMAX, /**< ARIA_VALUEMAX= */
TidyAttr_ARIA_VALUEMIN, /**< ARIA_VALUEMIN= */
TidyAttr_ARIA_VALUENOW, /**< ARIA_VALUENOW= */
TidyAttr_ARIA_VALUETEXT, /**< ARIA_VALUETEXT= */
/* SVG attributes (SVG 1.1) */
TidyAttr_X, /**< X= */
TidyAttr_Y, /**< Y= */
TidyAttr_VIEWBOX, /**< VIEWBOX= */
TidyAttr_PRESERVEASPECTRATIO, /**< PRESERVEASPECTRATIO= */
TidyAttr_ZOOMANDPAN, /**< ZOOMANDPAN= */
TidyAttr_BASEPROFILE, /**< BASEPROFILE= */
TidyAttr_CONTENTSCRIPTTYPE, /**< CONTENTSCRIPTTYPE= */
TidyAttr_CONTENTSTYLETYPE, /**< CONTENTSTYLETYPE= */
/* MathML <math> attributes */
TidyAttr_DISPLAY, /**< DISPLAY= (html5) */
/* RDFa global attributes */
TidyAttr_ABOUT, /**< ABOUT= */
TidyAttr_DATATYPE, /**< DATATYPE= */
TidyAttr_INLIST, /**< INLIST= */
TidyAttr_PREFIX, /**< PREFIX= */
TidyAttr_PROPERTY, /**< PROPERTY= */
TidyAttr_RESOURCE, /**< RESOURCE= */
TidyAttr_TYPEOF, /**< TYPEOF= */
TidyAttr_VOCAB, /**< VOCAB= */
TidyAttr_INTEGRITY, /**< INTEGRITY= */
TidyAttr_AS, /**< AS= */
TidyAttr_XMLNSXLINK, /**< svg xmls:xlink="url" */
TidyAttr_SLOT, /**< SLOT= */
TidyAttr_LOADING, /**< LOADING= */
/* SVG paint attributes (SVG 1.1) */
TidyAttr_FILL, /**< FILL= */
TidyAttr_FILLRULE, /**< FILLRULE= */
TidyAttr_STROKE, /**< STROKE= */
TidyAttr_STROKEDASHARRAY, /**< STROKEDASHARRAY= */
TidyAttr_STROKEDASHOFFSET, /**< STROKEDASHOFFSET= */
TidyAttr_STROKELINECAP, /**< STROKELINECAP= */
TidyAttr_STROKELINEJOIN, /**< STROKELINEJOIN= */
TidyAttr_STROKEMITERLIMIT, /**< STROKEMITERLIMIT= */
TidyAttr_STROKEWIDTH, /**< STROKEWIDTH= */
TidyAttr_COLORINTERPOLATION, /**< COLORINTERPOLATION= */
TidyAttr_COLORRENDERING, /**< COLORRENDERING= */
TidyAttr_OPACITY, /**< OPACITY= */
TidyAttr_STROKEOPACITY, /**< STROKEOPACITY= */
TidyAttr_FILLOPACITY, /**< FILLOPACITY= */
N_TIDY_ATTRIBS /**< Must be last */
} TidyAttrId;
/** @}
** @name I/O and Message Handling Interface
**
** Messages used throughout LibTidy and exposed to the public API have
** attributes which are communicated with these enumerations.
**
** @{
*/
/** Message severity level, used throughout LibTidy to indicate the severity
** or status of a message
**
** @remark These enum members all have associated localized strings available
** via their enum values. These strings are suitable for use as labels.
*/
typedef enum
{
TidyInfo = 350, /**< Report: Information about markup usage */
TidyWarning, /**< Report: Warning message */
TidyConfig, /**< Report: Configuration error */
TidyAccess, /**< Report: Accessibility message */
TidyError, /**< Report: Error message - output suppressed */
TidyBadDocument, /**< Report: I/O or file system error */
TidyFatal, /**< Report: Crash! */
TidyDialogueSummary, /**< Dialogue: Summary-related information */
TidyDialogueInfo, /**< Dialogue: Non-document related information */
TidyDialogueFootnote, /**< Dialogue: Footnote */
TidyDialogueDoc = TidyDialogueFootnote, /**< Dialogue: Deprecated (renamed) */
} TidyReportLevel;
/** Indicates the data type of a format string parameter used when Tidy
** emits reports and dialogue as part of the messaging callback functions.
** See `messageobj.h` for more information on this API.
*/
typedef enum
{
tidyFormatType_INT = 0, /**< Argument is signed integer. */
tidyFormatType_UINT, /**< Argument is unsigned integer. */
tidyFormatType_STRING, /**< Argument is a string. */
tidyFormatType_DOUBLE, /**< Argument is a double. */
tidyFormatType_UNKNOWN = 20 /**< Argument type is unknown! */
} TidyFormatParameterType;
/** @} */
/** @} end group public_enumerations*/
/* MARK: - Public Enumerations (con't) */
/** @addtogroup public_enumerations
** @{ */
/** @name Messages
** @{ */
/** The enumeration contains a list of every possible string that Tidy and the
** console application can output, _except_ for strings from the following
** enumerations:
** - `TidyOptionId`
** - `TidyConfigCategory`
** - `TidyReportLevel`
**
** They are used as keys internally within Tidy, and have corresponding text
** keys that are used in message callback filters (these are defined in
** `tidyStringsKeys[]`, but API users don't require access to it directly).
*/
typedef enum
{
/* This MUST be present and first. */
TIDYSTRINGS_FIRST = 500,
FOREACH_MSG_MISC(MAKE_ENUM)
FOREACH_FOOTNOTE_MSG(MAKE_ENUM)
FOREACH_DIALOG_MSG(MAKE_ENUM)
REPORT_MESSAGE_FIRST,
FOREACH_REPORT_MSG(MAKE_ENUM)
REPORT_MESSAGE_LAST,
FOREACH_ACCESS_MSG(MAKE_ENUM)
#if SUPPORT_CONSOLE_APP
FOREACH_MSG_CONSOLE(MAKE_ENUM)
#endif
/* This MUST be present and last. */
TIDYSTRINGS_LAST
} tidyStrings;
/** @} */
/** @} end group public_enumerations */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* __TIDYENUM_H__ */
| 69,009 | 1,473 | jart/cosmopolitan | false |
cosmopolitan/third_party/tidy/LICENSE.md | # HTML Tidy
## HTML parser and pretty printer
Copyright (c) 1998-2016 World Wide Web Consortium
(Massachusetts Institute of Technology, European Research
Consortium for Informatics and Mathematics, Keio University).
All Rights Reserved.
Additional contributions (c) 2001-2016 University of Toronto, Terry Teague,
@geoffmcl, HTACG, and others.
### Contributing Author(s):
Dave Raggett <[email protected]>
The contributing author(s) would like to thank all those who
helped with testing, bug fixes and suggestions for improvements.
This wouldn't have been possible without your help.
## COPYRIGHT NOTICE:
This software and documentation is provided "as is," and
the copyright holders and contributing author(s) make no
representations or warranties, express or implied, including
but not limited to, warranties of merchantability or fitness
for any particular purpose or that the use of the software or
documentation will not infringe any third party patents,
copyrights, trademarks or other rights.
The copyright holders and contributing author(s) will not be held
liable for any direct, indirect, special or consequential damages
arising out of any use of the software or documentation, even if
advised of the possibility of such damage.
Permission is hereby granted to use, copy, modify, and distribute
this source code, or portions hereof, documentation and executables,
for any purpose, without fee, subject to the following restrictions:
1. The origin of this source code must not be misrepresented.
2. Altered versions must be plainly marked as such and must
not be misrepresented as being the original source.
3. This Copyright notice may not be removed or altered from any
source or altered source distribution.
The copyright holders and contributing author(s) specifically
permit, without fee, and encourage the use of this source code
as a component for supporting the Hypertext Markup Language in
commercial products. If you use this source code in a product,
acknowledgement is not required but would be appreciated.
| 2,035 | 51 | jart/cosmopolitan | false |
cosmopolitan/third_party/tidy/tmbstr.c | /* clang-format off */
/* tmbstr.c -- Tidy string utility functions
(c) 1998-2006 (W3C) MIT, ERCIM, Keio University
See tidy.h for the copyright notice.
*/
#include "third_party/tidy/forward.h"
#include "third_party/tidy/tmbstr.h"
#include "libc/fmt/fmt.h"
#include "third_party/tidy/lexer.h"
/* like strdup but using an allocator */
tmbstr TY_(tmbstrdup)( TidyAllocator *allocator, ctmbstr str )
{
tmbstr s = NULL;
if ( str )
{
uint len = TY_(tmbstrlen)( str );
tmbstr cp = s = (tmbstr) TidyAlloc( allocator, 1+len );
while ( 0 != (*cp++ = *str++) )
/**/;
}
return s;
}
/* like strndup but using an allocator */
tmbstr TY_(tmbstrndup)( TidyAllocator *allocator, ctmbstr str, uint len )
{
tmbstr s = NULL;
if ( str && len > 0 )
{
tmbstr cp = s = (tmbstr) TidyAlloc( allocator, 1+len );
while ( len-- > 0 && (*cp++ = *str++) )
/**/;
*cp = 0;
}
return s;
}
/* exactly same as strncpy */
uint TY_(tmbstrncpy)( tmbstr s1, ctmbstr s2, uint size )
{
if ( s1 != NULL && s2 != NULL )
{
tmbstr cp = s1;
while ( *s2 && --size ) /* Predecrement: reserve byte */
*cp++ = *s2++; /* for NULL terminator. */
*cp = 0;
}
return size;
}
/* Allows expressions like: cp += tmbstrcpy( cp, "joebob" );
*/
uint TY_(tmbstrcpy)( tmbstr s1, ctmbstr s2 )
{
uint ncpy = 0;
while (0 != (*s1++ = *s2++) )
++ncpy;
return ncpy;
}
/* Allows expressions like: cp += tmbstrcat( cp, "joebob" );
*/
uint TY_(tmbstrcat)( tmbstr s1, ctmbstr s2 )
{
uint ncpy = 0;
while ( *s1 )
++s1;
while (0 != (*s1++ = *s2++) )
++ncpy;
return ncpy;
}
/* exactly same as strcmp */
int TY_(tmbstrcmp)( ctmbstr s1, ctmbstr s2 )
{
int c;
while ((c = *s1) == *s2)
{
if (c == '\0')
return 0;
++s1;
++s2;
}
return (*s1 > *s2 ? 1 : -1);
}
/* returns byte count, not char count */
uint TY_(tmbstrlen)( ctmbstr str )
{
uint len = 0;
if ( str )
{
while ( *str++ )
++len;
}
return len;
}
/*
MS C 4.2 (and ANSI C) doesn't include strcasecmp.
Note that tolower and toupper won't
work on chars > 127.
Neither does ToLower()!
*/
int TY_(tmbstrcasecmp)( ctmbstr s1, ctmbstr s2 )
{
uint c;
while (c = (uint)(*s1), TY_(ToLower)(c) == TY_(ToLower)((uint)(*s2)))
{
if (c == '\0')
return 0;
++s1;
++s2;
}
return (*s1 > *s2 ? 1 : -1);
}
int TY_(tmbstrncmp)( ctmbstr s1, ctmbstr s2, uint n )
{
uint c;
if (s1 == NULL || s2 == NULL)
{
if (s1 == s2)
return 0;
return (s1 == NULL ? -1 : 1);
}
while ((c = (byte)*s1) == (byte)*s2)
{
if (c == '\0')
return 0;
if (n == 0)
return 0;
++s1;
++s2;
--n;
}
if (n == 0)
return 0;
return (*s1 > *s2 ? 1 : -1);
}
int TY_(tmbstrncasecmp)( ctmbstr s1, ctmbstr s2, uint n )
{
uint c;
while (c = (uint)(*s1), TY_(ToLower)(c) == TY_(ToLower)((uint)(*s2)))
{
if (c == '\0')
return 0;
if (n == 0)
return 0;
++s1;
++s2;
--n;
}
if (n == 0)
return 0;
return (*s1 > *s2 ? 1 : -1);
}
ctmbstr TY_(tmbsubstrn)( ctmbstr s1, uint len1, ctmbstr s2 )
{
uint len2 = TY_(tmbstrlen)(s2);
int ix, diff = len1 - len2;
for ( ix = 0; ix <= diff; ++ix )
{
if ( TY_(tmbstrncmp)(s1+ix, s2, len2) == 0 )
return (ctmbstr) s1+ix;
}
return NULL;
}
ctmbstr TY_(tmbsubstr)( ctmbstr s1, ctmbstr s2 )
{
uint len1 = TY_(tmbstrlen)(s1), len2 = TY_(tmbstrlen)(s2);
int ix, diff = len1 - len2;
for ( ix = 0; ix <= diff; ++ix )
{
if ( TY_(tmbstrncasecmp)(s1+ix, s2, len2) == 0 )
return (ctmbstr) s1+ix;
}
return NULL;
}
/* Transform ASCII chars in string to lower case */
tmbstr TY_(tmbstrtolower)( tmbstr s )
{
tmbstr cp;
for ( cp=s; *cp; ++cp )
*cp = (tmbchar) TY_(ToLower)( *cp );
return s;
}
/* Transform ASCII chars in string to upper case */
tmbstr TY_(tmbstrtoupper)(tmbstr s)
{
tmbstr cp;
for (cp = s; *cp; ++cp)
*cp = (tmbchar)TY_(ToUpper)(*cp);
return s;
}
int TY_(tmbvsnprintf)(tmbstr buffer, size_t count, ctmbstr format, va_list args)
{
int retval;
#if HAS_VSNPRINTF
retval = vsnprintf(buffer, count - 1, format, args);
/* todo: conditionally null-terminate the string? */
buffer[count - 1] = 0;
#else
retval = vsprintf(buffer, format, args);
#endif /* HAS_VSNPRINTF */
return retval;
}
int TY_(tmbsnprintf)(tmbstr buffer, size_t count, ctmbstr format, ...)
{
int retval;
va_list args;
va_start(args, format);
retval = TY_(tmbvsnprintf)(buffer, count, format, args);
va_end(args);
return retval;
}
void TY_(strrep)(tmbstr buffer, ctmbstr str, ctmbstr rep)
{
char *p = strstr(buffer, str);
do
{
if(p)
{
char buf[1024];
memset(buf,'\0',strlen(buf));
if(buffer == p)
{
strcpy(buf,rep);
strcat(buf,p+strlen(str));
}
else
{
strncpy(buf,buffer,strlen(buffer) - strlen(p));
strcat(buf,rep);
strcat(buf,p+strlen(str));
}
memset(buffer,'\0',strlen(buffer));
strcpy(buffer,buf);
}
} while(p && (p = strstr(buffer, str)));
}
/*
* local variables:
* mode: c
* indent-tabs-mode: nil
* c-basic-offset: 4
* end:
*/
| 5,712 | 289 | jart/cosmopolitan | false |
cosmopolitan/third_party/tidy/tidy.h | #ifndef __TIDY_H__
#define __TIDY_H__
/* clang-format off */
/***************************************************************************//**
* @file
* Defines HTML Tidy public API implemented by LibTidy.
*
* This public interface provides the entire public API for LibTidy, and
* is the sole interface that you should use when implementing LibTidy in
* your own applications.
*
* See tidy.c as an example application implementing the public API.
*
* This API is const-correct and doesn't explicitly depend on any globals.
* Thus, thread-safety may be introduced without changing the interface.
*
* The API limits all exposure to internal structures and provides only
* accessors that return simple types such as C strings and integers, which
* makes it quite suitable for integration with any number of other languages.
*
* @author Dave Raggett [[email protected]]
* @author HTACG, et al (consult git log)
*
* @remarks The contributing author(s) would like to thank all those who
* helped with testing, bug fixes and suggestions for improvements.
* This wouldn't have been possible without your help.
*
* @copyright
* Copyright (c) 1998-2017 World Wide Web Consortium (Massachusetts
* Institute of Technology, European Research Consortium for Informatics
* and Mathematics, Keio University).
* @par
* All Rights Reserved.
* @par
* This software and documentation is provided "as is," and the copyright
* holders and contributing author(s) make no representations or warranties,
* express or implied, including but not limited to, warranties of
* merchantability or fitness for any particular purpose or that the use of
* the software or documentation will not infringe any third party patents,
* copyrights, trademarks or other rights.
* @par
* The copyright holders and contributing author(s) will not be held liable
* for any direct, indirect, special or consequential damages arising out of
* any use of the software or documentation, even if advised of the
* possibility of such damage.
* @par
* Permission is hereby granted to use, copy, modify, and distribute this
* source code, or portions hereof, documentation and executables, for any
* purpose, without fee, subject to the following restrictions:
* @par
* 1. The origin of this source code must not be misrepresented.
* 2. Altered versions must be plainly marked as such and must not be
* misrepresented as being the original source.
* 3. This Copyright notice may not be removed or altered from any source
* or altered source distribution.
* @par
* The copyright holders and contributing author(s) specifically permit,
* without fee, and encourage the use of this source code as a component for
* supporting the Hypertext Markup Language in commercial products. If you
* use this source code in a product, acknowledgment is not required but
* would be appreciated.
*
* @date Created 2001-05-20 by Charles Reitzel
* @date Updated 2002-07-01 by Charles Reitzel - 1st Implementation
* @date Updated 2015-06-09 by Geoff R. McLane - Add more doxygen syntax
* @date Additional updates: consult git log
******************************************************************************/
#include "third_party/tidy/tidyplatform.h"
#include "libc/stdio/stdio.h"
#include "third_party/tidy/tidyenum.h"
#ifdef __cplusplus
extern "C" {
#endif
/***************************************************************************//**
** @defgroup internal_api Internal API
** The Internal API is used exclusively within LibTidy. If you are an
** HTML Tidy developer, then the internals API will be of especial
** importance to you.
**
** @note Always check first to determine whether or not an internal API
** representation exists for a public API function before invoking a
** public API function internally. In most cases, the public API
** functions simply call an internal function.
** - - -
** @note This documentation _is not_ a substitute for browsing the source
** code. Although the public API is fairly well documented, the
** internal API is a very long, very slow, work-in-progress.
******************************************************************************/
/***************************************************************************//**
** @defgroup public_api External Public API
** The Public API is the API that LibTidy programmers must access in order
** to harness HTML Tidy as a library. The API limits all exposure to internal
** structures and provides only accessors that return simple types such as
** C strings and integers, which makes it quite suitable for integration with
** any number of other languages.
** @{
******************************************************************************/
/* MARK: - Opaque Types */
/***************************************************************************//**
** @defgroup Opaque Opaque Types
**
** Instances of these types are returned by LibTidy API functions, however
** they are opaque; you cannot see into them, and must use accessor functions
** to access the contents. This ensures that interfacing to LibTidy remains
** as universal as possible.
**
** @note Internally LibTidy developers will cast these to internal
** implementation types with access to all member fields.
** @{
******************************************************************************/
/** @struct TidyDoc
** Instances of this represent a Tidy document, which encapsulates everything
** there is to know about a single Tidy session. Many of the API functions
** return instance of TidyDoc, or expect instances as parameters.
*/
/** @struct TidyOption
** Instances of this represent a Tidy configuration option, which contains
** useful data about these options. Functions related to configuration options
** return or accept instances of this type.
*/
/** @struct TidyNode
** Single nodes of a TidyDocument are represented by this datatype. It can be
** returned by various API functions, or accepted as a function argument.
*/
/** @struct TidyAttr
** Attributes of a TidyNode are represented by this data type. The public API
** functions related to attributes work with this type.
*/
/** @struct TidyMessage
** Instances of this type represent messages generated by Tidy in reference
** to your document. This API is available in some of Tidy's message callback
** functions.
*/
/** @struct TidyMessageArgument
** Instances of this type represent the arguments that compose part of the
** message represented by TidyMessage. These arguments have an API to query
** information about them.
*/
/* Prevent Doxygen from listing these as functions. */
#ifndef DOXYGEN_SHOULD_SKIP_THIS
opaque_type( TidyDoc );
opaque_type( TidyOption );
opaque_type( TidyNode );
opaque_type( TidyAttr );
opaque_type( TidyMessage );
opaque_type( TidyMessageArgument );
#endif
/** @} end Opaque group */
/* MARK: - Memory Allocation */
/***************************************************************************//**
** @defgroup Memory Memory Allocation
**
** Tidy can use a user-provided allocator for all memory allocations. If this
** allocator is not provided, then a default allocator is used which simply
** wraps standard C malloc()/free() calls. These wrappers call the panic()
** function upon any failure. The default panic function prints an out of
** memory message to **stderr**, and calls `exit(2)`.
**
** For applications in which it is unacceptable to abort in the case of memory
** allocation, then the panic function can be replaced with one which
** `longjmps()` out of the LibTidy code. For this to clean up completely, you
** should be careful not to use any Tidy methods that open files as these will
** not be closed before `panic()` is called.
**
** Calling the `xxxWithAllocator()` family (`tidyCreateWithAllocator`,
** `tidyBufInitWithAllocator`, `tidyBufAllocWithAllocator`) allow setting
** custom allocators.
**
** All parts of the document use the same allocator. Calls that require a
** user-provided buffer can optionally use a different allocator.
**
** For reference in designing a plug-in allocator, most allocations made by
** LibTidy are less than 100 bytes, corresponding to attribute names and
** values, etc.
**
** There is also an additional class of much larger allocations which are where
** most of the data from the lexer is stored. It is not currently possible to
** use a separate allocator for the lexer; this would be a useful extension.
**
** In general, approximately 1/3rd of the memory used by LibTidy is freed
** during the parse, so if memory usage is an issue then an allocator that can
** reuse this memory is a good idea.
**
** **To create your own allocator, do something like the following:**
** @code{.c}
** typedef struct _MyAllocator {
** TidyAllocator base;
** // ...other custom allocator state...
** } MyAllocator;
**
** void* MyAllocator_alloc(TidyAllocator *base, void *block, size_t nBytes) {
** MyAllocator *self = (MyAllocator*)base;
** // ...
** }
** // etc.
**
** static const TidyAllocatorVtbl MyAllocatorVtbl = {
** MyAllocator_alloc,
** MyAllocator_realloc,
** MyAllocator_free,
** MyAllocator_panic
** };
**
** myAllocator allocator;
** TidyDoc doc;
**
** allocator.base.vtbl = &MyAllocatorVtbl;
** //...initialise allocator specific state...
** doc = tidyCreateWithAllocator(&allocator);
** @endcode
**
** Although this looks slightly long-winded, the advantage is that to create a
** custom allocator you simply need to set the vtbl pointer correctly. The vtbl
** itself can reside in static/global data, and hence does not need to be
** initialised each time an allocator is created, and furthermore the memory
** is shared amongst all created allocators.
**
** @{
******************************************************************************/
/* Forward declarations and typedefs. */
struct _TidyAllocatorVtbl;
struct _TidyAllocator;
typedef struct _TidyAllocatorVtbl TidyAllocatorVtbl;
typedef struct _TidyAllocator TidyAllocator;
/** Tidy's built-in default allocator. */
struct _TidyAllocator {
const TidyAllocatorVtbl *vtbl; /**< The allocator's function table. */
};
/** This structure is the function table for an allocator. Note that all
functions in this table must be provided. */
struct _TidyAllocatorVtbl
{
/* Doxygen has no idea how to parse these. */
#ifndef DOXYGEN_SHOULD_SKIP_THIS
void* (TIDY_CALL *alloc)( TidyAllocator *self, size_t nBytes );
void* (TIDY_CALL *realloc)(TidyAllocator *self, void *block, size_t nBytes );
void (TIDY_CALL *free)(TidyAllocator *self, void *block);
void (TIDY_CALL *panic)(TidyAllocator *self, ctmbstr msg);
#else
/** Called to allocate a block of nBytes of memory */
void* *alloc(TidyAllocator *self, /**< The TidyAllocator to use to alloc memory. */
size_t nBytes /**< The number of bytes to allocate. */
);
/** Called to resize (grow, in general) a block of memory.
Must support being called with `NULL`. */
void* *realloc(TidyAllocator *self, /**< The TidyAllocator to use to realloc memory. */
void *block, /**< The pointer to the existing block. */
size_t nBytes /**< The number of bytes to allocate. */
);
/** Called to free a previously allocated block of memory.
*/
void *free(TidyAllocator *self, /**< The TidyAllocator to use to free memory. */
void *block /**< The block to free. */
);
/** Called when a panic condition is detected. Must support `block == NULL`.
This function is not called if either alloc() or realloc() fails; it is
up to the allocator to do this. Currently this function can only be
called if an error is detected in the tree integrity via the internal
function CheckNodeIntegrity(). This is a situation that can only arise
in the case of a programming error in LibTidy. You can turn off node
integrity checking by defining the constant `NO_NODE_INTEGRITY_CHECK`
during the build.
**/
void *panic(TidyAllocator *self, /**< The TidyAllocator to use to panic. */
ctmbstr msg /**< The panic message. */
);
#endif /* Doxygen Fix */
};
/** Callback for `malloc` replacement */
typedef void* (TIDY_CALL *TidyMalloc)( size_t len );
/** Callback for `realloc` replacement */
typedef void* (TIDY_CALL *TidyRealloc)( void* buf, size_t len );
/** Callback for `free` replacement */
typedef void (TIDY_CALL *TidyFree)( void* buf );
/** Callback for out of memory panic state */
typedef void (TIDY_CALL *TidyPanic)( ctmbstr mssg );
/** Give Tidy a `malloc()` replacement */
Bool tidySetMallocCall( TidyMalloc fmalloc );
/** Give Tidy a `realloc()` replacement */
Bool tidySetReallocCall( TidyRealloc frealloc );
/** Give Tidy a `free()` replacement */
Bool tidySetFreeCall( TidyFree ffree );
/** Give Tidy an "out of memory" handler */
Bool tidySetPanicCall( TidyPanic fpanic );
/** @} end Memory group */
/* MARK: - Basic Operations */
/***************************************************************************//**
** @defgroup Basic Basic Operations
**
** For an excellent example of how to invoke LibTidy, please consult
** `console/tidy.c:main()` for in-depth implementation details. A simplified
** example can be seen on our site: https://www.html-tidy.org/developer/
**
** @{
******************************************************************************/
/** @name Instantiation and Destruction
** @{
*/
/** The primary creation of a document instance. Instances of a TidyDoc are used
** throughout the API as a token to represent a particular document. You must
** create at least one TidyDoc instance to initialize the library and begin
** interaction with the API. When done using a TidyDoc instance, be sure to
** `tidyRelease(myTidyDoc);` in order to free related memory.
** @result Returns a TidyDoc instance.
*/
TidyDoc tidyCreate(void);
/** Create a document supplying your own, custom TidyAllocator instead of using
** the built-in default. See the @ref Memory module if you want to create and
** use your own allocator.
** @param allocator The allocator to use for creating the document.
** @result Returns a TidyDoc instance.
*/
TidyDoc tidyCreateWithAllocator(TidyAllocator *allocator);
/** Free all memory and release the TidyDoc. The TidyDoc can not be used after
** this call.
** @param tdoc The TidyDoc to free.
*/
void tidyRelease(TidyDoc tdoc);
/** @}
** @name Host Application Data
** @{
*/
/** Allows the host application to store a chunk of data with each TidyDoc
** instance. This can be useful for callbacks, such as saving a reference to
** `self` within the document.
*/
void tidySetAppData(TidyDoc tdoc, /**< The document in which to store the data. */
void* appData /**< The pointer to a block of data to store. */
);
/** Returns the data previously stored with `tidySetAppData()`.
** @param tdoc document where data has been stored.
** @result The pointer to the data block previously stored.
*/
void* tidyGetAppData(TidyDoc tdoc);
/** @}
** @name LibTidy Version Information
** @{
*/
/** Get the release date for the current library.
** @result The string representing the release date.
*/
ctmbstr tidyReleaseDate(void);
/** Get the version number for the current library.
** @result The string representing the version number.
*/
ctmbstr tidyLibraryVersion(void);
/** Get the platform for which Tidy was built.
** @result The string representing the version number.
*/
ctmbstr tidyPlatform(void);
/** @}
** @name Diagnostics and Repair
** @{
*/
/** Get status of current document.
** @param tdoc An instance of a TidyDoc to query.
** @result Returns the highest of `2` indicating that errors were present in
** the document, `1` indicating warnings, and `0` in the case of
** everything being okay.
*/
int tidyStatus( TidyDoc tdoc );
/** Gets the version of HTML that was output, as an integer, times 100. For
** example, HTML5 will return 500; HTML4.0.1 will return 401.
** @param tdoc An instance of a TidyDoc to query.
** @result Returns the HTML version number (x100).
*/
int tidyDetectedHtmlVersion( TidyDoc tdoc );
/** Indicates whether the output document is or isn't XHTML.
** @param tdoc An instance of a TidyDoc to query.
** @result Returns `yes` if the document is an XHTML type.
*/
Bool tidyDetectedXhtml( TidyDoc tdoc );
/** Indicates whether or not the input document was XML. If TidyXml tags is
** true, or there was an XML declaration in the input document, then this
** function will return yes.
** @param tdoc An instance of a TidyDoc to query.
** @result Returns `yes` if the input document was XML.
*/
Bool tidyDetectedGenericXml( TidyDoc tdoc );
/** Indicates the number of TidyError messages that were generated. For any
** value greater than `0`, output is suppressed unless TidyForceOutput is set.
** @param tdoc An instance of a TidyDoc to query.
** @result Returns the number of TidyError messages that were generated.
*/
uint tidyErrorCount( TidyDoc tdoc );
/** Indicates the number of TidyWarning messages that were generated.
** @param tdoc An instance of a TidyDoc to query.
** @result Returns the number of TidyWarning messages that were generated.
*/
uint tidyWarningCount( TidyDoc tdoc );
/** Indicates the number of TidyAccess messages that were generated.
** @param tdoc An instance of a TidyDoc to query.
** @result Returns the number of TidyAccess messages that were generated.
*/
uint tidyAccessWarningCount( TidyDoc tdoc );
/** Indicates the number of configuration error messages that were generated.
** @param tdoc An instance of a TidyDoc to query.
** @result Returns the number of configuration error messages that were
** generated.
*/
uint tidyConfigErrorCount( TidyDoc tdoc );
/** Write more complete information about errors to current error sink.
** @param tdoc An instance of a TidyDoc to query.
*/
void tidyErrorSummary( TidyDoc tdoc );
/** Write more general information about markup to current error sink.
** @param tdoc An instance of a TidyDoc to query.
*/
void tidyGeneralInfo( TidyDoc tdoc );
/** @}
** @name Configuration, File, and Encoding Operations
** @{
*/
/** Load an ASCII Tidy configuration file and set the configuration per its
** contents. Reports config option errors, which can be filtered.
** @result Returns 0 upon success, or any other value if there was an option error.
*/
int tidyLoadConfig(TidyDoc tdoc, /**< The TidyDoc to which to apply the configuration. */
ctmbstr configFile /**< The complete path to the file to load. */
);
/** Load a Tidy configuration file with the specified character encoding, and
** set the configuration per its contents. Reports config option errors, which can be filtered.
** @result Returns 0 upon success, or any other value if there was an option error.
*/
int tidyLoadConfigEnc(TidyDoc tdoc, /**< The TidyDoc to which to apply the configuration. */
ctmbstr configFile, /**< The complete path to the file to load. */
ctmbstr charenc /**< The encoding to use. See the _enc2iana struct for valid values. */
);
/** Determine whether or not a particular file exists. On Unix systems, the use
** of the tilde to represent the user's home directory is supported.
** @result Returns `yes` or `no`, indicating whether or not the file exists.
*/
Bool tidyFileExists(TidyDoc tdoc, /**< The TidyDoc on whose behalf you are checking. */
ctmbstr filename /**< The path to the file whose existence you wish to check. */
);
/** Set the input/output character encoding for parsing markup. Valid values
** include `ascii`, `latin1`, `raw`, `utf8`, `iso2022`, `mac`, `win1252`,
** `utf16le`, `utf16be`, `utf16`, `big5`, and `shiftjis`. These values are not
** case sensitive.
** @note This is the same as using TidySetInCharEncoding() and
** TidySetOutCharEncoding() to set the same value.
** @result Returns 0 upon success, or a system standard error number `EINVAL`.
*/
int tidySetCharEncoding(TidyDoc tdoc, /**< The TidyDoc for which you are setting the encoding. */
ctmbstr encnam /**< The encoding name as described above. */
);
/** Set the input encoding for parsing markup. Valid values include `ascii`,
** `latin1`, `raw`, `utf8`, `iso2022`, `mac`, `win1252`, `utf16le`, `utf16be`,
** `utf16`, `big5`, and `shiftjis`. These values are not case sensitive.
** @result Returns 0 upon success, or a system standard error number `EINVAL`.
*/
int tidySetInCharEncoding(TidyDoc tdoc, /**< The TidyDoc for which you are setting the encoding. */
ctmbstr encnam /**< The encoding name as described above. */
);
/** Set the input encoding for writing markup. Valid values include `ascii`,
** `latin1`, `raw`, `utf8`, `iso2022`, `mac`, `win1252`, `utf16le`, `utf16be`,
** `utf16`, `big5`, and `shiftjis`. These values are not case sensitive.
** @result Returns 0 upon success, or a system standard error number `EINVAL`.
*/
int tidySetOutCharEncoding(TidyDoc tdoc, /**< The TidyDoc for which you are setting the encoding. */
ctmbstr encnam /**< The encoding name as described above. */
);
/** @} */
/** @} end Basic group */
/* MARK: - Configuration Options */
/***************************************************************************//**
** @defgroup Configuration Configuration Options
**
** Functions for getting and setting Tidy configuration options.
**
** @note In general, you should expect that options you set should stay set.
** This isn't always the case, though, because Tidy will adjust options
** for internal use during the lexing, parsing, cleaning, and printing
** phases. If you require access to user configuration values at any
** time after the tidyParseXXX() process, make sure to keep your own
** copy, or use tidyOptResetToSnapshot() when you no longer need to
** use any other tidy functions.
** @{
******************************************************************************/
/** @name Option Callback Functions
** @{
*/
/** This typedef represents the required signature for your provided callback
** function should you wish to register one with tidySetOptionCallback().
** Your callback function will be provided with the following parameters.
** Note that this is deprecated and you should instead migrate to
** tidySetConfigCallback().
** @param option The option name that was provided.
** @param value The option value that was provided
** @return Your callback function will return `yes` if it handles the provided
** option, or `no` if it does not. In the latter case, Tidy will issue
** an unknown configuration option error.
*/
typedef Bool (TIDY_CALL *TidyOptCallback)(ctmbstr option, ctmbstr value);
/** Applications using TidyLib may want to augment command-line and
** configuration file options. Setting this callback allows a LibTidy
** application developer to examine command-line and configuration file options
** after LibTidy has examined them and failed to recognize them.
** Note that this is deprecated and you should instead migrate to
** tidySetConfigCallback().
** @result Returns `yes` upon success.
*/
Bool tidySetOptionCallback(TidyDoc tdoc, /**< The document to apply the callback to. */
TidyOptCallback pOptCallback /**< The name of a function of type TidyOptCallback() to serve as your callback. */
);
/** This typedef represents the required signature for your provided callback
** function should you wish to register one with tidySetConfigCallback().
** Your callback function will be provided with the following parameters.
** @param tdoc The document instance for which the callback was invoked.
** @param option The option name that was provided.
** @param value The option value that was provided
** @return Your callback function will return `yes` if it handles the provided
** option, or `no` if it does not. In the latter case, Tidy will issue
** an unknown configuration option error.
*/
typedef Bool (TIDY_CALL *TidyConfigCallback)(TidyDoc tdoc, ctmbstr option, ctmbstr value);
/** Applications using TidyLib may want to augment command-line and
** configuration file options. Setting this callback allows a LibTidy
** application developer to examine command-line and configuration file options
** after LibTidy has examined them and failed to recognize them.
** @result Returns `yes` upon success.
*/
Bool tidySetConfigCallback(TidyDoc tdoc, /**< The document to apply the callback to. */
TidyConfigCallback pConfigCallback /**< The name of a function of type TidyConfigCallback() to serve as your callback. */
);
/** This typedef represents the required signature for your provided callback
** function should you wish to register one with tidySetConfigChangeCallback().
** Your callback function will be provided with the following parameters.
** @param tdoc The document instance for which the callback was invoked.
** @param option The option that will be changed.
*/
typedef void (TIDY_CALL *TidyConfigChangeCallback)(TidyDoc tdoc, TidyOption option);
/** Applications using TidyLib may want to be informed when changes to options
** are made. Temporary changes made internally by Tidy are not reported, but
** permanent changes made by Tidy (such as indent-spaces or output-encoding)
** will be reported.
** @note This callback is not currently implemented.
** @result Returns `yes` upon success.
*/
Bool tidySetConfigChangeCallback(TidyDoc tdoc, /**< The document to apply the callback to. */
TidyConfigChangeCallback pCallback /**< The name of a function of type TidyConfigChangeCallback() to serve as your callback. */
);
/** @}
** @name Option ID Discovery
** @{
*/
/** Get ID of given Option
** @param opt An instance of a TidyOption to query.
** @result The TidyOptionId of the given option.
*/
TidyOptionId tidyOptGetId( TidyOption opt );
/** Returns the TidyOptionId (enum value) by providing the name of a Tidy
** configuration option.
** @param optnam The name of the option ID to retrieve.
** @result The TidyOptionId of the given `optname`.
*/
TidyOptionId tidyOptGetIdForName(ctmbstr optnam);
/** @}
** @name Getting Instances of Tidy Options
** @{
*/
/** Initiates an iterator for a list of TidyOption instances, which allows you
** to iterate through all of the available options. In order to iterate through
** the available options, initiate the iterator with this function, and then
** use tidyGetNextOption() to retrieve the first and subsequent options. For
** example:
** @code{.c}
** TidyIterator itOpt = tidyGetOptionList( tdoc );
** while ( itOpt ) {
** TidyOption opt = tidyGetNextOption( tdoc, &itOpt );
** // Use other API to query or set set option values
** }
** @endcode
** @param tdoc An instance of a TidyDoc to query.
** @result Returns a TidyIterator, which is a token used to represent the
** current position in a list within LibTidy.
*/
TidyIterator tidyGetOptionList( TidyDoc tdoc );
/** Given a valid TidyIterator initiated with tidyGetOptionList(), returns
** the instance of the next TidyOption.
** @note This function will return internal-only option types including
** `TidyInternalCategory`; you should *never* use these. Always ensure
** that you use `tidyOptGetCategory()` before assuming that an option
** is okay to use in your application.
** @result An instance of TidyOption.
*/
TidyOption tidyGetNextOption(TidyDoc tdoc, /**< The document for which you are retrieving options. */
TidyIterator* pos /**< The TidyIterator (initiated with tidyGetOptionList()) token. */
);
/** Retrieves an instance of TidyOption given a valid TidyOptionId.
** @result An instance of TidyOption matching the provided TidyOptionId.
*/
TidyOption tidyGetOption(TidyDoc tdoc, /**< The document for which you are retrieving the option. */
TidyOptionId optId /**< The TidyOptionId to retrieve. */
);
/** Returns an instance of TidyOption by providing the name of a Tidy
** configuration option.
** @result The TidyOption of the given `optname`.
*/
TidyOption tidyGetOptionByName(TidyDoc tdoc, /**< The document for which you are retrieving the option. */
ctmbstr optnam /**< The name of the Tidy configuration option. */
);
/** @}
** @name Information About Options
** @{
*/
/** Get name of given Option
** @param opt An instance of a TidyOption to query.
** @result The name of the given option.
*/
ctmbstr tidyOptGetName( TidyOption opt );
/** Get datatype of given Option
** @param opt An instance of a TidyOption to query.
** @result The TidyOptionType of the given option.
*/
TidyOptionType tidyOptGetType( TidyOption opt );
/** Indicates that an option takes a list of items.
** @param opt An instance of a TidyOption to query.
** @result A bool indicating whether or not the option accepts a list.
*/
Bool tidyOptionIsList( TidyOption opt );
/** Is Option read-only? Some options (mainly internal use only options) are
** read-only.
** @deprecated This is no longer a valid test for the public API; instead
** you should test an option's availability using `tidyOptGetCategory()`
** against `TidyInternalCategory`. This API will be removed!
** @param opt An instance of a TidyOption to query.
** @result Returns `yes` or `no` depending on whether or not the specified
** option is read-only.
*/
Bool tidyOptIsReadOnly( TidyOption opt );
/** Get category of given Option
** @param opt An instance of a TidyOption to query.
** @result The TidyConfigCategory of the specified option.
*/
TidyConfigCategory tidyOptGetCategory( TidyOption opt );
/** Get default value of given Option as a string
** @param opt An instance of a TidyOption to query.
** @result A string indicating the default value of the specified option.
*/
ctmbstr tidyOptGetDefault( TidyOption opt );
/** Get default value of given Option as an unsigned integer
** @param opt An instance of a TidyOption to query.
** @result An unsigned integer indicating the default value of the specified
** option.
*/
ulong tidyOptGetDefaultInt( TidyOption opt );
/** Get default value of given Option as a Boolean value
** @param opt An instance of a TidyOption to query.
** @result A boolean indicating the default value of the specified option.
*/
Bool tidyOptGetDefaultBool( TidyOption opt );
/** Initiates an iterator for a list of TidyOption pick-list values, which
** allows you iterate through all of the available option values. In order to
** iterate through the available values, initiate the iterator with this
** function, and then use tidyOptGetNextPick() to retrieve the first and
** subsequent option values. For example:
** @code{.c}
** TidyIterator itOpt = tidyOptGetPickList( opt );
** while ( itOpt ) {
** printf("%s", tidyOptGetNextPick( opt, &itOpt ));
** }
** @endcode
** @param opt An instance of a TidyOption to query.
** @result Returns a TidyIterator, which is a token used to represent the
** current position in a list within LibTidy.
*/
TidyIterator tidyOptGetPickList( TidyOption opt );
/** Given a valid TidyIterator initiated with tidyOptGetPickList(), returns a
** string representing a possible option value.
** @result A string containing the next pick-list option value.
*/
ctmbstr tidyOptGetNextPick(TidyOption opt, /**< An instance of a TidyOption to query. */
TidyIterator* pos /**< The TidyIterator (initiated with tidyOptGetPickList()) token. */
);
/** @}
** @name Option Value Functions
** @{
*/
/** Get the current value of the option ID for the given document.
** @remark The optId *must* have a @ref TidyOptionType of @ref TidyString!
*/
ctmbstr tidyOptGetValue(TidyDoc tdoc, /**< The tidy document whose option value you wish to check. */
TidyOptionId optId /**< The option ID whose value you wish to check. */
);
/** Set the option value as a string.
** @remark The optId *must* have a @ref TidyOptionType of @ref TidyString!
** @result Returns a bool indicating success or failure.
*/
Bool tidyOptSetValue(TidyDoc tdoc, /**< The tidy document for which to set the value. */
TidyOptionId optId, /**< The option ID of the value to set. */
ctmbstr val /**< The string value to set. */
);
/** Set named option value as a string, regardless of the @ref TidyOptionType.
** @remark This is good setter if you are unsure of the type.
** @result Returns a bool indicating success or failure.
*/
Bool tidyOptParseValue(TidyDoc tdoc, /**< The tidy document for which to set the value. */
ctmbstr optnam, /**< The name of the option to set; this is the string value from the UI, e.g., `error-file`. */
ctmbstr val /**< The value to set, as a string. */
);
/** Get current option value as an integer.
** @result Returns the integer value of the specified option.
*/
ulong tidyOptGetInt(TidyDoc tdoc, /**< The tidy document for which to get the value. */
TidyOptionId optId /**< The option ID to get. */
);
/** Set option value as an integer.
** @result Returns a bool indicating success or failure.
*/
Bool tidyOptSetInt(TidyDoc tdoc, /**< The tidy document for which to set the value. */
TidyOptionId optId, /**< The option ID to set. */
ulong val /**< The value to set. */
);
/** Get current option value as a Boolean flag.
** @result Returns a bool indicating the value.
*/
Bool tidyOptGetBool(TidyDoc tdoc, /**< The tidy document for which to get the value. */
TidyOptionId optId /**< The option ID to get. */
);
/** Set option value as a Boolean flag.
** @result Returns a bool indicating success or failure.
*/
Bool tidyOptSetBool(TidyDoc tdoc, /**< The tidy document for which to set the value. */
TidyOptionId optId, /**< The option ID to set. */
Bool val /**< The value to set. */
);
/** Reset option to default value by ID.
** @result Returns a bool indicating success or failure.
*/
Bool tidyOptResetToDefault(TidyDoc tdoc, /**< The tidy document for which to reset the value. */
TidyOptionId opt /**< The option ID to reset. */
);
/** Reset all options to their default values.
** @param tdoc The tidy document for which to reset all values.
** @result Returns a bool indicating success or failure.
*/
Bool tidyOptResetAllToDefault( TidyDoc tdoc );
/** Take a snapshot of current config settings. These settings are stored
** within the tidy document. Note, however, that snapshots do not reliably
** survive the tidyParseXXX() process, as Tidy uses the snapshot mechanism
** in order to store the current configuration right at the beginning of the
** parsing process.
** @param tdoc The tidy document for which to take a snapshot.
** @result Returns a bool indicating success or failure.
*/
Bool tidyOptSnapshot( TidyDoc tdoc );
/** Apply a snapshot of config settings to a document.
** @param tdoc The tidy document for which to apply a snapshot.
** @result Returns a bool indicating success or failure.
*/
Bool tidyOptResetToSnapshot( TidyDoc tdoc );
/** Any settings different than default?
** @param tdoc The tidy document to check.
** @result Returns a bool indicating whether or not a difference exists.
*/
Bool tidyOptDiffThanDefault( TidyDoc tdoc );
/** Any settings different than snapshot?
** @param tdoc The tidy document to check.
** @result Returns a bool indicating whether or not a difference exists.
*/
Bool tidyOptDiffThanSnapshot( TidyDoc tdoc );
/** Copy current configuration settings from one document to another. Note
** that the destination document's existing settings will be stored as that
** document's snapshot prior to having its option values overwritten by the
** source document's settings.
** @result Returns a bool indicating success or failure.
*/
Bool tidyOptCopyConfig(TidyDoc tdocTo, /**< The destination tidy document. */
TidyDoc tdocFrom /**< The source tidy document. */
);
/** Get character encoding name. Used with @ref TidyCharEncoding,
** @ref TidyOutCharEncoding, and @ref TidyInCharEncoding.
** @result The encoding name as a string for the specified option.
*/
ctmbstr tidyOptGetEncName(TidyDoc tdoc, /**< The tidy document to query. */
TidyOptionId optId /**< The option ID whose value to check. */
);
/** Get the current pick list value for the option ID, which can be useful for
** enum types.
** @result Returns a string indicating the current value of the specified
** option.
*/
ctmbstr tidyOptGetCurrPick(TidyDoc tdoc, /**< The tidy document to query. */
TidyOptionId optId /**< The option ID whose value to check. */
);
/** Initiates an iterator for a list of user-declared tags, including autonomous
** custom tags detected in the document if @ref TidyUseCustomTags is not set to
** **no**. This iterator allows you to iterate through all of the custom tags.
** In order to iterate through the tags, initiate the iterator with this
** function, and then use tidyOptGetNextDeclTag() to retrieve the first and
** subsequent tags. For example:
** @code{.c}
** TidyIterator itTag = tidyOptGetDeclTagList( tdoc );
** while ( itTag ) {
** printf("%s", tidyOptGetNextDeclTag( tdoc, TidyBlockTags, &itTag ));
** }
** @endcode
** @param tdoc An instance of a TidyDoc to query.
** @result Returns a TidyIterator, which is a token used to represent the
** current position in a list within LibTidy.
*/
TidyIterator tidyOptGetDeclTagList( TidyDoc tdoc );
/** Given a valid TidyIterator initiated with tidyOptGetDeclTagList(), returns a
** string representing a user-declared or autonomous custom tag.
** @remark Specifying optId limits the scope of the tags to one of
** @ref TidyInlineTags, @ref TidyBlockTags, @ref TidyEmptyTags, or
** @ref TidyPreTags. Note that autonomous custom tags (if used) are
** added to one of these option types, depending on the value of
** @ref TidyUseCustomTags.
** @result A string containing the next tag.
*/
ctmbstr tidyOptGetNextDeclTag(TidyDoc tdoc, /**< The tidy document to query. */
TidyOptionId optId, /**< The option ID matching the type of tag to retrieve. */
TidyIterator* iter /**< The TidyIterator (initiated with tidyOptGetDeclTagList()) token. */
);
/** Initiates an iterator for a list of priority attributes. This iterator
** allows you to iterate through all of the priority attributes defined with
** the `priority-attributes` configuration option. In order to iterate through
** the attributes, initiate the iterator with this function, and then use
** tidyOptGetNextPriorityAttr() to retrieve the first and subsequent attributes.
** For example:
** @code{.c}
** TidyIterator itAttr = tidyOptGetPriorityAttrList( tdoc );
** while ( itAttr ) {
** printf("%s", tidyOptGetNextPriorityAttr( tdoc, &itAttr ));
** }
** @endcode
** @param tdoc An instance of a TidyDoc to query.
** @result Returns a TidyIterator, which is a token used to represent the
** current position in a list within LibTidy.
*/
TidyIterator tidyOptGetPriorityAttrList( TidyDoc tdoc );
/** Given a valid TidyIterator initiated with tidyOptGetPriorityAttrList(),
** returns a string representing a priority attribute.
** @result A string containing the next tag.
*/
ctmbstr tidyOptGetNextPriorityAttr(TidyDoc tdoc, /**< The tidy document to query. */
TidyIterator* iter /**< The TidyIterator (initiated with tidyOptGetPriorityAttrList()) token. */
);
/** Initiates an iterator for a list of muted messages. This iterator allows
** you to iterate through all of the priority attributes defined with the
** `mute` configuration option. In order to iterate through the list, initiate
** with this function, and then use tidyOptGetNextMutedMessage() to retrieve
** the first and subsequent attributes.
** For example:
** @code{.c}
** TidyIterator itAttr = tidyOptGetMutedMessageList( tdoc );
** while ( itAttr ) {
** printf("%s", tidyOptGetNextMutedMessage( tdoc, &itAttr ));
** }
** @endcode
** @param tdoc An instance of a TidyDoc to query.
** @result Returns a TidyIterator, which is a token used to represent the
** current position in a list within LibTidy.
*/
TidyIterator tidyOptGetMutedMessageList( TidyDoc tdoc );
/** Given a valid TidyIterator initiated with tidyOptGetMutedMessageList(),
** returns a string representing a muted message.
** @result A string containing the next tag.
*/
ctmbstr tidyOptGetNextMutedMessage(TidyDoc tdoc, /**< The tidy document to query. */
TidyIterator* iter /**< The TidyIterator (initiated with tidyOptGetMutedMessageList()) token. */
);
/** @}
** @name Option Documentation
** @{
*/
/** Get the description of the specified option.
** @result Returns a string containing a description of the given option.
*/
ctmbstr tidyOptGetDoc(TidyDoc tdoc, /**< The tidy document to query. */
TidyOption opt /**< The option ID of the option. */
);
/** Initiates an iterator for a list of options related to a given option. This
** iterator allows you to iterate through all of the related options, if any.
** In order to iterate through the options, initiate the iterator with this
** function, and then use tidyOptGetNextDocLinks() to retrieve the first and
** subsequent options. For example:
** @code{.c}
** TidyIterator itOpt = tidyOptGetDocLinksList( tdoc, TidyJoinStyles );
** while ( itOpt ) {
** TidyOption my_option = tidyOptGetNextDocLinks( tdoc, &itOpt );
** // do something with my_option
** }
** @endcode
** @result Returns a TidyIterator, which is a token used to represent the
** current position in a list within LibTidy.
*/
TidyIterator tidyOptGetDocLinksList(TidyDoc tdoc, /**< The tidy document to query. */
TidyOption opt /**< The option whose related options you wish to find. */
);
/** Given a valid TidyIterator initiated with tidyOptGetDocLinksList(), returns
** a TidyOption instance.
** @result Returns in instance of TidyOption.
*/
TidyOption tidyOptGetNextDocLinks(TidyDoc tdoc, /**< The tidy document to query. */
TidyIterator* pos /**< The TidyIterator (initiated with tidyOptGetDocLinksList()) token. */
);
/** @} */
/** @} end Configuration group */
/* MARK: - I/O and Messages */
/***************************************************************************//**
** @defgroup IO I/O and Messages
**
** Tidy provides flexible I/O. By default, Tidy will define, create and use
** instances of input and output handlers for standard C buffered I/O (i.e.,
** `FILE* stdin`, `FILE* stdout`, and `FILE* stderr` for content input,
** content output and diagnostic output, respectively. A `FILE* cfgFile`
** input handler will be used for config files. Command line options will
** just be set directly.
**
** @{
******************************************************************************/
/** @name Forward declarations and typedefs.
** @{
*/
TIDY_STRUCT struct _TidyBuffer;
typedef struct _TidyBuffer TidyBuffer;
/** @}
** @name Input Source
** If you wish to write to your own input sources, then these types, structs,
** and functions will allow them to work seamlessly with Tidy.
** @{
*/
/** End of input "character" */
#define EndOfStream (~0u)
/** Input Callback: get next byte of input */
typedef int (TIDY_CALL *TidyGetByteFunc)( void* sourceData );
/** Input Callback: unget a byte of input */
typedef void (TIDY_CALL *TidyUngetByteFunc)( void* sourceData, byte bt );
/** Input Callback: is end of input? */
typedef Bool (TIDY_CALL *TidyEOFFunc)( void* sourceData );
/** This type defines an input source capable of delivering raw bytes of input.
*/
TIDY_STRUCT
typedef struct _TidyInputSource
{
void* sourceData; /**< Input context. Passed to callbacks. */
TidyGetByteFunc getByte; /**< Pointer to "get byte" callback. */
TidyUngetByteFunc ungetByte; /**< Pointer to "unget" callback. */
TidyEOFFunc eof; /**< Pointer to "eof" callback. */
} TidyInputSource;
/** Facilitates user defined source by providing an entry point to marshal
** pointers-to-functions. This is needed by .NET, and possibly other language
** bindings.
** @result Returns a bool indicating success or failure.
*/
Bool tidyInitSource(TidyInputSource* source, /**< The source to populate with data. */
void* srcData, /**< The input context. */
TidyGetByteFunc gbFunc, /**< Pointer to the "get byte" callback. */
TidyUngetByteFunc ugbFunc, /**< Pointer to the "unget" callback. */
TidyEOFFunc endFunc /**< Pointer to the "eof" callback. */
);
/** Helper: get next byte from input source.
** @param source A pointer to your input source.
** @result Returns a byte as an unsigned integer.
*/
uint tidyGetByte( TidyInputSource* source );
/** Helper: unget byte back to input source. */
void tidyUngetByte(TidyInputSource* source, /**< The input source. */
uint byteValue /**< The byte to push back. */
);
/** Helper: check if input source at end.
** @param source The input source.
** @result Returns a bool indicating whether or not the source is at EOF.
*/
Bool tidyIsEOF( TidyInputSource* source );
/** @}
** @name Output Sink
** @{
*/
/** Output callback: send a byte to output */
typedef void (TIDY_CALL *TidyPutByteFunc)( void* sinkData, byte bt );
/** This type defines an output destination capable of accepting raw bytes
** of output
*/
TIDY_STRUCT
typedef struct _TidyOutputSink
{
void* sinkData; /**< Output context. Passed to callbacks. */
TidyPutByteFunc putByte; /**< Pointer to "put byte" callback */
} TidyOutputSink;
/** Facilitates user defined sinks by providing an entry point to marshal
** pointers-to-functions. This is needed by .NET, and possibly other language
** bindings.
** @result Returns a bool indicating success or failure.
*/
Bool tidyInitSink(TidyOutputSink* sink, /**< The sink to populate with data. */
void* snkData, /**< The output context. */
TidyPutByteFunc pbFunc /**< Pointer to the "put byte" callback function. */
);
/** Helper: send a byte to output. */
void tidyPutByte(TidyOutputSink* sink, /**< The output sink to send a byte. */
uint byteValue /**< The byte to be sent. */
);
/** @}
** @name Emacs-compatible reporting support.
** If you work with Emacs and prefer Tidy's report output to be in a form
** that is easy for Emacs to parse, then these functions may be valuable.
** @{
*/
/** Set the file path to use for reports when `TidyEmacs` is being used. This
** function provides a proper interface for using the hidden, internal-only
** `TidyEmacsFile` configuration option.
*/
void tidySetEmacsFile(TidyDoc tdoc, /**< The tidy document for which you are setting the filePath. */
ctmbstr filePath /**< The path of the document that should be reported. */
);
/** Get the file path to use for reports when `TidyEmacs` is being used. This
** function provides a proper interface for using the hidden, internal-only
** `TidyEmacsFile` configuration option.
** @param tdoc The tidy document for which you want to fetch the file path.
** @result Returns a string indicating the file path.
*/
ctmbstr tidyGetEmacsFile( TidyDoc tdoc );
/** @}
** @name Error Sink
** Send Tidy's output to any of several destinations with these functions.
** @{
*/
/** Set error sink to named file.
** @result Returns a file handle.
*/
FILE* tidySetErrorFile(TidyDoc tdoc, /**< The document to set. */
ctmbstr errfilnam /**< The file path to send output. */
);
/** Set error sink to given buffer.
** @result Returns 0 upon success or a standard error number.
*/
int tidySetErrorBuffer(TidyDoc tdoc, /**< The document to set. */
TidyBuffer* errbuf /**< The TidyBuffer to collect output. */
);
/** Set error sink to given generic sink.
** @result Returns 0 upon success or a standard error number.
*/
int tidySetErrorSink(TidyDoc tdoc, /**< The document to set. */
TidyOutputSink* sink /**< The TidyOutputSink to collect output. */
);
/** @}
** @name Error and Message Callbacks - TidyReportFilter
** A simple callback to filter or collect messages by diagnostic level,
** for example, TidyInfo, TidyWarning, etc. Its name reflects its original
** purpose as a filter, by which your application can inform LibTidy whether
** or not to output a particular report.
**
** @{
*/
/** This typedef represents the required signature for your provided callback
** function should you wish to register one with tidySetReportFilter().
** Your callback function will be provided with the following parameters.
** @param tdoc Indicates the tidy document the message comes from.
** @param lvl Specifies the TidyReportLevel of the message.
** @param line Indicates the line number in the source document the message applies to.
** @param col Indicates the column in the source document the message applies to.
** @param mssg Specifies the complete message as Tidy would emit it.
** @return Your callback function will return `yes` if Tidy should include the
** report in its own output sink, or `no` if Tidy should suppress it.
*/
typedef Bool (TIDY_CALL *TidyReportFilter)( TidyDoc tdoc, TidyReportLevel lvl, uint line, uint col, ctmbstr mssg );
/** This function informs Tidy to use the specified callback to send reports. */
Bool tidySetReportFilter(TidyDoc tdoc, /**< The tidy document for which the callback applies. */
TidyReportFilter filtCallback /**< A pointer to your callback function of type TidyReportFilter. */
);
/** @}
** @name Error and Message Callbacks - TidyReportCallback
** A simple callback to filter or collect messages reported by Tidy.
** Unlike TidyReportFilter, more data are provided (including a `va_list`),
** making this callback suitable for applications that provide more
** sophisticated handling of reports.
** @remark The use of a `va_list` may preclude using this callback from
** non-C-like languages, which is uncharacteristic of Tidy. For more
** flexibility, consider using TidyMessageCallback instead.
** @note This callback was previously `TidyMessageFilter3` in older versions
** of LibTidy.
** @{
*/
/** This typedef represents the required signature for your provided callback
** function should you wish to register one with tidySetReportCallback().
** Your callback function will be provided with the following parameters.
** @param tdoc Indicates the tidy document the message comes from.
** @param lvl Specifies the TidyReportLevel of the message.
** @param line Indicates the line number in the source document the message applies to.
** @param col Indicates the column in the source document the message applies to.
** @param code Specifies the message code representing the message. Note that
** this code is a string value that the API promises to hold constant,
** as opposed to an enum value that can change at any time. Although
** this is intended so that you can look up your own application's
** strings, you can retrieve Tidy's format string with this code by
** using tidyErrorCodeFromKey() and then the tidyLocalizedString()
** family of functions.
** @param args Is a `va_list` of arguments used to fill Tidy's message format string.
** @return Your callback function will return `yes` if Tidy should include the
** report in its own output sink, or `no` if Tidy should suppress it.
*/
typedef Bool (TIDY_CALL *TidyReportCallback)( TidyDoc tdoc, TidyReportLevel lvl,
uint line, uint col, ctmbstr code, va_list args );
/** This function informs Tidy to use the specified callback to send reports. */
Bool tidySetReportCallback(TidyDoc tdoc, /**< The tidy document for which the callback applies. */
TidyReportCallback filtCallback /**< A pointer to your callback function of type TidyReportCallback. */
);
/** @}
** @name Error and Message Callbacks - TidyMessageCallback
** A sophisticated and extensible callback to filter or collect messages
** reported by Tidy. It returns only an opaque type `TidyMessage` for every
** report and dialogue message, and this message can be queried with the
** TidyMessageCallback API, below. Note that unlike the older filters, this
** callback exposes *all* output that LibTidy emits (excluding the console
** application, which is a client of LibTidy).
*/
/** This typedef represents the required signature for your provided callback
** function should you wish to register one with tidySetMessageCallback().
** Your callback function will be provided with the following parameters.
** @param tmessage An opaque type used as a token against which other API
** calls can be made.
** @return Your callback function will return `yes` if Tidy should include the
** report in its own output sink, or `no` if Tidy should suppress it.
*/
typedef Bool (TIDY_CALL *TidyMessageCallback)( TidyMessage tmessage );
/** This function informs Tidy to use the specified callback to send reports. */
Bool tidySetMessageCallback(TidyDoc tdoc, /**< The tidy document for which the callback applies. */
TidyMessageCallback filtCallback /**< A pointer to your callback function of type TidyMessageCallback. */
);
/** @name TidyMessageCallback API
** When using `TidyMessageCallback` you will be supplied with a TidyMessage
** object, which is used as a token to be interrogated with the following
** API before the callback returns.
** @remark Upon returning from the callback, this object is destroyed so do
** not attempt to copy it, or keep it around, or use it in any way.
**
** @{
*/
/** Get the tidy document this message comes from.
** @param tmessage Specify the message that you are querying.
** @result Returns the TidyDoc that generated the message.
*/
TidyDoc tidyGetMessageDoc( TidyMessage tmessage );
/** Get the message code.
** @param tmessage Specify the message that you are querying.
** @result Returns a code representing the message. This code can be used
** directly with the localized strings API; however we never make
** any guarantees about the value of these codes. For code stability
** don't store this value in your own application. Instead use the
** enum field or use the message key string value.
*/
uint tidyGetMessageCode( TidyMessage tmessage );
/** Get the message key string.
** @param tmessage Specify the message that you are querying.
** @result Returns a string representing the message. This string is intended
** to be stable by the LibTidy API, and is suitable for use as a key
** in your own applications.
*/
ctmbstr tidyGetMessageKey( TidyMessage tmessage );
/** Get the line number the message applies to.
** @param tmessage Specify the message that you are querying.
** @result Returns the line number, if any, that generated the message.
*/
int tidyGetMessageLine( TidyMessage tmessage );
/** Get the column the message applies to.
** @param tmessage Specify the message that you are querying.
** @result Returns the column number, if any, that generated the message.
*/
int tidyGetMessageColumn( TidyMessage tmessage );
/** Get the TidyReportLevel of the message.
** @param tmessage Specify the message that you are querying.
** @result Returns a TidyReportLevel indicating the severity or status of the
** message.
*/
TidyReportLevel tidyGetMessageLevel( TidyMessage tmessage );
/** Get the muted status of the message, that is, whether or not the
** current configuration indicated that this message should be muted.
** @param tmessage Specify the message that you are querying.
** @result Returns a Bool indicating that the config indicates muting this
** message.
*/
Bool tidyGetMessageIsMuted( TidyMessage tmessage );
/** Get the default format string, which is the format string for the message
** in Tidy's default localization (en_us).
** @param tmessage Specify the message that you are querying.
** @result Returns the default localization format string of the message.
*/
ctmbstr tidyGetMessageFormatDefault( TidyMessage tmessage );
/** Get the localized format string. If a localized version of the format string
** doesn't exist, then the default version will be returned.
** @param tmessage Specify the message that you are querying.
** @result Returns the localized format string of the message.
*/
ctmbstr tidyGetMessageFormat( TidyMessage tmessage );
/** Get the message with the format string already completed, in Tidy's
** default localization.
** @param tmessage Specify the message that you are querying.
** @result Returns the message in the default localization.
*/
ctmbstr tidyGetMessageDefault( TidyMessage tmessage );
/** Get the message with the format string already completed, in Tidy's
** current localization.
** @param tmessage Specify the message that you are querying.
** @result Returns the message in the current localization.
*/
ctmbstr tidyGetMessage( TidyMessage tmessage );
/** Get the position part part of the message in the default language.
** @param tmessage Specify the message that you are querying.
** @result Returns the positional part of a string as Tidy would display it
** in the console application.
*/
ctmbstr tidyGetMessagePosDefault( TidyMessage tmessage );
/** Get the position part part of the message in the current language.
** @param tmessage Specify the message that you are querying.
** @result Returns the positional part of a string as Tidy would display it
** in the console application.
*/
ctmbstr tidyGetMessagePos( TidyMessage tmessage );
/** Get the prefix part of a message in the default language.
** @param tmessage Specify the message that you are querying.
** @result Returns the message prefix part of a string as Tidy would display
** it in the console application.
*/
ctmbstr tidyGetMessagePrefixDefault( TidyMessage tmessage );
/** Get the prefix part of a message in the current language.
** @param tmessage Specify the message that you are querying.
** @result Returns the message prefix part of a string as Tidy would display
** it in the console application.
*/
ctmbstr tidyGetMessagePrefix( TidyMessage tmessage );
/** Get the complete message as Tidy would emit it in the default localization.
** @param tmessage Specify the message that you are querying.
** @result Returns the complete message just as Tidy would display it on the
** console.
*/
ctmbstr tidyGetMessageOutputDefault( TidyMessage tmessage );
/** Get the complete message as Tidy would emit it in the current localization.
** @param tmessage Specify the message that you are querying.
** @result Returns the complete message just as Tidy would display it on the
** console.
*/
ctmbstr tidyGetMessageOutput( TidyMessage tmessage );
/** @} end subgroup TidyMessageCallback API */
/** @name TidyMessageCallback Arguments API
** When using `TidyMessageCallback` you will be supplied with a TidyMessage
** object which can be used as a token against which to query using this API.
** This API deals strictly with _arguments_ that a message may or may not have;
** these are the same arguments that Tidy would apply to a format string in
** order to fill in the placeholder fields and deliver a complete report or
** dialogue string to you.
**
** @{
*/
/** Initiates an iterator for a list of arguments related to a given message.
** This iterator allows you to iterate through all of the arguments, if any.
** In order to iterate through the arguments, initiate the iterator with this
** function, and then use tidyGetNextMessageArgument() to retrieve the first
** and subsequent arguments. For example:
** @code{.c}
** TidyIterator itArg = tidyGetMessageArguments( tmessage );
** while ( itArg ) {
** TidyMessageArgument my_arg = tidyGetNextMessageArgument( tmessage, &itArg );
** // do something with my_arg, such as inspect its value or format
** }
** @endcode
** @param tmessage The message about whose arguments you wish to query.
** @result Returns a TidyIterator, which is a token used to represent the
** current position in a list within LibTidy.
*/
TidyIterator tidyGetMessageArguments( TidyMessage tmessage );
/** Given a valid TidyIterator initiated with tidyGetMessageArguments(), returns
** an instance of the opaque type TidyMessageArgument, which serves as a token
** against which the remaining argument API functions may be used to query
** information.
** @result Returns an instance of TidyMessageArgument.
*/
TidyMessageArgument tidyGetNextMessageArgument(TidyMessage tmessage, /**< The message whose arguments you want to access. */
TidyIterator* iter /**< The TidyIterator (initiated with tidyOptGetDocLinksList()) token. */
);
/** Returns the `TidyFormatParameterType` of the given message argument.
** @result Returns the type of parameter of type TidyFormatParameterType.
*/
TidyFormatParameterType tidyGetArgType(TidyMessage tmessage, /**< The message whose arguments you want to access. */
TidyMessageArgument* arg /**< The argument that you are querying. */
);
/** Returns the format specifier of the given message argument. The memory for
** this string is cleared upon termination of the callback, so do be sure to
** make your own copy.
** @result Returns the format specifier string of the given argument.
*/
ctmbstr tidyGetArgFormat(TidyMessage tmessage, /**< The message whose arguments you want to access. */
TidyMessageArgument* arg /**< The argument that you are querying. */
);
/** Returns the string value of the given message argument. An assertion
** will be generated if the argument type is not a string.
** @result Returns the string value of the given argument.
*/
ctmbstr tidyGetArgValueString(TidyMessage tmessage, /**< The message whose arguments you want to access. */
TidyMessageArgument* arg /**< The argument that you are querying. */
);
/** Returns the unsigned integer value of the given message argument. An
** assertion will be generated if the argument type is not an unsigned int.
** @result Returns the unsigned integer value of the given argument.
*/
uint tidyGetArgValueUInt(TidyMessage tmessage, /**< The message whose arguments you want to access. */
TidyMessageArgument* arg /**< The argument that you are querying. */
);
/** Returns the integer value of the given message argument. An assertion
** will be generated if the argument type is not an integer.
** @result Returns the integer value of the given argument.
*/
int tidyGetArgValueInt(TidyMessage tmessage, /**< The message whose arguments you want to access. */
TidyMessageArgument* arg /**< The argument that you are querying. */
);
/**
* Returns the double value of the given message argument. An assertion
* will be generated if the argument type is not a double.
** @result Returns the double value of the given argument.
*/
double tidyGetArgValueDouble(TidyMessage tmessage, /**< The message whose arguments you want to access. */
TidyMessageArgument* arg /**< The argument that you are querying. */
);
/** @} end subgroup TidyMessageCallback Arguments API */
/** @name Printing
** LibTidy applications can somewhat track the progress of the tidying process
** by using this provided callback. It relates where something in the source
** document ended up in the output.
** @{
*/
/** This typedef represents the required signature for your provided callback
** function should you wish to register one with tidySetMessageCallback().
** Your callback function will be provided with the following parameters.
** @param tdoc Indicates the source tidy document.
** @param line Indicates the line in the source document at this point in the process.
** @param col Indicates the column in the source document at this point in the process.
** @param destLine Indicates the line number in the output document at this point in the process.
*/
typedef void (TIDY_CALL *TidyPPProgress)( TidyDoc tdoc, uint line, uint col, uint destLine );
/** This function informs Tidy to use the specified callback for tracking the
** pretty-printing process progress.
*/
Bool tidySetPrettyPrinterCallback(TidyDoc tdoc,
TidyPPProgress callback
);
/** @} */
/** @} end IO group */
/* MARK: - Document Parse */
/***************************************************************************//**
** @defgroup Parse Document Parse
**
** Functions for parsing markup from a given input source, as well as string
** and filename functions for added convenience. HTML/XHTML version determined
** from input.
**
** @{
******************************************************************************/
/** Parse markup in named file.
** @result Returns the highest of `2` indicating that errors were present in
** the document, `1` indicating warnings, and `0` in the case of
** everything being okay.
*/
int tidyParseFile(TidyDoc tdoc, /**< The tidy document to use for parsing. */
ctmbstr filename /**< The filename to parse. */
);
/** Parse markup from the standard input.
** @param tdoc The tidy document to use for parsing.
** @result Returns the highest of `2` indicating that errors were present in
** the document, `1` indicating warnings, and `0` in the case of
** everything being okay.
*/
int tidyParseStdin( TidyDoc tdoc );
/** Parse markup in given string. Note that the supplied string is of type
** `ctmbstr` based on `char` and therefore doesn't support the use of
** UTF-16 strings. Use `tidyParseBuffer()` if parsing multibyte strings.
** @result Returns the highest of `2` indicating that errors were present in
** the document, `1` indicating warnings, and `0` in the case of
** everything being okay.
*/
int tidyParseString(TidyDoc tdoc, /**< The tidy document to use for parsing. */
ctmbstr content /**< The string to parse. */
);
/** Parse markup in given buffer.
** @result Returns the highest of `2` indicating that errors were present in
** the document, `1` indicating warnings, and `0` in the case of
** everything being okay.
*/
int tidyParseBuffer(TidyDoc tdoc, /**< The tidy document to use for parsing. */
TidyBuffer* buf /**< The TidyBuffer containing data to parse. */
);
/** Parse markup in given generic input source.
** @result Returns the highest of `2` indicating that errors were present in
** the document, `1` indicating warnings, and `0` in the case of
** everything being okay.
*/
int tidyParseSource(TidyDoc tdoc, /**< The tidy document to use for parsing. */
TidyInputSource* source /**< A TidyInputSource containing data to parse. */
);
/** @} End Parse group */
/* MARK: - Diagnostics and Repair */
/***************************************************************************//**
** @defgroup Clean Diagnostics and Repair
**
** After parsing the document, you can use these functions to attempt cleanup,
** repair, get additional diagnostics, and determine the document type.
** @{
******************************************************************************/
/** Execute configured cleanup and repair operations on parsed markup.
** @param tdoc The tidy document to use.
** @result An integer representing the status.
*/
int tidyCleanAndRepair( TidyDoc tdoc );
/** Reports the document type and diagnostic statistics on parsed and repaired
** markup. You must call tidyCleanAndRepair() before using this function.
** @param tdoc The tidy document to use.
** @result An integer representing the status.
*/
int tidyRunDiagnostics( TidyDoc tdoc );
/** Reports the document type into the output sink.
** @param tdoc The tidy document to use.
** @result An integer representing the status.
*/
int tidyReportDoctype( TidyDoc tdoc );
/** @} end Clean group */
/* MARK: - Document Save Functions */
/***************************************************************************//**
** @defgroup Save Document Save Functions
**
** Save currently parsed document to the given output sink. File name
** and string/buffer functions provided for convenience.
**
** @{
******************************************************************************/
/** Save the tidy document to the named file.
** @result An integer representing the status.
*/
int tidySaveFile(TidyDoc tdoc, /**< The tidy document to save. */
ctmbstr filename /**< The destination file name. */
);
/** Save the tidy document to standard output (FILE*).
** @param tdoc The tidy document to save.
** @result An integer representing the status.
*/
int tidySaveStdout( TidyDoc tdoc );
/** Save the tidy document to given TidyBuffer object.
** @result An integer representing the status.
*/
int tidySaveBuffer(TidyDoc tdoc, /**< The tidy document to save. */
TidyBuffer* buf /**< The buffer to place the output. */
);
/** Save the tidy document to an application buffer. If TidyShowMarkup and the
** document has no errors, or TidyForceOutput, then the current document (per
** the current configuration) will be pretty printed to this application
** buffer. The document byte length (not character length) will be placed into
** *buflen. The document will not be null terminated. If the buffer is not big
** enough, ENOMEM will be returned, else the actual document status.
** @result An integer representing the status.
*/
int tidySaveString(TidyDoc tdoc, /**< The tidy document to save. */
tmbstr buffer, /**< The buffer to save to. */
uint* buflen /**< [out] The byte length written. */
);
/** Save to given generic output sink.
** @result An integer representing the status.
*/
int tidySaveSink(TidyDoc tdoc, /**< The tidy document to save. */
TidyOutputSink* sink /**< The output sink to save to. */
);
/** Save current settings to named file. Only writes non-default values.
** @result An integer representing the status.
*/
int tidyOptSaveFile(TidyDoc tdoc, /**< The tidy document to save. */
ctmbstr cfgfil /**< The filename to save the configuration to. */
);
/** Save current settings to given output sink. Only non-default values are
** written.
** @result An integer representing the status.
*/
int tidyOptSaveSink(TidyDoc tdoc, /**< The tidy document to save. */
TidyOutputSink* sink /**< The output sink to save the configuration to. */
);
/** @} end Save group */
/* MARK: - Document Tree */
/***************************************************************************//**
** @defgroup Tree Document Tree
**
** A parsed (and optionally repaired) document is represented by Tidy as a
** tree, much like a W3C DOM. This tree may be traversed using these
** functions. The following snippet gives a basic idea how these functions
** can be used.
**
** @code{.c}
** void dumpNode( TidyNode tnod, int indent ) {
** TidyNode child;
**
** for ( child = tidyGetChild(tnod); child; child = tidyGetNext(child) ) {
** ctmbstr name;
** switch ( tidyNodeGetType(child) ) {
** case TidyNode_Root: name = "Root"; break;
** case TidyNode_DocType: name = "DOCTYPE"; break;
** case TidyNode_Comment: name = "Comment"; break;
** case TidyNode_ProcIns: name = "Processing Instruction"; break;
** case TidyNode_Text: name = "Text"; break;
** case TidyNode_CDATA: name = "CDATA"; break;
** case TidyNode_Section: name = "XML Section"; break;
** case TidyNode_Asp: name = "ASP"; break;
** case TidyNode_Jste: name = "JSTE"; break;
** case TidyNode_Php: name = "PHP"; break;
** case TidyNode_XmlDecl: name = "XML Declaration"; break;
**
** case TidyNode_Start:
** case TidyNode_End:
** case TidyNode_StartEnd:
** default:
** name = tidyNodeGetName( child );
** break;
** }
** assert( name != NULL );
** printf( "\%*.*sNode: \%s\\n", indent, indent, " ", name );
** dumpNode( child, indent + 4 );
** }
** }
**
** void dumpDoc( TidyDoc tdoc ) {
** dumpNode( tidyGetRoot(tdoc), 0 );
** }
**
** void dumpBody( TidyDoc tdoc ) {
** dumpNode( tidyGetBody(tdoc), 0 );
** }
** @endcode
**
** @{
******************************************************************************/
/** @name Nodes for Document Sections
** @{
*/
/** Get the root node.
** @param tdoc The document to query.
** @result Returns a tidy node.
*/
TidyNode tidyGetRoot( TidyDoc tdoc );
/** Get the HTML node.
** @param tdoc The document to query.
** @result Returns a tidy node.
*/
TidyNode tidyGetHtml( TidyDoc tdoc );
/** Get the HEAD node.
** @param tdoc The document to query.
** @result Returns a tidy node.
*/
TidyNode tidyGetHead( TidyDoc tdoc );
/** Get the BODY node.
** @param tdoc The document to query.
** @result Returns a tidy node.
*/
TidyNode tidyGetBody( TidyDoc tdoc );
/** @}
** @name Relative Nodes
** @{
*/
/** Get the parent of the indicated node.
** @param tnod The node to query.
** @result Returns a tidy node.
*/
TidyNode tidyGetParent( TidyNode tnod );
/** Get the child of the indicated node.
** @param tnod The node to query.
** @result Returns a tidy node.
*/
TidyNode tidyGetChild( TidyNode tnod );
/** Get the next sibling node.
** @param tnod The node to query.
** @result Returns a tidy node.
*/
TidyNode tidyGetNext( TidyNode tnod );
/** Get the previous sibling node.
** @param tnod The node to query.
** @result Returns a tidy node.
*/
TidyNode tidyGetPrev( TidyNode tnod );
/** @}
** @name Miscellaneous Node Functions
** @{
*/
/** Remove the indicated node.
** @result Returns the next tidy node.
*/
TidyNode tidyDiscardElement(TidyDoc tdoc, /**< The tidy document from which to remove the node. */
TidyNode tnod /**< The node to remove */
);
/** @}
** @name Node Attribute Functions
** @{
*/
/** Get the first attribute.
** @param tnod The node for which to get attributes.
** @result Returns an instance of TidyAttr.
*/
TidyAttr tidyAttrFirst( TidyNode tnod );
/** Get the next attribute.
** @param tattr The current attribute, so the next one can be returned.
** @result Returns and instance of TidyAttr.
*/
TidyAttr tidyAttrNext( TidyAttr tattr );
/** Get the name of a TidyAttr instance.
** @param tattr The tidy attribute to query.
** @result Returns a string indicating the name of the attribute.
*/
ctmbstr tidyAttrName( TidyAttr tattr );
/** Get the value of a TidyAttr instance.
** @param tattr The tidy attribute to query.
** @result Returns a string indicating the value of the attribute.
*/
ctmbstr tidyAttrValue( TidyAttr tattr );
/** Discard an attribute. */
void tidyAttrDiscard(TidyDoc itdoc, /**< The tidy document from which to discard the attribute. */
TidyNode tnod, /**< The node from which to discard the attribute. */
TidyAttr tattr /**< The attribute to discard. */
);
/** Get the attribute ID given a tidy attribute.
** @param tattr The attribute to query.
** @result Returns the TidyAttrId of the given attribute.
**/
TidyAttrId tidyAttrGetId( TidyAttr tattr );
/** Indicates whether or not a given attribute is an event attribute.
** @param tattr The attribute to query.
** @result Returns a bool indicating whether or not the attribute is an event.
**/
Bool tidyAttrIsEvent( TidyAttr tattr );
/** Get an instance of TidyAttr by specifying an attribute ID.
** @result Returns a TidyAttr instance.
*/
TidyAttr tidyAttrGetById(TidyNode tnod, /**< The node to query. */
TidyAttrId attId /**< The attribute ID to find. */
);
/** @}
** @name Additional Node Interrogation
** @{
*/
/** Get the type of node.
** @param tnod The node to query.
** @result Returns the type of node as TidyNodeType.
*/
TidyNodeType tidyNodeGetType( TidyNode tnod );
/** Get the name of the node.
** @param tnod The node to query.
** @result Returns a string indicating the name of the node.
*/
ctmbstr tidyNodeGetName( TidyNode tnod );
/** Indicates whether or not a node is a text node.
** @param tnod The node to query.
** @result Returns a bool indicating whether or not the node is a text node.
*/
Bool tidyNodeIsText( TidyNode tnod );
/** Indicates whether or not the node is a propriety type.
** @result Returns a bool indicating whether or not the node is a proprietary type.
*/
Bool tidyNodeIsProp(TidyDoc tdoc, /**< The document to query. */
TidyNode tnod /**< The node to query */
);
/** Indicates whether or not a node represents and HTML header element, such
** as h1, h2, etc.
** @param tnod The node to query.
** @result Returns a bool indicating whether or not the node is an HTML header.
*/
Bool tidyNodeIsHeader( TidyNode tnod );
/** Indicates whether or not the node has text.
** @result Returns the type of node as TidyNodeType.
*/
Bool tidyNodeHasText(TidyDoc tdoc, /**< The document to query. */
TidyNode tnod /**< The node to query. */
);
/** Gets the text of a node and places it into the given TidyBuffer. The text will be terminated with a `TidyNewline`.
** If you want the raw utf-8 stream see `tidyNodeGetValue()`.
** @result Returns a bool indicating success or not.
*/
Bool tidyNodeGetText(TidyDoc tdoc, /**< The document to query. */
TidyNode tnod, /**< The node to query. */
TidyBuffer* buf /**< [out] A TidyBuffer used to receive the node's text. */
);
/** Get the value of the node. This copies the unescaped value of this node into
** the given TidyBuffer at UTF-8.
** @result Returns a bool indicating success or not.
*/
Bool tidyNodeGetValue(TidyDoc tdoc, /**< The document to query */
TidyNode tnod, /**< The node to query */
TidyBuffer* buf /**< [out] A TidyBuffer used to receive the node's value. */
);
/** Get the tag ID of the node.
** @param tnod The node to query.
** @result Returns the tag ID of the node as TidyTagId.
*/
TidyTagId tidyNodeGetId( TidyNode tnod );
/** Get the line number where the node occurs.
** @param tnod The node to query.
** @result Returns the line number.
*/
uint tidyNodeLine( TidyNode tnod );
/** Get the column location of the node.
** @param tnod The node to query.
** @result Returns the column location of the node.
*/
uint tidyNodeColumn( TidyNode tnod );
/** @} */
/** @} end Tree group */
/* MARK: - Message Key Management */
/***************************************************************************//**
** @defgroup MessagesKeys Message Key Management
**
** These functions serve to manage message codes, i.e., codes that are used
** Tidy and communicated via its callback filters to represent reports and
** dialogue that Tidy emits.
**
** @remark These codes only reflect complete messages, and are specifically
** distinct from the internal codes that are used to lookup individual
** strings for localization purposes.
**
** @{
******************************************************************************/
/**
** Given a message code, return the text key that represents it.
** @param code The error code to lookup.
** @result The string representing the error code.
*/
ctmbstr tidyErrorCodeAsKey(uint code);
/**
** Given a text key representing a message code, return the uint that
** represents it.
**
** @remark We establish that for external purposes, the API will ensure that
** string keys remain consistent. *Never* count on the integer value
** of a message code. Always use this function to ensure that the
** integer is valid if you need one.
** @param code The string representing the error code.
** @result Returns an integer that represents the error code, which can be
** used to lookup Tidy's built-in strings. If the provided string does
** not have a matching message code, then UINT_MAX will be returned.
*/
uint tidyErrorCodeFromKey(ctmbstr code);
/** Initiates an iterator for a list of message codes available in Tidy.
** This iterator allows you to iterate through all of the code. In orde to
** iterate through the codes, initiate the iterator with this function, and
** then use getNextErrorCode() to retrieve the first and subsequent codes.
** For example:
** @code{.c}
** TidyIterator itMessage = getErrorCodeList();
** while ( itMessage ) {
** uint code = getNextErrorCode( &itMessage );
** // do something with the code, such as lookup a string.
** }
** @endcode
** @result Returns a TidyIterator, which is a token used to represent the
** current position in a list within LibTidy.
*/
TidyIterator getErrorCodeList(void);
/** Given a valid TidyIterator initiated with getErrorCodeList(), returns
** an instance of the opaque type TidyMessageArgument, which serves as a token
** against which the remaining argument API functions may be used to query
** information.
** @param iter The TidyIterator (initiated with getErrorCodeList()) token.
** @result Returns a message code.
*/
uint getNextErrorCode( TidyIterator* iter );
/** @} end MessagesKeys group */
/* MARK: - Localization Support */
/***************************************************************************//**
** @defgroup Localization Localization Support
**
** These functions help manage localization in Tidy.
**
** @{
******************************************************************************/
/** @name Tidy's Locale
** @{
*/
/** Tells Tidy to use a different language for output.
** @param languageCode A Windows or POSIX language code, and must match
** a TIDY_LANGUAGE for an installed language.
** @result Indicates that a setting was applied, but not necessarily the
** specific request, i.e., true indicates a language and/or region
** was applied. If es_mx is requested but not installed, and es is
** installed, then es will be selected and this function will return
** true. However the opposite is not true; if es is requested but
** not present, Tidy will not try to select from the es_XX variants.
*/
Bool tidySetLanguage( ctmbstr languageCode );
/** Gets the current language used by Tidy.
** @result Returns a string indicating the currently set language.
*/
ctmbstr tidyGetLanguage(void);
/** @}
** @name Locale Mappings
** @{
*/
/** @struct tidyLocaleMapItem
** Represents an opaque type we can use for tidyLocaleMapItem, which
** is used to iterate through the language list, and used to access
** the windowsName() and the posixName().
*/
/* Prevent Doxygen from listing this as a function. */
#ifndef DOXYGEN_SHOULD_SKIP_THIS
opaque_type(tidyLocaleMapItem);
#endif
/** Initiates an iterator for a list of Tidy's Windows<->POSIX locale mappings.
** This iterator allows you to iterate through this list. In order to
** iterate through the list, initiate the iterator with this function, and then
** use getNextWindowsLanguage() to retrieve the first and subsequent codes.
** For example:
** @code{.c}
** TidyIterator itList = getWindowsLanguageList();
** while ( itList ) {
** tidyLocaleMapItem *item = getNextWindowsLanguage( &itList );
** // do something such as get the TidyLangWindowsName(item).
** }
** @endcode
** @result Returns a TidyIterator, which is a token used to represent the
** current position in a list within LibTidy.
*/
TidyIterator getWindowsLanguageList(void);
/** Given a valid TidyIterator initiated with getWindowsLanguageList(), returns
** a pointer to a tidyLocaleMapItem, which can be further interrogated with
** TidyLangWindowsName() or TidyLangPosixName().
** @param iter The TidyIterator (initiated with getWindowsLanguageList()) token.
** @result Returns a pointer to a tidyLocaleMapItem.
*/
const tidyLocaleMapItem* getNextWindowsLanguage( TidyIterator* iter );
/** Given a `tidyLocaleMapItem`, return the Windows name.
** @param item An instance of tidyLocaleMapItem to query.
** @result Returns a string with the Windows name of the mapping.
*/
ctmbstr TidyLangWindowsName( const tidyLocaleMapItem *item );
/** Given a `tidyLocaleMapItem`, return the POSIX name.
** @param item An instance of tidyLocaleMapItem to query.
** @result Returns a string with the POSIX name of the mapping.
*/
ctmbstr TidyLangPosixName( const tidyLocaleMapItem *item );
/** @}
** @name Getting Localized Strings
** @{
*/
/** Provides a string given `messageType` in the current localization for
** `quantity`. Some strings have one or more plural forms, and this function
** will ensure that the correct singular or plural form is returned for the
** specified quantity.
** @result Returns the desired string.
*/
ctmbstr tidyLocalizedStringN(uint messageType, /**< The message type. */
uint quantity /**< The quantity. */
);
/** Provides a string given `messageType` in the current localization for the
** single case.
** @param messageType The message type.
** @result Returns the desired string.
*/
ctmbstr tidyLocalizedString( uint messageType );
/** Provides a string given `messageType` in the default localization for
** `quantity`. Some strings have one or more plural forms, and this function
** will ensure that the correct singular or plural form is returned for the
** specified quantity.
** @result Returns the desired string.
*/
ctmbstr tidyDefaultStringN(uint messageType, /**< The message type. */
uint quantity /**< The quantity. */
);
/** Provides a string given `messageType` in the default localization (which
** is `en`).
** @param messageType The message type.
** @result Returns the desired string.
*/
ctmbstr tidyDefaultString( uint messageType );
/** Initiates an iterator for a list of string key codes available in Tidy.
** This iterator allows you to iterate through all of the codes. In order to
** iterate through the codes, initiate the iterator with this function, and
** then use getNextStringKey() to retrieve the first and subsequent codes.
** For example:
** @code{.c}
** TidyIterator itKey = getErrorCodeList();
** while ( itKey ) {
** uint code = getNextStringKey( &itKey );
** // do something with the code, such as lookup a string.
** }
** @endcode
** @remark These are provided for documentation generation purposes, and
** probably aren't of much use to the average LibTidy implementor.
** @result Returns a TidyIterator, which is a token used to represent the
** current position in a list within LibTidy.
*/
TidyIterator getStringKeyList(void);
/** Given a valid TidyIterator initiated with getStringKeyList(), returns
** an unsigned integer representing the next key value.
** @remark These are provided for documentation generation purposes, and
** probably aren't of much use to the average LibTidy implementor.
** @param iter The TidyIterator (initiated with getStringKeyList()) token.
** @result Returns a message code.
*/
uint getNextStringKey( TidyIterator* iter );
/** @}
** @name Available Languages
** @{
*/
/** Initiates an iterator for a list of Tidy's installed languages. This
** iterator allows you to iterate through this list. In order to iterate
** through the list, initiate the iterator with this function, and then use
** use getNextInstalledLanguage() to retrieve the first and subsequent strings.
** For example:
** @code{.c}
** TidyIterator itList = getInstalledLanguageList();
** while ( itList ) {
** printf("%s", getNextInstalledLanguage( &itList ));
** }
** @endcode
** @result Returns a TidyIterator, which is a token used to represent the
** current position in a list within LibTidy.
*/
TidyIterator getInstalledLanguageList(void);
/** Given a valid TidyIterator initiated with getInstalledLanguageList(),
** returns a string representing a language name that is installed in Tidy.
** @param iter The TidyIterator (initiated with getInstalledLanguageList())
** token.
** @result Returns a string indicating the installed language.
*/
ctmbstr getNextInstalledLanguage( TidyIterator* iter );
/** @} */
/** @} end MessagesKeys group */
/** @} end public_api group */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* __TIDY_H__ */
/*
* local variables:
* mode: c
* indent-tabs-mode: nil
* c-basic-offset: 4
* end:
*/
| 94,382 | 2,222 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/output.c | /* Output to stdout / stderr for GNU make
Copyright (C) 2013-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* clang-format off */
#include "third_party/make/makeint.inc"
#include "third_party/make/os.h"
#include "third_party/make/output.h"
#include "libc/calls/struct/flock.h"
/* GNU make no longer supports pre-ANSI89 environments. */
struct output *output_context = NULL;
unsigned int stdio_traced = 0;
#define OUTPUT_NONE (-1)
#define OUTPUT_ISSET(_out) ((_out)->out >= 0 || (_out)->err >= 0)
#ifdef HAVE_FCNTL_H
# define STREAM_OK(_s) ((fcntl (fileno (_s), F_GETFD) != -1) || (errno != EBADF))
#else
# define STREAM_OK(_s) 1
#endif
/* Write a string to the current STDOUT or STDERR. */
static void
_outputs (struct output *out, int is_err, const char *msg)
{
if (! out || ! out->syncout)
{
FILE *f = is_err ? stderr : stdout;
fputs (msg, f);
fflush (f);
}
else
{
int fd = is_err ? out->err : out->out;
size_t len = strlen (msg);
int r;
EINTRLOOP (r, lseek (fd, 0, SEEK_END));
writebuf (fd, msg, len);
}
}
/* Write a message indicating that we've just entered or
left (according to ENTERING) the current directory. */
static int
log_working_directory (int entering)
{
static char *buf = NULL;
static size_t len = 0;
size_t need;
const char *fmt;
char *p;
/* Get enough space for the longest possible output. */
need = strlen (program) + INTSTR_LENGTH + 2 + 1;
if (starting_directory)
need += strlen (starting_directory);
/* Use entire sentences to give the translators a fighting chance. */
if (makelevel == 0)
if (starting_directory == 0)
if (entering)
fmt = _("%s: Entering an unknown directory\n");
else
fmt = _("%s: Leaving an unknown directory\n");
else
if (entering)
fmt = _("%s: Entering directory '%s'\n");
else
fmt = _("%s: Leaving directory '%s'\n");
else
if (starting_directory == 0)
if (entering)
fmt = _("%s[%u]: Entering an unknown directory\n");
else
fmt = _("%s[%u]: Leaving an unknown directory\n");
else
if (entering)
fmt = _("%s[%u]: Entering directory '%s'\n");
else
fmt = _("%s[%u]: Leaving directory '%s'\n");
need += strlen (fmt);
if (need > len)
{
buf = xrealloc (buf, need);
len = need;
}
p = buf;
if (print_data_base_flag)
{
*(p++) = '#';
*(p++) = ' ';
}
if (makelevel == 0)
if (starting_directory == 0)
sprintf (p, fmt , program);
else
sprintf (p, fmt, program, starting_directory);
else if (starting_directory == 0)
sprintf (p, fmt, program, makelevel);
else
sprintf (p, fmt, program, makelevel, starting_directory);
_outputs (NULL, 0, buf);
return 1;
}
/* Set a file descriptor to be in O_APPEND mode.
If it fails, just ignore it. */
static void
set_append_mode (int fd)
{
#if defined(F_GETFL) && defined(F_SETFL) && defined(O_APPEND)
int flags = fcntl (fd, F_GETFL, 0);
if (flags >= 0)
{
int r;
EINTRLOOP(r, fcntl (fd, F_SETFL, flags | O_APPEND));
}
#endif
}
#ifndef NO_OUTPUT_SYNC
/* Semaphore for use in -j mode with output_sync. */
static sync_handle_t sync_handle = -1;
#define FD_NOT_EMPTY(_f) ((_f) != OUTPUT_NONE && lseek ((_f), 0, SEEK_END) > 0)
/* Set up the sync handle. Disables output_sync on error. */
static int
sync_init (void)
{
int combined_output = 0;
#ifdef WINDOWS32
if ((!STREAM_OK (stdout) && !STREAM_OK (stderr))
|| (sync_handle = create_mutex ()) == -1)
{
perror_with_name ("output-sync suppressed: ", "stderr");
output_sync = 0;
}
else
{
combined_output = same_stream (stdout, stderr);
prepare_mutex_handle_string (sync_handle);
}
#else
if (STREAM_OK (stdout))
{
struct stat stbuf_o, stbuf_e;
sync_handle = fileno (stdout);
combined_output = (fstat (fileno (stdout), &stbuf_o) == 0
&& fstat (fileno (stderr), &stbuf_e) == 0
&& stbuf_o.st_dev == stbuf_e.st_dev
&& stbuf_o.st_ino == stbuf_e.st_ino);
}
else if (STREAM_OK (stderr))
sync_handle = fileno (stderr);
else
{
perror_with_name ("output-sync suppressed: ", "stderr");
output_sync = 0;
}
#endif
return combined_output;
}
/* Support routine for output_sync() */
static void
pump_from_tmp (int from, FILE *to)
{
static char buffer[8192];
#ifdef WINDOWS32
int prev_mode;
/* "from" is opened by open_tmpfd, which does it in binary mode, so
we need the mode of "to" to match that. */
prev_mode = _setmode (fileno (to), _O_BINARY);
#endif
if (lseek (from, 0, SEEK_SET) == -1)
perror ("lseek()");
while (1)
{
int len;
EINTRLOOP (len, read (from, buffer, sizeof (buffer)));
if (len < 0)
perror ("read()");
if (len <= 0)
break;
if (fwrite (buffer, len, 1, to) < 1)
{
perror ("fwrite()");
break;
}
fflush (to);
}
#ifdef WINDOWS32
/* Switch "to" back to its original mode, so that log messages by
Make have the same EOL format as without --output-sync. */
_setmode (fileno (to), prev_mode);
#endif
}
/* Obtain the lock for writing output. */
static void *
acquire_semaphore (void)
{
static struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 1;
if (fcntl (sync_handle, F_SETLKW, &fl) != -1)
return &fl;
perror ("fcntl()");
return NULL;
}
/* Release the lock for writing output. */
static void
release_semaphore (void *sem)
{
struct flock *flp = (struct flock *)sem;
flp->l_type = F_UNLCK;
if (fcntl (sync_handle, F_SETLKW, flp) == -1)
perror ("fcntl()");
}
/* Returns a file descriptor to a temporary file. The file is automatically
closed/deleted on exit. Don't use a FILE* stream. */
int
output_tmpfd (void)
{
mode_t mask = umask (0077);
int fd = -1;
FILE *tfile = tmpfile ();
if (! tfile)
pfatal_with_name ("tmpfile");
/* Create a duplicate so we can close the stream. */
fd = dup (fileno (tfile));
if (fd < 0)
pfatal_with_name ("dup");
fclose (tfile);
set_append_mode (fd);
umask (mask);
return fd;
}
/* Adds file descriptors to the child structure to support output_sync; one
for stdout and one for stderr as long as they are open. If stdout and
stderr share a device they can share a temp file too.
Will reset output_sync on error. */
static void
setup_tmpfile (struct output *out)
{
/* Is make's stdout going to the same place as stderr? */
static int combined_output = -1;
if (combined_output < 0)
combined_output = sync_init ();
if (STREAM_OK (stdout))
{
int fd = output_tmpfd ();
if (fd < 0)
goto error;
fd_noinherit (fd);
out->out = fd;
}
if (STREAM_OK (stderr))
{
if (out->out != OUTPUT_NONE && combined_output)
out->err = out->out;
else
{
int fd = output_tmpfd ();
if (fd < 0)
goto error;
fd_noinherit (fd);
out->err = fd;
}
}
return;
/* If we failed to create a temp file, disable output sync going forward. */
error:
output_close (out);
output_sync = OUTPUT_SYNC_NONE;
}
/* Synchronize the output of jobs in -j mode to keep the results of
each job together. This is done by holding the results in temp files,
one for stdout and potentially another for stderr, and only releasing
them to "real" stdout/stderr when a semaphore can be obtained. */
void
output_dump (struct output *out)
{
int outfd_not_empty = FD_NOT_EMPTY (out->out);
int errfd_not_empty = FD_NOT_EMPTY (out->err);
if (outfd_not_empty || errfd_not_empty)
{
int traced = 0;
/* Try to acquire the semaphore. If it fails, dump the output
unsynchronized; still better than silently discarding it.
We want to keep this lock for as little time as possible. */
void *sem = acquire_semaphore ();
/* Log the working directory for this dump. */
if (print_directory_flag && output_sync != OUTPUT_SYNC_RECURSE)
traced = log_working_directory (1);
if (outfd_not_empty)
pump_from_tmp (out->out, stdout);
if (errfd_not_empty && out->err != out->out)
pump_from_tmp (out->err, stderr);
if (traced)
log_working_directory (0);
/* Exit the critical section. */
if (sem)
release_semaphore (sem);
/* Truncate and reset the output, in case we use it again. */
if (out->out != OUTPUT_NONE)
{
int e;
lseek (out->out, 0, SEEK_SET);
EINTRLOOP (e, ftruncate (out->out, 0));
}
if (out->err != OUTPUT_NONE && out->err != out->out)
{
int e;
lseek (out->err, 0, SEEK_SET);
EINTRLOOP (e, ftruncate (out->err, 0));
}
}
}
#endif /* NO_OUTPUT_SYNC */
/* This code is stolen from gnulib.
If/when we abandon the requirement to work with K&R compilers, we can
remove this (and perhaps other parts of GNU make!) and migrate to using
gnulib directly.
This is called only through atexit(), which means die() has already been
invoked. So, call exit() here directly. Apparently that works...?
*/
/* Close standard output, exiting with status 'exit_failure' on failure.
If a program writes *anything* to stdout, that program should close
stdout and make sure that it succeeds before exiting. Otherwise,
suppose that you go to the extreme of checking the return status
of every function that does an explicit write to stdout. The last
printf can succeed in writing to the internal stream buffer, and yet
the fclose(stdout) could still fail (due e.g., to a disk full error)
when it tries to write out that buffered data. Thus, you would be
left with an incomplete output file and the offending program would
exit successfully. Even calling fflush is not always sufficient,
since some file systems (NFS and CODA) buffer written/flushed data
until an actual close call.
Besides, it's wasteful to check the return value from every call
that writes to stdout -- just let the internal stream state record
the failure. That's what the ferror test is checking below.
It's important to detect such failures and exit nonzero because many
tools (most notably 'make' and other build-management systems) depend
on being able to detect failure in other tools via their exit status. */
static void
close_stdout (void)
{
int prev_fail = ferror (stdout);
int fclose_fail = fclose (stdout);
if (prev_fail || fclose_fail)
{
if (fclose_fail)
perror_with_name (_("write error: stdout"), "");
else
O (error, NILF, _("write error: stdout"));
exit (MAKE_TROUBLE);
}
}
void
output_init (struct output *out)
{
if (out)
{
out->out = out->err = OUTPUT_NONE;
out->syncout = !!output_sync;
return;
}
/* Configure this instance of make. Be sure stdout is line-buffered. */
#ifdef HAVE_SETVBUF
# ifdef SETVBUF_REVERSED
setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
# else /* setvbuf not reversed. */
/* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
setvbuf (stdout, 0, _IOLBF, BUFSIZ);
# endif /* setvbuf reversed. */
#elif HAVE_SETLINEBUF
setlinebuf (stdout);
#endif /* setlinebuf missing. */
/* Force stdout/stderr into append mode. This ensures parallel jobs won't
lose output due to overlapping writes. */
set_append_mode (fileno (stdout));
set_append_mode (fileno (stderr));
#ifdef HAVE_ATEXIT
if (STREAM_OK (stdout))
atexit (close_stdout);
#endif
}
void
output_close (struct output *out)
{
if (! out)
{
if (stdio_traced)
log_working_directory (0);
return;
}
#ifndef NO_OUTPUT_SYNC
output_dump (out);
#endif
if (out->out >= 0)
close (out->out);
if (out->err >= 0 && out->err != out->out)
close (out->err);
output_init (out);
}
/* We're about to generate output: be sure it's set up. */
void
output_start (void)
{
#ifndef NO_OUTPUT_SYNC
/* If we're syncing output make sure the temporary file is set up. */
if (output_context && output_context->syncout)
if (! OUTPUT_ISSET(output_context))
setup_tmpfile (output_context);
#endif
/* If we're not syncing this output per-line or per-target, make sure we emit
the "Entering..." message where appropriate. */
if (output_sync == OUTPUT_SYNC_NONE || output_sync == OUTPUT_SYNC_RECURSE)
if (! stdio_traced && print_directory_flag)
stdio_traced = log_working_directory (1);
}
void
outputs (int is_err, const char *msg)
{
if (! msg || *msg == '\0')
return;
output_start ();
_outputs (output_context, is_err, msg);
}
static struct fmtstring
{
char *buffer;
size_t size;
} fmtbuf = { NULL, 0 };
static char *
get_buffer (size_t need)
{
/* Make sure we have room. NEED includes space for \0. */
if (need > fmtbuf.size)
{
fmtbuf.size += need * 2;
fmtbuf.buffer = xrealloc (fmtbuf.buffer, fmtbuf.size);
}
fmtbuf.buffer[need-1] = '\0';
return fmtbuf.buffer;
}
/* Print a message on stdout. */
void
message (int prefix, size_t len, const char *fmt, ...)
{
va_list args;
char *p;
len += strlen (fmt) + strlen (program) + INTSTR_LENGTH + 4 + 1 + 1;
p = get_buffer (len);
if (prefix)
{
if (makelevel == 0)
sprintf (p, "%s: ", program);
else
sprintf (p, "%s[%u]: ", program, makelevel);
p += strlen (p);
}
va_start (args, fmt);
vsprintf (p, fmt, args);
va_end (args);
strcat (p, "\n");
assert (fmtbuf.buffer[len-1] == '\0');
outputs (0, fmtbuf.buffer);
}
/* Print an error message. */
void
error (const floc *flocp, size_t len, const char *fmt, ...)
{
va_list args;
char *p;
len += (strlen (fmt) + strlen (program)
+ (flocp && flocp->filenm ? strlen (flocp->filenm) : 0)
+ INTSTR_LENGTH + 4 + 1 + 1);
p = get_buffer (len);
if (flocp && flocp->filenm)
sprintf (p, "%s:%lu: ", flocp->filenm, flocp->lineno + flocp->offset);
else if (makelevel == 0)
sprintf (p, "%s: ", program);
else
sprintf (p, "%s[%u]: ", program, makelevel);
p += strlen (p);
va_start (args, fmt);
vsprintf (p, fmt, args);
va_end (args);
strcat (p, "\n");
assert (fmtbuf.buffer[len-1] == '\0');
outputs (1, fmtbuf.buffer);
}
/* Print an error message and exit. */
void
fatal (const floc *flocp, size_t len, const char *fmt, ...)
{
va_list args;
const char *stop = _(". Stop.\n");
char *p;
len += (strlen (fmt) + strlen (program)
+ (flocp && flocp->filenm ? strlen (flocp->filenm) : 0)
+ INTSTR_LENGTH + 8 + strlen (stop) + 1);
p = get_buffer (len);
if (flocp && flocp->filenm)
sprintf (p, "%s:%lu: *** ", flocp->filenm, flocp->lineno + flocp->offset);
else if (makelevel == 0)
sprintf (p, "%s: *** ", program);
else
sprintf (p, "%s[%u]: *** ", program, makelevel);
p += strlen (p);
va_start (args, fmt);
vsprintf (p, fmt, args);
va_end (args);
strcat (p, stop);
assert (fmtbuf.buffer[len-1] == '\0');
outputs (1, fmtbuf.buffer);
die (MAKE_FAILURE);
}
/* Print an error message from errno. */
void
perror_with_name (const char *str, const char *name)
{
const char *err = strerror (errno);
OSSS (error, NILF, _("%s%s: %s"), str, name, err);
}
/* Print an error message from errno and exit. */
void
pfatal_with_name (const char *name)
{
const char *err = strerror (errno);
OSS (fatal, NILF, _("%s: %s"), name, err);
/* NOTREACHED */
}
/* Print a message about out of memory (not using more heap) and exit.
Our goal here is to be sure we don't try to allocate more memory, which
means we don't want to use string translations or normal cleanup. */
void
out_of_memory ()
{
writebuf (FD_STDOUT, program, strlen (program));
writebuf (FD_STDOUT, STRING_SIZE_TUPLE (": *** virtual memory exhausted\n"));
exit (MAKE_FAILURE);
}
| 16,838 | 665 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/stdint.h | /* clang-format off */
/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* Copyright (C) 2001-2002, 2004-2020 Free Software Foundation, Inc.
Written by Paul Eggert, Bruno Haible, Sam Steingold, Peter Burwood.
This file is part of gnulib.
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, 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/>. */
/*
* ISO C 99 <stdint.h> for platforms that lack it.
* <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/stdint.h.html>
*/
#ifndef _GL_STDINT_H
#if __GNUC__ >= 3
#pragma GCC system_header
#endif
/* When including a system file that in turn includes <inttypes.h>,
use the system <inttypes.h>, not our substitute. This avoids
problems with (for example) VMS, whose <sys/bitypes.h> includes
<inttypes.h>. */
#define _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H
/* On Android (Bionic libc), <sys/types.h> includes this file before
having defined 'time_t'. Therefore in this case avoid including
other system header files; just include the system's <stdint.h>.
Ideally we should test __BIONIC__ here, but it is only defined after
<sys/cdefs.h> has been included; hence test __ANDROID__ instead. */
#if defined __ANDROID__ && defined _GL_INCLUDING_SYS_TYPES_H
#else
/* Get those types that are already defined in other system include
files, so that we can "#define int8_t signed char" below without
worrying about a later system include file containing a "typedef
signed char int8_t;" that will get messed up by our macro. Our
macros should all be consistent with the system versions, except
for the "fast" types and macros, which we recommend against using
in public interfaces due to compiler differences. */
#if 1
# if defined __sgi && ! defined __c99
/* Bypass IRIX's <stdint.h> if in C89 mode, since it merely annoys users
with "This header file is to be used only for c99 mode compilations"
diagnostics. */
# define __STDINT_H__
# endif
/* Some pre-C++11 <stdint.h> implementations need this. */
# ifdef __cplusplus
# ifndef __STDC_CONSTANT_MACROS
# define __STDC_CONSTANT_MACROS 1
# endif
# ifndef __STDC_LIMIT_MACROS
# define __STDC_LIMIT_MACROS 1
# endif
# endif
/* Other systems may have an incomplete or buggy <stdint.h>.
in <inttypes.h> would reinclude us, skipping our contents because
_GL_STDINT_H is defined.
The include_next requires a split double-inclusion guard. */
#endif
#if ! defined _GL_STDINT_H && ! defined _GL_JUST_INCLUDE_SYSTEM_STDINT_H
#define _GL_STDINT_H
/* Get SCHAR_MIN, SCHAR_MAX, UCHAR_MAX, INT_MIN, INT_MAX,
LONG_MIN, LONG_MAX, ULONG_MAX, _GL_INTEGER_WIDTH. */
/* Override WINT_MIN and WINT_MAX if gnulib's <wchar.h> or <wctype.h> overrides
wint_t. */
#if 0
# undef WINT_MIN
# undef WINT_MAX
# define WINT_MIN 0x0U
# define WINT_MAX 0xffffffffU
#endif
#if ! 0
/* <sys/types.h> defines some of the stdint.h types as well, on glibc,
IRIX 6.5, and OpenBSD 3.8 (via <machine/types.h>).
AIX 5.2 <sys/types.h> isn't needed and causes troubles.
Mac OS X 10.4.6 <sys/types.h> includes <stdint.h> (which is us), but
relies on the system <stdint.h> definitions, so include
<sys/types.h> after <stdint.h>. */
# if 1 && ! defined _AIX
# endif
# if 1
/* In OpenBSD 3.8, <inttypes.h> includes <machine/types.h>, which defines
int{8,16,32,64}_t, uint{8,16,32,64}_t and __BIT_TYPES_DEFINED__.
<inttypes.h> also defines intptr_t and uintptr_t. */
# elif 0
/* Solaris 7 <sys/inttypes.h> has the types except the *_fast*_t types, and
the macros except for *_FAST*_*, INTPTR_MIN, PTRDIFF_MIN, PTRDIFF_MAX. */
# endif
# if 0 && ! defined __BIT_TYPES_DEFINED__
/* Linux libc4 >= 4.6.7 and libc5 have a <sys/bitypes.h> that defines
int{8,16,32,64}_t and __BIT_TYPES_DEFINED__. In libc5 >= 5.2.2 it is
included by <sys/types.h>. */
# endif
# undef _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H
/* Minimum and maximum values for an integer type under the usual assumption.
Return an unspecified value if BITS == 0, adding a check to pacify
picky compilers. */
/* These are separate macros, because if you try to merge these macros into
a single one, HP-UX cc rejects the resulting expression in constant
expressions. */
# define _STDINT_UNSIGNED_MIN(bits, zero) \
(zero)
# define _STDINT_SIGNED_MIN(bits, zero) \
(~ _STDINT_MAX (1, bits, zero))
# define _STDINT_MAX(signed, bits, zero) \
(((((zero) + 1) << ((bits) ? (bits) - 1 - (signed) : 0)) - 1) * 2 + 1)
#if !GNULIB_defined_stdint_types
/* 7.18.1.1. Exact-width integer types */
/* Here we assume a standard architecture where the hardware integer
types have 8, 16, 32, optionally 64 bits. */
# undef int8_t
# undef uint8_t
typedef signed char gl_int8_t;
typedef unsigned char gl_uint8_t;
# define int8_t gl_int8_t
# define uint8_t gl_uint8_t
# undef int16_t
# undef uint16_t
typedef short int gl_int16_t;
typedef unsigned short int gl_uint16_t;
# define int16_t gl_int16_t
# define uint16_t gl_uint16_t
# undef int32_t
# undef uint32_t
typedef int gl_int32_t;
typedef unsigned int gl_uint32_t;
# define int32_t gl_int32_t
# define uint32_t gl_uint32_t
/* If the system defines INT64_MAX, assume int64_t works. That way,
if the underlying platform defines int64_t to be a 64-bit long long
int, the code below won't mistakenly define it to be a 64-bit long
int, which would mess up C++ name mangling. We must use #ifdef
rather than #if, to avoid an error with HP-UX 10.20 cc. */
# ifdef INT64_MAX
# define GL_INT64_T
# else
/* Do not undefine int64_t if gnulib is not being used with 64-bit
types, since otherwise it breaks platforms like Tandem/NSK. */
# if LONG_MAX >> 31 >> 31 == 1
# undef int64_t
typedef long int gl_int64_t;
# define int64_t gl_int64_t
# define GL_INT64_T
# elif defined _MSC_VER
# undef int64_t
typedef __int64 gl_int64_t;
# define int64_t gl_int64_t
# define GL_INT64_T
# else
# undef int64_t
typedef long long int gl_int64_t;
# define int64_t gl_int64_t
# define GL_INT64_T
# endif
# endif
# ifdef UINT64_MAX
# define GL_UINT64_T
# else
# if ULONG_MAX >> 31 >> 31 >> 1 == 1
# undef uint64_t
typedef unsigned long int gl_uint64_t;
# define uint64_t gl_uint64_t
# define GL_UINT64_T
# elif defined _MSC_VER
# undef uint64_t
typedef unsigned __int64 gl_uint64_t;
# define uint64_t gl_uint64_t
# define GL_UINT64_T
# else
# undef uint64_t
typedef unsigned long long int gl_uint64_t;
# define uint64_t gl_uint64_t
# define GL_UINT64_T
# endif
# endif
/* Avoid collision with Solaris 2.5.1 <pthread.h> etc. */
# define _UINT8_T
# define _UINT32_T
# define _UINT64_T
/* 7.18.1.2. Minimum-width integer types */
/* Here we assume a standard architecture where the hardware integer
types have 8, 16, 32, optionally 64 bits. Therefore the leastN_t types
are the same as the corresponding N_t types. */
# undef int_least8_t
# undef uint_least8_t
# undef int_least16_t
# undef uint_least16_t
# undef int_least32_t
# undef uint_least32_t
# undef int_least64_t
# undef uint_least64_t
# define int_least8_t int8_t
# define uint_least8_t uint8_t
# define int_least16_t int16_t
# define uint_least16_t uint16_t
# define int_least32_t int32_t
# define uint_least32_t uint32_t
# ifdef GL_INT64_T
# define int_least64_t int64_t
# endif
# ifdef GL_UINT64_T
# define uint_least64_t uint64_t
# endif
/* 7.18.1.3. Fastest minimum-width integer types */
/* Note: Other <stdint.h> substitutes may define these types differently.
It is not recommended to use these types in public header files. */
/* Here we assume a standard architecture where the hardware integer
types have 8, 16, 32, optionally 64 bits. Therefore the fastN_t types
are taken from the same list of types. The following code normally
uses types consistent with glibc, as that lessens the chance of
incompatibility with older GNU hosts. */
# undef int_fast8_t
# undef uint_fast8_t
# undef int_fast16_t
# undef uint_fast16_t
# undef int_fast32_t
# undef uint_fast32_t
# undef int_fast64_t
# undef uint_fast64_t
typedef signed char gl_int_fast8_t;
typedef unsigned char gl_uint_fast8_t;
# ifdef __sun
/* Define types compatible with SunOS 5.10, so that code compiled under
earlier SunOS versions works with code compiled under SunOS 5.10. */
typedef int gl_int_fast32_t;
typedef unsigned int gl_uint_fast32_t;
# else
typedef long int gl_int_fast32_t;
typedef unsigned long int gl_uint_fast32_t;
# endif
typedef gl_int_fast32_t gl_int_fast16_t;
typedef gl_uint_fast32_t gl_uint_fast16_t;
# define int_fast8_t gl_int_fast8_t
# define uint_fast8_t gl_uint_fast8_t
# define int_fast16_t gl_int_fast16_t
# define uint_fast16_t gl_uint_fast16_t
# define int_fast32_t gl_int_fast32_t
# define uint_fast32_t gl_uint_fast32_t
# ifdef GL_INT64_T
# define int_fast64_t int64_t
# endif
# ifdef GL_UINT64_T
# define uint_fast64_t uint64_t
# endif
/* 7.18.1.4. Integer types capable of holding object pointers */
/* kLIBC's <stdint.h> defines _INTPTR_T_DECLARED and needs its own
definitions of intptr_t and uintptr_t (which use int and unsigned)
to avoid clashes with declarations of system functions like sbrk.
Similarly, mingw 5.22 <crtdefs.h> defines _INTPTR_T_DEFINED and
_UINTPTR_T_DEFINED and needs its own definitions of intptr_t and
uintptr_t to avoid conflicting declarations of system functions like
_findclose in <io.h>. */
# if !((defined __KLIBC__ && defined _INTPTR_T_DECLARED) \
|| (defined __MINGW32__ && defined _INTPTR_T_DEFINED && defined _UINTPTR_T_DEFINED))
# undef intptr_t
# undef uintptr_t
# ifdef _WIN64
typedef long long int gl_intptr_t;
typedef unsigned long long int gl_uintptr_t;
# else
typedef long int gl_intptr_t;
typedef unsigned long int gl_uintptr_t;
# endif
# define intptr_t gl_intptr_t
# define uintptr_t gl_uintptr_t
# endif
/* 7.18.1.5. Greatest-width integer types */
/* Note: These types are compiler dependent. It may be unwise to use them in
public header files. */
/* If the system defines INTMAX_MAX, assume that intmax_t works, and
similarly for UINTMAX_MAX and uintmax_t. This avoids problems with
assuming one type where another is used by the system. */
# ifndef INTMAX_MAX
# undef INTMAX_C
# undef intmax_t
# if LONG_MAX >> 30 == 1
typedef long long int gl_intmax_t;
# define intmax_t gl_intmax_t
# elif defined GL_INT64_T
# define intmax_t int64_t
# else
typedef long int gl_intmax_t;
# define intmax_t gl_intmax_t
# endif
# endif
# ifndef UINTMAX_MAX
# undef UINTMAX_C
# undef uintmax_t
# if ULONG_MAX >> 31 == 1
typedef unsigned long long int gl_uintmax_t;
# define uintmax_t gl_uintmax_t
# elif defined GL_UINT64_T
# define uintmax_t uint64_t
# else
typedef unsigned long int gl_uintmax_t;
# define uintmax_t gl_uintmax_t
# endif
# endif
/* Verify that intmax_t and uintmax_t have the same size. Too much code
breaks if this is not the case. If this check fails, the reason is likely
to be found in the autoconf macros. */
typedef int _verify_intmax_size[sizeof (intmax_t) == sizeof (uintmax_t)
? 1 : -1];
# define GNULIB_defined_stdint_types 1
# endif /* !GNULIB_defined_stdint_types */
/* 7.18.2. Limits of specified-width integer types */
/* 7.18.2.1. Limits of exact-width integer types */
/* Here we assume a standard architecture where the hardware integer
types have 8, 16, 32, optionally 64 bits. */
# undef INT8_MIN
# undef INT8_MAX
# undef UINT8_MAX
# define INT8_MIN (~ INT8_MAX)
# define INT8_MAX 127
# define UINT8_MAX 255
# undef INT16_MIN
# undef INT16_MAX
# undef UINT16_MAX
# define INT16_MIN (~ INT16_MAX)
# define INT16_MAX 32767
# define UINT16_MAX 65535
# undef INT32_MIN
# undef INT32_MAX
# undef UINT32_MAX
# define INT32_MIN (~ INT32_MAX)
# define INT32_MAX 2147483647
# define UINT32_MAX 4294967295U
# if defined GL_INT64_T && ! defined INT64_MAX
/* Prefer (- INTMAX_C (1) << 63) over (~ INT64_MAX) because SunPRO C 5.0
evaluates the latter incorrectly in preprocessor expressions. */
# define INT64_MIN (- INTMAX_C (1) << 63)
# define INT64_MAX INTMAX_C (9223372036854775807)
# endif
# if defined GL_UINT64_T && ! defined UINT64_MAX
# define UINT64_MAX UINTMAX_C (18446744073709551615)
# endif
/* 7.18.2.2. Limits of minimum-width integer types */
/* Here we assume a standard architecture where the hardware integer
types have 8, 16, 32, optionally 64 bits. Therefore the leastN_t types
are the same as the corresponding N_t types. */
# undef INT_LEAST8_MIN
# undef INT_LEAST8_MAX
# undef UINT_LEAST8_MAX
# define INT_LEAST8_MIN INT8_MIN
# define INT_LEAST8_MAX INT8_MAX
# define UINT_LEAST8_MAX UINT8_MAX
# undef INT_LEAST16_MIN
# undef INT_LEAST16_MAX
# undef UINT_LEAST16_MAX
# define INT_LEAST16_MIN INT16_MIN
# define INT_LEAST16_MAX INT16_MAX
# define UINT_LEAST16_MAX UINT16_MAX
# undef INT_LEAST32_MIN
# undef INT_LEAST32_MAX
# undef UINT_LEAST32_MAX
# define INT_LEAST32_MIN INT32_MIN
# define INT_LEAST32_MAX INT32_MAX
# define UINT_LEAST32_MAX UINT32_MAX
# undef INT_LEAST64_MIN
# undef INT_LEAST64_MAX
# ifdef GL_INT64_T
# define INT_LEAST64_MIN INT64_MIN
# define INT_LEAST64_MAX INT64_MAX
# endif
# undef UINT_LEAST64_MAX
# ifdef GL_UINT64_T
# define UINT_LEAST64_MAX UINT64_MAX
# endif
/* 7.18.2.3. Limits of fastest minimum-width integer types */
/* Here we assume a standard architecture where the hardware integer
types have 8, 16, 32, optionally 64 bits. Therefore the fastN_t types
are taken from the same list of types. */
# undef INT_FAST8_MIN
# undef INT_FAST8_MAX
# undef UINT_FAST8_MAX
# define INT_FAST8_MIN SCHAR_MIN
# define INT_FAST8_MAX SCHAR_MAX
# define UINT_FAST8_MAX UCHAR_MAX
# undef INT_FAST16_MIN
# undef INT_FAST16_MAX
# undef UINT_FAST16_MAX
# define INT_FAST16_MIN INT_FAST32_MIN
# define INT_FAST16_MAX INT_FAST32_MAX
# define UINT_FAST16_MAX UINT_FAST32_MAX
# undef INT_FAST32_MIN
# undef INT_FAST32_MAX
# undef UINT_FAST32_MAX
# ifdef __sun
# define INT_FAST32_MIN INT_MIN
# define INT_FAST32_MAX INT_MAX
# define UINT_FAST32_MAX UINT_MAX
# else
# define INT_FAST32_MIN LONG_MIN
# define INT_FAST32_MAX LONG_MAX
# define UINT_FAST32_MAX ULONG_MAX
# endif
# undef INT_FAST64_MIN
# undef INT_FAST64_MAX
# ifdef GL_INT64_T
# define INT_FAST64_MIN INT64_MIN
# define INT_FAST64_MAX INT64_MAX
# endif
# undef UINT_FAST64_MAX
# ifdef GL_UINT64_T
# define UINT_FAST64_MAX UINT64_MAX
# endif
/* 7.18.2.4. Limits of integer types capable of holding object pointers */
# undef INTPTR_MIN
# undef INTPTR_MAX
# undef UINTPTR_MAX
# ifdef _WIN64
# define INTPTR_MIN LLONG_MIN
# define INTPTR_MAX LLONG_MAX
# define UINTPTR_MAX ULLONG_MAX
# else
# define INTPTR_MIN LONG_MIN
# define INTPTR_MAX LONG_MAX
# define UINTPTR_MAX ULONG_MAX
# endif
/* 7.18.2.5. Limits of greatest-width integer types */
# ifndef INTMAX_MAX
# undef INTMAX_MIN
# ifdef INT64_MAX
# define INTMAX_MIN INT64_MIN
# define INTMAX_MAX INT64_MAX
# else
# define INTMAX_MIN INT32_MIN
# define INTMAX_MAX INT32_MAX
# endif
# endif
# ifndef UINTMAX_MAX
# ifdef UINT64_MAX
# define UINTMAX_MAX UINT64_MAX
# else
# define UINTMAX_MAX UINT32_MAX
# endif
# endif
/* 7.18.3. Limits of other integer types */
/* ptrdiff_t limits */
# undef PTRDIFF_MIN
# undef PTRDIFF_MAX
# if 0
# ifdef _LP64
# define PTRDIFF_MIN _STDINT_SIGNED_MIN (64, 0l)
# define PTRDIFF_MAX _STDINT_MAX (1, 64, 0l)
# else
# define PTRDIFF_MIN _STDINT_SIGNED_MIN (32, 0)
# define PTRDIFF_MAX _STDINT_MAX (1, 32, 0)
# endif
# else
# define PTRDIFF_MIN \
_STDINT_SIGNED_MIN (64, 0l)
# define PTRDIFF_MAX \
_STDINT_MAX (1, 64, 0l)
# endif
/* sig_atomic_t limits */
# undef SIG_ATOMIC_MIN
# undef SIG_ATOMIC_MAX
# if 1
# define SIG_ATOMIC_MIN \
_STDINT_SIGNED_MIN (32, 0)
# else
# define SIG_ATOMIC_MIN \
_STDINT_UNSIGNED_MIN (32, 0)
# endif
# define SIG_ATOMIC_MAX \
_STDINT_MAX (1, 32, \
0)
/* size_t limit */
# undef SIZE_MAX
# if 0
# ifdef _LP64
# define SIZE_MAX _STDINT_MAX (0, 64, 0ul)
# else
# define SIZE_MAX _STDINT_MAX (0, 32, 0ul)
# endif
# else
# define SIZE_MAX _STDINT_MAX (0, 64, 0ul)
# endif
/* wchar_t limits */
/* Get WCHAR_MIN, WCHAR_MAX.
This include is not on the top, above, because on OSF/1 4.0 we have a
sequence of nested includes
<wchar.h> -> <stdio.h> -> <getopt.h> -> <stdlib.h>, and the latter includes
<stdint.h> and assumes its types are already defined. */
# if 1 && ! (defined WCHAR_MIN && defined WCHAR_MAX)
/* BSD/OS 4.0.1 has a bug: <stddef.h>, <stdio.h> and <time.h> must be
included before <wchar.h>. */
# define _GL_JUST_INCLUDE_SYSTEM_WCHAR_H
# undef _GL_JUST_INCLUDE_SYSTEM_WCHAR_H
# endif
# undef WCHAR_MIN
# undef WCHAR_MAX
# if 1
# define WCHAR_MIN \
_STDINT_SIGNED_MIN (32, 0)
# else
# define WCHAR_MIN \
_STDINT_UNSIGNED_MIN (32, 0)
# endif
# define WCHAR_MAX \
_STDINT_MAX (1, 32, 0)
/* wint_t limits */
/* If gnulib's <wchar.h> or <wctype.h> overrides wint_t, u is not
accurate, therefore use the definitions from above. */
# if !0
# undef WINT_MIN
# undef WINT_MAX
# if 0
# define WINT_MIN \
_STDINT_SIGNED_MIN (32, 0u)
# else
# define WINT_MIN \
_STDINT_UNSIGNED_MIN (32, 0u)
# endif
# define WINT_MAX \
_STDINT_MAX (0, 32, 0u)
# endif
/* 7.18.4. Macros for integer constants */
/* 7.18.4.1. Macros for minimum-width integer constants */
/* According to ISO C 99 Technical Corrigendum 1 */
/* Here we assume a standard architecture where the hardware integer
types have 8, 16, 32, optionally 64 bits, and int is 32 bits. */
# undef INT8_C
# undef UINT8_C
# define INT8_C(x) x
# define UINT8_C(x) x
# undef INT16_C
# undef UINT16_C
# define INT16_C(x) x
# define UINT16_C(x) x
# undef INT32_C
# undef UINT32_C
# define INT32_C(x) x
# define UINT32_C(x) x ## U
# undef INT64_C
# undef UINT64_C
# if LONG_MAX >> 31 >> 31 == 1
# define INT64_C(x) x##L
# elif defined _MSC_VER
# define INT64_C(x) x##i64
# else
# define INT64_C(x) x##LL
# endif
# if ULONG_MAX >> 31 >> 31 >> 1 == 1
# define UINT64_C(x) x##UL
# elif defined _MSC_VER
# define UINT64_C(x) x##ui64
# else
# define UINT64_C(x) x##ULL
# endif
/* 7.18.4.2. Macros for greatest-width integer constants */
# ifndef INTMAX_C
# if LONG_MAX >> 30 == 1
# define INTMAX_C(x) x##LL
# elif defined GL_INT64_T
# define INTMAX_C(x) INT64_C(x)
# else
# define INTMAX_C(x) x##L
# endif
# endif
# ifndef UINTMAX_C
# if ULONG_MAX >> 31 == 1
# define UINTMAX_C(x) x##ULL
# elif defined GL_UINT64_T
# define UINTMAX_C(x) UINT64_C(x)
# else
# define UINTMAX_C(x) x##UL
# endif
# endif
#endif /* !0 */
/* Macros specified by ISO/IEC TS 18661-1:2014. */
#if (!defined UINTMAX_WIDTH \
&& (defined _GNU_SOURCE || defined __STDC_WANT_IEC_60559_BFP_EXT__))
# ifdef INT8_MAX
# define INT8_WIDTH _GL_INTEGER_WIDTH (INT8_MIN, INT8_MAX)
# endif
# ifdef UINT8_MAX
# define UINT8_WIDTH _GL_INTEGER_WIDTH (0, UINT8_MAX)
# endif
# ifdef INT16_MAX
# define INT16_WIDTH _GL_INTEGER_WIDTH (INT16_MIN, INT16_MAX)
# endif
# ifdef UINT16_MAX
# define UINT16_WIDTH _GL_INTEGER_WIDTH (0, UINT16_MAX)
# endif
# ifdef INT32_MAX
# define INT32_WIDTH _GL_INTEGER_WIDTH (INT32_MIN, INT32_MAX)
# endif
# ifdef UINT32_MAX
# define UINT32_WIDTH _GL_INTEGER_WIDTH (0, UINT32_MAX)
# endif
# ifdef INT64_MAX
# define INT64_WIDTH _GL_INTEGER_WIDTH (INT64_MIN, INT64_MAX)
# endif
# ifdef UINT64_MAX
# define UINT64_WIDTH _GL_INTEGER_WIDTH (0, UINT64_MAX)
# endif
# define INT_LEAST8_WIDTH _GL_INTEGER_WIDTH (INT_LEAST8_MIN, INT_LEAST8_MAX)
# define UINT_LEAST8_WIDTH _GL_INTEGER_WIDTH (0, UINT_LEAST8_MAX)
# define INT_LEAST16_WIDTH _GL_INTEGER_WIDTH (INT_LEAST16_MIN, INT_LEAST16_MAX)
# define UINT_LEAST16_WIDTH _GL_INTEGER_WIDTH (0, UINT_LEAST16_MAX)
# define INT_LEAST32_WIDTH _GL_INTEGER_WIDTH (INT_LEAST32_MIN, INT_LEAST32_MAX)
# define UINT_LEAST32_WIDTH _GL_INTEGER_WIDTH (0, UINT_LEAST32_MAX)
# define INT_LEAST64_WIDTH _GL_INTEGER_WIDTH (INT_LEAST64_MIN, INT_LEAST64_MAX)
# define UINT_LEAST64_WIDTH _GL_INTEGER_WIDTH (0, UINT_LEAST64_MAX)
# define INT_FAST8_WIDTH _GL_INTEGER_WIDTH (INT_FAST8_MIN, INT_FAST8_MAX)
# define UINT_FAST8_WIDTH _GL_INTEGER_WIDTH (0, UINT_FAST8_MAX)
# define INT_FAST16_WIDTH _GL_INTEGER_WIDTH (INT_FAST16_MIN, INT_FAST16_MAX)
# define UINT_FAST16_WIDTH _GL_INTEGER_WIDTH (0, UINT_FAST16_MAX)
# define INT_FAST32_WIDTH _GL_INTEGER_WIDTH (INT_FAST32_MIN, INT_FAST32_MAX)
# define UINT_FAST32_WIDTH _GL_INTEGER_WIDTH (0, UINT_FAST32_MAX)
# define INT_FAST64_WIDTH _GL_INTEGER_WIDTH (INT_FAST64_MIN, INT_FAST64_MAX)
# define UINT_FAST64_WIDTH _GL_INTEGER_WIDTH (0, UINT_FAST64_MAX)
# define INTPTR_WIDTH _GL_INTEGER_WIDTH (INTPTR_MIN, INTPTR_MAX)
# define UINTPTR_WIDTH _GL_INTEGER_WIDTH (0, UINTPTR_MAX)
# define INTMAX_WIDTH _GL_INTEGER_WIDTH (INTMAX_MIN, INTMAX_MAX)
# define UINTMAX_WIDTH _GL_INTEGER_WIDTH (0, UINTMAX_MAX)
# define PTRDIFF_WIDTH _GL_INTEGER_WIDTH (PTRDIFF_MIN, PTRDIFF_MAX)
# define SIZE_WIDTH _GL_INTEGER_WIDTH (0, SIZE_MAX)
# define WCHAR_WIDTH _GL_INTEGER_WIDTH (WCHAR_MIN, WCHAR_MAX)
# ifdef WINT_MAX
# define WINT_WIDTH _GL_INTEGER_WIDTH (WINT_MIN, WINT_MAX)
# endif
# ifdef SIG_ATOMIC_MAX
# define SIG_ATOMIC_WIDTH _GL_INTEGER_WIDTH (SIG_ATOMIC_MIN, SIG_ATOMIC_MAX)
# endif
#endif /* !WINT_WIDTH && (_GNU_SOURCE || __STDC_WANT_IEC_60559_BFP_EXT__) */
#endif /* _GL_STDINT_H */
#endif /* !(defined __ANDROID__ && ...) */
#endif /* !defined _GL_STDINT_H && !defined _GL_JUST_INCLUDE_SYSTEM_STDINT_H */
| 22,125 | 737 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/concat-filename.c | /* Construct a full filename from a directory and a relative filename.
Copyright (C) 2001-2004, 2006-2020 Free Software Foundation, 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; either version 3 of the License, or 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/>. */
/* Written by Bruno Haible <[email protected]>. */
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "third_party/make/concat-filename.h"
#include "third_party/make/filename.h"
#include "third_party/make/config.h"
/* clang-format off */
/* Concatenate a directory filename, a relative filename and an optional
suffix. The directory may end with the directory separator. The second
argument may not start with the directory separator (it is relative).
Return a freshly allocated filename. Return NULL and set errno
upon memory allocation failure. */
char *
concatenated_filename (const char *directory, const char *filename,
const char *suffix)
{
char *result;
char *p;
if (strcmp (directory, ".") == 0)
{
/* No need to prepend the directory. */
result = (char *) malloc (strlen (filename)
+ (suffix != NULL ? strlen (suffix) : 0)
+ 1);
if (result == NULL)
return NULL; /* errno is set here */
p = result;
}
else
{
size_t directory_len = strlen (directory);
int need_slash =
(directory_len > FILE_SYSTEM_PREFIX_LEN (directory)
&& !ISSLASH (directory[directory_len - 1]));
result = (char *) malloc (directory_len + need_slash
+ strlen (filename)
+ (suffix != NULL ? strlen (suffix) : 0)
+ 1);
if (result == NULL)
return NULL; /* errno is set here */
memcpy (result, directory, directory_len);
p = result + directory_len;
if (need_slash)
*p++ = '/';
}
p = stpcpy (p, filename);
if (suffix != NULL)
stpcpy (p, suffix);
return result;
}
| 2,564 | 70 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/getprogname.c | /* Program name management.
Copyright (C) 2016-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* clang-format off */
#include "third_party/make/config.h"
#include "third_party/make/getprogname.h"
#include "libc/intrin/safemacros.internal.h"
#include "third_party/make/dirname.h"
char const *
getprogname (void)
{
return firstnonnull(program_invocation_short_name, "unknown");
}
/*
* Hey Emacs!
* Local Variables:
* coding: utf-8
* End:
*/
| 1,089 | 35 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/vpath.c | /* Implementation of pattern-matching file search paths for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* clang-format off */
#include "third_party/make/makeint.inc"
#include "third_party/make/filedef.h"
#include "third_party/make/variable.h"
/* Structure used to represent a selective VPATH searchpath. */
struct vpath
{
struct vpath *next; /* Pointer to next struct in the linked list. */
const char *pattern; /* The pattern to match. */
const char *percent; /* Pointer into 'pattern' where the '%' is. */
size_t patlen; /* Length of the pattern. */
const char **searchpath; /* Null-terminated list of directories. */
size_t maxlen; /* Maximum length of any entry in the list. */
};
/* Linked-list of all selective VPATHs. */
static struct vpath *vpaths;
/* Structure for the general VPATH given in the variable. */
static struct vpath *general_vpath;
/* Structure for GPATH given in the variable. */
static struct vpath *gpaths;
/* Reverse the chain of selective VPATH lists so they will be searched in the
order given in the makefiles and construct the list from the VPATH
variable. */
void
build_vpath_lists (void)
{
struct vpath *new = 0;
struct vpath *old, *nexto;
char *p;
/* Reverse the chain. */
for (old = vpaths; old != 0; old = nexto)
{
nexto = old->next;
old->next = new;
new = old;
}
vpaths = new;
/* If there is a VPATH variable with a nonnull value, construct the
general VPATH list from it. We use variable_expand rather than just
calling lookup_variable so that it will be recursively expanded. */
{
/* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
int save = warn_undefined_variables_flag;
warn_undefined_variables_flag = 0;
p = variable_expand ("$(strip $(VPATH))");
warn_undefined_variables_flag = save;
}
if (*p != '\0')
{
/* Save the list of vpaths. */
struct vpath *save_vpaths = vpaths;
char gp[] = "%";
/* Empty 'vpaths' so the new one will have no next, and 'vpaths'
will still be nil if P contains no existing directories. */
vpaths = 0;
/* Parse P. */
construct_vpath_list (gp, p);
/* Store the created path as the general path,
and restore the old list of vpaths. */
general_vpath = vpaths;
vpaths = save_vpaths;
}
/* If there is a GPATH variable with a nonnull value, construct the
GPATH list from it. We use variable_expand rather than just
calling lookup_variable so that it will be recursively expanded. */
{
/* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
int save = warn_undefined_variables_flag;
warn_undefined_variables_flag = 0;
p = variable_expand ("$(strip $(GPATH))");
warn_undefined_variables_flag = save;
}
if (*p != '\0')
{
/* Save the list of vpaths. */
struct vpath *save_vpaths = vpaths;
char gp[] = "%";
/* Empty 'vpaths' so the new one will have no next, and 'vpaths'
will still be nil if P contains no existing directories. */
vpaths = 0;
/* Parse P. */
construct_vpath_list (gp, p);
/* Store the created path as the GPATH,
and restore the old list of vpaths. */
gpaths = vpaths;
vpaths = save_vpaths;
}
}
/* Construct the VPATH listing for the PATTERN and DIRPATH given.
This function is called to generate selective VPATH lists and also for
the general VPATH list (which is in fact just a selective VPATH that
is applied to everything). The returned pointer is either put in the
linked list of all selective VPATH lists or in the GENERAL_VPATH
variable.
If DIRPATH is nil, remove all previous listings with the same
pattern. If PATTERN is nil, remove all VPATH listings. Existing
and readable directories that are not "." given in the DIRPATH
separated by the path element separator (defined in makeint.h) are
loaded into the directory hash table if they are not there already
and put in the VPATH searchpath for the given pattern with trailing
slashes stripped off if present (and if the directory is not the
root, "/"). The length of the longest entry in the list is put in
the structure as well. The new entry will be at the head of the
VPATHS chain. */
void
construct_vpath_list (char *pattern, char *dirpath)
{
unsigned int elem;
char *p;
const char **vpath;
size_t maxvpath;
unsigned int maxelem;
const char *percent = NULL;
if (pattern != 0)
percent = find_percent (pattern);
if (dirpath == 0)
{
/* Remove matching listings. */
struct vpath *path, *lastpath;
lastpath = 0;
path = vpaths;
while (path != 0)
{
struct vpath *next = path->next;
if (pattern == 0
|| (((percent == 0 && path->percent == 0)
|| (percent - pattern == path->percent - path->pattern))
&& streq (pattern, path->pattern)))
{
/* Remove it from the linked list. */
if (lastpath == 0)
vpaths = path->next;
else
lastpath->next = next;
/* Free its unused storage. */
/* MSVC erroneously warns without a cast here. */
free ((void *)path->searchpath);
free (path);
}
else
lastpath = path;
path = next;
}
return;
}
#ifdef WINDOWS32
convert_vpath_to_windows32 (dirpath, ';');
#endif
/* Skip over any initial separators and blanks. */
while (STOP_SET (*dirpath, MAP_BLANK|MAP_PATHSEP))
++dirpath;
/* Figure out the maximum number of VPATH entries and put it in
MAXELEM. We start with 2, one before the first separator and one
nil (the list terminator) and increment our estimated number for
each separator or blank we find. */
maxelem = 2;
p = dirpath;
while (*p != '\0')
if (STOP_SET (*p++, MAP_BLANK|MAP_PATHSEP))
++maxelem;
vpath = xmalloc (maxelem * sizeof (const char *));
maxvpath = 0;
elem = 0;
p = dirpath;
while (*p != '\0')
{
char *v;
size_t len;
/* Find the end of this entry. */
v = p;
while (*p != '\0'
#if defined(HAVE_DOS_PATHS) && (PATH_SEPARATOR_CHAR == ':')
/* Platforms whose PATH_SEPARATOR_CHAR is ':' and which
also define HAVE_DOS_PATHS would like us to recognize
colons after the drive letter in the likes of
"D:/foo/bar:C:/xyzzy". */
&& (*p != PATH_SEPARATOR_CHAR
|| (p == v + 1 && (p[1] == '/' || p[1] == '\\')))
#else
&& *p != PATH_SEPARATOR_CHAR
#endif
&& !ISBLANK (*p))
++p;
len = p - v;
/* Make sure there's no trailing slash,
but still allow "/" as a directory. */
#if defined(__MSDOS__) || defined(__EMX__) || defined(HAVE_DOS_PATHS)
/* We need also to leave alone a trailing slash in "d:/". */
if (len > 3 || (len > 1 && v[1] != ':'))
#endif
if (len > 1 && p[-1] == '/')
--len;
/* Put the directory on the vpath list. */
if (len > 1 || *v != '.')
{
vpath[elem++] = dir_name (strcache_add_len (v, len));
if (len > maxvpath)
maxvpath = len;
}
/* Skip over separators and blanks between entries. */
while (STOP_SET (*p, MAP_BLANK|MAP_PATHSEP))
++p;
}
if (elem > 0)
{
struct vpath *path;
/* ELEM is now incremented one element past the last
entry, to where the nil-pointer terminator goes.
Usually this is maxelem - 1. If not, shrink down. */
if (elem < (maxelem - 1))
vpath = xrealloc (vpath, (elem+1) * sizeof (const char *));
/* Put the nil-pointer terminator on the end of the VPATH list. */
vpath[elem] = NULL;
/* Construct the vpath structure and put it into the linked list. */
path = xmalloc (sizeof (struct vpath));
path->searchpath = vpath;
path->maxlen = maxvpath;
path->next = vpaths;
vpaths = path;
/* Set up the members. */
path->pattern = strcache_add (pattern);
path->patlen = strlen (pattern);
path->percent = percent ? path->pattern + (percent - pattern) : 0;
}
else
/* There were no entries, so free whatever space we allocated. */
/* MSVC erroneously warns without a cast here. */
free ((void *)vpath);
}
/* Search the GPATH list for a pathname string that matches the one passed
in. If it is found, return 1. Otherwise we return 0. */
int
gpath_search (const char *file, size_t len)
{
if (gpaths && (len <= gpaths->maxlen))
{
const char **gp;
for (gp = gpaths->searchpath; *gp != NULL; ++gp)
if (strneq (*gp, file, len) && (*gp)[len] == '\0')
return 1;
}
return 0;
}
/* Search the given VPATH list for a directory where the name pointed to by
FILE exists. If it is found, we return a cached name of the existing file
and set *MTIME_PTR (if MTIME_PTR is not NULL) to its modtime (or zero if no
stat call was done). Also set the matching directory index in PATH_INDEX
if it is not NULL. Otherwise we return NULL. */
static const char *
selective_vpath_search (struct vpath *path, const char *file,
FILE_TIMESTAMP *mtime_ptr, unsigned int* path_index)
{
int not_target;
char *name;
const char *n;
const char *filename;
const char **vpath = path->searchpath;
size_t maxvpath = path->maxlen;
unsigned int i;
size_t flen, name_dplen;
int exists = 0;
/* Find out if *FILE is a target.
If and only if it is NOT a target, we will accept prospective
files that don't exist but are mentioned in a makefile. */
{
struct file *f = lookup_file (file);
not_target = f == 0 || !f->is_target;
}
flen = strlen (file);
/* Split *FILE into a directory prefix and a name-within-directory.
NAME_DPLEN gets the length of the prefix; FILENAME gets the pointer to
the name-within-directory and FLEN is its length. */
n = strrchr (file, '/');
#ifdef HAVE_DOS_PATHS
/* We need the rightmost slash or backslash. */
{
const char *bslash = strrchr (file, '\\');
if (!n || bslash > n)
n = bslash;
}
#endif
name_dplen = n != 0 ? n - file : 0;
filename = name_dplen > 0 ? n + 1 : file;
if (name_dplen > 0)
flen -= name_dplen + 1;
/* Get enough space for the biggest VPATH entry, a slash, the directory
prefix that came with FILE, another slash (although this one may not
always be necessary), the filename, and a null terminator. */
name = alloca (maxvpath + 1 + name_dplen + 1 + flen + 1);
/* Try each VPATH entry. */
for (i = 0; vpath[i] != 0; ++i)
{
int exists_in_cache = 0;
char *p = name;
size_t vlen = strlen (vpath[i]);
/* Put the next VPATH entry into NAME at P and increment P past it. */
memcpy (p, vpath[i], vlen);
p += vlen;
/* Add the directory prefix already in *FILE. */
if (name_dplen > 0)
{
*p++ = '/';
memcpy (p, file, name_dplen);
p += name_dplen;
}
#ifdef HAVE_DOS_PATHS
/* Cause the next if to treat backslash and slash alike. */
if (p != name && p[-1] == '\\' )
p[-1] = '/';
#endif
/* Now add the name-within-directory at the end of NAME. */
if (p != name && p[-1] != '/')
{
*p = '/';
memcpy (p + 1, filename, flen + 1);
}
else
memcpy (p, filename, flen + 1);
/* Check if the file is mentioned in a makefile. If *FILE is not
a target, that is enough for us to decide this file exists.
If *FILE is a target, then the file must be mentioned in the
makefile also as a target to be chosen.
The restriction that *FILE must not be a target for a
makefile-mentioned file to be chosen was added by an
inadequately commented change in July 1990; I am not sure off
hand what problem it fixes.
In December 1993 I loosened this restriction to allow a file
to be chosen if it is mentioned as a target in a makefile. This
seem logical.
Special handling for -W / -o: make sure we preserve the special
values here. Actually this whole thing is a little bogus: I think
we should ditch the name/hname thing and look into the renamed
capability that already exists for files: that is, have a new struct
file* entry for the VPATH-found file, and set the renamed field if
we use it.
*/
{
struct file *f = lookup_file (name);
if (f != 0)
{
exists = not_target || f->is_target;
if (exists && mtime_ptr
&& (f->last_mtime == OLD_MTIME || f->last_mtime == NEW_MTIME))
{
*mtime_ptr = f->last_mtime;
mtime_ptr = 0;
}
}
}
if (!exists)
{
/* That file wasn't mentioned in the makefile.
See if it actually exists. */
/* Clobber a null into the name at the last slash.
Now NAME is the name of the directory to look in. */
*p = '\0';
/* We know the directory is in the hash table now because either
construct_vpath_list or the code just above put it there.
Does the file we seek exist in it? */
exists_in_cache = exists = dir_file_exists_p (name, filename);
}
if (exists)
{
/* The file is in the directory cache.
Now check that it actually exists in the filesystem.
The cache may be out of date. When vpath thinks a file
exists, but stat fails for it, confusion results in the
higher levels. */
struct stat st;
/* Put the slash back in NAME. */
*p = '/';
if (exists_in_cache) /* Makefile-mentioned file need not exist. */
{
int e;
EINTRLOOP (e, stat (name, &st)); /* Does it really exist? */
if (e != 0)
{
exists = 0;
continue;
}
/* Store the modtime into *MTIME_PTR for the caller. */
if (mtime_ptr != 0)
{
*mtime_ptr = FILE_TIMESTAMP_STAT_MODTIME (name, st);
mtime_ptr = 0;
}
}
/* We have found a file.
If we get here and mtime_ptr hasn't been set, record
UNKNOWN_MTIME to indicate this. */
if (mtime_ptr != 0)
*mtime_ptr = UNKNOWN_MTIME;
/* Store the name we found and return it. */
if (path_index)
*path_index = i;
return strcache_add_len (name, (p + 1 - name) + flen);
}
}
return 0;
}
/* Search the VPATH list whose pattern matches FILE for a directory where FILE
exists. If it is found, return the cached name of an existing file, and
set *MTIME_PTR (if MTIME_PTR is not NULL) to its modtime (or zero if no
stat call was done). Also set the matching directory index in VPATH_INDEX
and PATH_INDEX if they are not NULL. Otherwise we return 0. */
const char *
vpath_search (const char *file, FILE_TIMESTAMP *mtime_ptr,
unsigned int* vpath_index, unsigned int* path_index)
{
struct vpath *v;
/* If there are no VPATH entries or FILENAME starts at the root,
there is nothing we can do. */
if (file[0] == '/'
#ifdef HAVE_DOS_PATHS
|| file[0] == '\\' || file[1] == ':'
#endif
|| (vpaths == 0 && general_vpath == 0))
return 0;
if (vpath_index)
{
*vpath_index = 0;
*path_index = 0;
}
for (v = vpaths; v != 0; v = v->next)
{
if (pattern_matches (v->pattern, v->percent, file))
{
const char *p = selective_vpath_search (
v, file, mtime_ptr, path_index);
if (p)
return p;
}
if (vpath_index)
++*vpath_index;
}
if (general_vpath != 0)
{
const char *p = selective_vpath_search (
general_vpath, file, mtime_ptr, path_index);
if (p)
return p;
}
return 0;
}
/* Print the data base of VPATH search paths. */
void
print_vpath_data_base (void)
{
unsigned int nvpaths;
struct vpath *v;
puts (_("\n# VPATH Search Paths\n"));
nvpaths = 0;
for (v = vpaths; v != 0; v = v->next)
{
unsigned int i;
++nvpaths;
printf ("vpath %s ", v->pattern);
for (i = 0; v->searchpath[i] != 0; ++i)
printf ("%s%c", v->searchpath[i],
v->searchpath[i + 1] == 0 ? '\n' : PATH_SEPARATOR_CHAR);
}
if (vpaths == 0)
puts (_("# No 'vpath' search paths."));
else
printf (_("\n# %u 'vpath' search paths.\n"), nvpaths);
if (general_vpath == 0)
puts (_("\n# No general ('VPATH' variable) search path."));
else
{
const char **path = general_vpath->searchpath;
unsigned int i;
fputs (_("\n# General ('VPATH' variable) search path:\n# "), stdout);
for (i = 0; path[i] != 0; ++i)
printf ("%s%c", path[i],
path[i + 1] == 0 ? '\n' : PATH_SEPARATOR_CHAR);
}
}
| 18,262 | 602 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/dep.h | /* clang-format off */
/* Definitions of dependency data structures for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* Structure used in chains of names, for parsing and globbing. */
#define NAMESEQ(_t) \
_t *next; \
const char *name
struct nameseq
{
NAMESEQ (struct nameseq);
};
/* Flag bits for the second argument to 'read_makefile'.
These flags are saved in the 'flags' field of each
'struct goaldep' in the chain returned by 'read_all_makefiles'. */
#define RM_NO_DEFAULT_GOAL (1 << 0) /* Do not set default goal. */
#define RM_INCLUDED (1 << 1) /* Search makefile search path. */
#define RM_DONTCARE (1 << 2) /* No error if it doesn't exist. */
#define RM_NO_TILDE (1 << 3) /* Don't expand ~ in file name. */
#define RM_NOFLAG 0
/* Structure representing one dependency of a file.
Each struct file's 'deps' points to a chain of these, through 'next'.
'stem' is the stem for this dep line of static pattern rule or NULL. */
#define DEP(_t) \
NAMESEQ (_t); \
struct file *file; \
const char *stem; \
unsigned int flags : 8; \
unsigned int changed : 1; \
unsigned int ignore_mtime : 1; \
unsigned int staticpattern : 1; \
unsigned int need_2nd_expansion : 1; \
unsigned int ignore_automatic_vars : 1
struct dep
{
DEP (struct dep);
};
/* Structure representing one goal.
The goals to be built constitute a chain of these, chained through 'next'.
'stem' is not used, but it's simpler to include and ignore it. */
struct goaldep
{
DEP (struct goaldep);
int error;
floc floc;
};
/* Options for parsing lists of filenames. */
#define PARSEFS_NONE 0x0000
#define PARSEFS_NOSTRIP 0x0001
#define PARSEFS_NOAR 0x0002
#define PARSEFS_NOGLOB 0x0004
#define PARSEFS_EXISTS 0x0008
#define PARSEFS_NOCACHE 0x0010
#define PARSEFS_ONEWORD 0x0020
#define PARSE_FILE_SEQ(_s,_t,_c,_p,_f) \
(_t *)parse_file_seq ((_s),sizeof (_t),(_c),(_p),(_f))
#define PARSE_SIMPLE_SEQ(_s,_t) \
(_t *)parse_file_seq ((_s),sizeof (_t),MAP_NUL,NULL,PARSEFS_NONE)
#ifdef VMS
void *parse_file_seq ();
#else
void *parse_file_seq (char **stringp, size_t size,
int stopmap, const char *prefix, int flags);
#endif
char *tilde_expand (const char *name);
#ifndef NO_ARCHIVES
struct nameseq *ar_glob (const char *arname, const char *member_pattern, size_t size);
#endif
#define dep_name(d) ((d)->name ? (d)->name : (d)->file->name)
#define alloc_seq_elt(_t) xcalloc (sizeof (_t))
void free_ns_chain (struct nameseq *n);
#if defined(MAKE_MAINTAINER_MODE) && defined(__GNUC__) && !defined(__STRICT_ANSI__)
/* Use inline to get real type-checking. */
#define SI static inline
SI struct nameseq *alloc_ns() { return alloc_seq_elt (struct nameseq); }
SI struct dep *alloc_dep() { return alloc_seq_elt (struct dep); }
SI struct goaldep *alloc_goaldep() { return alloc_seq_elt (struct goaldep); }
SI void free_ns(struct nameseq *n) { free (n); }
SI void free_dep(struct dep *d) { free_ns ((struct nameseq *)d); }
SI void free_goaldep(struct goaldep *g) { free_dep ((struct dep *)g); }
SI void free_dep_chain(struct dep *d) { free_ns_chain((struct nameseq *)d); }
SI void free_goal_chain(struct goaldep *g) { free_dep_chain((struct dep *)g); }
#else
# define alloc_ns() alloc_seq_elt (struct nameseq)
# define alloc_dep() alloc_seq_elt (struct dep)
# define alloc_goaldep() alloc_seq_elt (struct goaldep)
# define free_ns(_n) free (_n)
# define free_dep(_d) free_ns (_d)
# define free_goaldep(_g) free_dep (_g)
# define free_dep_chain(_d) free_ns_chain ((struct nameseq *)(_d))
# define free_goal_chain(_g) free_ns_chain ((struct nameseq *)(_g))
#endif
struct dep *copy_dep_chain (const struct dep *d);
struct goaldep *read_all_makefiles (const char **makefiles);
void eval_buffer (char *buffer, const floc *floc);
enum update_status update_goal_chain (struct goaldep *goals);
| 4,903 | 135 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/rule.c | /* Pattern and suffix rule internals for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* clang-format off */
#include "third_party/make/makeint.inc"
#include "third_party/make/filedef.h"
#include "third_party/make/dep.h"
#include "third_party/make/job.h"
#include "third_party/make/commands.h"
#include "third_party/make/variable.h"
#include "third_party/make/rule.h"
static void freerule (struct rule *rule, struct rule *lastrule);
/* Chain of all pattern rules. */
struct rule *pattern_rules;
/* Pointer to last rule in the chain, so we can add onto the end. */
struct rule *last_pattern_rule;
/* Number of rules in the chain. */
unsigned int num_pattern_rules;
/* Maximum number of target patterns of any pattern rule. */
unsigned int max_pattern_targets;
/* Maximum number of dependencies of any pattern rule. */
unsigned int max_pattern_deps;
/* Maximum length of the name of a dependencies of any pattern rule. */
size_t max_pattern_dep_length;
/* Pointer to structure for the file .SUFFIXES
whose dependencies are the suffixes to be searched. */
struct file *suffix_file;
/* Maximum length of a suffix. */
static size_t maxsuffix;
/* Compute the maximum dependency length and maximum number of dependencies of
all implicit rules. Also sets the subdir flag for a rule when appropriate,
possibly removing the rule completely when appropriate.
Add any global EXTRA_PREREQS here as well. */
void
snap_implicit_rules (void)
{
char *name = NULL;
size_t namelen = 0;
struct rule *rule;
struct dep *dep;
struct dep *prereqs = expand_extra_prereqs (lookup_variable (STRING_SIZE_TUPLE(".EXTRA_PREREQS")));
unsigned int pre_deps = 0;
max_pattern_dep_length = 0;
for (dep = prereqs; dep; dep = dep->next)
{
size_t l = strlen (dep_name (dep));
if (l > max_pattern_dep_length)
max_pattern_dep_length = l;
++pre_deps;
}
num_pattern_rules = max_pattern_targets = max_pattern_deps = 0;
for (rule = pattern_rules; rule; rule = rule->next)
{
unsigned int ndeps = pre_deps;
struct dep *lastdep = NULL;
++num_pattern_rules;
if (rule->num > max_pattern_targets)
max_pattern_targets = rule->num;
for (dep = rule->deps; dep != 0; dep = dep->next)
{
const char *dname = dep_name (dep);
size_t len = strlen (dname);
const char *p = strrchr (dname, '/');
const char *p2 = p ? strchr (p, '%') : 0;
ndeps++;
if (len > max_pattern_dep_length)
max_pattern_dep_length = len;
if (!dep->next)
lastdep = dep;
if (p2)
{
/* There is a slash before the % in the dep name.
Extract the directory name. */
if (p == dname)
++p;
if ((size_t) (p - dname) > namelen)
{
namelen = p - dname;
name = xrealloc (name, namelen + 1);
}
memcpy (name, dname, p - dname);
name[p - dname] = '\0';
/* In the deps of an implicit rule the 'changed' flag
actually indicates that the dependency is in a
nonexistent subdirectory. */
dep->changed = !dir_file_exists_p (name, "");
}
else
/* This dependency does not reside in a subdirectory. */
dep->changed = 0;
}
if (prereqs)
{
if (lastdep)
lastdep->next = copy_dep_chain (prereqs);
else
rule->deps = copy_dep_chain (prereqs);
}
if (ndeps > max_pattern_deps)
max_pattern_deps = ndeps;
}
free (name);
free_dep_chain (prereqs);
}
/* Create a pattern rule from a suffix rule.
TARGET is the target suffix; SOURCE is the source suffix.
CMDS are the commands.
If TARGET is nil, it means the target pattern should be '(%.o)'.
If SOURCE is nil, it means there should be no deps. */
static void
convert_suffix_rule (const char *target, const char *source,
struct commands *cmds)
{
const char **names, **percents;
struct dep *deps;
names = xmalloc (sizeof (const char *));
percents = xmalloc (sizeof (const char *));
if (target == 0)
{
/* Special case: TARGET being nil means we are defining a '.X.a' suffix
rule; the target pattern is always '(%.o)'. */
*names = strcache_add_len ("(%.o)", 5);
*percents = *names + 1;
}
else
{
/* Construct the target name. */
size_t len = strlen (target);
char *p = alloca (1 + len + 1);
p[0] = '%';
memcpy (p + 1, target, len + 1);
*names = strcache_add_len (p, len + 1);
*percents = *names;
}
if (source == 0)
deps = 0;
else
{
/* Construct the dependency name. */
size_t len = strlen (source);
char *p = alloca (1 + len + 1);
p[0] = '%';
memcpy (p + 1, source, len + 1);
deps = alloc_dep ();
deps->name = strcache_add_len (p, len + 1);
}
create_pattern_rule (names, percents, 1, 0, deps, cmds, 0);
}
/* Convert old-style suffix rules to pattern rules.
All rules for the suffixes on the .SUFFIXES list are converted and added to
the chain of pattern rules. */
void
convert_to_pattern (void)
{
struct dep *d, *d2;
char *rulename;
/* We will compute every potential suffix rule (.x.y) from the list of
suffixes in the .SUFFIXES target's dependencies and see if it exists.
First find the longest of the suffixes. */
maxsuffix = 0;
for (d = suffix_file->deps; d != 0; d = d->next)
{
size_t l = strlen (dep_name (d));
if (l > maxsuffix)
maxsuffix = l;
}
/* Space to construct the suffix rule target name. */
rulename = alloca ((maxsuffix * 2) + 1);
for (d = suffix_file->deps; d != 0; d = d->next)
{
size_t slen;
/* Make a rule that is just the suffix, with no deps or commands.
This rule exists solely to disqualify match-anything rules. */
convert_suffix_rule (dep_name (d), 0, 0);
if (d->file->cmds != 0)
/* Record a pattern for this suffix's null-suffix rule. */
convert_suffix_rule ("", dep_name (d), d->file->cmds);
/* Add every other suffix to this one and see if it exists as a
two-suffix rule. */
slen = strlen (dep_name (d));
memcpy (rulename, dep_name (d), slen);
for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
{
struct file *f;
size_t s2len;
s2len = strlen (dep_name (d2));
/* Can't build something from itself. */
if (slen == s2len && streq (dep_name (d), dep_name (d2)))
continue;
memcpy (rulename + slen, dep_name (d2), s2len + 1);
f = lookup_file (rulename);
/* No target, or no commands: it can't be a suffix rule. */
if (f == 0 || f->cmds == 0)
continue;
/* POSIX says that suffix rules can't have prerequisites.
In POSIX mode, don't make this a suffix rule. Previous versions
of GNU make did treat this as a suffix rule and ignored the
prerequisites, which is bad. In the future we'll do the same as
POSIX, but for now preserve the old behavior and warn about it. */
if (f->deps != 0)
{
if (posix_pedantic)
continue;
error (&f->cmds->fileinfo, 0,
_("warning: ignoring prerequisites on suffix rule definition"));
}
if (s2len == 2 && rulename[slen] == '.' && rulename[slen + 1] == 'a')
/* A suffix rule '.X.a:' generates the pattern rule '(%.o): %.X'.
It also generates a normal '%.a: %.X' rule below. */
convert_suffix_rule (NULL, /* Indicates '(%.o)'. */
dep_name (d),
f->cmds);
/* The suffix rule '.X.Y:' is converted
to the pattern rule '%.Y: %.X'. */
convert_suffix_rule (dep_name (d2), dep_name (d), f->cmds);
}
}
}
/* Install the pattern rule RULE (whose fields have been filled in) at the end
of the list (so that any rules previously defined will take precedence).
If this rule duplicates a previous one (identical target and dependencies),
the old one is replaced if OVERRIDE is nonzero, otherwise this new one is
thrown out. When an old rule is replaced, the new one is put at the end of
the list. Return nonzero if RULE is used; zero if not. */
static int
new_pattern_rule (struct rule *rule, int override)
{
struct rule *r, *lastrule;
unsigned int i, j;
rule->in_use = 0;
rule->terminal = 0;
rule->next = 0;
/* Search for an identical rule. */
lastrule = 0;
for (r = pattern_rules; r != 0; lastrule = r, r = r->next)
for (i = 0; i < rule->num; ++i)
{
for (j = 0; j < r->num; ++j)
if (!streq (rule->targets[i], r->targets[j]))
break;
/* If all the targets matched... */
if (j == r->num)
{
struct dep *d, *d2;
for (d = rule->deps, d2 = r->deps;
d != 0 && d2 != 0; d = d->next, d2 = d2->next)
if (!streq (dep_name (d), dep_name (d2)))
break;
if (d == 0 && d2 == 0)
{
/* All the dependencies matched. */
if (override)
{
/* Remove the old rule. */
freerule (r, lastrule);
/* Install the new one. */
if (pattern_rules == 0)
pattern_rules = rule;
else
last_pattern_rule->next = rule;
last_pattern_rule = rule;
/* We got one. Stop looking. */
goto matched;
}
else
{
/* The old rule stays intact. Destroy the new one. */
freerule (rule, (struct rule *) 0);
return 0;
}
}
}
}
matched:;
if (r == 0)
{
/* There was no rule to replace. */
if (pattern_rules == 0)
pattern_rules = rule;
else
last_pattern_rule->next = rule;
last_pattern_rule = rule;
}
return 1;
}
/* Install an implicit pattern rule based on the three text strings
in the structure P points to. These strings come from one of
the arrays of default implicit pattern rules.
TERMINAL specifies what the 'terminal' field of the rule should be. */
void
install_pattern_rule (struct pspec *p, int terminal)
{
struct rule *r;
const char *ptr;
r = xmalloc (sizeof (struct rule));
r->num = 1;
r->targets = xmalloc (sizeof (const char *));
r->suffixes = xmalloc (sizeof (const char *));
r->lens = xmalloc (sizeof (unsigned int));
r->lens[0] = (unsigned int) strlen (p->target);
r->targets[0] = p->target;
r->suffixes[0] = find_percent_cached (&r->targets[0]);
assert (r->suffixes[0] != NULL);
++r->suffixes[0];
ptr = p->dep;
r->deps = PARSE_SIMPLE_SEQ ((char **)&ptr, struct dep);
if (new_pattern_rule (r, 0))
{
r->terminal = terminal ? 1 : 0;
r->cmds = xmalloc (sizeof (struct commands));
r->cmds->fileinfo.filenm = 0;
r->cmds->fileinfo.lineno = 0;
r->cmds->fileinfo.offset = 0;
/* These will all be string literals, but we malloc space for them
anyway because somebody might want to free them later. */
r->cmds->commands = xstrdup (p->commands);
r->cmds->command_lines = 0;
r->cmds->recipe_prefix = RECIPEPREFIX_DEFAULT;
}
}
/* Free all the storage used in RULE and take it out of the
pattern_rules chain. LASTRULE is the rule whose next pointer
points to RULE. */
static void
freerule (struct rule *rule, struct rule *lastrule)
{
struct rule *next = rule->next;
free_dep_chain (rule->deps);
/* MSVC erroneously warns without a cast here. */
free ((void *)rule->targets);
free ((void *)rule->suffixes);
free (rule->lens);
/* We can't free the storage for the commands because there
are ways that they could be in more than one place:
* If the commands came from a suffix rule, they could also be in
the 'struct file's for other suffix rules or plain targets given
on the same makefile line.
* If two suffixes that together make a two-suffix rule were each
given twice in the .SUFFIXES list, and in the proper order, two
identical pattern rules would be created and the second one would
be discarded here, but both would contain the same 'struct commands'
pointer from the 'struct file' for the suffix rule. */
free (rule);
if (pattern_rules == rule)
if (lastrule != 0)
abort ();
else
pattern_rules = next;
else if (lastrule != 0)
lastrule->next = next;
if (last_pattern_rule == rule)
last_pattern_rule = lastrule;
}
/* Create a new pattern rule with the targets in the nil-terminated array
TARGETS. TARGET_PERCENTS is an array of pointers to the % in each element
of TARGETS. N is the number of items in the array (not counting the nil
element). The new rule has dependencies DEPS and commands from COMMANDS.
It is a terminal rule if TERMINAL is nonzero. This rule overrides
identical rules with different commands if OVERRIDE is nonzero.
The storage for TARGETS and its elements and TARGET_PERCENTS is used and
must not be freed until the rule is destroyed. */
void
create_pattern_rule (const char **targets, const char **target_percents,
unsigned short n, int terminal, struct dep *deps,
struct commands *commands, int override)
{
unsigned int i;
struct rule *r = xmalloc (sizeof (struct rule));
r->num = n;
r->cmds = commands;
r->deps = deps;
r->targets = targets;
r->suffixes = target_percents;
r->lens = xmalloc (n * sizeof (unsigned int));
for (i = 0; i < n; ++i)
{
r->lens[i] = (unsigned int) strlen (targets[i]);
assert (r->suffixes[i] != NULL);
++r->suffixes[i];
}
if (new_pattern_rule (r, override))
r->terminal = terminal ? 1 : 0;
}
/* Print the data base of rules. */
static void /* Useful to call from gdb. */
print_rule (struct rule *r)
{
unsigned int i;
for (i = 0; i < r->num; ++i)
{
fputs (r->targets[i], stdout);
putchar ((i + 1 == r->num) ? ':' : ' ');
}
if (r->terminal)
putchar (':');
print_prereqs (r->deps);
if (r->cmds != 0)
print_commands (r->cmds);
}
void
print_rule_data_base (void)
{
unsigned int rules, terminal;
struct rule *r;
puts (_("\n# Implicit Rules"));
rules = terminal = 0;
for (r = pattern_rules; r != 0; r = r->next)
{
++rules;
putchar ('\n');
print_rule (r);
if (r->terminal)
++terminal;
}
if (rules == 0)
puts (_("\n# No implicit rules."));
else
{
printf (_("\n# %u implicit rules, %u (%.1f%%) terminal."),
rules, terminal, (double) terminal / (double) rules * 100.0);
}
if (num_pattern_rules != rules)
{
/* This can happen if a fatal error was detected while reading the
makefiles and thus count_implicit_rule_limits wasn't called yet. */
if (num_pattern_rules != 0)
ONN (fatal, NILF, _("BUG: num_pattern_rules is wrong! %u != %u"),
num_pattern_rules, rules);
}
}
| 16,415 | 547 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/implicit.c | /* clang-format off */
/* Implicit rule searching for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
#include "third_party/make/filedef.h"
#include "third_party/make/rule.h"
#include "third_party/make/dep.h"
#include "third_party/make/debug.h"
#include "third_party/make/variable.h"
#include "third_party/make/job.h" /* struct child, used inside commands.h */
#include "third_party/make/commands.h" /* set_file_variables */
static int pattern_search (struct file *file, int archive,
unsigned int depth, unsigned int recursions);
/* For a FILE which has no commands specified, try to figure out some
from the implicit pattern rules.
Returns 1 if a suitable implicit rule was found,
after modifying FILE to contain the appropriate commands and deps,
or returns 0 if no implicit rule was found. */
int
try_implicit_rule (struct file *file, unsigned int depth)
{
DBF (DB_IMPLICIT, _("Looking for an implicit rule for '%s'.\n"));
/* The order of these searches was previously reversed. My logic now is
that since the non-archive search uses more information in the target
(the archive search omits the archive name), it is more specific and
should come first. */
if (pattern_search (file, 0, depth, 0))
return 1;
#ifndef NO_ARCHIVES
/* If this is an archive member reference, use just the
archive member name to search for implicit rules. */
if (ar_name (file->name))
{
DBF (DB_IMPLICIT,
_("Looking for archive-member implicit rule for '%s'.\n"));
if (pattern_search (file, 1, depth, 0))
return 1;
}
#endif
return 0;
}
/* Scans the BUFFER for the next word with whitespace as a separator.
Returns the pointer to the beginning of the word. LENGTH hold the
length of the word. */
static const char *
get_next_word (const char *buffer, size_t *length)
{
const char *p = buffer, *beg;
char c;
/* Skip any leading whitespace. */
NEXT_TOKEN (p);
beg = p;
c = *(p++);
if (c == '\0')
return 0;
/* We already found the first value of "c", above. */
while (1)
{
char closeparen;
int count;
switch (c)
{
case '\0':
case ' ':
case '\t':
goto done_word;
case '$':
c = *(p++);
if (c == '$')
break;
/* This is a variable reference, so read it to the matching
close paren. */
if (c == '(')
closeparen = ')';
else if (c == '{')
closeparen = '}';
else
/* This is a single-letter variable reference. */
break;
for (count = 0; *p != '\0'; ++p)
{
if (*p == c)
++count;
else if (*p == closeparen && --count < 0)
{
++p;
break;
}
}
break;
case '|':
goto done;
default:
break;
}
c = *(p++);
}
done_word:
--p;
done:
if (length)
*length = p - beg;
return beg;
}
/* This structure stores information about the expanded prerequisites for a
pattern rule. NAME is always set to the strcache'd name of the prereq.
FILE and PATTERN will be set for intermediate files only. IGNORE_MTIME is
copied from the prerequisite we expanded.
*/
struct patdeps
{
const char *name;
const char *pattern;
struct file *file;
unsigned int ignore_mtime : 1;
unsigned int ignore_automatic_vars : 1;
};
/* This structure stores information about pattern rules that we need
to try.
*/
struct tryrule
{
struct rule *rule;
/* Stem length for this match. */
size_t stemlen;
/* Index of the target in this rule that matched the file. */
unsigned int matches;
/* Definition order of this rule. Used to implement stable sort.*/
unsigned int order;
/* Nonzero if the LASTSLASH logic was used in matching this rule. */
char checked_lastslash;
};
int
stemlen_compare (const void *v1, const void *v2)
{
const struct tryrule *r1 = v1;
const struct tryrule *r2 = v2;
int r = (int) (r1->stemlen - r2->stemlen);
return r != 0 ? r : (int) (r1->order - r2->order);
}
/* Search the pattern rules for a rule with an existing dependency to make
FILE. If a rule is found, the appropriate commands and deps are put in FILE
and 1 is returned. If not, 0 is returned.
If ARCHIVE is nonzero, FILE->name is of the form "LIB(MEMBER)". A rule for
"(MEMBER)" will be searched for, and "(MEMBER)" will not be chopped up into
directory and filename parts.
If an intermediate file is found by pattern search, the intermediate file
is set up as a target by the recursive call and is also made a dependency
of FILE.
DEPTH is used for debugging messages. */
static int
pattern_search (struct file *file, int archive,
unsigned int depth, unsigned int recursions)
{
/* Filename we are searching for a rule for. */
const char *filename = archive ? strchr (file->name, '(') : file->name;
/* Length of FILENAME. */
size_t namelen = strlen (filename);
/* The last slash in FILENAME (or nil if there is none). */
const char *lastslash;
/* This is a file-object used as an argument in
recursive calls. It never contains any data
except during a recursive call. */
struct file *int_file = 0;
/* List of dependencies found recursively. */
unsigned int max_deps = max_pattern_deps;
struct patdeps *deplist = xmalloc (max_deps * sizeof (struct patdeps));
struct patdeps *pat = deplist;
/* Names of possible dependencies are constructed in this buffer.
We may replace % by $(*F) for second expansion, increasing the length. */
char *depname = alloca (namelen + max_pattern_dep_length + 4);
/* The start and length of the stem of FILENAME for the current rule. */
const char *stem = 0;
size_t stemlen = 0;
size_t fullstemlen = 0;
/* Buffer in which we store all the rules that are possibly applicable. */
struct tryrule *tryrules = xmalloc (num_pattern_rules * max_pattern_targets
* sizeof (struct tryrule));
/* Number of valid elements in TRYRULES. */
unsigned int nrules;
/* The index in TRYRULES of the rule we found. */
unsigned int foundrule;
/* Nonzero if should consider intermediate files as dependencies. */
int intermed_ok;
/* Nonzero if we have initialized file variables for this target. */
int file_vars_initialized = 0;
/* Nonzero if we have matched a pattern-rule target
that is not just '%'. */
int specific_rule_matched = 0;
unsigned int ri; /* uninit checks OK */
struct rule *rule;
char *pathdir = NULL;
size_t pathlen;
PATH_VAR (stem_str); /* @@ Need to get rid of stem, stemlen, etc. */
#ifndef NO_ARCHIVES
if (archive || ar_name (filename))
lastslash = 0;
else
#endif
{
/* Set LASTSLASH to point at the last slash in FILENAME
but not counting any slash at the end. (foo/bar/ counts as
bar/ in directory foo/, not empty in directory foo/bar/.) */
lastslash = memrchr (filename, '/', namelen - 1);
#ifdef HAVE_DOS_PATHS
/* Handle backslashes (possibly mixed with forward slashes)
and the case of "d:file". */
{
char *bslash = memrchr (filename, '\\', namelen - 1);
if (lastslash == 0 || bslash > lastslash)
lastslash = bslash;
if (lastslash == 0 && filename[0] && filename[1] == ':')
lastslash = filename + 1;
}
#endif
}
pathlen = lastslash ? lastslash - filename + 1 : 0;
/* First see which pattern rules match this target and may be considered.
Put them in TRYRULES. */
nrules = 0;
for (rule = pattern_rules; rule != 0; rule = rule->next)
{
unsigned int ti;
/* If the pattern rule has deps but no commands, ignore it.
Users cancel built-in rules by redefining them without commands. */
if (rule->deps != 0 && rule->cmds == 0)
continue;
/* If this rule is in use by a parent pattern_search,
don't use it here. */
if (rule->in_use)
{
DBS (DB_IMPLICIT, (_("Avoiding implicit rule recursion.\n")));
continue;
}
for (ti = 0; ti < rule->num; ++ti)
{
const char *target = rule->targets[ti];
const char *suffix = rule->suffixes[ti];
char check_lastslash;
/* Rules that can match any filename and are not terminal
are ignored if we're recursing, so that they cannot be
intermediate files. */
if (recursions > 0 && target[1] == '\0' && !rule->terminal)
continue;
if (rule->lens[ti] > namelen)
/* It can't possibly match. */
continue;
/* From the lengths of the filename and the pattern parts,
find the stem: the part of the filename that matches the %. */
stem = filename + (suffix - target - 1);
stemlen = namelen - rule->lens[ti] + 1;
/* Set CHECK_LASTSLASH if FILENAME contains a directory
prefix and the target pattern does not contain a slash. */
check_lastslash = 0;
if (lastslash)
{
check_lastslash = strchr (target, '/') == 0;
#ifdef HAVE_DOS_PATHS
/* Didn't find it yet: check for DOS-type directories. */
if (check_lastslash)
{
char *b = strchr (target, '\\');
check_lastslash = !(b || (target[0] && target[1] == ':'));
}
#endif
}
if (check_lastslash)
{
/* If so, don't include the directory prefix in STEM here. */
if (pathlen > stemlen)
continue;
stemlen -= pathlen;
stem += pathlen;
}
/* Check that the rule pattern matches the text before the stem. */
if (check_lastslash)
{
if (stem > (lastslash + 1)
&& !strneq (target, lastslash + 1, stem - lastslash - 1))
continue;
}
else if (stem > filename
&& !strneq (target, filename, stem - filename))
continue;
/* Check that the rule pattern matches the text after the stem.
We could test simply use streq, but this way we compare the
first two characters immediately. This saves time in the very
common case where the first character matches because it is a
period. */
if (*suffix != stem[stemlen]
|| (*suffix != '\0' && !streq (&suffix[1], &stem[stemlen + 1])))
continue;
/* Record if we match a rule that not all filenames will match. */
if (target[1] != '\0')
specific_rule_matched = 1;
/* A rule with no dependencies and no commands exists solely to set
specific_rule_matched when it matches. Don't try to use it. */
if (rule->deps == 0 && rule->cmds == 0)
continue;
/* Record this rule in TRYRULES and the index of the matching
target in MATCHES. If several targets of the same rule match,
that rule will be in TRYRULES more than once. */
tryrules[nrules].rule = rule;
tryrules[nrules].matches = ti;
tryrules[nrules].stemlen = stemlen + (check_lastslash ? pathlen : 0);
tryrules[nrules].order = nrules;
tryrules[nrules].checked_lastslash = check_lastslash;
++nrules;
}
}
/* Bail out early if we haven't found any rules. */
if (nrules == 0)
goto done;
/* Sort the rules to place matches with the shortest stem first. This
way the most specific rules will be tried first. */
if (nrules > 1)
qsort (tryrules, nrules, sizeof (struct tryrule), stemlen_compare);
/* If we have found a matching rule that won't match all filenames,
retroactively reject any non-"terminal" rules that do always match. */
if (specific_rule_matched)
for (ri = 0; ri < nrules; ++ri)
if (!tryrules[ri].rule->terminal)
{
unsigned int j;
for (j = 0; j < tryrules[ri].rule->num; ++j)
if (tryrules[ri].rule->targets[j][1] == '\0')
{
tryrules[ri].rule = 0;
break;
}
}
/* Try each rule once without intermediate files, then once with them. */
for (intermed_ok = 0; intermed_ok < 2; ++intermed_ok)
{
pat = deplist;
/* Try each pattern rule till we find one that applies. If it does,
expand its dependencies (as substituted) and chain them in DEPS. */
for (ri = 0; ri < nrules; ri++)
{
struct dep *dep;
char check_lastslash;
unsigned int failed = 0;
int file_variables_set = 0;
unsigned int deps_found = 0;
/* NPTR points to the part of the prereq we haven't processed. */
const char *nptr = 0;
int order_only = 0;
unsigned int matches;
rule = tryrules[ri].rule;
/* RULE is nil when we discover that a rule, already placed in
TRYRULES, should not be applied. */
if (rule == 0)
continue;
/* Reject any terminal rules if we're looking to make intermediate
files. */
if (intermed_ok && rule->terminal)
continue;
/* From the lengths of the filename and the matching pattern parts,
find the stem: the part of the filename that matches the %. */
matches = tryrules[ri].matches;
stem = filename + (rule->suffixes[matches]
- rule->targets[matches]) - 1;
stemlen = (namelen - rule->lens[matches]) + 1;
check_lastslash = tryrules[ri].checked_lastslash;
if (check_lastslash)
{
stem += pathlen;
stemlen -= pathlen;
/* We need to add the directory prefix, so set it up. */
if (! pathdir)
{
pathdir = alloca (pathlen + 1);
memcpy (pathdir, filename, pathlen);
pathdir[pathlen] = '\0';
}
}
if (stemlen + (check_lastslash ? pathlen : 0) > GET_PATH_MAX)
{
DBS (DB_IMPLICIT, (_("Stem too long: '%s%.*s'.\n"),
check_lastslash ? pathdir : "",
(int) stemlen, stem));
continue;
}
DBS (DB_IMPLICIT, (_("Trying pattern rule with stem '%.*s'.\n"),
(int) stemlen, stem));
if (!check_lastslash)
{
memcpy (stem_str, stem, stemlen);
stem_str[stemlen] = '\0';
}
else
{
/* We want to prepend the directory from
the original FILENAME onto the stem. */
memcpy (stem_str, filename, pathlen);
memcpy (stem_str + pathlen, stem, stemlen);
stem_str[pathlen + stemlen] = '\0';
}
/* If there are no prerequisites, then this rule matches. */
if (rule->deps == 0)
break;
/* Temporary assign STEM to file->stem (needed to set file
variables below). */
file->stem = stem_str;
/* Mark this rule as in use so a recursive pattern_search won't try
to use it. */
rule->in_use = 1;
/* Try each prerequisite; see if it exists or can be created. We'll
build a list of prereq info in DEPLIST. Due to 2nd expansion we
may have to process multiple prereqs for a single dep entry. */
pat = deplist;
dep = rule->deps;
nptr = dep_name (dep);
while (1)
{
struct dep *dl, *d;
char *p;
/* If we're out of name to parse, start the next prereq. */
if (! nptr)
{
dep = dep->next;
if (dep == 0)
break;
nptr = dep_name (dep);
}
/* If we don't need a second expansion, just replace the %. */
if (! dep->need_2nd_expansion)
{
p = strchr (nptr, '%');
if (p == 0)
strcpy (depname, nptr);
else
{
char *o = depname;
if (check_lastslash)
{
memcpy (o, filename, pathlen);
o += pathlen;
}
memcpy (o, nptr, p - nptr);
o += p - nptr;
memcpy (o, stem, stemlen);
o += stemlen;
strcpy (o, p + 1);
}
/* Parse the expanded string. It might have wildcards. */
p = depname;
dl = PARSE_FILE_SEQ (&p, struct dep, MAP_NUL, NULL, PARSEFS_ONEWORD);
for (d = dl; d != NULL; d = d->next)
{
++deps_found;
d->ignore_mtime = dep->ignore_mtime;
d->ignore_automatic_vars = dep->ignore_automatic_vars;
}
/* We've used up this dep, so next time get a new one. */
nptr = 0;
}
/* We have to perform second expansion on this prereq. In an
ideal world we would take the dependency line, substitute the
stem, re-expand the whole line and chop it into individual
prerequisites. Unfortunately this won't work because of the
"check_lastslash" twist. Instead, we will have to go word by
word, taking $()'s into account. For each word we will
substitute the stem, re-expand, chop it up, and, if
check_lastslash != 0, add the directory part to each
resulting prerequisite. */
else
{
int add_dir = 0;
size_t len;
struct dep **dptr;
nptr = get_next_word (nptr, &len);
if (nptr == 0)
continue;
/* See this is a transition to order-only prereqs. */
if (! order_only && len == 1 && nptr[0] == '|')
{
order_only = 1;
nptr += len;
continue;
}
/* If the dependency name has %, substitute the stem. If we
just replace % with the stem value then later, when we do
the 2nd expansion, we will re-expand this stem value
again. This is not good if you have certain characters
in your stem (like $).
Instead, we will replace % with $* or $(*F) and allow the
second expansion to take care of it for us. This way
(since $* and $(*F) are simple variables) there won't be
additional re-expansion of the stem. */
p = lindex (nptr, nptr + len, '%');
if (p == 0)
{
memcpy (depname, nptr, len);
depname[len] = '\0';
}
else
{
size_t i = p - nptr;
char *o = depname;
memcpy (o, nptr, i);
o += i;
if (check_lastslash)
{
add_dir = 1;
memcpy (o, "$(*F)", 5);
o += 5;
}
else
{
memcpy (o, "$*", 2);
o += 2;
}
memcpy (o, p + 1, len - i - 1);
o[len - i - 1] = '\0';
}
/* Set up for the next word. */
nptr += len;
/* Initialize and set file variables if we haven't already
done so. */
if (!file_vars_initialized)
{
initialize_file_variables (file, 0);
set_file_variables (file);
file_vars_initialized = 1;
}
/* Update the stem value in $* for this rule. */
else if (!file_variables_set)
{
define_variable_for_file (
"*", 1, file->stem, o_automatic, 0, file);
file_variables_set = 1;
}
/* Perform the 2nd expansion. */
p = variable_expand_for_file (depname, file);
dptr = &dl;
/* Parse the results into a deps list. */
do
{
/* Parse the expanded string. */
struct dep *dp = PARSE_FILE_SEQ (&p, struct dep,
order_only ? MAP_NUL : MAP_PIPE,
add_dir ? pathdir : NULL, PARSEFS_NONE);
*dptr = dp;
for (d = dp; d != NULL; d = d->next)
{
++deps_found;
if (order_only)
d->ignore_mtime = 1;
dptr = &d->next;
}
/* If we stopped due to an order-only token, note it. */
if (*p == '|')
{
order_only = 1;
++p;
}
}
while (*p != '\0');
}
/* If there are more than max_pattern_deps prerequisites (due to
2nd expansion), reset it and realloc the arrays. */
if (deps_found > max_deps)
{
size_t l = pat - deplist;
/* This might have changed due to recursion. */
max_pattern_deps = MAX(max_pattern_deps, deps_found);
max_deps = max_pattern_deps;
deplist = xrealloc (deplist,
max_deps * sizeof (struct patdeps));
pat = deplist + l;
}
/* Go through the nameseq and handle each as a prereq name. */
for (d = dl; d != 0; d = d->next)
{
struct dep *expl_d;
int is_rule = d->name == dep_name (dep);
if (file_impossible_p (d->name))
{
/* If this prereq has already been ruled "impossible",
then the rule fails. Don't bother trying it on the
second pass either since we know that will fail. */
DBS (DB_IMPLICIT,
(is_rule
? _("Rejecting impossible rule prerequisite '%s'.\n")
: _("Rejecting impossible implicit prerequisite '%s'.\n"),
d->name));
tryrules[ri].rule = 0;
failed = 1;
break;
}
memset (pat, '\0', sizeof (struct patdeps));
pat->ignore_mtime = d->ignore_mtime;
pat->ignore_automatic_vars = d->ignore_automatic_vars;
DBS (DB_IMPLICIT,
(is_rule
? _("Trying rule prerequisite '%s'.\n")
: _("Trying implicit prerequisite '%s'.\n"), d->name));
/* If this prereq is also explicitly mentioned for FILE,
skip all tests below since it must be built no matter
which implicit rule we choose. */
for (expl_d = file->deps; expl_d != 0; expl_d = expl_d->next)
if (streq (dep_name (expl_d), d->name))
break;
if (expl_d != 0)
{
(pat++)->name = d->name;
continue;
}
/* The DEP->changed flag says that this dependency resides
in a nonexistent directory. So we normally can skip
looking for the file. However, if CHECK_LASTSLASH is
set, then the dependency file we are actually looking for
is in a different directory (the one gotten by prepending
FILENAME's directory), so it might actually exist. */
/* @@ dep->changed check is disabled. */
if (lookup_file (d->name) != 0
/*|| ((!dep->changed || check_lastslash) && */
|| file_exists_p (d->name))
{
(pat++)->name = d->name;
continue;
}
/* This code, given FILENAME = "lib/foo.o", dependency name
"lib/foo.c", and VPATH=src, searches for
"src/lib/foo.c". */
{
const char *vname = vpath_search (d->name, 0, NULL, NULL);
if (vname)
{
DBS (DB_IMPLICIT,
(_("Found prerequisite '%s' as VPATH '%s'\n"),
d->name, vname));
(pat++)->name = d->name;
continue;
}
}
/* We could not find the file in any place we should look.
Try to make this dependency as an intermediate file, but
only on the second pass. */
if (intermed_ok)
{
DBS (DB_IMPLICIT,
(_("Looking for a rule with intermediate file '%s'.\n"),
d->name));
if (int_file == 0)
int_file = alloca (sizeof (struct file));
memset (int_file, '\0', sizeof (struct file));
int_file->name = d->name;
if (pattern_search (int_file,
0,
depth + 1,
recursions + 1))
{
pat->pattern = int_file->name;
int_file->name = d->name;
pat->file = int_file;
int_file = 0;
(pat++)->name = d->name;
continue;
}
/* If we have tried to find P as an intermediate file
and failed, mark that name as impossible so we won't
go through the search again later. */
if (int_file->variables)
free_variable_set (int_file->variables);
if (int_file->pat_variables)
free_variable_set (int_file->pat_variables);
file_impossible (d->name);
}
/* A dependency of this rule does not exist. Therefore, this
rule fails. */
failed = 1;
break;
}
/* Free the ns chain. */
free_dep_chain (dl);
if (failed)
break;
}
/* Reset the stem in FILE. */
file->stem = 0;
/* This rule is no longer 'in use' for recursive searches. */
rule->in_use = 0;
if (! failed)
/* This pattern rule does apply. Stop looking for one. */
break;
/* This pattern rule does not apply. Keep looking. */
}
/* If we found an applicable rule without intermediate files, don't try
with them. */
if (ri < nrules)
break;
rule = 0;
}
/* RULE is nil if the loop went through the list but everything failed. */
if (rule == 0)
goto done;
foundrule = ri;
/* If we are recursing, store the pattern that matched FILENAME in
FILE->name for use in upper levels. */
if (recursions > 0)
/* Kludge-o-matic */
file->name = rule->targets[tryrules[foundrule].matches];
/* DEPLIST lists the prerequisites for the rule we found. This includes the
intermediate files, if any. Convert them into entries on the deps-chain
of FILE. */
while (pat-- > deplist)
{
struct dep *dep;
const char *s;
if (pat->file != 0)
{
/* If we need to use an intermediate file, make sure it is entered
as a target, with the info that was found for it in the recursive
pattern_search call. We know that the intermediate file did not
already exist as a target; therefore we can assume that the deps
and cmds of F below are null before we change them. */
struct file *imf = pat->file;
struct file *f = lookup_file (imf->name);
/* We don't want to delete an intermediate file that happened
to be a prerequisite of some (other) target. Mark it as
secondary. We don't want it to be precious as that disables
DELETE_ON_ERROR etc. */
if (f != 0)
f->secondary = 1;
else
f = enter_file (imf->name);
f->deps = imf->deps;
f->cmds = imf->cmds;
f->stem = imf->stem;
f->variables = imf->variables;
f->pat_variables = imf->pat_variables;
f->pat_searched = imf->pat_searched;
f->also_make = imf->also_make;
f->is_target = 1;
f->intermediate = 1;
f->tried_implicit = 1;
imf = lookup_file (pat->pattern);
if (imf != 0 && imf->precious)
f->precious = 1;
for (dep = f->deps; dep != 0; dep = dep->next)
{
dep->file = enter_file (dep->name);
dep->name = 0;
dep->file->tried_implicit |= dep->changed;
}
}
dep = alloc_dep ();
dep->ignore_mtime = pat->ignore_mtime;
dep->ignore_automatic_vars = pat->ignore_automatic_vars;
s = strcache_add (pat->name);
if (recursions)
dep->name = s;
else
{
dep->file = lookup_file (s);
if (dep->file == 0)
dep->file = enter_file (s);
}
if (pat->file == 0 && tryrules[foundrule].rule->terminal)
{
/* If the file actually existed (was not an intermediate file), and
the rule that found it was a terminal one, then we want to mark
the found file so that it will not have implicit rule search done
for it. If we are not entering a 'struct file' for it now, we
indicate this with the 'changed' flag. */
if (dep->file == 0)
dep->changed = 1;
else
dep->file->tried_implicit = 1;
}
dep->next = file->deps;
file->deps = dep;
}
if (!tryrules[foundrule].checked_lastslash)
{
/* Always allocate new storage, since STEM might be on the stack for an
intermediate file. */
file->stem = strcache_add_len (stem, stemlen);
fullstemlen = stemlen;
}
else
{
/* We want to prepend the directory from
the original FILENAME onto the stem. */
fullstemlen = pathlen + stemlen;
memcpy (stem_str, filename, pathlen);
memcpy (stem_str + pathlen, stem, stemlen);
stem_str[fullstemlen] = '\0';
file->stem = strcache_add (stem_str);
}
file->cmds = rule->cmds;
file->is_target = 1;
/* Set precious flag. */
{
struct file *f = lookup_file (rule->targets[tryrules[foundrule].matches]);
if (f && f->precious)
file->precious = 1;
}
/* If this rule builds other targets, too, put the others into FILE's
'also_make' member. */
if (rule->num > 1)
for (ri = 0; ri < rule->num; ++ri)
if (ri != tryrules[foundrule].matches)
{
char *nm = alloca (rule->lens[ri] + fullstemlen + 1);
char *p = nm;
struct file *f;
struct dep *new = alloc_dep ();
/* GKM FIMXE: handle '|' here too */
memcpy (p, rule->targets[ri],
rule->suffixes[ri] - rule->targets[ri] - 1);
p += rule->suffixes[ri] - rule->targets[ri] - 1;
memcpy (p, file->stem, fullstemlen);
p += fullstemlen;
memcpy (p, rule->suffixes[ri],
rule->lens[ri] - (rule->suffixes[ri] - rule->targets[ri])+1);
new->name = strcache_add (nm);
new->file = enter_file (new->name);
new->next = file->also_make;
/* Set precious flag. */
f = lookup_file (rule->targets[ri]);
if (f && f->precious)
new->file->precious = 1;
/* Set the is_target flag so that this file is not treated as
intermediate by the pattern rule search algorithm and
file_exists_p cannot pick it up yet. */
new->file->is_target = 1;
file->also_make = new;
}
done:
free (tryrules);
free (deplist);
return rule != 0;
}
| 35,223 | 1,007 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/unistd.h | /* clang-format off */
/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* Substitute for and wrapper around <unistd.h>.
Copyright (C) 2003-2020 Free Software Foundation, 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; either version 3, 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/>. */
#ifndef _GL_UNISTD_H
#if __GNUC__ >= 3
#pragma GCC system_header
#endif
#if 1 && defined _GL_INCLUDING_UNISTD_H
/* Special invocation convention:
- On Mac OS X 10.3.9 we have a sequence of nested includes
<unistd.h> -> <signal.h> -> <pthread.h> -> <unistd.h>
In this situation, the functions are not yet declared, therefore we cannot
provide the C++ aliases. */
#else
/* Normal invocation convention. */
/* The include_next requires a split double-inclusion guard. */
#if 1
# define _GL_INCLUDING_UNISTD_H
# undef _GL_INCLUDING_UNISTD_H
#endif
/* Get all possible declarations of gethostname(). */
#if 0 && 0 \
&& !defined _GL_INCLUDING_WINSOCK2_H
# define _GL_INCLUDING_WINSOCK2_H
# undef _GL_INCLUDING_WINSOCK2_H
#endif
#if !defined _GL_UNISTD_H && !defined _GL_INCLUDING_WINSOCK2_H
#define _GL_UNISTD_H
/* NetBSD 5.0 mis-defines NULL. Also get size_t. */
/* But avoid namespace pollution on glibc systems. */
#ifndef __GLIBC__
#endif
/* mingw doesn't define the SEEK_* or *_FILENO macros in <unistd.h>. */
/* MSVC declares 'unlink' in <stdio.h>, not in <unistd.h>. We must include
it before we #define unlink rpl_unlink. */
/* Cygwin 1.7.1 declares symlinkat in <stdio.h>, not in <unistd.h>. */
/* But avoid namespace pollution on glibc systems. */
#if (!(defined SEEK_CUR && defined SEEK_END && defined SEEK_SET) \
|| ((0 || defined GNULIB_POSIXCHECK) \
&& (defined _WIN32 && ! defined __CYGWIN__)) \
|| ((0 || defined GNULIB_POSIXCHECK) \
&& defined __CYGWIN__)) \
&& ! defined __GLIBC__
#endif
/* Cygwin 1.7.1 and Android 4.3 declare unlinkat in <fcntl.h>, not in
<unistd.h>. */
/* But avoid namespace pollution on glibc systems. */
#if (0 || defined GNULIB_POSIXCHECK) \
&& (defined __CYGWIN__ || defined __ANDROID__) \
&& ! defined __GLIBC__
#endif
/* mingw fails to declare _exit in <unistd.h>. */
/* mingw, MSVC, BeOS, Haiku declare environ in <stdlib.h>, not in
<unistd.h>. */
/* Solaris declares getcwd not only in <unistd.h> but also in <stdlib.h>. */
/* OSF Tru64 Unix cannot see gnulib rpl_strtod when system <stdlib.h> is
included here. */
/* But avoid namespace pollution on glibc systems. */
#if !defined __GLIBC__ && !defined __osf__
# define __need_system_stdlib_h
# undef __need_system_stdlib_h
#endif
/* Native Windows platforms declare chdir, getcwd, rmdir in
<io.h> and/or <direct.h>, not in <unistd.h>.
They also declare access(), chmod(), close(), dup(), dup2(), isatty(),
lseek(), read(), unlink(), write() in <io.h>. */
#if ((0 || 0 || 0 \
|| defined GNULIB_POSIXCHECK) \
&& (defined _WIN32 && ! defined __CYGWIN__))
#elif (1 || 0 || 1 || 0 \
|| 0 || 0 || 0 || 0 \
|| defined GNULIB_POSIXCHECK) \
&& (defined _WIN32 && ! defined __CYGWIN__)
#endif
/* AIX and OSF/1 5.1 declare getdomainname in <netdb.h>, not in <unistd.h>.
NonStop Kernel declares gethostname in <netdb.h>, not in <unistd.h>. */
/* But avoid namespace pollution on glibc systems. */
#if ((0 && (defined _AIX || defined __osf__)) \
|| (0 && defined __TANDEM)) \
&& !defined __GLIBC__
#endif
/* Android 4.3 declares fchownat in <sys/stat.h>, not in <unistd.h>. */
/* But avoid namespace pollution on glibc systems. */
#if (0 || defined GNULIB_POSIXCHECK) && defined __ANDROID__ \
&& !defined __GLIBC__
#endif
/* MSVC defines off_t in <sys/types.h>.
May also define off_t to a 64-bit type on native Windows. */
/* But avoid namespace pollution on glibc systems. */
#ifndef __GLIBC__
/* Get off_t, ssize_t. */
#endif
/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
/* C++ compatible function declaration macros.
Copyright (C) 2010-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#ifndef _GL_CXXDEFS_H
#define _GL_CXXDEFS_H
/* Begin/end the GNULIB_NAMESPACE namespace. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_BEGIN_NAMESPACE namespace GNULIB_NAMESPACE {
# define _GL_END_NAMESPACE }
#else
# define _GL_BEGIN_NAMESPACE
# define _GL_END_NAMESPACE
#endif
/* The three most frequent use cases of these macros are:
* For providing a substitute for a function that is missing on some
platforms, but is declared and works fine on the platforms on which
it exists:
#if @GNULIB_FOO@
# if !@HAVE_FOO@
_GL_FUNCDECL_SYS (foo, ...);
# endif
_GL_CXXALIAS_SYS (foo, ...);
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
* For providing a replacement for a function that exists on all platforms,
but is broken/insufficient and needs to be replaced on some platforms:
#if @GNULIB_FOO@
# if @REPLACE_FOO@
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef foo
# define foo rpl_foo
# endif
_GL_FUNCDECL_RPL (foo, ...);
_GL_CXXALIAS_RPL (foo, ...);
# else
_GL_CXXALIAS_SYS (foo, ...);
# endif
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
* For providing a replacement for a function that exists on some platforms
but is broken/insufficient and needs to be replaced on some of them and
is additionally either missing or undeclared on some other platforms:
#if @GNULIB_FOO@
# if @REPLACE_FOO@
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef foo
# define foo rpl_foo
# endif
_GL_FUNCDECL_RPL (foo, ...);
_GL_CXXALIAS_RPL (foo, ...);
# else
# if !@HAVE_FOO@ or if !@HAVE_DECL_FOO@
_GL_FUNCDECL_SYS (foo, ...);
# endif
_GL_CXXALIAS_SYS (foo, ...);
# endif
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
*/
/* _GL_EXTERN_C declaration;
performs the declaration with C linkage. */
#if defined __cplusplus
# define _GL_EXTERN_C extern "C"
#else
# define _GL_EXTERN_C extern
#endif
/* _GL_FUNCDECL_RPL (func, rettype, parameters_and_attributes);
declares a replacement function, named rpl_func, with the given prototype,
consisting of return type, parameters, and attributes.
Example:
_GL_FUNCDECL_RPL (open, int, (const char *filename, int flags, ...)
_GL_ARG_NONNULL ((1)));
*/
#define _GL_FUNCDECL_RPL(func,rettype,parameters_and_attributes) \
_GL_FUNCDECL_RPL_1 (rpl_##func, rettype, parameters_and_attributes)
#define _GL_FUNCDECL_RPL_1(rpl_func,rettype,parameters_and_attributes) \
_GL_EXTERN_C rettype rpl_func parameters_and_attributes
/* _GL_FUNCDECL_SYS (func, rettype, parameters_and_attributes);
declares the system function, named func, with the given prototype,
consisting of return type, parameters, and attributes.
Example:
_GL_FUNCDECL_SYS (open, int, (const char *filename, int flags, ...)
_GL_ARG_NONNULL ((1)));
*/
#define _GL_FUNCDECL_SYS(func,rettype,parameters_and_attributes) \
_GL_EXTERN_C rettype func parameters_and_attributes
/* _GL_CXXALIAS_RPL (func, rettype, parameters);
declares a C++ alias called GNULIB_NAMESPACE::func
that redirects to rpl_func, if GNULIB_NAMESPACE is defined.
Example:
_GL_CXXALIAS_RPL (open, int, (const char *filename, int flags, ...));
Wrapping rpl_func in an object with an inline conversion operator
avoids a reference to rpl_func unless GNULIB_NAMESPACE::func is
actually used in the program. */
#define _GL_CXXALIAS_RPL(func,rettype,parameters) \
_GL_CXXALIAS_RPL_1 (func, rpl_##func, rettype, parameters)
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_RPL_1(func,rpl_func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return ::rpl_func; \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_RPL_1(func,rpl_func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_RPL_CAST_1 (func, rpl_func, rettype, parameters);
is like _GL_CXXALIAS_RPL_1 (func, rpl_func, rettype, parameters);
except that the C function rpl_func may have a slightly different
declaration. A cast is used to silence the "invalid conversion" error
that would otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_RPL_CAST_1(func,rpl_func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return reinterpret_cast<type>(::rpl_func); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_RPL_CAST_1(func,rpl_func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS (func, rettype, parameters);
declares a C++ alias called GNULIB_NAMESPACE::func
that redirects to the system provided function func, if GNULIB_NAMESPACE
is defined.
Example:
_GL_CXXALIAS_SYS (open, int, (const char *filename, int flags, ...));
Wrapping func in an object with an inline conversion operator
avoids a reference to func unless GNULIB_NAMESPACE::func is
actually used in the program. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_SYS(func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return ::func; \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_SYS(func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS_CAST (func, rettype, parameters);
is like _GL_CXXALIAS_SYS (func, rettype, parameters);
except that the C function func may have a slightly different declaration.
A cast is used to silence the "invalid conversion" error that would
otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_SYS_CAST(func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return reinterpret_cast<type>(::func); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_SYS_CAST(func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS_CAST2 (func, rettype, parameters, rettype2, parameters2);
is like _GL_CXXALIAS_SYS (func, rettype, parameters);
except that the C function is picked among a set of overloaded functions,
namely the one with rettype2 and parameters2. Two consecutive casts
are used to silence the "cannot find a match" and "invalid conversion"
errors that would otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
/* The outer cast must be a reinterpret_cast.
The inner cast: When the function is defined as a set of overloaded
functions, it works as a static_cast<>, choosing the designated variant.
When the function is defined as a single variant, it works as a
reinterpret_cast<>. The parenthesized cast syntax works both ways. */
# define _GL_CXXALIAS_SYS_CAST2(func,rettype,parameters,rettype2,parameters2) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return reinterpret_cast<type>((rettype2 (*) parameters2)(::func)); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_SYS_CAST2(func,rettype,parameters,rettype2,parameters2) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIASWARN (func);
causes a warning to be emitted when ::func is used but not when
GNULIB_NAMESPACE::func is used. func must be defined without overloaded
variants. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIASWARN(func) \
_GL_CXXALIASWARN_1 (func, GNULIB_NAMESPACE)
# define _GL_CXXALIASWARN_1(func,namespace) \
_GL_CXXALIASWARN_2 (func, namespace)
/* To work around GCC bug <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=43881>,
we enable the warning only when not optimizing. */
# if !__OPTIMIZE__
# define _GL_CXXALIASWARN_2(func,namespace) \
_GL_WARN_ON_USE (func, \
"The symbol ::" #func " refers to the system function. " \
"Use " #namespace "::" #func " instead.")
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
# define _GL_CXXALIASWARN_2(func,namespace) \
extern __typeof__ (func) func
# else
# define _GL_CXXALIASWARN_2(func,namespace) \
_GL_EXTERN_C int _gl_cxxalias_dummy
# endif
#else
# define _GL_CXXALIASWARN(func) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIASWARN1 (func, rettype, parameters_and_attributes);
causes a warning to be emitted when the given overloaded variant of ::func
is used but not when GNULIB_NAMESPACE::func is used. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIASWARN1(func,rettype,parameters_and_attributes) \
_GL_CXXALIASWARN1_1 (func, rettype, parameters_and_attributes, \
GNULIB_NAMESPACE)
# define _GL_CXXALIASWARN1_1(func,rettype,parameters_and_attributes,namespace) \
_GL_CXXALIASWARN1_2 (func, rettype, parameters_and_attributes, namespace)
/* To work around GCC bug <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=43881>,
we enable the warning only when not optimizing. */
# if !__OPTIMIZE__
# define _GL_CXXALIASWARN1_2(func,rettype,parameters_and_attributes,namespace) \
_GL_WARN_ON_USE_CXX (func, rettype, parameters_and_attributes, \
"The symbol ::" #func " refers to the system function. " \
"Use " #namespace "::" #func " instead.")
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
# define _GL_CXXALIASWARN1_2(func,rettype,parameters_and_attributes,namespace) \
extern __typeof__ (func) func
# else
# define _GL_CXXALIASWARN1_2(func,rettype,parameters_and_attributes,namespace) \
_GL_EXTERN_C int _gl_cxxalias_dummy
# endif
#else
# define _GL_CXXALIASWARN1(func,rettype,parameters_and_attributes) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
#endif /* _GL_CXXDEFS_H */
/* The definition of _GL_ARG_NONNULL is copied here. */
/* A C macro for declaring that specific arguments must not be NULL.
Copyright (C) 2009-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* _GL_ARG_NONNULL((n,...,m)) tells the compiler and static analyzer tools
that the values passed as arguments n, ..., m must be non-NULL pointers.
n = 1 stands for the first argument, n = 2 for the second argument etc. */
#ifndef _GL_ARG_NONNULL
# if (__GNUC__ == 3 && __GNUC_MINOR__ >= 3) || __GNUC__ > 3
# define _GL_ARG_NONNULL(params) __attribute__ ((__nonnull__ params))
# else
# define _GL_ARG_NONNULL(params)
# endif
#endif
/* The definition of _GL_WARN_ON_USE is copied here. */
/* A C macro for emitting warnings if a function is used.
Copyright (C) 2010-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* _GL_WARN_ON_USE (function, "literal string") issues a declaration
for FUNCTION which will then trigger a compiler warning containing
the text of "literal string" anywhere that function is called, if
supported by the compiler. If the compiler does not support this
feature, the macro expands to an unused extern declaration.
_GL_WARN_ON_USE_ATTRIBUTE ("literal string") expands to the
attribute used in _GL_WARN_ON_USE. If the compiler does not support
this feature, it expands to empty.
These macros are useful for marking a function as a potential
portability trap, with the intent that "literal string" include
instructions on the replacement function that should be used
instead.
_GL_WARN_ON_USE is for functions with 'extern' linkage.
_GL_WARN_ON_USE_ATTRIBUTE is for functions with 'static' or 'inline'
linkage.
However, one of the reasons that a function is a portability trap is
if it has the wrong signature. Declaring FUNCTION with a different
signature in C is a compilation error, so this macro must use the
same type as any existing declaration so that programs that avoid
the problematic FUNCTION do not fail to compile merely because they
included a header that poisoned the function. But this implies that
_GL_WARN_ON_USE is only safe to use if FUNCTION is known to already
have a declaration. Use of this macro implies that there must not
be any other macro hiding the declaration of FUNCTION; but
undefining FUNCTION first is part of the poisoning process anyway
(although for symbols that are provided only via a macro, the result
is a compilation error rather than a warning containing
"literal string"). Also note that in C++, it is only safe to use if
FUNCTION has no overloads.
For an example, it is possible to poison 'getline' by:
[getline]) in configure.ac, which potentially defines
HAVE_RAW_DECL_GETLINE
- adding this code to a header that wraps the system <stdio.h>:
#undef getline
#if HAVE_RAW_DECL_GETLINE
_GL_WARN_ON_USE (getline, "getline is required by POSIX 2008, but"
"not universally present; use the gnulib module getline");
#endif
It is not possible to directly poison global variables. But it is
possible to write a wrapper accessor function, and poison that
(less common usage, like &environ, will cause a compilation error
rather than issue the nice warning, but the end result of informing
the developer about their portability problem is still achieved):
#if HAVE_RAW_DECL_ENVIRON
static char ***
rpl_environ (void) { return &environ; }
_GL_WARN_ON_USE (rpl_environ, "environ is not always properly declared");
# undef environ
# define environ (*rpl_environ ())
#endif
or better (avoiding contradictory use of 'static' and 'extern'):
#if HAVE_RAW_DECL_ENVIRON
static char ***
_GL_WARN_ON_USE_ATTRIBUTE ("environ is not always properly declared")
rpl_environ (void) { return &environ; }
# undef environ
# define environ (*rpl_environ ())
#endif
*/
#ifndef _GL_WARN_ON_USE
# if 4 < __GNUC__ || (__GNUC__ == 4 && 3 <= __GNUC_MINOR__)
/* A compiler attribute is available in gcc versions 4.3.0 and later. */
# define _GL_WARN_ON_USE(function, message) \
extern __typeof__ (function) function __attribute__ ((__warning__ (message)))
# define _GL_WARN_ON_USE_ATTRIBUTE(message) \
__attribute__ ((__warning__ (message)))
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
/* Verify the existence of the function. */
# define _GL_WARN_ON_USE(function, message) \
extern __typeof__ (function) function
# define _GL_WARN_ON_USE_ATTRIBUTE(message)
# else /* Unsupported. */
# define _GL_WARN_ON_USE(function, message) \
_GL_WARN_EXTERN_C int _gl_warn_on_use
# define _GL_WARN_ON_USE_ATTRIBUTE(message)
# endif
#endif
/* _GL_WARN_ON_USE_CXX (function, rettype, parameters_and_attributes, "string")
is like _GL_WARN_ON_USE (function, "string"), except that the function is
declared with the given prototype, consisting of return type, parameters,
and attributes.
This variant is useful for overloaded functions in C++. _GL_WARN_ON_USE does
not work in this case. */
#ifndef _GL_WARN_ON_USE_CXX
# if 4 < __GNUC__ || (__GNUC__ == 4 && 3 <= __GNUC_MINOR__)
# define _GL_WARN_ON_USE_CXX(function,rettype,parameters_and_attributes,msg) \
extern rettype function parameters_and_attributes \
__attribute__ ((__warning__ (msg)))
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
/* Verify the existence of the function. */
# define _GL_WARN_ON_USE_CXX(function,rettype,parameters_and_attributes,msg) \
extern rettype function parameters_and_attributes
# else /* Unsupported. */
# define _GL_WARN_ON_USE_CXX(function,rettype,parameters_and_attributes,msg) \
_GL_WARN_EXTERN_C int _gl_warn_on_use
# endif
#endif
/* _GL_WARN_EXTERN_C declaration;
performs the declaration with C linkage. */
#ifndef _GL_WARN_EXTERN_C
# if defined __cplusplus
# define _GL_WARN_EXTERN_C extern "C"
# else
# define _GL_WARN_EXTERN_C extern
# endif
#endif
/* Get getopt(), optarg, optind, opterr, optopt. */
#if 0 && !defined _GL_SYSTEM_GETOPT
#endif
#ifndef _GL_INLINE_HEADER_BEGIN
#error "Please include config.h first."
#endif
_GL_INLINE_HEADER_BEGIN
#ifndef _GL_UNISTD_INLINE
# define _GL_UNISTD_INLINE _GL_INLINE
#endif
/* Hide some function declarations from <winsock2.h>. */
#if 0 && 0
# if !defined _GL_SYS_SOCKET_H
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef socket
# define socket socket_used_without_including_sys_socket_h
# undef connect
# define connect connect_used_without_including_sys_socket_h
# undef accept
# define accept accept_used_without_including_sys_socket_h
# undef bind
# define bind bind_used_without_including_sys_socket_h
# undef getpeername
# define getpeername getpeername_used_without_including_sys_socket_h
# undef getsockname
# define getsockname getsockname_used_without_including_sys_socket_h
# undef getsockopt
# define getsockopt getsockopt_used_without_including_sys_socket_h
# undef listen
# define listen listen_used_without_including_sys_socket_h
# undef recv
# define recv recv_used_without_including_sys_socket_h
# undef send
# define send send_used_without_including_sys_socket_h
# undef recvfrom
# define recvfrom recvfrom_used_without_including_sys_socket_h
# undef sendto
# define sendto sendto_used_without_including_sys_socket_h
# undef setsockopt
# define setsockopt setsockopt_used_without_including_sys_socket_h
# undef shutdown
# define shutdown shutdown_used_without_including_sys_socket_h
# else
_GL_WARN_ON_USE (socket,
"socket() used without including <sys/socket.h>");
_GL_WARN_ON_USE (connect,
"connect() used without including <sys/socket.h>");
_GL_WARN_ON_USE (accept,
"accept() used without including <sys/socket.h>");
_GL_WARN_ON_USE (bind,
"bind() used without including <sys/socket.h>");
_GL_WARN_ON_USE (getpeername,
"getpeername() used without including <sys/socket.h>");
_GL_WARN_ON_USE (getsockname,
"getsockname() used without including <sys/socket.h>");
_GL_WARN_ON_USE (getsockopt,
"getsockopt() used without including <sys/socket.h>");
_GL_WARN_ON_USE (listen,
"listen() used without including <sys/socket.h>");
_GL_WARN_ON_USE (recv,
"recv() used without including <sys/socket.h>");
_GL_WARN_ON_USE (send,
"send() used without including <sys/socket.h>");
_GL_WARN_ON_USE (recvfrom,
"recvfrom() used without including <sys/socket.h>");
_GL_WARN_ON_USE (sendto,
"sendto() used without including <sys/socket.h>");
_GL_WARN_ON_USE (setsockopt,
"setsockopt() used without including <sys/socket.h>");
_GL_WARN_ON_USE (shutdown,
"shutdown() used without including <sys/socket.h>");
# endif
# endif
# if !defined _GL_SYS_SELECT_H
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef select
# define select select_used_without_including_sys_select_h
# else
_GL_WARN_ON_USE (select,
"select() used without including <sys/select.h>");
# endif
# endif
#endif
/* OS/2 EMX lacks these macros. */
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
/* Ensure *_OK macros exist. */
#ifndef F_OK
# define F_OK 0
# define X_OK 1
# define W_OK 2
# define R_OK 4
#endif
/* Declare overridden functions. */
#if 1
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef access
# define access rpl_access
# endif
_GL_FUNCDECL_RPL (access, int, (const char *file, int mode)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (access, int, (const char *file, int mode));
# else
_GL_CXXALIAS_SYS (access, int, (const char *file, int mode));
# endif
_GL_CXXALIASWARN (access);
#elif defined GNULIB_POSIXCHECK
# undef access
# if HAVE_RAW_DECL_ACCESS
/* The access() function is a security risk. */
_GL_WARN_ON_USE (access, "access does not always support X_OK - "
"use gnulib module access for portability; "
"also, this function is a security risk - "
"use the gnulib module faccessat instead");
# endif
#endif
#if 0
_GL_CXXALIAS_SYS (chdir, int, (const char *file) _GL_ARG_NONNULL ((1)));
_GL_CXXALIASWARN (chdir);
#elif defined GNULIB_POSIXCHECK
# undef chdir
# if HAVE_RAW_DECL_CHDIR
_GL_WARN_ON_USE (chown, "chdir is not always in <unistd.h> - "
"use gnulib module chdir for portability");
# endif
#endif
#if 0
/* Change the owner of FILE to UID (if UID is not -1) and the group of FILE
to GID (if GID is not -1). Follow symbolic links.
Return 0 if successful, otherwise -1 and errno set.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/chown.html. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef chown
# define chown rpl_chown
# endif
_GL_FUNCDECL_RPL (chown, int, (const char *file, uid_t uid, gid_t gid)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (chown, int, (const char *file, uid_t uid, gid_t gid));
# else
# if !1
_GL_FUNCDECL_SYS (chown, int, (const char *file, uid_t uid, gid_t gid)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (chown, int, (const char *file, uid_t uid, gid_t gid));
# endif
_GL_CXXALIASWARN (chown);
#elif defined GNULIB_POSIXCHECK
# undef chown
# if HAVE_RAW_DECL_CHOWN
_GL_WARN_ON_USE (chown, "chown fails to follow symlinks on some systems and "
"doesn't treat a uid or gid of -1 on some systems - "
"use gnulib module chown for portability");
# endif
#endif
#if 1
# if 0
/* Automatically included by modules that need a replacement for close. */
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef close
# define close rpl_close
# endif
_GL_FUNCDECL_RPL (close, int, (int fd));
_GL_CXXALIAS_RPL (close, int, (int fd));
# else
_GL_CXXALIAS_SYS (close, int, (int fd));
# endif
_GL_CXXALIASWARN (close);
#elif 0
# undef close
# define close close_used_without_requesting_gnulib_module_close
#elif defined GNULIB_POSIXCHECK
# undef close
/* Assume close is always declared. */
_GL_WARN_ON_USE (close, "close does not portably work on sockets - "
"use gnulib module close for portability");
#endif
#if 0
# if !1
_GL_FUNCDECL_SYS (copy_file_range, ssize_t, (int ifd, off_t *ipos,
int ofd, off_t *opos,
size_t len, unsigned flags));
_GL_CXXALIAS_SYS (copy_file_range, ssize_t, (int ifd, off_t *ipos,
int ofd, off_t *opos,
size_t len, unsigned flags));
# endif
_GL_CXXALIASWARN (copy_file_range);
#elif defined GNULIB_POSIXCHECK
/* Assume copy_file_range is always declared. */
_GL_WARN_ON_USE (copy_file_range,
"copy_file_range is unportable - "
"use gnulib module copy_file_range for portability");
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define dup rpl_dup
# endif
_GL_FUNCDECL_RPL (dup, int, (int oldfd));
_GL_CXXALIAS_RPL (dup, int, (int oldfd));
# else
_GL_CXXALIAS_SYS (dup, int, (int oldfd));
# endif
_GL_CXXALIASWARN (dup);
#elif defined GNULIB_POSIXCHECK
# undef dup
# if HAVE_RAW_DECL_DUP
_GL_WARN_ON_USE (dup, "dup is unportable - "
"use gnulib module dup for portability");
# endif
#endif
#if 1
/* Copy the file descriptor OLDFD into file descriptor NEWFD. Do nothing if
NEWFD = OLDFD, otherwise close NEWFD first if it is open.
Return newfd if successful, otherwise -1 and errno set.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/dup2.html>. */
# if 1
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define dup2 rpl_dup2
# endif
_GL_FUNCDECL_RPL (dup2, int, (int oldfd, int newfd));
_GL_CXXALIAS_RPL (dup2, int, (int oldfd, int newfd));
# else
# if !1
_GL_FUNCDECL_SYS (dup2, int, (int oldfd, int newfd));
# endif
_GL_CXXALIAS_SYS (dup2, int, (int oldfd, int newfd));
# endif
_GL_CXXALIASWARN (dup2);
#elif defined GNULIB_POSIXCHECK
# undef dup2
# if HAVE_RAW_DECL_DUP2
_GL_WARN_ON_USE (dup2, "dup2 is unportable - "
"use gnulib module dup2 for portability");
# endif
#endif
#if 0
/* Copy the file descriptor OLDFD into file descriptor NEWFD, with the
specified flags.
The flags are a bitmask, possibly including O_CLOEXEC (defined in <fcntl.h>)
and O_TEXT, O_BINARY (defined in "binary-io.h").
Close NEWFD first if it is open.
Return newfd if successful, otherwise -1 and errno set.
See the Linux man page at
<https://www.kernel.org/doc/man-pages/online/pages/man2/dup3.2.html>. */
# if 1
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define dup3 rpl_dup3
# endif
_GL_FUNCDECL_RPL (dup3, int, (int oldfd, int newfd, int flags));
_GL_CXXALIAS_RPL (dup3, int, (int oldfd, int newfd, int flags));
# else
_GL_FUNCDECL_SYS (dup3, int, (int oldfd, int newfd, int flags));
_GL_CXXALIAS_SYS (dup3, int, (int oldfd, int newfd, int flags));
# endif
_GL_CXXALIASWARN (dup3);
#elif defined GNULIB_POSIXCHECK
# undef dup3
# if HAVE_RAW_DECL_DUP3
_GL_WARN_ON_USE (dup3, "dup3 is unportable - "
"use gnulib module dup3 for portability");
# endif
#endif
#if 0
# if defined __CYGWIN__ && !defined __i386__
/* The 'environ' variable is defined in a DLL. Therefore its declaration needs
the '__declspec(dllimport)' attribute, but the system's <unistd.h> lacks it.
This leads to a link error on 64-bit Cygwin when the option
-Wl,--disable-auto-import is in use. */
_GL_EXTERN_C __declspec(dllimport) char **environ;
# endif
# if !1
/* Set of environment variables and values. An array of strings of the form
"VARIABLE=VALUE", terminated with a NULL. */
# if defined __APPLE__ && defined __MACH__
# if !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR
# define _GL_USE_CRT_EXTERNS
# endif
# endif
# ifdef _GL_USE_CRT_EXTERNS
# define environ (*_NSGetEnviron ())
# else
# ifdef __cplusplus
extern "C" {
# endif
extern char **environ;
# ifdef __cplusplus
}
# endif
# endif
# endif
#elif defined GNULIB_POSIXCHECK
# if HAVE_RAW_DECL_ENVIRON
_GL_UNISTD_INLINE char ***
_GL_WARN_ON_USE_ATTRIBUTE ("environ is unportable - "
"use gnulib module environ for portability")
rpl_environ (void)
{
return &environ;
}
# undef environ
# define environ (*rpl_environ ())
# endif
#endif
#if 0
/* Like access(), except that it uses the effective user id and group id of
the current process. */
# if !1
_GL_FUNCDECL_SYS (euidaccess, int, (const char *filename, int mode)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (euidaccess, int, (const char *filename, int mode));
_GL_CXXALIASWARN (euidaccess);
# if defined GNULIB_POSIXCHECK
/* Like access(), this function is a security risk. */
_GL_WARN_ON_USE (euidaccess, "the euidaccess function is a security risk - "
"use the gnulib module faccessat instead");
# endif
#elif defined GNULIB_POSIXCHECK
# undef euidaccess
# if HAVE_RAW_DECL_EUIDACCESS
_GL_WARN_ON_USE (euidaccess, "euidaccess is unportable - "
"use gnulib module euidaccess for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef faccessat
# define faccessat rpl_faccessat
# endif
_GL_FUNCDECL_RPL (faccessat, int,
(int fd, char const *name, int mode, int flag)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (faccessat, int,
(int fd, char const *name, int mode, int flag));
# else
# if !1
_GL_FUNCDECL_SYS (faccessat, int,
(int fd, char const *file, int mode, int flag)
_GL_ARG_NONNULL ((2)));
# endif
_GL_CXXALIAS_SYS (faccessat, int,
(int fd, char const *file, int mode, int flag));
# endif
_GL_CXXALIASWARN (faccessat);
#elif defined GNULIB_POSIXCHECK
# undef faccessat
# if HAVE_RAW_DECL_FACCESSAT
_GL_WARN_ON_USE (faccessat, "faccessat is not portable - "
"use gnulib module faccessat for portability");
# endif
#endif
#if 0
/* Change the process' current working directory to the directory on which
the given file descriptor is open.
Return 0 if successful, otherwise -1 and errno set.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/fchdir.html>. */
# if ! 1
_GL_FUNCDECL_SYS (fchdir, int, (int /*fd*/));
/* Gnulib internal hooks needed to maintain the fchdir metadata. */
_GL_EXTERN_C int _gl_register_fd (int fd, const char *filename)
_GL_ARG_NONNULL ((2));
_GL_EXTERN_C void _gl_unregister_fd (int fd);
_GL_EXTERN_C int _gl_register_dup (int oldfd, int newfd);
_GL_EXTERN_C const char *_gl_directory_name (int fd);
# else
# if !1
_GL_FUNCDECL_SYS (fchdir, int, (int /*fd*/));
# endif
# endif
_GL_CXXALIAS_SYS (fchdir, int, (int /*fd*/));
_GL_CXXALIASWARN (fchdir);
#elif defined GNULIB_POSIXCHECK
# undef fchdir
# if HAVE_RAW_DECL_FCHDIR
_GL_WARN_ON_USE (fchdir, "fchdir is unportable - "
"use gnulib module fchdir for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fchownat
# define fchownat rpl_fchownat
# endif
_GL_FUNCDECL_RPL (fchownat, int, (int fd, char const *file,
uid_t owner, gid_t group, int flag)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (fchownat, int, (int fd, char const *file,
uid_t owner, gid_t group, int flag));
# else
# if !1
_GL_FUNCDECL_SYS (fchownat, int, (int fd, char const *file,
uid_t owner, gid_t group, int flag)
_GL_ARG_NONNULL ((2)));
# endif
_GL_CXXALIAS_SYS (fchownat, int, (int fd, char const *file,
uid_t owner, gid_t group, int flag));
# endif
_GL_CXXALIASWARN (fchownat);
#elif defined GNULIB_POSIXCHECK
# undef fchownat
# if HAVE_RAW_DECL_FCHOWNAT
_GL_WARN_ON_USE (fchownat, "fchownat is not portable - "
"use gnulib module openat for portability");
# endif
#endif
#if 0
/* Synchronize changes to a file.
Return 0 if successful, otherwise -1 and errno set.
See POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/fdatasync.html>. */
# if !1 || !1
_GL_FUNCDECL_SYS (fdatasync, int, (int fd));
# endif
_GL_CXXALIAS_SYS (fdatasync, int, (int fd));
_GL_CXXALIASWARN (fdatasync);
#elif defined GNULIB_POSIXCHECK
# undef fdatasync
# if HAVE_RAW_DECL_FDATASYNC
_GL_WARN_ON_USE (fdatasync, "fdatasync is unportable - "
"use gnulib module fdatasync for portability");
# endif
#endif
#if 0
/* Synchronize changes, including metadata, to a file.
Return 0 if successful, otherwise -1 and errno set.
See POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/fsync.html>. */
# if !1
_GL_FUNCDECL_SYS (fsync, int, (int fd));
# endif
_GL_CXXALIAS_SYS (fsync, int, (int fd));
_GL_CXXALIASWARN (fsync);
#elif defined GNULIB_POSIXCHECK
# undef fsync
# if HAVE_RAW_DECL_FSYNC
_GL_WARN_ON_USE (fsync, "fsync is unportable - "
"use gnulib module fsync for portability");
# endif
#endif
#if 0
/* Change the size of the file to which FD is opened to become equal to LENGTH.
Return 0 if successful, otherwise -1 and errno set.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef ftruncate
# define ftruncate rpl_ftruncate
# endif
_GL_FUNCDECL_RPL (ftruncate, int, (int fd, off_t length));
_GL_CXXALIAS_RPL (ftruncate, int, (int fd, off_t length));
# else
# if !1
_GL_FUNCDECL_SYS (ftruncate, int, (int fd, off_t length));
# endif
_GL_CXXALIAS_SYS (ftruncate, int, (int fd, off_t length));
# endif
_GL_CXXALIASWARN (ftruncate);
#elif defined GNULIB_POSIXCHECK
# undef ftruncate
# if HAVE_RAW_DECL_FTRUNCATE
_GL_WARN_ON_USE (ftruncate, "ftruncate is unportable - "
"use gnulib module ftruncate for portability");
# endif
#endif
#if 0
/* Get the name of the current working directory, and put it in SIZE bytes
of BUF.
Return BUF if successful, or NULL if the directory couldn't be determined
or SIZE was too small.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html>.
Additionally, the gnulib module 'getcwd' guarantees the following GNU
extension: If BUF is NULL, an array is allocated with 'malloc'; the array
is SIZE bytes long, unless SIZE == 0, in which case it is as big as
necessary. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define getcwd rpl_getcwd
# endif
_GL_FUNCDECL_RPL (getcwd, char *, (char *buf, size_t size));
_GL_CXXALIAS_RPL (getcwd, char *, (char *buf, size_t size));
# else
/* Need to cast, because on mingw, the second parameter is
int size. */
_GL_CXXALIAS_SYS_CAST (getcwd, char *, (char *buf, size_t size));
# endif
_GL_CXXALIASWARN (getcwd);
#elif defined GNULIB_POSIXCHECK
# undef getcwd
# if HAVE_RAW_DECL_GETCWD
_GL_WARN_ON_USE (getcwd, "getcwd is unportable - "
"use gnulib module getcwd for portability");
# endif
#endif
#if 0
/* Return the NIS domain name of the machine.
WARNING! The NIS domain name is unrelated to the fully qualified host name
of the machine. It is also unrelated to email addresses.
WARNING! The NIS domain name is usually the empty string or "(none)" when
not using NIS.
Put up to LEN bytes of the NIS domain name into NAME.
Null terminate it if the name is shorter than LEN.
If the NIS domain name is longer than LEN, set errno = EINVAL and return -1.
Return 0 if successful, otherwise set errno and return -1. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef getdomainname
# define getdomainname rpl_getdomainname
# endif
_GL_FUNCDECL_RPL (getdomainname, int, (char *name, size_t len)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (getdomainname, int, (char *name, size_t len));
# else
# if !1
_GL_FUNCDECL_SYS (getdomainname, int, (char *name, size_t len)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (getdomainname, int, (char *name, size_t len));
# endif
_GL_CXXALIASWARN (getdomainname);
#elif defined GNULIB_POSIXCHECK
# undef getdomainname
# if HAVE_RAW_DECL_GETDOMAINNAME
_GL_WARN_ON_USE (getdomainname, "getdomainname is unportable - "
"use gnulib module getdomainname for portability");
# endif
#endif
#if 1
/* Return the maximum number of file descriptors in the current process.
In POSIX, this is same as sysconf (_SC_OPEN_MAX). */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef getdtablesize
# define getdtablesize rpl_getdtablesize
# endif
_GL_FUNCDECL_RPL (getdtablesize, int, (void));
_GL_CXXALIAS_RPL (getdtablesize, int, (void));
# else
# if !1
_GL_FUNCDECL_SYS (getdtablesize, int, (void));
# endif
/* Need to cast, because on AIX, the parameter list is
(...). */
_GL_CXXALIAS_SYS_CAST (getdtablesize, int, (void));
# endif
_GL_CXXALIASWARN (getdtablesize);
#elif defined GNULIB_POSIXCHECK
# undef getdtablesize
# if HAVE_RAW_DECL_GETDTABLESIZE
_GL_WARN_ON_USE (getdtablesize, "getdtablesize is unportable - "
"use gnulib module getdtablesize for portability");
# endif
#endif
#if 0
/* Return the supplemental groups that the current process belongs to.
It is unspecified whether the effective group id is in the list.
If N is 0, return the group count; otherwise, N describes how many
entries are available in GROUPS. Return -1 and set errno if N is
not 0 and not large enough. Fails with ENOSYS on some systems. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef getgroups
# define getgroups rpl_getgroups
# endif
_GL_FUNCDECL_RPL (getgroups, int, (int n, gid_t *groups));
_GL_CXXALIAS_RPL (getgroups, int, (int n, gid_t *groups));
# else
# if !1
_GL_FUNCDECL_SYS (getgroups, int, (int n, gid_t *groups));
# endif
_GL_CXXALIAS_SYS (getgroups, int, (int n, gid_t *groups));
# endif
_GL_CXXALIASWARN (getgroups);
#elif defined GNULIB_POSIXCHECK
# undef getgroups
# if HAVE_RAW_DECL_GETGROUPS
_GL_WARN_ON_USE (getgroups, "getgroups is unportable - "
"use gnulib module getgroups for portability");
# endif
#endif
#if 0
/* Return the standard host name of the machine.
WARNING! The host name may or may not be fully qualified.
Put up to LEN bytes of the host name into NAME.
Null terminate it if the name is shorter than LEN.
If the host name is longer than LEN, set errno = EINVAL and return -1.
Return 0 if successful, otherwise set errno and return -1. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef gethostname
# define gethostname rpl_gethostname
# endif
_GL_FUNCDECL_RPL (gethostname, int, (char *name, size_t len)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (gethostname, int, (char *name, size_t len));
# else
# if !1
_GL_FUNCDECL_SYS (gethostname, int, (char *name, size_t len)
_GL_ARG_NONNULL ((1)));
# endif
/* Need to cast, because on Solaris 10 and OSF/1 5.1 systems, the second
parameter is
int len. */
_GL_CXXALIAS_SYS_CAST (gethostname, int, (char *name, size_t len));
# endif
_GL_CXXALIASWARN (gethostname);
#elif 0
# undef gethostname
# define gethostname gethostname_used_without_requesting_gnulib_module_gethostname
#elif defined GNULIB_POSIXCHECK
# undef gethostname
# if HAVE_RAW_DECL_GETHOSTNAME
_GL_WARN_ON_USE (gethostname, "gethostname is unportable - "
"use gnulib module gethostname for portability");
# endif
#endif
#if 0
/* Returns the user's login name, or NULL if it cannot be found. Upon error,
returns NULL with errno set.
See <https://pubs.opengroup.org/onlinepubs/9699919799/functions/getlogin.html>.
Most programs don't need to use this function, because the information is
available through environment variables:
${LOGNAME-$USER} on Unix platforms,
$USERNAME on native Windows platforms.
*/
# if !1
_GL_FUNCDECL_SYS (getlogin, char *, (void));
# endif
_GL_CXXALIAS_SYS (getlogin, char *, (void));
_GL_CXXALIASWARN (getlogin);
#elif defined GNULIB_POSIXCHECK
# undef getlogin
# if HAVE_RAW_DECL_GETLOGIN
_GL_WARN_ON_USE (getlogin, "getlogin is unportable - "
"use gnulib module getlogin for portability");
# endif
#endif
#if 0
/* Copies the user's login name to NAME.
The array pointed to by NAME has room for SIZE bytes.
Returns 0 if successful. Upon error, an error number is returned, or -1 in
the case that the login name cannot be found but no specific error is
provided (this case is hopefully rare but is left open by the POSIX spec).
See <https://pubs.opengroup.org/onlinepubs/9699919799/functions/getlogin.html>.
Most programs don't need to use this function, because the information is
available through environment variables:
${LOGNAME-$USER} on Unix platforms,
$USERNAME on native Windows platforms.
*/
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define getlogin_r rpl_getlogin_r
# endif
_GL_FUNCDECL_RPL (getlogin_r, int, (char *name, size_t size)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (getlogin_r, int, (char *name, size_t size));
# else
# if !1
_GL_FUNCDECL_SYS (getlogin_r, int, (char *name, size_t size)
_GL_ARG_NONNULL ((1)));
# endif
/* Need to cast, because on Solaris 10 systems, the second argument is
int size. */
_GL_CXXALIAS_SYS_CAST (getlogin_r, int, (char *name, size_t size));
# endif
_GL_CXXALIASWARN (getlogin_r);
#elif defined GNULIB_POSIXCHECK
# undef getlogin_r
# if HAVE_RAW_DECL_GETLOGIN_R
_GL_WARN_ON_USE (getlogin_r, "getlogin_r is unportable - "
"use gnulib module getlogin_r for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define getpagesize rpl_getpagesize
# endif
_GL_FUNCDECL_RPL (getpagesize, int, (void));
_GL_CXXALIAS_RPL (getpagesize, int, (void));
# else
/* On HP-UX, getpagesize exists, but it is not declared in <unistd.h> even if
the compiler options -D_HPUX_SOURCE -D_XOPEN_SOURCE=600 are used. */
# if defined __hpux
_GL_FUNCDECL_SYS (getpagesize, int, (void));
# endif
# if !1
# if !defined getpagesize
/* This is for POSIX systems. */
# if !defined _gl_getpagesize && defined _SC_PAGESIZE
# if ! (defined __VMS && __VMS_VER < 70000000)
# define _gl_getpagesize() sysconf (_SC_PAGESIZE)
# endif
# endif
/* This is for older VMS. */
# if !defined _gl_getpagesize && defined __VMS
# ifdef __ALPHA
# define _gl_getpagesize() 8192
# else
# define _gl_getpagesize() 512
# endif
# endif
/* This is for BeOS. */
# if !defined _gl_getpagesize && 0
# if defined B_PAGE_SIZE
# define _gl_getpagesize() B_PAGE_SIZE
# endif
# endif
/* This is for AmigaOS4.0. */
# if !defined _gl_getpagesize && defined __amigaos4__
# define _gl_getpagesize() 2048
# endif
/* This is for older Unix systems. */
# if !defined _gl_getpagesize && 0
# ifdef EXEC_PAGESIZE
# define _gl_getpagesize() EXEC_PAGESIZE
# else
# ifdef NBPG
# ifndef CLSIZE
# define CLSIZE 1
# endif
# define _gl_getpagesize() (NBPG * CLSIZE)
# else
# ifdef NBPC
# define _gl_getpagesize() NBPC
# endif
# endif
# endif
# endif
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define getpagesize() _gl_getpagesize ()
# else
# if !GNULIB_defined_getpagesize_function
_GL_UNISTD_INLINE int
getpagesize ()
{
return _gl_getpagesize ();
}
# define GNULIB_defined_getpagesize_function 1
# endif
# endif
# endif
# endif
/* Need to cast, because on Cygwin 1.5.x systems, the return type is size_t. */
_GL_CXXALIAS_SYS_CAST (getpagesize, int, (void));
# endif
# if 1
_GL_CXXALIASWARN (getpagesize);
# endif
#elif defined GNULIB_POSIXCHECK
# undef getpagesize
# if HAVE_RAW_DECL_GETPAGESIZE
_GL_WARN_ON_USE (getpagesize, "getpagesize is unportable - "
"use gnulib module getpagesize for portability");
# endif
#endif
#if 0
/* Function getpass() from module 'getpass':
Read a password from /dev/tty or stdin.
Function getpass() from module 'getpass-gnu':
Read a password of arbitrary length from /dev/tty or stdin. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef getpass
# define getpass rpl_getpass
# endif
_GL_FUNCDECL_RPL (getpass, char *, (const char *prompt)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (getpass, char *, (const char *prompt));
# else
# if !1
_GL_FUNCDECL_SYS (getpass, char *, (const char *prompt)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (getpass, char *, (const char *prompt));
# endif
_GL_CXXALIASWARN (getpass);
#elif defined GNULIB_POSIXCHECK
# undef getpass
# if HAVE_RAW_DECL_GETPASS
_GL_WARN_ON_USE (getpass, "getpass is unportable - "
"use gnulib module getpass or getpass-gnu for portability");
# endif
#endif
#if 0
/* Return the next valid login shell on the system, or NULL when the end of
the list has been reached. */
# if !1
_GL_FUNCDECL_SYS (getusershell, char *, (void));
# endif
_GL_CXXALIAS_SYS (getusershell, char *, (void));
_GL_CXXALIASWARN (getusershell);
#elif defined GNULIB_POSIXCHECK
# undef getusershell
# if HAVE_RAW_DECL_GETUSERSHELL
_GL_WARN_ON_USE (getusershell, "getusershell is unportable - "
"use gnulib module getusershell for portability");
# endif
#endif
#if 0
/* Rewind to pointer that is advanced at each getusershell() call. */
# if !1
_GL_FUNCDECL_SYS (setusershell, void, (void));
# endif
_GL_CXXALIAS_SYS (setusershell, void, (void));
_GL_CXXALIASWARN (setusershell);
#elif defined GNULIB_POSIXCHECK
# undef setusershell
# if HAVE_RAW_DECL_SETUSERSHELL
_GL_WARN_ON_USE (setusershell, "setusershell is unportable - "
"use gnulib module getusershell for portability");
# endif
#endif
#if 0
/* Free the pointer that is advanced at each getusershell() call and
associated resources. */
# if !1
_GL_FUNCDECL_SYS (endusershell, void, (void));
# endif
_GL_CXXALIAS_SYS (endusershell, void, (void));
_GL_CXXALIASWARN (endusershell);
#elif defined GNULIB_POSIXCHECK
# undef endusershell
# if HAVE_RAW_DECL_ENDUSERSHELL
_GL_WARN_ON_USE (endusershell, "endusershell is unportable - "
"use gnulib module getusershell for portability");
# endif
#endif
#if 0
/* Determine whether group id is in calling user's group list. */
# if !1
_GL_FUNCDECL_SYS (group_member, int, (gid_t gid));
# endif
_GL_CXXALIAS_SYS (group_member, int, (gid_t gid));
_GL_CXXALIASWARN (group_member);
#elif defined GNULIB_POSIXCHECK
# undef group_member
# if HAVE_RAW_DECL_GROUP_MEMBER
_GL_WARN_ON_USE (group_member, "group_member is unportable - "
"use gnulib module group-member for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef isatty
# define isatty rpl_isatty
# endif
_GL_FUNCDECL_RPL (isatty, int, (int fd));
_GL_CXXALIAS_RPL (isatty, int, (int fd));
# else
_GL_CXXALIAS_SYS (isatty, int, (int fd));
# endif
_GL_CXXALIASWARN (isatty);
#elif defined GNULIB_POSIXCHECK
# undef isatty
# if HAVE_RAW_DECL_ISATTY
_GL_WARN_ON_USE (isatty, "isatty has portability problems on native Windows - "
"use gnulib module isatty for portability");
# endif
#endif
#if 0
/* Change the owner of FILE to UID (if UID is not -1) and the group of FILE
to GID (if GID is not -1). Do not follow symbolic links.
Return 0 if successful, otherwise -1 and errno set.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/lchown.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef lchown
# define lchown rpl_lchown
# endif
_GL_FUNCDECL_RPL (lchown, int, (char const *file, uid_t owner, gid_t group)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (lchown, int, (char const *file, uid_t owner, gid_t group));
# else
# if !1
_GL_FUNCDECL_SYS (lchown, int, (char const *file, uid_t owner, gid_t group)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (lchown, int, (char const *file, uid_t owner, gid_t group));
# endif
_GL_CXXALIASWARN (lchown);
#elif defined GNULIB_POSIXCHECK
# undef lchown
# if HAVE_RAW_DECL_LCHOWN
_GL_WARN_ON_USE (lchown, "lchown is unportable to pre-POSIX.1-2001 systems - "
"use gnulib module lchown for portability");
# endif
#endif
#if 0
/* Create a new hard link for an existing file.
Return 0 if successful, otherwise -1 and errno set.
See POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/link.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define link rpl_link
# endif
_GL_FUNCDECL_RPL (link, int, (const char *path1, const char *path2)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (link, int, (const char *path1, const char *path2));
# else
# if !1
_GL_FUNCDECL_SYS (link, int, (const char *path1, const char *path2)
_GL_ARG_NONNULL ((1, 2)));
# endif
_GL_CXXALIAS_SYS (link, int, (const char *path1, const char *path2));
# endif
_GL_CXXALIASWARN (link);
#elif defined GNULIB_POSIXCHECK
# undef link
# if HAVE_RAW_DECL_LINK
_GL_WARN_ON_USE (link, "link is unportable - "
"use gnulib module link for portability");
# endif
#endif
#if 0
/* Create a new hard link for an existing file, relative to two
directories. FLAG controls whether symlinks are followed.
Return 0 if successful, otherwise -1 and errno set. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef linkat
# define linkat rpl_linkat
# endif
_GL_FUNCDECL_RPL (linkat, int,
(int fd1, const char *path1, int fd2, const char *path2,
int flag)
_GL_ARG_NONNULL ((2, 4)));
_GL_CXXALIAS_RPL (linkat, int,
(int fd1, const char *path1, int fd2, const char *path2,
int flag));
# else
# if !1
_GL_FUNCDECL_SYS (linkat, int,
(int fd1, const char *path1, int fd2, const char *path2,
int flag)
_GL_ARG_NONNULL ((2, 4)));
# endif
_GL_CXXALIAS_SYS (linkat, int,
(int fd1, const char *path1, int fd2, const char *path2,
int flag));
# endif
_GL_CXXALIASWARN (linkat);
#elif defined GNULIB_POSIXCHECK
# undef linkat
# if HAVE_RAW_DECL_LINKAT
_GL_WARN_ON_USE (linkat, "linkat is unportable - "
"use gnulib module linkat for portability");
# endif
#endif
#if 0
/* Set the offset of FD relative to SEEK_SET, SEEK_CUR, or SEEK_END.
Return the new offset if successful, otherwise -1 and errno set.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/lseek.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define lseek rpl_lseek
# endif
_GL_FUNCDECL_RPL (lseek, off_t, (int fd, off_t offset, int whence));
_GL_CXXALIAS_RPL (lseek, off_t, (int fd, off_t offset, int whence));
# else
_GL_CXXALIAS_SYS (lseek, off_t, (int fd, off_t offset, int whence));
# endif
_GL_CXXALIASWARN (lseek);
#elif defined GNULIB_POSIXCHECK
# undef lseek
# if HAVE_RAW_DECL_LSEEK
_GL_WARN_ON_USE (lseek, "lseek does not fail with ESPIPE on pipes on some "
"systems - use gnulib module lseek for portability");
# endif
#endif
#if 0
/* Create a pipe, defaulting to O_BINARY mode.
Store the read-end as fd[0] and the write-end as fd[1].
Return 0 upon success, or -1 with errno set upon failure. */
# if !1
_GL_FUNCDECL_SYS (pipe, int, (int fd[2]) _GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (pipe, int, (int fd[2]));
_GL_CXXALIASWARN (pipe);
#elif defined GNULIB_POSIXCHECK
# undef pipe
# if HAVE_RAW_DECL_PIPE
_GL_WARN_ON_USE (pipe, "pipe is unportable - "
"use gnulib module pipe-posix for portability");
# endif
#endif
#if 0
/* Create a pipe, applying the given flags when opening the read-end of the
pipe and the write-end of the pipe.
The flags are a bitmask, possibly including O_CLOEXEC (defined in <fcntl.h>)
and O_TEXT, O_BINARY (defined in "binary-io.h").
Store the read-end as fd[0] and the write-end as fd[1].
Return 0 upon success, or -1 with errno set upon failure.
See also the Linux man page at
<https://www.kernel.org/doc/man-pages/online/pages/man2/pipe2.2.html>. */
# if 1
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define pipe2 rpl_pipe2
# endif
_GL_FUNCDECL_RPL (pipe2, int, (int fd[2], int flags) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (pipe2, int, (int fd[2], int flags));
# else
_GL_FUNCDECL_SYS (pipe2, int, (int fd[2], int flags) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_SYS (pipe2, int, (int fd[2], int flags));
# endif
_GL_CXXALIASWARN (pipe2);
#elif defined GNULIB_POSIXCHECK
# undef pipe2
# if HAVE_RAW_DECL_PIPE2
_GL_WARN_ON_USE (pipe2, "pipe2 is unportable - "
"use gnulib module pipe2 for portability");
# endif
#endif
#if 0
/* Read at most BUFSIZE bytes from FD into BUF, starting at OFFSET.
Return the number of bytes placed into BUF if successful, otherwise
set errno and return -1. 0 indicates EOF.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/pread.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef pread
# define pread rpl_pread
# endif
_GL_FUNCDECL_RPL (pread, ssize_t,
(int fd, void *buf, size_t bufsize, off_t offset)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (pread, ssize_t,
(int fd, void *buf, size_t bufsize, off_t offset));
# else
# if !1
_GL_FUNCDECL_SYS (pread, ssize_t,
(int fd, void *buf, size_t bufsize, off_t offset)
_GL_ARG_NONNULL ((2)));
# endif
_GL_CXXALIAS_SYS (pread, ssize_t,
(int fd, void *buf, size_t bufsize, off_t offset));
# endif
_GL_CXXALIASWARN (pread);
#elif defined GNULIB_POSIXCHECK
# undef pread
# if HAVE_RAW_DECL_PREAD
_GL_WARN_ON_USE (pread, "pread is unportable - "
"use gnulib module pread for portability");
# endif
#endif
#if 0
/* Write at most BUFSIZE bytes from BUF into FD, starting at OFFSET.
Return the number of bytes written if successful, otherwise
set errno and return -1. 0 indicates nothing written. See the
POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/pwrite.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef pwrite
# define pwrite rpl_pwrite
# endif
_GL_FUNCDECL_RPL (pwrite, ssize_t,
(int fd, const void *buf, size_t bufsize, off_t offset)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (pwrite, ssize_t,
(int fd, const void *buf, size_t bufsize, off_t offset));
# else
# if !1
_GL_FUNCDECL_SYS (pwrite, ssize_t,
(int fd, const void *buf, size_t bufsize, off_t offset)
_GL_ARG_NONNULL ((2)));
# endif
_GL_CXXALIAS_SYS (pwrite, ssize_t,
(int fd, const void *buf, size_t bufsize, off_t offset));
# endif
_GL_CXXALIASWARN (pwrite);
#elif defined GNULIB_POSIXCHECK
# undef pwrite
# if HAVE_RAW_DECL_PWRITE
_GL_WARN_ON_USE (pwrite, "pwrite is unportable - "
"use gnulib module pwrite for portability");
# endif
#endif
#if 0
/* Read up to COUNT bytes from file descriptor FD into the buffer starting
at BUF. See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef read
# define read rpl_read
# endif
_GL_FUNCDECL_RPL (read, ssize_t, (int fd, void *buf, size_t count)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (read, ssize_t, (int fd, void *buf, size_t count));
# else
/* Need to cast, because on mingw, the third parameter is
unsigned int count
and the return type is 'int'. */
_GL_CXXALIAS_SYS_CAST (read, ssize_t, (int fd, void *buf, size_t count));
# endif
_GL_CXXALIASWARN (read);
#endif
#if 0
/* Read the contents of the symbolic link FILE and place the first BUFSIZE
bytes of it into BUF. Return the number of bytes placed into BUF if
successful, otherwise -1 and errno set.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/readlink.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define readlink rpl_readlink
# endif
_GL_FUNCDECL_RPL (readlink, ssize_t,
(const char *file, char *buf, size_t bufsize)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (readlink, ssize_t,
(const char *file, char *buf, size_t bufsize));
# else
# if !1
_GL_FUNCDECL_SYS (readlink, ssize_t,
(const char *file, char *buf, size_t bufsize)
_GL_ARG_NONNULL ((1, 2)));
# endif
_GL_CXXALIAS_SYS (readlink, ssize_t,
(const char *file, char *buf, size_t bufsize));
# endif
_GL_CXXALIASWARN (readlink);
#elif defined GNULIB_POSIXCHECK
# undef readlink
# if HAVE_RAW_DECL_READLINK
_GL_WARN_ON_USE (readlink, "readlink is unportable - "
"use gnulib module readlink for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define readlinkat rpl_readlinkat
# endif
_GL_FUNCDECL_RPL (readlinkat, ssize_t,
(int fd, char const *file, char *buf, size_t len)
_GL_ARG_NONNULL ((2, 3)));
_GL_CXXALIAS_RPL (readlinkat, ssize_t,
(int fd, char const *file, char *buf, size_t len));
# else
# if !1
_GL_FUNCDECL_SYS (readlinkat, ssize_t,
(int fd, char const *file, char *buf, size_t len)
_GL_ARG_NONNULL ((2, 3)));
# endif
_GL_CXXALIAS_SYS (readlinkat, ssize_t,
(int fd, char const *file, char *buf, size_t len));
# endif
_GL_CXXALIASWARN (readlinkat);
#elif defined GNULIB_POSIXCHECK
# undef readlinkat
# if HAVE_RAW_DECL_READLINKAT
_GL_WARN_ON_USE (readlinkat, "readlinkat is not portable - "
"use gnulib module readlinkat for portability");
# endif
#endif
#if 0
/* Remove the directory DIR. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define rmdir rpl_rmdir
# endif
_GL_FUNCDECL_RPL (rmdir, int, (char const *name) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (rmdir, int, (char const *name));
# else
_GL_CXXALIAS_SYS (rmdir, int, (char const *name));
# endif
_GL_CXXALIASWARN (rmdir);
#elif defined GNULIB_POSIXCHECK
# undef rmdir
# if HAVE_RAW_DECL_RMDIR
_GL_WARN_ON_USE (rmdir, "rmdir is unportable - "
"use gnulib module rmdir for portability");
# endif
#endif
#if 0
/* Set the host name of the machine.
The host name may or may not be fully qualified.
Put LEN bytes of NAME into the host name.
Return 0 if successful, otherwise, set errno and return -1.
Platforms with no ability to set the hostname return -1 and set
errno = ENOSYS. */
# if !1 || !1
_GL_FUNCDECL_SYS (sethostname, int, (const char *name, size_t len)
_GL_ARG_NONNULL ((1)));
# endif
/* Need to cast, because on Solaris 11 2011-10, Mac OS X 10.5, IRIX 6.5
and FreeBSD 6.4 the second parameter is int. On Solaris 11
2011-10, the first parameter is not const. */
_GL_CXXALIAS_SYS_CAST (sethostname, int, (const char *name, size_t len));
_GL_CXXALIASWARN (sethostname);
#elif defined GNULIB_POSIXCHECK
# undef sethostname
# if HAVE_RAW_DECL_SETHOSTNAME
_GL_WARN_ON_USE (sethostname, "sethostname is unportable - "
"use gnulib module sethostname for portability");
# endif
#endif
#if 0
/* Pause the execution of the current thread for N seconds.
Returns the number of seconds left to sleep.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/sleep.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef sleep
# define sleep rpl_sleep
# endif
_GL_FUNCDECL_RPL (sleep, unsigned int, (unsigned int n));
_GL_CXXALIAS_RPL (sleep, unsigned int, (unsigned int n));
# else
# if !1
_GL_FUNCDECL_SYS (sleep, unsigned int, (unsigned int n));
# endif
_GL_CXXALIAS_SYS (sleep, unsigned int, (unsigned int n));
# endif
_GL_CXXALIASWARN (sleep);
#elif defined GNULIB_POSIXCHECK
# undef sleep
# if HAVE_RAW_DECL_SLEEP
_GL_WARN_ON_USE (sleep, "sleep is unportable - "
"use gnulib module sleep for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef symlink
# define symlink rpl_symlink
# endif
_GL_FUNCDECL_RPL (symlink, int, (char const *contents, char const *file)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (symlink, int, (char const *contents, char const *file));
# else
# if !1
_GL_FUNCDECL_SYS (symlink, int, (char const *contents, char const *file)
_GL_ARG_NONNULL ((1, 2)));
# endif
_GL_CXXALIAS_SYS (symlink, int, (char const *contents, char const *file));
# endif
_GL_CXXALIASWARN (symlink);
#elif defined GNULIB_POSIXCHECK
# undef symlink
# if HAVE_RAW_DECL_SYMLINK
_GL_WARN_ON_USE (symlink, "symlink is not portable - "
"use gnulib module symlink for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef symlinkat
# define symlinkat rpl_symlinkat
# endif
_GL_FUNCDECL_RPL (symlinkat, int,
(char const *contents, int fd, char const *file)
_GL_ARG_NONNULL ((1, 3)));
_GL_CXXALIAS_RPL (symlinkat, int,
(char const *contents, int fd, char const *file));
# else
# if !1
_GL_FUNCDECL_SYS (symlinkat, int,
(char const *contents, int fd, char const *file)
_GL_ARG_NONNULL ((1, 3)));
# endif
_GL_CXXALIAS_SYS (symlinkat, int,
(char const *contents, int fd, char const *file));
# endif
_GL_CXXALIASWARN (symlinkat);
#elif defined GNULIB_POSIXCHECK
# undef symlinkat
# if HAVE_RAW_DECL_SYMLINKAT
_GL_WARN_ON_USE (symlinkat, "symlinkat is not portable - "
"use gnulib module symlinkat for portability");
# endif
#endif
#if 0
/* Change the size of the file designated by FILENAME to become equal to LENGTH.
Return 0 if successful, otherwise -1 and errno set.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/truncate.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef truncate
# define truncate rpl_truncate
# endif
_GL_FUNCDECL_RPL (truncate, int, (const char *filename, off_t length)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (truncate, int, (const char *filename, off_t length));
# else
# if !1
_GL_FUNCDECL_SYS (truncate, int, (const char *filename, off_t length)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (truncate, int, (const char *filename, off_t length));
# endif
_GL_CXXALIASWARN (truncate);
#elif defined GNULIB_POSIXCHECK
# undef truncate
# if HAVE_RAW_DECL_TRUNCATE
_GL_WARN_ON_USE (truncate, "truncate is unportable - "
"use gnulib module truncate for portability");
# endif
#endif
#if 0
/* Store at most BUFLEN characters of the pathname of the terminal FD is
open on in BUF. Return 0 on success, otherwise an error number. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef ttyname_r
# define ttyname_r rpl_ttyname_r
# endif
_GL_FUNCDECL_RPL (ttyname_r, int,
(int fd, char *buf, size_t buflen) _GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (ttyname_r, int,
(int fd, char *buf, size_t buflen));
# else
# if !1
_GL_FUNCDECL_SYS (ttyname_r, int,
(int fd, char *buf, size_t buflen) _GL_ARG_NONNULL ((2)));
# endif
_GL_CXXALIAS_SYS (ttyname_r, int,
(int fd, char *buf, size_t buflen));
# endif
_GL_CXXALIASWARN (ttyname_r);
#elif defined GNULIB_POSIXCHECK
# undef ttyname_r
# if HAVE_RAW_DECL_TTYNAME_R
_GL_WARN_ON_USE (ttyname_r, "ttyname_r is not portable - "
"use gnulib module ttyname_r for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef unlink
# define unlink rpl_unlink
# endif
_GL_FUNCDECL_RPL (unlink, int, (char const *file) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (unlink, int, (char const *file));
# else
_GL_CXXALIAS_SYS (unlink, int, (char const *file));
# endif
_GL_CXXALIASWARN (unlink);
#elif defined GNULIB_POSIXCHECK
# undef unlink
# if HAVE_RAW_DECL_UNLINK
_GL_WARN_ON_USE (unlink, "unlink is not portable - "
"use gnulib module unlink for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef unlinkat
# define unlinkat rpl_unlinkat
# endif
_GL_FUNCDECL_RPL (unlinkat, int, (int fd, char const *file, int flag)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (unlinkat, int, (int fd, char const *file, int flag));
# else
# if !1
_GL_FUNCDECL_SYS (unlinkat, int, (int fd, char const *file, int flag)
_GL_ARG_NONNULL ((2)));
# endif
_GL_CXXALIAS_SYS (unlinkat, int, (int fd, char const *file, int flag));
# endif
_GL_CXXALIASWARN (unlinkat);
#elif defined GNULIB_POSIXCHECK
# undef unlinkat
# if HAVE_RAW_DECL_UNLINKAT
_GL_WARN_ON_USE (unlinkat, "unlinkat is not portable - "
"use gnulib module openat for portability");
# endif
#endif
#if 0
/* Pause the execution of the current thread for N microseconds.
Returns 0 on completion, or -1 on range error.
See the POSIX:2001 specification
<https://pubs.opengroup.org/onlinepubs/009695399/functions/usleep.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef usleep
# define usleep rpl_usleep
# endif
_GL_FUNCDECL_RPL (usleep, int, (useconds_t n));
_GL_CXXALIAS_RPL (usleep, int, (useconds_t n));
# else
# if !1
_GL_FUNCDECL_SYS (usleep, int, (useconds_t n));
# endif
/* Need to cast, because on Haiku, the first parameter is
unsigned int n. */
_GL_CXXALIAS_SYS_CAST (usleep, int, (useconds_t n));
# endif
_GL_CXXALIASWARN (usleep);
#elif defined GNULIB_POSIXCHECK
# undef usleep
# if HAVE_RAW_DECL_USLEEP
_GL_WARN_ON_USE (usleep, "usleep is unportable - "
"use gnulib module usleep for portability");
# endif
#endif
#if 0
/* Write up to COUNT bytes starting at BUF to file descriptor FD.
See the POSIX:2008 specification
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html>. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef write
# define write rpl_write
# endif
_GL_FUNCDECL_RPL (write, ssize_t, (int fd, const void *buf, size_t count)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (write, ssize_t, (int fd, const void *buf, size_t count));
# else
/* Need to cast, because on mingw, the third parameter is
unsigned int count
and the return type is 'int'. */
_GL_CXXALIAS_SYS_CAST (write, ssize_t, (int fd, const void *buf, size_t count));
# endif
_GL_CXXALIASWARN (write);
#endif
_GL_INLINE_HEADER_END
#endif /* _GL_UNISTD_H */
#endif /* _GL_INCLUDING_UNISTD_H */
#endif /* _GL_UNISTD_H */
| 77,377 | 2,175 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/remote-stub.c | /* clang-format off */
/* Template for the remote job exportation interface to GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
#include "third_party/make/filedef.h"
#include "third_party/make/job.h"
#include "third_party/make/commands.h"
char *remote_description = 0;
/* Call once at startup even if no commands are run. */
void
remote_setup (void)
{
}
/* Called before exit. */
void
remote_cleanup (void)
{
}
/* Return nonzero if the next job should be done remotely. */
int
start_remote_job_p (int first_p UNUSED)
{
return 0;
}
/* Start a remote job running the command in ARGV,
with environment from ENVP. It gets standard input from STDIN_FD. On
failure, return nonzero. On success, return zero, and set *USED_STDIN
to nonzero if it will actually use STDIN_FD, zero if not, set *ID_PTR to
a unique identification, and set *IS_REMOTE to zero if the job is local,
nonzero if it is remote (meaning *ID_PTR is a process ID). */
int
start_remote_job (char **argv UNUSED, char **envp UNUSED, int stdin_fd UNUSED,
int *is_remote UNUSED, pid_t *id_ptr UNUSED,
int *used_stdin UNUSED)
{
return -1;
}
/* Get the status of a dead remote child. Block waiting for one to die
if BLOCK is nonzero. Set *EXIT_CODE_PTR to the exit status, *SIGNAL_PTR
to the termination signal or zero if it exited normally, and *COREDUMP_PTR
nonzero if it dumped core. Return the ID of the child that died,
0 if we would have to block and !BLOCK, or < 0 if there were none. */
int
remote_status (int *exit_code_ptr UNUSED, int *signal_ptr UNUSED,
int *coredump_ptr UNUSED, int block UNUSED)
{
errno = ECHILD;
return -1;
}
/* Block asynchronous notification of remote child death.
If this notification is done by raising the child termination
signal, do not block that signal. */
void
block_remote_children (void)
{
return;
}
/* Restore asynchronous notification of remote child death.
If this is done by raising the child termination signal,
do not unblock that signal. */
void
unblock_remote_children (void)
{
return;
}
/* Send signal SIG to child ID. Return 0 if successful, -1 if not. */
int
remote_kill (pid_t id UNUSED, int sig UNUSED)
{
return -1;
}
| 2,962 | 101 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/stripslash.c | /* clang-format off */
/* stripslash.c -- remove redundant trailing slashes from a file name
Copyright (C) 1990, 2001, 2003-2006, 2009-2020 Free Software Foundation,
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; 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 <https://www.gnu.org/licenses/>. */
#include "third_party/make/config.h"
#include "third_party/make/dirname.h"
/* Remove trailing slashes from FILE. Return true if a trailing slash
was removed. This is useful when using file name completion from a
shell that adds a "/" after directory names (such as tcsh and
bash), because on symlinks to directories, several system calls
have different semantics according to whether a trailing slash is
present. */
bool
strip_trailing_slashes (char *file)
{
char *base = last_component (file);
char *base_lim;
bool had_slash;
/* last_component returns "" for file system roots, but we need to turn
"///" into "/". */
if (! *base)
base = file;
base_lim = base + base_len (base);
had_slash = (*base_lim != '\0');
*base_lim = '\0';
return had_slash;
}
| 1,627 | 47 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/fd-hook.h | /* clang-format off */
/* Hook for making file descriptor functions close(), ioctl() extensible.
Copyright (C) 2009-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#ifndef FD_HOOK_H
#define FD_HOOK_H
#ifdef __cplusplus
extern "C" {
#endif
/* Currently, this entire code is only needed for the handling of sockets
on native Windows platforms. */
#if WINDOWS_SOCKETS
/* Type of function that closes FD. */
typedef int (*gl_close_fn) (int fd);
/* Type of function that applies a control request to FD. */
typedef int (*gl_ioctl_fn) (int fd, int request, void *arg);
/* An element of the list of file descriptor hooks.
In CLOS (Common Lisp Object System) speak, it consists of an "around"
method for the close() function and an "around" method for the ioctl()
function.
The fields of this structure are considered private. */
struct fd_hook
{
/* Doubly linked list. */
struct fd_hook *private_next;
struct fd_hook *private_prev;
/* Function that treats the types of FD that it knows about and calls
execute_close_hooks (REMAINING_LIST, PRIMARY, FD) as a fallback. */
int (*private_close_fn) (const struct fd_hook *remaining_list,
gl_close_fn primary,
int fd);
/* Function that treats the types of FD that it knows about and calls
execute_ioctl_hooks (REMAINING_LIST, PRIMARY, FD, REQUEST, ARG) as a
fallback. */
int (*private_ioctl_fn) (const struct fd_hook *remaining_list,
gl_ioctl_fn primary,
int fd, int request, void *arg);
};
/* This type of function closes FD, applying special knowledge for the FD
types it knows about, and calls
execute_close_hooks (REMAINING_LIST, PRIMARY, FD)
for the other FD types.
In CLOS speak, REMAINING_LIST is the remaining list of "around" methods,
and PRIMARY is the "primary" method for close(). */
typedef int (*close_hook_fn) (const struct fd_hook *remaining_list,
gl_close_fn primary,
int fd);
/* Execute the close hooks in REMAINING_LIST, with PRIMARY as "primary" method.
Return 0 or -1, like close() would do. */
extern int execute_close_hooks (const struct fd_hook *remaining_list,
gl_close_fn primary,
int fd);
/* Execute all close hooks, with PRIMARY as "primary" method.
Return 0 or -1, like close() would do. */
extern int execute_all_close_hooks (gl_close_fn primary, int fd);
/* This type of function applies a control request to FD, applying special
knowledge for the FD types it knows about, and calls
execute_ioctl_hooks (REMAINING_LIST, PRIMARY, FD, REQUEST, ARG)
for the other FD types.
In CLOS speak, REMAINING_LIST is the remaining list of "around" methods,
and PRIMARY is the "primary" method for ioctl(). */
typedef int (*ioctl_hook_fn) (const struct fd_hook *remaining_list,
gl_ioctl_fn primary,
int fd, int request, void *arg);
/* Execute the ioctl hooks in REMAINING_LIST, with PRIMARY as "primary" method.
Return 0 or -1, like ioctl() would do. */
extern int execute_ioctl_hooks (const struct fd_hook *remaining_list,
gl_ioctl_fn primary,
int fd, int request, void *arg);
/* Execute all ioctl hooks, with PRIMARY as "primary" method.
Return 0 or -1, like ioctl() would do. */
extern int execute_all_ioctl_hooks (gl_ioctl_fn primary,
int fd, int request, void *arg);
/* Add a function pair to the list of file descriptor hooks.
CLOSE_HOOK and IOCTL_HOOK may be NULL, indicating no change.
The LINK variable points to a piece of memory which is guaranteed to be
accessible until the corresponding call to unregister_fd_hook. */
extern void register_fd_hook (close_hook_fn close_hook, ioctl_hook_fn ioctl_hook,
struct fd_hook *link);
/* Removes a hook from the list of file descriptor hooks. */
extern void unregister_fd_hook (struct fd_hook *link);
#endif
#ifdef __cplusplus
}
#endif
#endif /* FD_HOOK_H */
| 4,858 | 121 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/alloca.h | /* clang-format off */
/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* Memory allocation on the stack.
Copyright (C) 1995, 1999, 2001-2004, 2006-2020 Free Software Foundation,
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; either version 3, 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/>.
*/
/* Avoid using the symbol _ALLOCA_H here, as Bison assumes _ALLOCA_H
means there is a real alloca function. */
#ifndef _GL_ALLOCA_H
#define _GL_ALLOCA_H
/* alloca (N) returns a pointer to N bytes of memory
allocated on the stack, which will last until the function returns.
Use of alloca should be avoided:
- inside arguments of function calls - undefined behaviour,
- in inline functions - the allocation may actually last until the
calling function returns,
- for huge N (say, N >= 65536) - you never know how large (or small)
the stack is, and when the stack cannot fulfill the memory allocation
request, the program just crashes.
*/
#ifndef alloca
# ifdef __GNUC__
/* Some version of mingw have an <alloca.h> that causes trouble when
included after 'alloca' gets defined as a macro. As a workaround, include
this <alloca.h> first and define 'alloca' as a macro afterwards. */
# if (defined _WIN32 && ! defined __CYGWIN__) && 1
# endif
# define alloca __builtin_alloca
# elif defined _AIX
# define alloca __alloca
# elif defined _MSC_VER
# define alloca _alloca
# elif defined __DECC && defined __VMS
# define alloca __ALLOCA
# elif defined __TANDEM && defined _TNS_E_TARGET
# ifdef __cplusplus
extern "C"
# endif
void *_alloca (unsigned short);
# pragma intrinsic (_alloca)
# define alloca _alloca
# elif defined __MVS__
# else
# ifdef __cplusplus
extern "C"
# endif
void *alloca (size_t);
# endif
#endif
#endif /* _GL_ALLOCA_H */
| 2,340 | 70 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/remake.c | /* clang-format off */
/* Basic dependency engine for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
#include "third_party/make/filedef.h"
#include "third_party/make/job.h"
#include "third_party/make/commands.h"
#include "third_party/make/dep.h"
#include "third_party/make/variable.h"
#include "third_party/make/debug.h"
/* The test for circular dependencies is based on the 'updating' bit in
'struct file'. However, double colon targets have separate 'struct
file's; make sure we always use the base of the double colon chain. */
#define start_updating(_f) (((_f)->double_colon ? (_f)->double_colon : (_f))\
->updating = 1)
#define finish_updating(_f) (((_f)->double_colon ? (_f)->double_colon : (_f))\
->updating = 0)
#define is_updating(_f) (((_f)->double_colon ? (_f)->double_colon : (_f))\
->updating)
/* Incremented when a command is started (under -n, when one would be). */
unsigned int commands_started = 0;
/* Set to the goal dependency. Mostly needed for remaking makefiles. */
static struct goaldep *goal_list;
static struct dep *goal_dep;
/* Current value for pruning the scan of the goal chain.
All files start with considered == 0. */
static unsigned int considered = 0;
static enum update_status update_file (struct file *file, unsigned int depth);
static enum update_status update_file_1 (struct file *file, unsigned int depth);
static enum update_status check_dep (struct file *file, unsigned int depth,
FILE_TIMESTAMP this_mtime, int *must_make);
static enum update_status touch_file (struct file *file);
static void remake_file (struct file *file);
static FILE_TIMESTAMP name_mtime (const char *name);
static const char *library_search (const char *lib, FILE_TIMESTAMP *mtime_ptr);
/* Remake all the goals in the 'struct dep' chain GOALS. Return -1 if nothing
was done, 0 if all goals were updated successfully, or 1 if a goal failed.
If rebuilding_makefiles is nonzero, these goals are makefiles, so -t, -q,
and -n should be disabled for them unless they were also command-line
targets, and we should only make one goal at a time and return as soon as
one goal whose 'changed' member is nonzero is successfully made. */
enum update_status
update_goal_chain (struct goaldep *goaldeps)
{
int t = touch_flag, q = question_flag, n = just_print_flag;
enum update_status status = us_none;
/* Duplicate the chain so we can remove things from it. */
struct dep *goals = copy_dep_chain ((struct dep *)goaldeps);
goal_list = rebuilding_makefiles ? goaldeps : NULL;
#define MTIME(file) (rebuilding_makefiles ? file_mtime_no_search (file) \
: file_mtime (file))
/* Start a fresh batch of consideration. */
++considered;
/* Update all the goals until they are all finished. */
while (goals != 0)
{
struct dep *g, *lastgoal;
/* Start jobs that are waiting for the load to go down. */
start_waiting_jobs ();
/* Wait for a child to die. */
reap_children (1, 0);
lastgoal = 0;
g = goals;
while (g != 0)
{
/* Iterate over all double-colon entries for this file. */
struct file *file;
int stop = 0, any_not_updated = 0;
goal_dep = g;
for (file = g->file->double_colon ? g->file->double_colon : g->file;
file != NULL;
file = file->prev)
{
unsigned int ocommands_started;
enum update_status fail;
file->dontcare = ANY_SET (g->flags, RM_DONTCARE);
check_renamed (file);
if (rebuilding_makefiles)
{
if (file->cmd_target)
{
touch_flag = t;
question_flag = q;
just_print_flag = n;
}
else
touch_flag = question_flag = just_print_flag = 0;
}
/* Save the old value of 'commands_started' so we can compare
later. It will be incremented when any commands are
actually run. */
ocommands_started = commands_started;
fail = update_file (file, rebuilding_makefiles ? 1 : 0);
check_renamed (file);
/* Set the goal's 'changed' flag if any commands were started
by calling update_file above. We check this flag below to
decide when to give an "up to date" diagnostic. */
if (commands_started > ocommands_started)
g->changed = 1;
stop = 0;
if ((fail || file->updated) && status < us_question)
{
/* We updated this goal. Update STATUS and decide whether
to stop. */
if (file->update_status)
{
/* Updating failed, or -q triggered. The STATUS value
tells our caller which. */
status = file->update_status;
/* If -q just triggered, stop immediately. It doesn't
matter how much more we run, since we already know
the answer to return. */
stop = (question_flag && !keep_going_flag
&& !rebuilding_makefiles);
}
else
{
FILE_TIMESTAMP mtime = MTIME (file);
check_renamed (file);
if (file->updated && g->changed &&
mtime != file->mtime_before_update)
{
/* Updating was done. If this is a makefile and
just_print_flag or question_flag is set (meaning
-n or -q was given and this file was specified
as a command-line target), don't change STATUS.
If STATUS is changed, we will get re-exec'd, and
enter an infinite loop. */
if (!rebuilding_makefiles
|| (!just_print_flag && !question_flag))
status = us_success;
if (rebuilding_makefiles && file->dontcare)
/* This is a default makefile; stop remaking. */
stop = 1;
}
}
}
/* Keep track if any double-colon entry is not finished.
When they are all finished, the goal is finished. */
any_not_updated |= !file->updated;
file->dontcare = 0;
if (stop)
break;
}
/* Reset FILE since it is null at the end of the loop. */
file = g->file;
if (stop || !any_not_updated)
{
/* If we have found nothing whatever to do for the goal,
print a message saying nothing needs doing. */
if (!rebuilding_makefiles
/* If the update_status is success, we updated successfully
or not at all. G->changed will have been set above if
any commands were actually started for this goal. */
&& file->update_status == us_success && !g->changed
/* Never give a message under -s or -q. */
&& !run_silent && !question_flag)
OS (message, 1, ((file->phony || file->cmds == 0)
? _("Nothing to be done for '%s'.")
: _("'%s' is up to date.")),
file->name);
/* This goal is finished. Remove it from the chain. */
if (lastgoal == 0)
goals = g->next;
else
lastgoal->next = g->next;
/* Free the storage. */
free (g);
g = lastgoal == 0 ? goals : lastgoal->next;
if (stop)
break;
}
else
{
lastgoal = g;
g = g->next;
}
}
/* If we reached the end of the dependency graph update CONSIDERED
for the next pass. */
if (g == 0)
++considered;
}
if (rebuilding_makefiles)
{
touch_flag = t;
question_flag = q;
just_print_flag = n;
}
return status;
}
/* If we're rebuilding an included makefile that failed, and we care
about errors, show an error message the first time. */
void
show_goal_error (void)
{
struct goaldep *goal;
if ((goal_dep->flags & (RM_INCLUDED|RM_DONTCARE)) != RM_INCLUDED)
return;
for (goal = goal_list; goal; goal = goal->next)
if (goal_dep->file == goal->file)
{
if (goal->error)
{
OSS (error, &goal->floc, "%s: %s",
goal->file->name, strerror ((int)goal->error));
goal->error = 0;
}
return;
}
}
/* If FILE is not up to date, execute the commands for it.
Return 0 if successful, non-0 if unsuccessful;
but with some flag settings, just call 'exit' if unsuccessful.
DEPTH is the depth in recursions of this function.
We increment it during the consideration of our dependencies,
then decrement it again after finding out whether this file
is out of date.
If there are multiple double-colon entries for FILE,
each is considered in turn. */
static enum update_status
update_file (struct file *file, unsigned int depth)
{
enum update_status status = us_success;
struct file *f;
f = file->double_colon ? file->double_colon : file;
/* Prune the dependency graph: if we've already been here on _this_
pass through the dependency graph, we don't have to go any further.
We won't reap_children until we start the next pass, so no state
change is possible below here until then. */
if (f->considered == considered)
{
/* Check for the case where a target has been tried and failed but
the diagnostics haven't been issued. If we need the diagnostics
then we will have to continue. */
if (!(f->updated && f->update_status > us_none
&& !f->dontcare && f->no_diag))
{
DBF (DB_VERBOSE, _("Pruning file '%s'.\n"));
return f->command_state == cs_finished ? f->update_status : us_success;
}
}
/* This loop runs until we start commands for a double colon rule, or until
the chain is exhausted. */
for (; f != 0; f = f->prev)
{
enum update_status new;
f->considered = considered;
new = update_file_1 (f, depth);
check_renamed (f);
/* Clean up any alloca() used during the update. */
void *volatile wat = alloca (0);
/* If we got an error, don't bother with double_colon etc. */
if (new && !keep_going_flag)
return new;
if (f->command_state == cs_running
|| f->command_state == cs_deps_running)
/* Don't run other :: rules for this target until
this rule is finished. */
return us_success;
if (new > status)
status = new;
}
return status;
}
/* Show a message stating the target failed to build. */
static void
complain (struct file *file)
{
/* If this file has no_diag set then it means we tried to update it
before in the dontcare mode and failed. The target that actually
failed is not necessarily this file but could be one of its direct
or indirect dependencies. So traverse this file's dependencies and
find the one that actually caused the failure. */
struct dep *d;
for (d = file->deps; d != 0; d = d->next)
{
if (d->file->updated && d->file->update_status > us_none && file->no_diag)
{
complain (d->file);
break;
}
}
if (d == 0)
{
show_goal_error ();
/* Didn't find any dependencies to complain about. */
if (file->parent)
{
size_t l = strlen (file->name) + strlen (file->parent->name) + 4;
const char *m = _("%sNo rule to make target '%s', needed by '%s'%s");
if (!keep_going_flag)
fatal (NILF, l, m, "", file->name, file->parent->name, "");
error (NILF, l, m, "*** ", file->name, file->parent->name, ".");
}
else
{
size_t l = strlen (file->name) + 4;
const char *m = _("%sNo rule to make target '%s'%s");
if (!keep_going_flag)
fatal (NILF, l, m, "", file->name, "");
error (NILF, l, m, "*** ", file->name, ".");
}
file->no_diag = 0;
}
}
/* Consider a single 'struct file' and update it as appropriate.
Return 0 on success, or non-0 on failure. */
static enum update_status
update_file_1 (struct file *file, unsigned int depth)
{
enum update_status dep_status = us_success;
FILE_TIMESTAMP this_mtime;
int noexist, must_make, deps_changed;
struct file *ofile;
struct dep *d, *ad;
struct dep amake;
int running = 0;
DBF (DB_VERBOSE, _("Considering target file '%s'.\n"));
if (file->updated)
{
if (file->update_status > us_none)
{
DBF (DB_VERBOSE,
_("Recently tried and failed to update file '%s'.\n"));
/* If the file we tried to make is marked no_diag then no message
was printed about it when it failed during the makefile rebuild.
If we're trying to build it again in the normal rebuild, print a
message now. */
if (file->no_diag && !file->dontcare)
complain (file);
return file->update_status;
}
DBF (DB_VERBOSE, _("File '%s' was considered already.\n"));
return 0;
}
switch (file->command_state)
{
case cs_not_started:
case cs_deps_running:
break;
case cs_running:
DBF (DB_VERBOSE, _("Still updating file '%s'.\n"));
return 0;
case cs_finished:
DBF (DB_VERBOSE, _("Finished updating file '%s'.\n"));
return file->update_status;
default:
abort ();
}
/* Determine whether the diagnostics will be issued should this update
fail. */
file->no_diag = file->dontcare;
++depth;
/* Notice recursive update of the same file. */
start_updating (file);
/* We might change file if we find a different one via vpath;
remember this one to turn off updating. */
ofile = file;
/* Looking at the file's modtime beforehand allows the possibility
that its name may be changed by a VPATH search, and thus it may
not need an implicit rule. If this were not done, the file
might get implicit commands that apply to its initial name, only
to have that name replaced with another found by VPATH search. */
this_mtime = file_mtime (file);
check_renamed (file);
noexist = this_mtime == NONEXISTENT_MTIME;
if (noexist)
DBF (DB_BASIC, _("File '%s' does not exist.\n"));
else if (ORDINARY_MTIME_MIN <= this_mtime && this_mtime <= ORDINARY_MTIME_MAX
&& file->low_resolution_time)
{
/* Avoid spurious rebuilds due to low resolution time stamps. */
int ns = FILE_TIMESTAMP_NS (this_mtime);
if (ns != 0)
OS (error, NILF,
_("*** Warning: .LOW_RESOLUTION_TIME file '%s' has a high resolution time stamp"),
file->name);
this_mtime += FILE_TIMESTAMPS_PER_S - 1 - ns;
}
must_make = noexist;
/* If file was specified as a target with no commands,
come up with some default commands. */
if (!file->phony && file->cmds == 0 && !file->tried_implicit)
{
if (try_implicit_rule (file, depth))
DBF (DB_IMPLICIT, _("Found an implicit rule for '%s'.\n"));
else
DBF (DB_IMPLICIT, _("No implicit rule found for '%s'.\n"));
file->tried_implicit = 1;
}
if (file->cmds == 0 && !file->is_target
&& default_file != 0 && default_file->cmds != 0)
{
DBF (DB_IMPLICIT, _("Using default recipe for '%s'.\n"));
file->cmds = default_file->cmds;
}
/* Update all non-intermediate files we depend on, if necessary, and see
whether any of them is more recent than this file. We need to walk our
deps, AND the deps of any also_make targets to ensure everything happens
in the correct order. */
amake.file = file;
amake.next = file->also_make;
ad = &amake;
while (ad)
{
struct dep *lastd = 0;
/* Find the deps we're scanning */
d = ad->file->deps;
ad = ad->next;
while (d)
{
enum update_status new;
FILE_TIMESTAMP mtime;
int maybe_make;
int dontcare = 0;
check_renamed (d->file);
mtime = file_mtime (d->file);
check_renamed (d->file);
if (is_updating (d->file))
{
OSS (error, NILF, _("Circular %s <- %s dependency dropped."),
file->name, d->file->name);
/* We cannot free D here because our the caller will still have
a reference to it when we were called recursively via
check_dep below. */
if (lastd == 0)
file->deps = d->next;
else
lastd->next = d->next;
d = d->next;
continue;
}
d->file->parent = file;
maybe_make = must_make;
/* Inherit dontcare flag from our parent. */
if (rebuilding_makefiles)
{
dontcare = d->file->dontcare;
d->file->dontcare = file->dontcare;
}
new = check_dep (d->file, depth, this_mtime, &maybe_make);
if (new > dep_status)
dep_status = new;
/* Restore original dontcare flag. */
if (rebuilding_makefiles)
d->file->dontcare = dontcare;
if (! d->ignore_mtime)
must_make = maybe_make;
check_renamed (d->file);
{
struct file *f = d->file;
if (f->double_colon)
f = f->double_colon;
do
{
running |= (f->command_state == cs_running
|| f->command_state == cs_deps_running);
f = f->prev;
}
while (f != 0);
}
if (dep_status && !keep_going_flag)
break;
if (!running)
/* The prereq is considered changed if the timestamp has changed
while it was built, OR it doesn't exist. */
d->changed = ((file_mtime (d->file) != mtime)
|| (mtime == NONEXISTENT_MTIME));
lastd = d;
d = d->next;
}
}
/* Now we know whether this target needs updating.
If it does, update all the intermediate files we depend on. */
if (must_make || always_make_flag)
{
for (d = file->deps; d != 0; d = d->next)
if (d->file->intermediate)
{
enum update_status new;
int dontcare = 0;
FILE_TIMESTAMP mtime = file_mtime (d->file);
check_renamed (d->file);
d->file->parent = file;
/* Inherit dontcare flag from our parent. */
if (rebuilding_makefiles)
{
dontcare = d->file->dontcare;
d->file->dontcare = file->dontcare;
}
/* We may have already considered this file, when we didn't know
we'd need to update it. Force update_file() to consider it and
not prune it. */
d->file->considered = 0;
new = update_file (d->file, depth);
if (new > dep_status)
dep_status = new;
/* Restore original dontcare flag. */
if (rebuilding_makefiles)
d->file->dontcare = dontcare;
check_renamed (d->file);
{
struct file *f = d->file;
if (f->double_colon)
f = f->double_colon;
do
{
running |= (f->command_state == cs_running
|| f->command_state == cs_deps_running);
f = f->prev;
}
while (f != 0);
}
if (dep_status && !keep_going_flag)
break;
if (!running)
d->changed = ((file->phony && file->cmds != 0)
|| file_mtime (d->file) != mtime);
}
}
finish_updating (file);
finish_updating (ofile);
DBF (DB_VERBOSE, _("Finished prerequisites of target file '%s'.\n"));
if (running)
{
set_command_state (file, cs_deps_running);
--depth;
DBF (DB_VERBOSE, _("The prerequisites of '%s' are being made.\n"));
return 0;
}
/* If any dependency failed, give up now. */
if (dep_status)
{
/* I'm not sure if we can't just assign dep_status... */
file->update_status = dep_status == us_none ? us_failed : dep_status;
notice_finished_file (file);
--depth;
DBF (DB_VERBOSE, _("Giving up on target file '%s'.\n"));
if (depth == 0 && keep_going_flag
&& !just_print_flag && !question_flag)
OS (error, NILF,
_("Target '%s' not remade because of errors."), file->name);
return dep_status;
}
if (file->command_state == cs_deps_running)
/* The commands for some deps were running on the last iteration, but
they have finished now. Reset the command_state to not_started to
simplify later bookkeeping. It is important that we do this only
when the prior state was cs_deps_running, because that prior state
was definitely propagated to FILE's also_make's by set_command_state
(called above), but in another state an also_make may have
independently changed to finished state, and we would confuse that
file's bookkeeping (updated, but not_started is bogus state). */
set_command_state (file, cs_not_started);
/* Now record which prerequisites are more
recent than this file, so we can define $?. */
deps_changed = 0;
for (d = file->deps; d != 0; d = d->next)
{
FILE_TIMESTAMP d_mtime = file_mtime (d->file);
check_renamed (d->file);
if (! d->ignore_mtime)
{
#if 1
/* %%% In version 4, remove this code completely to
implement not remaking deps if their deps are newer
than their parents. */
if (d_mtime == NONEXISTENT_MTIME && !d->file->intermediate)
/* We must remake if this dep does not
exist and is not intermediate. */
must_make = 1;
#endif
/* Set DEPS_CHANGED if this dep actually changed. */
deps_changed |= d->changed;
}
/* Set D->changed if either this dep actually changed,
or its dependent, FILE, is older or does not exist. */
d->changed |= noexist || d_mtime > this_mtime;
if (!noexist && ISDB (DB_BASIC|DB_VERBOSE))
{
const char *fmt = 0;
if (d->ignore_mtime)
{
if (ISDB (DB_VERBOSE))
fmt = _("Prerequisite '%s' is order-only for target '%s'.\n");
}
else if (d_mtime == NONEXISTENT_MTIME)
{
if (ISDB (DB_BASIC))
fmt = _("Prerequisite '%s' of target '%s' does not exist.\n");
}
else if (d->changed)
{
if (ISDB (DB_BASIC))
fmt = _("Prerequisite '%s' is newer than target '%s'.\n");
}
else if (ISDB (DB_VERBOSE))
fmt = _("Prerequisite '%s' is older than target '%s'.\n");
if (fmt)
{
print_spaces (depth);
printf (fmt, dep_name (d), file->name);
fflush (stdout);
}
}
}
/* Here depth returns to the value it had when we were called. */
depth--;
if (file->double_colon && file->deps == 0)
{
must_make = 1;
DBF (DB_BASIC,
_("Target '%s' is double-colon and has no prerequisites.\n"));
}
else if (!noexist && file->is_target && !deps_changed && file->cmds == 0
&& !always_make_flag)
{
must_make = 0;
DBF (DB_VERBOSE,
_("No recipe for '%s' and no prerequisites actually changed.\n"));
}
else if (!must_make && file->cmds != 0 && always_make_flag)
{
must_make = 1;
DBF (DB_VERBOSE, _("Making '%s' due to always-make flag.\n"));
}
if (!must_make)
{
if (ISDB (DB_VERBOSE))
{
print_spaces (depth);
printf (_("No need to remake target '%s'"), file->name);
if (!streq (file->name, file->hname))
printf (_("; using VPATH name '%s'"), file->hname);
puts (".");
fflush (stdout);
}
notice_finished_file (file);
/* Since we don't need to remake the file, convert it to use the
VPATH filename if we found one. hfile will be either the
local name if no VPATH or the VPATH name if one was found. */
while (file)
{
file->name = file->hname;
file = file->prev;
}
return 0;
}
DBF (DB_BASIC, _("Must remake target '%s'.\n"));
/* It needs to be remade. If it's VPATH and not reset via GPATH, toss the
VPATH. */
if (!streq (file->name, file->hname))
{
DB (DB_BASIC, (_(" Ignoring VPATH name '%s'.\n"), file->hname));
file->ignore_vpath = 1;
}
/* Now, take appropriate actions to remake the file. */
remake_file (file);
if (file->command_state != cs_finished)
{
DBF (DB_VERBOSE, _("Recipe of '%s' is being run.\n"));
return 0;
}
switch (file->update_status)
{
case us_failed:
DBF (DB_BASIC, _("Failed to remake target file '%s'.\n"));
break;
case us_success:
DBF (DB_BASIC, _("Successfully remade target file '%s'.\n"));
break;
case us_question:
DBF (DB_BASIC, _("Target file '%s' needs to be remade under -q.\n"));
break;
case us_none:
break;
}
file->updated = 1;
return file->update_status;
}
/* Set FILE's 'updated' flag and re-check its mtime and the mtime's of all
files listed in its 'also_make' member. Under -t, this function also
touches FILE.
On return, FILE->update_status will no longer be us_none if it was. */
void
notice_finished_file (struct file *file)
{
struct dep *d;
int ran = file->command_state == cs_running;
int touched = 0;
file->command_state = cs_finished;
file->updated = 1;
if (touch_flag
/* The update status will be:
us_success if 0 or more commands (+ or ${MAKE}) were run and won;
us_none if this target was not remade;
>us_none if some commands were run and lost.
We touch the target if it has commands which either were not run
or won when they ran (i.e. status is 0). */
&& file->update_status == us_success)
{
if (file->cmds != 0 && file->cmds->any_recurse)
{
/* If all the command lines were recursive,
we don't want to do the touching. */
unsigned int i;
for (i = 0; i < file->cmds->ncommand_lines; ++i)
if (!(file->cmds->lines_flags[i] & COMMANDS_RECURSE))
goto have_nonrecursing;
}
else
{
have_nonrecursing:
if (file->phony)
file->update_status = us_success;
/* According to POSIX, -t doesn't affect targets with no cmds. */
else if (file->cmds != 0)
{
/* Should set file's modification date and do nothing else. */
file->update_status = touch_file (file);
/* Pretend we ran a real touch command, to suppress the
"'foo' is up to date" message. */
commands_started++;
/* Request for the timestamp to be updated (and distributed
to the double-colon entries). Simply setting ran=1 would
almost have done the trick, but messes up with the also_make
updating logic below. */
touched = 1;
}
}
}
if (file->mtime_before_update == UNKNOWN_MTIME)
file->mtime_before_update = file->last_mtime;
if ((ran && !file->phony) || touched)
{
int i = 0;
/* If -n, -t, or -q and all the commands are recursive, we ran them so
really check the target's mtime again. Otherwise, assume the target
would have been updated. */
if ((question_flag || just_print_flag || touch_flag) && file->cmds)
{
for (i = file->cmds->ncommand_lines; i > 0; --i)
if (! (file->cmds->lines_flags[i-1] & COMMANDS_RECURSE))
break;
}
/* If there were no commands at all, it's always new. */
else if (file->is_target && file->cmds == 0)
i = 1;
file->last_mtime = i == 0 ? UNKNOWN_MTIME : NEW_MTIME;
}
if (file->double_colon)
{
/* If this is a double colon rule and it is the last one to be
updated, propagate the change of modification time to all the
double-colon entries for this file.
We do it on the last update because it is important to handle
individual entries as separate rules with separate timestamps
while they are treated as targets and then as one rule with the
unified timestamp when they are considered as a prerequisite
of some target. */
struct file *f;
FILE_TIMESTAMP max_mtime = file->last_mtime;
/* Check that all rules were updated and at the same time find
the max timestamp. We assume UNKNOWN_MTIME is newer then
any other value. */
for (f = file->double_colon; f != 0 && f->updated; f = f->prev)
if (max_mtime != UNKNOWN_MTIME
&& (f->last_mtime == UNKNOWN_MTIME || f->last_mtime > max_mtime))
max_mtime = f->last_mtime;
if (f == 0)
for (f = file->double_colon; f != 0; f = f->prev)
f->last_mtime = max_mtime;
}
if (ran && file->update_status != us_none)
/* We actually tried to update FILE, which has
updated its also_make's as well (if it worked).
If it didn't work, it wouldn't work again for them.
So mark them as updated with the same status. */
for (d = file->also_make; d != 0; d = d->next)
{
d->file->command_state = cs_finished;
d->file->updated = 1;
d->file->update_status = file->update_status;
if (ran && !d->file->phony)
/* Fetch the new modification time.
We do this instead of just invalidating the cached time
so that a vpath_search can happen. Otherwise, it would
never be done because the target is already updated. */
f_mtime (d->file, 0);
}
else if (file->update_status == us_none)
/* Nothing was done for FILE, but it needed nothing done.
So mark it now as "succeeded". */
file->update_status = us_success;
}
/* Check whether another file (whose mtime is THIS_MTIME) needs updating on
account of a dependency which is file FILE. If it does, store 1 in
*MUST_MAKE_PTR. In the process, update any non-intermediate files that
FILE depends on (including FILE itself). Return nonzero if any updating
failed. */
static enum update_status
check_dep (struct file *file, unsigned int depth,
FILE_TIMESTAMP this_mtime, int *must_make_ptr)
{
struct file *ofile;
struct dep *d;
enum update_status dep_status = us_success;
++depth;
start_updating (file);
/* We might change file if we find a different one via vpath;
remember this one to turn off updating. */
ofile = file;
if (file->phony || !file->intermediate)
{
/* If this is a non-intermediate file, update it and record whether it
is newer than THIS_MTIME. */
FILE_TIMESTAMP mtime;
dep_status = update_file (file, depth);
check_renamed (file);
mtime = file_mtime (file);
check_renamed (file);
if (mtime == NONEXISTENT_MTIME || mtime > this_mtime)
*must_make_ptr = 1;
}
else
{
/* FILE is an intermediate file. */
FILE_TIMESTAMP mtime;
if (!file->phony && file->cmds == 0 && !file->tried_implicit)
{
if (try_implicit_rule (file, depth))
DBF (DB_IMPLICIT, _("Found an implicit rule for '%s'.\n"));
else
DBF (DB_IMPLICIT, _("No implicit rule found for '%s'.\n"));
file->tried_implicit = 1;
}
if (file->cmds == 0 && !file->is_target
&& default_file != 0 && default_file->cmds != 0)
{
DBF (DB_IMPLICIT, _("Using default commands for '%s'.\n"));
file->cmds = default_file->cmds;
}
check_renamed (file);
mtime = file_mtime (file);
check_renamed (file);
if (mtime != NONEXISTENT_MTIME && mtime > this_mtime)
/* If the intermediate file actually exists and is newer, then we
should remake from it. */
*must_make_ptr = 1;
else
{
/* Otherwise, update all non-intermediate files we depend on, if
necessary, and see whether any of them is more recent than the
file on whose behalf we are checking. */
struct dep *ld;
int deps_running = 0;
/* If this target is not running, set it's state so that we check it
fresh. It could be it was checked as part of an order-only
prerequisite and so wasn't rebuilt then, but should be now. */
if (file->command_state != cs_running)
{
/* If the target was waiting for a dependency it has to be
reconsidered, as that dependency might have finished. */
if (file->command_state == cs_deps_running)
file->considered = 0;
set_command_state (file, cs_not_started);
}
ld = 0;
d = file->deps;
while (d != 0)
{
enum update_status new;
int maybe_make;
if (is_updating (d->file))
{
OSS (error, NILF, _("Circular %s <- %s dependency dropped."),
file->name, d->file->name);
if (ld == 0)
{
file->deps = d->next;
free_dep (d);
d = file->deps;
}
else
{
ld->next = d->next;
free_dep (d);
d = ld->next;
}
continue;
}
d->file->parent = file;
maybe_make = *must_make_ptr;
new = check_dep (d->file, depth, this_mtime, &maybe_make);
if (new > dep_status)
dep_status = new;
if (! d->ignore_mtime)
*must_make_ptr = maybe_make;
check_renamed (d->file);
if (dep_status && !keep_going_flag)
break;
if (d->file->command_state == cs_running
|| d->file->command_state == cs_deps_running)
deps_running = 1;
ld = d;
d = d->next;
}
if (deps_running)
/* Record that some of FILE's deps are still being made.
This tells the upper levels to wait on processing it until the
commands are finished. */
set_command_state (file, cs_deps_running);
}
}
finish_updating (file);
finish_updating (ofile);
return dep_status;
}
/* Touch FILE. Return us_success if successful, us_failed if not. */
#define TOUCH_ERROR(call) do{ perror_with_name ((call), file->name); \
return us_failed; }while(0)
static enum update_status
touch_file (struct file *file)
{
if (!run_silent)
OS (message, 0, "touch %s", file->name);
/* Print-only (-n) takes precedence over touch (-t). */
if (just_print_flag)
return us_success;
#ifndef NO_ARCHIVES
if (ar_name (file->name))
return ar_touch (file->name) ? us_failed : us_success;
else
#endif
{
int fd;
EINTRLOOP (fd, open (file->name, O_RDWR | O_CREAT, 0666));
if (fd < 0)
TOUCH_ERROR ("touch: open: ");
else
{
struct stat statbuf;
char buf = 'x';
int e;
EINTRLOOP (e, fstat (fd, &statbuf));
if (e < 0)
TOUCH_ERROR ("touch: fstat: ");
/* Rewrite character 0 same as it already is. */
EINTRLOOP (e, read (fd, &buf, 1));
if (e < 0)
TOUCH_ERROR ("touch: read: ");
{
off_t o;
EINTRLOOP (o, lseek (fd, 0L, 0));
if (o < 0L)
TOUCH_ERROR ("touch: lseek: ");
}
EINTRLOOP (e, write (fd, &buf, 1));
if (e < 0)
TOUCH_ERROR ("touch: write: ");
/* If file length was 0, we just changed it, so change it back. */
if (statbuf.st_size == 0)
{
(void) close (fd);
EINTRLOOP (fd, open (file->name, O_RDWR | O_TRUNC, 0666));
if (fd < 0)
TOUCH_ERROR ("touch: open: ");
}
(void) close (fd);
}
}
return us_success;
}
/* Having checked and updated the dependencies of FILE,
do whatever is appropriate to remake FILE itself.
Return the status from executing FILE's commands. */
static void
remake_file (struct file *file)
{
if (file->cmds == 0)
{
if (file->phony)
/* Phony target. Pretend it succeeded. */
file->update_status = us_success;
else if (file->is_target)
/* This is a nonexistent target file we cannot make.
Pretend it was successfully remade. */
file->update_status = us_success;
else
{
/* This is a dependency file we cannot remake. Fail. */
if (!rebuilding_makefiles || !file->dontcare)
complain (file);
file->update_status = us_failed;
}
}
else
{
chop_commands (file->cmds);
/* The normal case: start some commands. */
if (!touch_flag || file->cmds->any_recurse)
{
execute_file_commands (file);
return;
}
/* This tells notice_finished_file it is ok to touch the file. */
file->update_status = us_success;
}
/* This does the touching under -t. */
notice_finished_file (file);
}
/* Return the mtime of a file, given a 'struct file'.
Caches the time in the struct file to avoid excess stat calls.
If the file is not found, and SEARCH is nonzero, VPATH searching and
replacement is done. If that fails, a library (-lLIBNAME) is tried and
the library's actual name (/lib/libLIBNAME.a, etc.) is substituted into
FILE. */
FILE_TIMESTAMP
f_mtime (struct file *file, int search)
{
FILE_TIMESTAMP mtime;
unsigned int propagate_timestamp;
/* File's mtime is not known; must get it from the system. */
#ifndef NO_ARCHIVES
if (ar_name (file->name))
{
/* This file is an archive-member reference. */
char *arname, *memname;
struct file *arfile;
time_t member_date;
/* Find the archive's name. */
ar_parse_name (file->name, &arname, &memname);
/* Find the modification time of the archive itself.
Also allow for its name to be changed via VPATH search. */
arfile = lookup_file (arname);
if (arfile == 0)
arfile = enter_file (strcache_add (arname));
mtime = f_mtime (arfile, search);
check_renamed (arfile);
if (search && strcmp (arfile->hname, arname))
{
/* The archive's name has changed.
Change the archive-member reference accordingly. */
char *name;
size_t arlen, memlen;
arlen = strlen (arfile->hname);
memlen = strlen (memname);
name = alloca (arlen + 1 + memlen + 2);
memcpy (name, arfile->hname, arlen);
name[arlen] = '(';
memcpy (name + arlen + 1, memname, memlen);
name[arlen + 1 + memlen] = ')';
name[arlen + 1 + memlen + 1] = '\0';
/* If the archive was found with GPATH, make the change permanent;
otherwise defer it until later. */
if (arfile->name == arfile->hname)
rename_file (file, strcache_add (name));
else
rehash_file (file, strcache_add (name));
check_renamed (file);
}
free (arname);
file->low_resolution_time = 1;
if (mtime == NONEXISTENT_MTIME)
/* The archive doesn't exist, so its members don't exist either. */
return NONEXISTENT_MTIME;
member_date = ar_member_date (file->hname);
mtime = (member_date == (time_t) -1
? NONEXISTENT_MTIME
: file_timestamp_cons (file->hname, member_date, 0));
}
else
#endif
{
mtime = name_mtime (file->name);
if (mtime == NONEXISTENT_MTIME && search && !file->ignore_vpath)
{
/* If name_mtime failed, search VPATH. */
const char *name = vpath_search (file->name, &mtime, NULL, NULL);
if (name
/* Last resort, is it a library (-lxxx)? */
|| (file->name[0] == '-' && file->name[1] == 'l'
&& (name = library_search (file->name, &mtime)) != 0))
{
size_t name_len;
if (mtime != UNKNOWN_MTIME)
/* vpath_search and library_search store UNKNOWN_MTIME
if they didn't need to do a stat call for their work. */
file->last_mtime = mtime;
/* If we found it in VPATH, see if it's in GPATH too; if so,
change the name right now; if not, defer until after the
dependencies are updated. */
name_len = strlen (name) - strlen (file->name) - 1;
if (gpath_search (name, name_len))
{
rename_file (file, name);
check_renamed (file);
return file_mtime (file);
}
rehash_file (file, name);
check_renamed (file);
/* If the result of a vpath search is -o or -W, preserve it.
Otherwise, find the mtime of the resulting file. */
if (mtime != OLD_MTIME && mtime != NEW_MTIME)
mtime = name_mtime (name);
}
}
}
/* Files can have bogus timestamps that nothing newly made will be
"newer" than. Updating their dependents could just result in loops.
So notify the user of the anomaly with a warning.
We only need to do this once, for now. */
if (!clock_skew_detected
&& mtime != NONEXISTENT_MTIME && mtime != NEW_MTIME
&& !file->updated)
{
static FILE_TIMESTAMP adjusted_now;
FILE_TIMESTAMP adjusted_mtime = mtime;
#if defined(WINDOWS32) || defined(__MSDOS__)
/* Experimentation has shown that FAT filesystems can set file times
up to 3 seconds into the future! Play it safe. */
#define FAT_ADJ_OFFSET (FILE_TIMESTAMP) 3
FILE_TIMESTAMP adjustment = FAT_ADJ_OFFSET << FILE_TIMESTAMP_LO_BITS;
if (ORDINARY_MTIME_MIN + adjustment <= adjusted_mtime)
adjusted_mtime -= adjustment;
#endif
/* If the file's time appears to be in the future, update our
concept of the present and try once more. */
if (adjusted_now < adjusted_mtime)
{
int resolution;
FILE_TIMESTAMP now = file_timestamp_now (&resolution);
adjusted_now = now + (resolution - 1);
if (adjusted_now < adjusted_mtime)
{
double from_now =
(FILE_TIMESTAMP_S (mtime) - FILE_TIMESTAMP_S (now)
+ ((FILE_TIMESTAMP_NS (mtime) - FILE_TIMESTAMP_NS (now))
/ 1e9));
char from_now_string[100];
if (from_now >= 99 && from_now <= ULONG_MAX)
sprintf (from_now_string, "%lu", (unsigned long) from_now);
else
sprintf (from_now_string, "%.2g", from_now);
OSS (error, NILF,
_("Warning: File '%s' has modification time %s s in the future"),
file->name, from_now_string);
clock_skew_detected = 1;
}
}
}
/* Store the mtime into all the entries for this file for which it is safe
to do so: avoid propagating timestamps to double-colon rules that haven't
been examined so they're run or not based on the pre-update timestamp. */
if (file->double_colon)
file = file->double_colon;
propagate_timestamp = file->updated;
do
{
/* If this file is not implicit but it is intermediate then it was
made so by the .INTERMEDIATE target. If this file has never
been built by us but was found now, it existed before make
started. So, turn off the intermediate bit so make doesn't
delete it, since it didn't create it. */
if (mtime != NONEXISTENT_MTIME && file->command_state == cs_not_started
&& !file->tried_implicit && file->intermediate)
file->intermediate = 0;
if (file->updated == propagate_timestamp)
file->last_mtime = mtime;
file = file->prev;
}
while (file != 0);
return mtime;
}
/* Return the mtime of the file or archive-member reference NAME. */
/* First, we check with stat(). If the file does not exist, then we return
NONEXISTENT_MTIME. If it does, and the symlink check flag is set, then
examine each indirection of the symlink and find the newest mtime.
This causes one duplicate stat() when -L is being used, but the code is
much cleaner. */
static FILE_TIMESTAMP
name_mtime (const char *name)
{
FILE_TIMESTAMP mtime;
struct stat st;
int e;
#if defined(WINDOWS32)
{
char tem[MAXPATHLEN], *tstart, *tend;
const char *p = name + strlen (name);
/* Remove any trailing slashes and "."/"..". MS-Windows stat
fails on valid directories if NAME ends in a slash, and we need
to emulate the Posix behavior where stat on "foo/" or "foo/."
succeeds ONLY if "foo" is a directory. */
if (p > name)
{
memcpy (tem, name, p - name + 1);
tstart = tem;
if (tstart[1] == ':')
tstart += 2;
tend = tem + (p - name - 1);
if (*tend == '.' && tend > tstart)
tend--;
if (*tend == '.' && tend > tstart)
tend--;
for ( ; tend > tstart && (*tend == '/' || *tend == '\\'); tend--)
*tend = '\0';
}
else
{
tem[0] = '\0';
tend = &tem[0];
}
e = stat (tem, &st);
if (e == 0 && !_S_ISDIR (st.st_mode) && tend < tem + (p - name - 1))
{
errno = ENOTDIR;
e = -1;
}
}
#else
EINTRLOOP (e, stat (name, &st));
#endif
if (e == 0)
mtime = FILE_TIMESTAMP_STAT_MODTIME (name, st);
else if (errno == ENOENT || errno == ENOTDIR)
mtime = NONEXISTENT_MTIME;
else
{
perror_with_name ("stat: ", name);
return NONEXISTENT_MTIME;
}
/* If we get here we either found it, or it doesn't exist.
If it doesn't exist see if we can use a symlink mtime instead. */
#ifdef MAKE_SYMLINKS
#ifndef S_ISLNK
# define S_ISLNK(_m) (((_m)&S_IFMT)==S_IFLNK)
#endif
if (check_symlink_flag && strlen (name) <= GET_PATH_MAX)
{
PATH_VAR (lpath);
/* Check each symbolic link segment (if any). Find the latest mtime
amongst all of them (and the target file of course).
Note that we have already successfully dereferenced all the links
above. So, if we run into any error trying to lstat(), or
readlink(), or whatever, something bizarre-o happened. Just give up
and use whatever mtime we've already computed at that point. */
strcpy (lpath, name);
while (1)
{
FILE_TIMESTAMP ltime;
PATH_VAR (lbuf);
long llen;
char *p;
EINTRLOOP (e, lstat (lpath, &st));
if (e)
{
/* Just take what we have so far. */
if (errno != ENOENT && errno != ENOTDIR)
perror_with_name ("lstat: ", lpath);
break;
}
/* If this is not a symlink, we're done (we started with the real
file's mtime so we don't need to test it again). */
if (!S_ISLNK (st.st_mode))
break;
/* If this mtime is newer than what we had, keep the new one. */
ltime = FILE_TIMESTAMP_STAT_MODTIME (lpath, st);
if (ltime > mtime)
mtime = ltime;
/* Set up to check the file pointed to by this link. */
EINTRLOOP (llen, readlink (lpath, lbuf, GET_PATH_MAX));
if (llen < 0)
{
/* Eh? Just take what we have. */
perror_with_name ("readlink: ", lpath);
break;
}
lbuf[llen] = '\0';
/* If the target is fully-qualified or the source is just a
filename, then the new path is the target. Otherwise it's the
source directory plus the target. */
if (lbuf[0] == '/' || (p = strrchr (lpath, '/')) == NULL)
strcpy (lpath, lbuf);
else if ((p - lpath) + llen + 2 > GET_PATH_MAX)
/* Eh? Path too long! Again, just go with what we have. */
break;
else
/* Create the next step in the symlink chain. */
strcpy (p+1, lbuf);
}
}
#endif
return mtime;
}
/* Search for a library file specified as -lLIBNAME, searching for a
suitable library file in the system library directories and the VPATH
directories. */
static const char *
library_search (const char *lib, FILE_TIMESTAMP *mtime_ptr)
{
static const char *dirs[] =
{
#if !defined(_AMIGA) && !defined(__COSMOPOLITAN__)
"/lib",
"/usr/lib",
#endif
#if defined(WINDOWS32) && !defined(LIBDIR)
/*
* This is completely up to the user at product install time. Just define
* a placeholder.
*/
#define LIBDIR "."
#endif
LIBDIR, /* Defined by configuration. */
0
};
const char *file = 0;
char *libpatterns;
FILE_TIMESTAMP mtime;
/* Loop variables for the libpatterns value. */
char *p;
const char *p2;
size_t len;
size_t liblen;
/* Information about the earliest (in the vpath sequence) match. */
unsigned int best_vpath = 0, best_path = 0;
const char **dp;
libpatterns = xstrdup (variable_expand ("$(.LIBPATTERNS)"));
/* Skip the '-l'. */
lib += 2;
liblen = strlen (lib);
/* Loop through all the patterns in .LIBPATTERNS, and search on each one.
To implement the linker-compatible behavior we have to search through
all entries in .LIBPATTERNS and choose the "earliest" one. */
p2 = libpatterns;
while ((p = find_next_token (&p2, &len)) != 0)
{
static char *buf = NULL;
static size_t buflen = 0;
static size_t libdir_maxlen = 0;
static unsigned int std_dirs = 0;
char *libbuf = variable_expand ("");
/* Expand the pattern using LIB as a replacement. */
{
char c = p[len];
char *p3, *p4;
p[len] = '\0';
p3 = find_percent (p);
if (!p3)
{
/* Give a warning if there is no pattern. */
OS (error, NILF,
_(".LIBPATTERNS element '%s' is not a pattern"), p);
p[len] = c;
continue;
}
p4 = variable_buffer_output (libbuf, p, p3-p);
p4 = variable_buffer_output (p4, lib, liblen);
p4 = variable_buffer_output (p4, p3+1, len - (p3-p));
p[len] = c;
}
/* Look first for 'libNAME.a' in the current directory. */
mtime = name_mtime (libbuf);
if (mtime != NONEXISTENT_MTIME)
{
if (mtime_ptr != 0)
*mtime_ptr = mtime;
file = strcache_add (libbuf);
/* This by definition will have the best index, so stop now. */
break;
}
/* Now try VPATH search on that. */
{
unsigned int vpath_index, path_index;
const char* f = vpath_search (libbuf, mtime_ptr ? &mtime : NULL,
&vpath_index, &path_index);
if (f)
{
/* If we have a better match, record it. */
if (file == 0 ||
vpath_index < best_vpath ||
(vpath_index == best_vpath && path_index < best_path))
{
file = f;
best_vpath = vpath_index;
best_path = path_index;
if (mtime_ptr != 0)
*mtime_ptr = mtime;
}
}
}
/* Now try the standard set of directories. */
if (!buflen)
{
for (dp = dirs; *dp != 0; ++dp)
{
size_t l = strlen (*dp);
if (l > libdir_maxlen)
libdir_maxlen = l;
std_dirs++;
}
buflen = strlen (libbuf);
buf = xmalloc (libdir_maxlen + buflen + 2);
}
else if (buflen < strlen (libbuf))
{
buflen = strlen (libbuf);
buf = xrealloc (buf, libdir_maxlen + buflen + 2);
}
{
/* Use the last std_dirs index for standard directories. This
was it will always be greater than the VPATH index. */
unsigned int vpath_index = ~((unsigned int)0) - std_dirs;
for (dp = dirs; *dp != 0; ++dp)
{
sprintf (buf, "%s/%s", *dp, libbuf);
mtime = name_mtime (buf);
if (mtime != NONEXISTENT_MTIME)
{
if (file == 0 || vpath_index < best_vpath)
{
file = strcache_add (buf);
best_vpath = vpath_index;
if (mtime_ptr != 0)
*mtime_ptr = mtime;
}
}
vpath_index++;
}
}
}
free (libpatterns);
return file;
}
| 55,908 | 1,727 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/default.c | /* Data base of default implicit rules for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* clang-format off */
#include "third_party/make/makeint.inc"
/**/
#include "third_party/make/filedef.h"
#include "third_party/make/variable.h"
#include "third_party/make/rule.h"
#include "third_party/make/dep.h"
#include "third_party/make/job.h"
#include "libc/assert.h"
#include "third_party/make/commands.h"
/* This is the default list of suffixes for suffix rules.
'.s' must come last, so that a '.o' file will be made from
a '.c' or '.p' or ... file rather than from a .s file. */
static char default_suffixes[]
= ".out .a .ln .o .c .cc .C .cpp .p .f .F .m .r .y .l .ym .yl .s .S \
.mod .sym .def .h .info .dvi .tex .texinfo .texi .txinfo \
.w .ch .web .sh .elc .el";
static struct pspec default_pattern_rules[] =
{
{ "(%)", "%",
"$(AR) $(ARFLAGS) $@ $<" },
/* The X.out rules are only in BSD's default set because
BSD Make has no null-suffix rules, so 'foo.out' and
'foo' are the same thing. */
#ifdef __COSMOPOLITAN__
{ "%.exe", "%",
"$(CP) $< $@" },
#endif
{ "%.out", "%",
"@rm -f $@ \n cp $< $@" },
/* Syntax is "ctangle foo.w foo.ch foo.c". */
{ "%.c", "%.w %.ch",
"$(CTANGLE) $^ $@" },
{ "%.tex", "%.w %.ch",
"$(CWEAVE) $^ $@" },
{ 0, 0, 0 }
};
static struct pspec default_terminal_rules[] =
{
/* RCS. */
{ "%", "%,v",
"$(CHECKOUT,v)" },
{ "%", "RCS/%,v",
"$(CHECKOUT,v)" },
{ "%", "RCS/%",
"$(CHECKOUT,v)" },
/* SCCS. */
{ "%", "s.%",
"$(GET) $(GFLAGS) $(SCCS_OUTPUT_OPTION) $<" },
{ "%", "SCCS/s.%",
"$(GET) $(GFLAGS) $(SCCS_OUTPUT_OPTION) $<" },
{ 0, 0, 0 }
};
static const char *default_suffix_rules[] =
{
".o",
"$(LINK.o) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".s",
"$(LINK.s) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".S",
"$(LINK.S) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".c",
"$(LINK.c) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".cc",
"$(LINK.cc) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".C",
"$(LINK.C) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".cpp",
"$(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".f",
"$(LINK.f) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".m",
"$(LINK.m) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".p",
"$(LINK.p) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".F",
"$(LINK.F) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".r",
"$(LINK.r) $^ $(LOADLIBES) $(LDLIBS) -o $@",
".mod",
"$(COMPILE.mod) -o $@ -e $@ $^",
".def.sym",
"$(COMPILE.def) -o $@ $<",
".sh",
"cat $< >$@ \n chmod a+x $@",
".s.o",
"$(COMPILE.s) -o $@ $<",
".S.o",
"$(COMPILE.S) -o $@ $<",
".c.o",
"$(COMPILE.c) $(OUTPUT_OPTION) $<",
".cc.o",
"$(COMPILE.cc) $(OUTPUT_OPTION) $<",
".C.o",
"$(COMPILE.C) $(OUTPUT_OPTION) $<",
".cpp.o",
"$(COMPILE.cpp) $(OUTPUT_OPTION) $<",
".f.o",
"$(COMPILE.f) $(OUTPUT_OPTION) $<",
".m.o",
"$(COMPILE.m) $(OUTPUT_OPTION) $<",
".p.o",
"$(COMPILE.p) $(OUTPUT_OPTION) $<",
".F.o",
"$(COMPILE.F) $(OUTPUT_OPTION) $<",
".r.o",
"$(COMPILE.r) $(OUTPUT_OPTION) $<",
".mod.o",
"$(COMPILE.mod) -o $@ $<",
".c.ln",
"$(LINT.c) -C$* $<",
".y.ln",
"$(YACC.y) $< \n $(LINT.c) -C$* y.tab.c \n $(RM) y.tab.c",
".l.ln",
"@$(RM) $*.c\n $(LEX.l) $< > $*.c\n$(LINT.c) -i $*.c -o $@\n $(RM) $*.c",
".y.c",
"$(YACC.y) $< \n mv -f y.tab.c $@",
".l.c",
"@$(RM) $@ \n $(LEX.l) $< > $@",
".ym.m",
"$(YACC.m) $< \n mv -f y.tab.c $@",
".lm.m",
"@$(RM) $@ \n $(LEX.m) $< > $@",
".F.f",
"$(PREPROCESS.F) $(OUTPUT_OPTION) $<",
".r.f",
"$(PREPROCESS.r) $(OUTPUT_OPTION) $<",
/* This might actually make lex.yy.c if there's no %R% directive in $*.l,
but in that case why were you trying to make $*.r anyway? */
".l.r",
"$(LEX.l) $< > $@ \n mv -f lex.yy.r $@",
".S.s",
"$(PREPROCESS.S) $< > $@",
".texinfo.info",
"$(MAKEINFO) $(MAKEINFO_FLAGS) $< -o $@",
".texi.info",
"$(MAKEINFO) $(MAKEINFO_FLAGS) $< -o $@",
".txinfo.info",
"$(MAKEINFO) $(MAKEINFO_FLAGS) $< -o $@",
".tex.dvi",
"$(TEX) $<",
".texinfo.dvi",
"$(TEXI2DVI) $(TEXI2DVI_FLAGS) $<",
".texi.dvi",
"$(TEXI2DVI) $(TEXI2DVI_FLAGS) $<",
".txinfo.dvi",
"$(TEXI2DVI) $(TEXI2DVI_FLAGS) $<",
".w.c",
"$(CTANGLE) $< - $@", /* The '-' says there is no '.ch' file. */
".web.p",
"$(TANGLE) $<",
".w.tex",
"$(CWEAVE) $< - $@", /* The '-' says there is no '.ch' file. */
".web.tex",
"$(WEAVE) $<",
0, 0,
};
static const char *default_variables[] =
{
"AR", "ar",
"ARFLAGS", "rv",
"AS", "as",
#ifdef GCC_IS_NATIVE
"CC", "gcc",
"CXX", "gcc",
"OBJC", "gcc",
#else
"CC", "cc",
"CXX", "g++",
"OBJC", "cc",
#endif
/* This expands to $(CO) $(COFLAGS) $< $@ if $@ does not exist,
and to the empty string if $@ does exist. */
"CHECKOUT,v", "+$(if $(wildcard $@),,$(CO) $(COFLAGS) $< $@)",
"CO", "co",
"COFLAGS", "",
"CPP", "$(CC) -E",
"FC", "f77",
/* System V uses these, so explicit rules using them should work.
However, there is no way to make implicit rules use them and FC. */
"F77", "$(FC)",
"F77FLAGS", "$(FFLAGS)",
"GET", SCCS_GET,
"LD", "ld",
#ifdef GCC_IS_NATIVE
"LEX", "flex",
#else
"LEX", "lex",
#endif
"LINT", "lint",
"M2C", "m2c",
#ifdef pyr
"PC", "pascal",
#else
"PC", "pc",
#endif /* pyr. */
#ifdef GCC_IS_NATIVE
"YACC", "bison -y",
#else
"YACC", "yacc", /* Or "bison -y" */
#endif
"MAKEINFO", "makeinfo",
"TEX", "tex",
"TEXI2DVI", "texi2dvi",
"WEAVE", "weave",
"CWEAVE", "cweave",
"TANGLE", "tangle",
"CTANGLE", "ctangle",
"RM", "rm -f",
"LINK.o", "$(CC) $(LDFLAGS) $(TARGET_ARCH)",
"COMPILE.c", "$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c",
"LINK.c", "$(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
"COMPILE.m", "$(OBJC) $(OBJCFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c",
"LINK.m", "$(OBJC) $(OBJCFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
"COMPILE.cc", "$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c",
#ifndef HAVE_CASE_INSENSITIVE_FS
/* On case-insensitive filesystems, treat *.C files as *.c files,
to avoid erroneously compiling C sources as C++, which will
probably fail. */
"COMPILE.C", "$(COMPILE.cc)",
#else
"COMPILE.C", "$(COMPILE.c)",
#endif
"COMPILE.cpp", "$(COMPILE.cc)",
"LINK.cc", "$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
#ifndef HAVE_CASE_INSENSITIVE_FS
"LINK.C", "$(LINK.cc)",
#else
"LINK.C", "$(LINK.c)",
#endif
"LINK.cpp", "$(LINK.cc)",
"YACC.y", "$(YACC) $(YFLAGS)",
"LEX.l", "$(LEX) $(LFLAGS) -t",
"YACC.m", "$(YACC) $(YFLAGS)",
"LEX.m", "$(LEX) $(LFLAGS) -t",
"COMPILE.f", "$(FC) $(FFLAGS) $(TARGET_ARCH) -c",
"LINK.f", "$(FC) $(FFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
"COMPILE.F", "$(FC) $(FFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c",
"LINK.F", "$(FC) $(FFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
"COMPILE.r", "$(FC) $(FFLAGS) $(RFLAGS) $(TARGET_ARCH) -c",
"LINK.r", "$(FC) $(FFLAGS) $(RFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
"COMPILE.def", "$(M2C) $(M2FLAGS) $(DEFFLAGS) $(TARGET_ARCH)",
"COMPILE.mod", "$(M2C) $(M2FLAGS) $(MODFLAGS) $(TARGET_ARCH)",
"COMPILE.p", "$(PC) $(PFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c",
"LINK.p", "$(PC) $(PFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
"LINK.s", "$(CC) $(ASFLAGS) $(LDFLAGS) $(TARGET_MACH)",
"COMPILE.s", "$(AS) $(ASFLAGS) $(TARGET_MACH)",
"LINK.S", "$(CC) $(ASFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_MACH)",
"COMPILE.S", "$(CC) $(ASFLAGS) $(CPPFLAGS) $(TARGET_MACH) -c",
"PREPROCESS.S", "$(CC) -E $(CPPFLAGS)",
"PREPROCESS.F", "$(FC) $(FFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -F",
"PREPROCESS.r", "$(FC) $(FFLAGS) $(RFLAGS) $(TARGET_ARCH) -F",
"LINT.c", "$(LINT) $(LINTFLAGS) $(CPPFLAGS) $(TARGET_ARCH)",
"OUTPUT_OPTION", "-o $@",
".LIBPATTERNS", "lib%.so lib%.a",
/* Make this assignment to avoid undefined variable warnings. */
"GNUMAKEFLAGS", "",
0, 0
};
/* Set up the default .SUFFIXES list. */
void
set_default_suffixes (void)
{
suffix_file = enter_file (strcache_add (".SUFFIXES"));
suffix_file->builtin = 1;
if (no_builtin_rules_flag)
define_variable_cname ("SUFFIXES", "", o_default, 0);
else
{
struct dep *d;
const char *p = default_suffixes;
suffix_file->deps = enter_prereqs (PARSE_SIMPLE_SEQ ((char **)&p, struct dep),
NULL);
for (d = suffix_file->deps; d; d = d->next)
d->file->builtin = 1;
define_variable_cname ("SUFFIXES", default_suffixes, o_default, 0);
}
}
/* Enter the default suffix rules as file rules. This used to be done in
install_default_implicit_rules, but that loses because we want the
suffix rules installed before reading makefiles, and the pattern rules
installed after. */
void
install_default_suffix_rules (void)
{
const char **s;
if (no_builtin_rules_flag)
return;
for (s = default_suffix_rules; *s != 0; s += 2)
{
struct file *f = enter_file (strcache_add (s[0]));
/* This function should run before any makefile is parsed. */
assert (f->cmds == 0);
f->cmds = xmalloc (sizeof (struct commands));
f->cmds->fileinfo.filenm = 0;
f->cmds->commands = xstrdup (s[1]);
f->cmds->command_lines = 0;
f->cmds->recipe_prefix = RECIPEPREFIX_DEFAULT;
f->builtin = 1;
}
}
/* Install the default pattern rules. */
void
install_default_implicit_rules (void)
{
struct pspec *p;
if (no_builtin_rules_flag)
return;
for (p = default_pattern_rules; p->target != 0; ++p)
install_pattern_rule (p, 0);
for (p = default_terminal_rules; p->target != 0; ++p)
install_pattern_rule (p, 1);
}
void
define_default_variables (void)
{
const char **s;
if (no_builtin_variables_flag)
return;
for (s = default_variables; *s != 0; s += 2)
define_variable (s[0], strlen (s[0]), s[1], o_default, 1);
}
void
undefine_default_variables (void)
{
const char **s;
for (s = default_variables; *s != 0; s += 2)
undefine_variable_global (s[0], strlen (s[0]), o_default);
}
| 11,124 | 399 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/hash.h | /* clang-format off */
/* hash.h -- decls for hash table
Copyright (C) 1995, 1999, 2002, 2010 Free Software Foundation, Inc.
Written by Greg McGary <[email protected]> <[email protected]>
GNU Make 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.
GNU Make 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/>. */
#ifndef _hash_h_
#define _hash_h_
#if defined __cplusplus || (defined __STDC__ && __STDC__) || defined WINDOWS32
# if !defined __GLIBC__ || !defined __P
# undef __P
# define __P(protos) protos
# endif
#else /* Not C++ or ANSI C. */
# undef __P
# define __P(protos) ()
/* We can get away without defining 'const' here only because in this file
it is used only inside the prototype for 'fnmatch', which is elided in
non-ANSI C where 'const' is problematical. */
#endif /* C++ or ANSI C. */
typedef unsigned long (*hash_func_t) __P((void const *key));
typedef int (*hash_cmp_func_t) __P((void const *x, void const *y));
typedef void (*hash_map_func_t) __P((void const *item));
typedef void (*hash_map_arg_func_t) __P((void const *item, void *arg));
struct hash_table
{
void **ht_vec;
hash_func_t ht_hash_1; /* primary hash function */
hash_func_t ht_hash_2; /* secondary hash function */
hash_cmp_func_t ht_compare; /* comparison function */
unsigned long ht_size; /* total number of slots (power of 2) */
unsigned long ht_capacity; /* usable slots, limited by loading-factor */
unsigned long ht_fill; /* items in table */
unsigned long ht_empty_slots; /* empty slots not including deleted slots */
unsigned long ht_collisions; /* # of failed calls to comparison function */
unsigned long ht_lookups; /* # of queries */
unsigned int ht_rehashes; /* # of times we've expanded table */
};
typedef int (*qsort_cmp_t) __P((void const *, void const *));
void hash_init __P((struct hash_table *ht, unsigned long size,
hash_func_t hash_1, hash_func_t hash_2, hash_cmp_func_t hash_cmp));
void hash_load __P((struct hash_table *ht, void *item_table,
unsigned long cardinality, unsigned long size));
void **hash_find_slot __P((struct hash_table *ht, void const *key));
void *hash_find_item __P((struct hash_table *ht, void const *key));
void *hash_insert __P((struct hash_table *ht, const void *item));
void *hash_insert_at __P((struct hash_table *ht, const void *item, void const *slot));
void *hash_delete __P((struct hash_table *ht, void const *item));
void *hash_delete_at __P((struct hash_table *ht, void const *slot));
void hash_delete_items __P((struct hash_table *ht));
void hash_free_items __P((struct hash_table *ht));
void hash_free __P((struct hash_table *ht, int free_items));
void hash_map __P((struct hash_table *ht, hash_map_func_t map));
void hash_map_arg __P((struct hash_table *ht, hash_map_arg_func_t map, void *arg));
void hash_print_stats __P((struct hash_table *ht, FILE *out_FILE));
void **hash_dump __P((struct hash_table *ht, void **vector_0, qsort_cmp_t compare));
extern unsigned jhash(unsigned char const *key, int n);
extern unsigned jhash_string(unsigned char const *key);
extern void *hash_deleted_item;
#define HASH_VACANT(item) ((item) == 0 || (void *) (item) == hash_deleted_item)
/* hash and comparison macros for case-sensitive string keys. */
/* Due to the strcache, it's not uncommon for the string pointers to
be identical. Take advantage of that to short-circuit string compares. */
#define STRING_HASH_1(KEY, RESULT) do { \
unsigned char const *_key_ = (unsigned char const *) (KEY); \
(RESULT) += jhash_string(_key_); \
} while (0)
#define return_STRING_HASH_1(KEY) do { \
unsigned long _result_ = 0; \
STRING_HASH_1 ((KEY), _result_); \
return _result_; \
} while (0)
/* No need for a second hash because jhash already provides
pretty good results. However, do evaluate the arguments
to avoid warnings. */
#define STRING_HASH_2(KEY, RESULT) do { \
(void)(KEY); \
} while (0)
#define return_STRING_HASH_2(KEY) do { \
unsigned long _result_ = 0; \
STRING_HASH_2 ((KEY), _result_); \
return _result_; \
} while (0)
#define STRING_COMPARE(X, Y, RESULT) do { \
RESULT = (X) == (Y) ? 0 : strcmp ((X), (Y)); \
} while (0)
#define return_STRING_COMPARE(X, Y) do { \
return (X) == (Y) ? 0 : strcmp ((X), (Y)); \
} while (0)
#define STRING_N_HASH_1(KEY, N, RESULT) do { \
unsigned char const *_key_ = (unsigned char const *) (KEY); \
(RESULT) += jhash(_key_, N); \
} while (0)
#define return_STRING_N_HASH_1(KEY, N) do { \
unsigned long _result_ = 0; \
STRING_N_HASH_1 ((KEY), (N), _result_); \
return _result_; \
} while (0)
/* No need for a second hash because jhash already provides
pretty good results. However, do evaluate the arguments
to avoid warnings. */
#define STRING_N_HASH_2(KEY, N, RESULT) do { \
(void)(KEY); \
(void)(N); \
} while (0)
#define return_STRING_N_HASH_2(KEY, N) do { \
unsigned long _result_ = 0; \
STRING_N_HASH_2 ((KEY), (N), _result_); \
return _result_; \
} while (0)
#define STRING_N_COMPARE(X, Y, N, RESULT) do { \
RESULT = (X) == (Y) ? 0 : memcmp ((X), (Y), (N)); \
} while (0)
#define return_STRING_N_COMPARE(X, Y, N) do { \
return (X) == (Y) ? 0 : memcmp ((X), (Y), (N)); \
} while (0)
#ifdef HAVE_CASE_INSENSITIVE_FS
/* hash and comparison macros for case-insensitive string _key_s. */
#define ISTRING_HASH_1(KEY, RESULT) do { \
unsigned char const *_key_ = (unsigned char const *) (KEY) - 1; \
while (*++_key_) \
(RESULT) += ((isupper (*_key_) ? tolower (*_key_) : *_key_) << (_key_[1] & 0xf)); \
} while (0)
#define return_ISTRING_HASH_1(KEY) do { \
unsigned long _result_ = 0; \
ISTRING_HASH_1 ((KEY), _result_); \
return _result_; \
} while (0)
#define ISTRING_HASH_2(KEY, RESULT) do { \
unsigned char const *_key_ = (unsigned char const *) (KEY) - 1; \
while (*++_key_) \
(RESULT) += ((isupper (*_key_) ? tolower (*_key_) : *_key_) << (_key_[1] & 0x7)); \
} while (0)
#define return_ISTRING_HASH_2(KEY) do { \
unsigned long _result_ = 0; \
ISTRING_HASH_2 ((KEY), _result_); \
return _result_; \
} while (0)
#define ISTRING_COMPARE(X, Y, RESULT) do { \
RESULT = (X) == (Y) ? 0 : strcasecmp ((X), (Y)); \
} while (0)
#define return_ISTRING_COMPARE(X, Y) do { \
return (X) == (Y) ? 0 : strcasecmp ((X), (Y)); \
} while (0)
#else
#define ISTRING_HASH_1(KEY, RESULT) STRING_HASH_1 ((KEY), (RESULT))
#define return_ISTRING_HASH_1(KEY) return_STRING_HASH_1 (KEY)
#define ISTRING_HASH_2(KEY, RESULT) STRING_HASH_2 ((KEY), (RESULT))
#define return_ISTRING_HASH_2(KEY) return_STRING_HASH_2 (KEY)
#define ISTRING_COMPARE(X, Y, RESULT) STRING_COMPARE ((X), (Y), (RESULT))
#define return_ISTRING_COMPARE(X, Y) return_STRING_COMPARE ((X), (Y))
#endif
/* hash and comparison macros for integer _key_s. */
#define INTEGER_HASH_1(KEY, RESULT) do { \
(RESULT) += ((unsigned long)(KEY)); \
} while (0)
#define return_INTEGER_HASH_1(KEY) do { \
unsigned long _result_ = 0; \
INTEGER_HASH_1 ((KEY), _result_); \
return _result_; \
} while (0)
#define INTEGER_HASH_2(KEY, RESULT) do { \
(RESULT) += ~((unsigned long)(KEY)); \
} while (0)
#define return_INTEGER_HASH_2(KEY) do { \
unsigned long _result_ = 0; \
INTEGER_HASH_2 ((KEY), _result_); \
return _result_; \
} while (0)
#define INTEGER_COMPARE(X, Y, RESULT) do { \
(RESULT) = X - Y; \
} while (0)
#define return_INTEGER_COMPARE(X, Y) do { \
int _result_; \
INTEGER_COMPARE (X, Y, _result_); \
return _result_; \
} while (0)
/* hash and comparison macros for address keys. */
#define ADDRESS_HASH_1(KEY, RESULT) INTEGER_HASH_1 (((unsigned long)(KEY)) >> 3, (RESULT))
#define ADDRESS_HASH_2(KEY, RESULT) INTEGER_HASH_2 (((unsigned long)(KEY)) >> 3, (RESULT))
#define ADDRESS_COMPARE(X, Y, RESULT) INTEGER_COMPARE ((X), (Y), (RESULT))
#define return_ADDRESS_HASH_1(KEY) return_INTEGER_HASH_1 (((unsigned long)(KEY)) >> 3)
#define return_ADDRESS_HASH_2(KEY) return_INTEGER_HASH_2 (((unsigned long)(KEY)) >> 3)
#define return_ADDRESS_COMPARE(X, Y) return_INTEGER_COMPARE ((X), (Y))
#endif /* not _hash_h_ */
| 8,499 | 233 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/commands.h | /* clang-format off */
/* Definition of data structures describing shell commands for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* Structure that gives the commands to make a file
and information about where these commands came from. */
struct commands
{
floc fileinfo; /* Where commands were defined. */
char *commands; /* Commands text. */
char **command_lines; /* Commands chopped up into lines. */
unsigned char *lines_flags; /* One set of flag bits for each line. */
unsigned short ncommand_lines;/* Number of command lines. */
char recipe_prefix; /* Recipe prefix for this command set. */
unsigned int any_recurse:1; /* Nonzero if any 'lines_flags' elt has */
/* the COMMANDS_RECURSE bit set. */
};
/* Bits in 'lines_flags'. */
#define COMMANDS_RECURSE 1 /* Recurses: + or $(MAKE). */
#define COMMANDS_SILENT 2 /* Silent: @. */
#define COMMANDS_NOERROR 4 /* No errors: -. */
RETSIGTYPE fatal_error_signal (int sig);
void execute_file_commands (struct file *file);
void print_commands (const struct commands *cmds);
void delete_child_targets (struct child *child);
void chop_commands (struct commands *cmds);
void set_file_variables (struct file *file);
| 1,966 | 44 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/makeint.inc | /* Miscellaneous global declarations and portability cruft for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/makedev.h"
#include "libc/calls/struct/rlimit.h"
#include "libc/calls/struct/rusage.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/siginfo.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/struct/stat.macros.h"
#include "libc/calls/weirdtypes.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/fmt.h"
#include "libc/limits.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/mem/alg.h"
#include "libc/mem/alloca.h"
#include "libc/mem/mem.h"
#include "libc/runtime/stack.h"
#include "libc/stdio/stdio.h"
#include "libc/stdio/temp.h"
#include "libc/str/locale.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prio.h"
#include "libc/sysv/consts/rlim.h"
#include "libc/sysv/consts/rlimit.h"
#include "libc/sysv/consts/rusage.h"
#include "libc/sysv/consts/s.h"
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sicode.h"
#include "libc/sysv/consts/w.h"
#include "libc/time/struct/tm.h"
#include "libc/time/time.h"
#include "libc/x/x.h"
#include "third_party/gdtoa/gdtoa.h"
#include "third_party/musl/glob.h"
/* clang-format off */
/* We use <config.h> instead of "config.h" so that a compilation
using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
(which it would do because makeint.h was found in $srcdir). */
#include "third_party/make/config.h"
#pragma GCC diagnostic ignored "-Wredundant-decls"
#undef HAVE_CONFIG_H
#define HAVE_CONFIG_H 1
/* Specify we want GNU source code. This must be defined before any
system headers are included. */
#define POSIX 1
#define _GNU_SOURCE 1
/* Disable assert() unless we're a maintainer.
Some asserts are compute-intensive. */
#ifndef MAKE_MAINTAINER_MODE
# define NDEBUG 1
#endif
/* Include the externally-visible content.
Be sure to use the local one, and not one installed on the system.
Define GMK_BUILDING_MAKE for proper selection of dllexport/dllimport
declarations for MS-Windows. */
#ifdef WINDOWS32
# define GMK_BUILDING_MAKE
#endif
#include "third_party/make/gnumake.h"
/* If we're compiling for the dmalloc debugger, turn off string inlining. */
#if defined(HAVE_DMALLOC_H) && defined(__GNUC__)
# define __NO_STRING_INLINES
#endif
#ifndef RETSIGTYPE
# define RETSIGTYPE void
#endif
#ifndef sigmask
# define sigmask(sig) (1 << ((sig) - 1))
#endif
#ifndef MAXPATHLEN
# define MAXPATHLEN 1024
#endif
#ifdef PATH_MAX
# define GET_PATH_MAX PATH_MAX
# define PATH_VAR(var) char var[PATH_MAX+1]
#else
# define NEED_GET_PATH_MAX 1
# define GET_PATH_MAX (get_path_max ())
# define PATH_VAR(var) char *var = alloca (GET_PATH_MAX+1)
unsigned int get_path_max (void);
#endif
#ifndef CHAR_BIT
# define CHAR_BIT 8
#endif
#ifndef USHRT_MAX
# define USHRT_MAX 65535
#endif
/* Nonzero if the integer type T is signed.
Use <= to avoid GCC warnings about always-false expressions. */
#define INTEGER_TYPE_SIGNED(t) ((t) -1 <= 0)
/* The minimum and maximum values for the integer type T.
Use ~ (t) 0, not -1, for portability to 1's complement hosts. */
#define INTEGER_TYPE_MINIMUM(t) \
(! INTEGER_TYPE_SIGNED (t) ? (t) 0 : ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1))
#define INTEGER_TYPE_MAXIMUM(t) (~ (t) 0 - INTEGER_TYPE_MINIMUM (t))
#ifndef CHAR_MAX
# define CHAR_MAX INTEGER_TYPE_MAXIMUM (char)
#endif
#ifdef STAT_MACROS_BROKEN
# ifdef S_ISREG
# undef S_ISREG
# endif
# ifdef S_ISDIR
# undef S_ISDIR
# endif
#endif /* STAT_MACROS_BROKEN. */
#if !defined(__attribute__) && (__GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__)
/* Don't use __attribute__ if it's not supported. */
# define ATTRIBUTE(x)
#else
# define ATTRIBUTE(x) __attribute__ (x)
#endif
/* The __-protected variants of 'format' and 'printf' attributes
are accepted by gcc versions 2.6.4 (effectively 2.7) and later. */
#if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
# define __format__ format
# define __printf__ printf
#endif
#define UNUSED ATTRIBUTE ((unused))
#define NORETURN ATTRIBUTE ((noreturn))
#if defined (STDC_HEADERS) || defined (__GNU_LIBRARY__)
# define ANSI_STRING 1
#else /* No standard headers. */
# ifdef HAVE_STRING_H
# define ANSI_STRING 1
# else
# endif
# ifdef HAVE_MEMORY_H
# endif
# ifdef HAVE_STDLIB_H
# else
# endif /* HAVE_STDLIB_H. */
#endif /* Standard headers. */
/* These should be in stdlib.h. Make sure we have them. */
#ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
# define EXIT_FAILURE 1
#endif
#ifndef ANSI_STRING
/* SCO Xenix has a buggy macro definition in <string.h>. */
#undef strerror
#if !defined(__DECC)
char *strerror (int errnum);
#endif
#endif /* !ANSI_STRING. */
#undef ANSI_STRING
#define FILE_TIMESTAMP uintmax_t
#if !defined(HAVE_STRSIGNAL)
char *strsignal (int signum);
#endif
#if !defined(HAVE_UMASK)
typedef int mode_t;
extern mode_t umask (mode_t);
#endif
/* ISDIGIT offers the following features:
- Its arg may be any int or unsigned int; it need not be an unsigned char.
- It's guaranteed to evaluate its argument exactly once.
NOTE! Make relies on this behavior, don't change it!
- It's typically faster.
POSIX 1003.2-1992 section 2.5.2.1 page 50 lines 1556-1558 says that
only '0' through '9' are digits. Prefer ISDIGIT to isdigit() unless
it's important to use the locale's definition of 'digit' even when the
host does not conform to POSIX. */
#define ISDIGIT(c) ((unsigned) (c) - '0' <= 9)
/* Test if two strings are equal. Is this worthwhile? Should be profiled. */
#define streq(a, b) \
((a) == (b) || \
(*(a) == *(b) && (*(a) == '\0' || !strcmp ((a) + 1, (b) + 1))))
/* Test if two strings are equal, but match case-insensitively on systems
which have case-insensitive filesystems. Should only be used for
filenames! */
#ifdef HAVE_CASE_INSENSITIVE_FS
# define patheq(a, b) \
((a) == (b) \
|| (tolower((unsigned char)*(a)) == tolower((unsigned char)*(b)) \
&& (*(a) == '\0' || !strcasecmp ((a) + 1, (b) + 1))))
#else
# define patheq(a, b) streq(a, b)
#endif
#define strneq(a, b, l) (strncmp ((a), (b), (l)) == 0)
#if defined(ENUM_BITFIELDS) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define ENUM_BITFIELD(bits) :bits
#else
# define ENUM_BITFIELD(bits)
#endif
/* Handle gettext and locales. */
#include "third_party/make/gettext.h"
#define _(msgid) gettext (msgid)
#define N_(msgid) gettext_noop (msgid)
#define S_(msg1,msg2,num) ngettext (msg1,msg2,num)
#ifdef WINDOWS32
# define pipe(_p) _pipe((_p), 512, O_BINARY)
# define kill(_pid,_sig) w32_kill((_pid),(_sig))
/* MSVC and Watcom C don't have ftruncate. */
# if defined(_MSC_VER) || defined(__WATCOMC__)
# define ftruncate(_fd,_len) _chsize(_fd,_len)
# endif
/* MinGW64 doesn't have _S_ISDIR. */
# ifndef _S_ISDIR
# define _S_ISDIR(m) S_ISDIR(m)
# endif
void sync_Path_environment (void);
int w32_kill (pid_t pid, int sig);
int find_and_set_default_shell (const char *token);
/* indicates whether or not we have Bourne shell */
extern int no_default_sh_exe;
/* is default_shell unixy? */
extern int unixy_shell;
/* We don't have a preferred fixed value for LOCALEDIR. */
# ifndef LOCALEDIR
# define LOCALEDIR NULL
# endif
/* Include only the minimal stuff from windows.h. */
# define WIN32_LEAN_AND_MEAN
#endif /* WINDOWS32 */
#define ANY_SET(_v,_m) (((_v)&(_m)) != 0)
#define NONE_SET(_v,_m) (! ANY_SET ((_v),(_m)))
#define MAP_NUL 0x0001
#define MAP_BLANK 0x0002
#define MAP_NEWLINE 0x0004
#define MAP_COMMENT 0x0008
#define MAP_SEMI 0x0010
#define MAP_EQUALS 0x0020
#define MAP_COLON 0x0040
#define MAP_VARSEP 0x0080
#define MAP_PIPE 0x0100
#define MAP_DOT 0x0200
#define MAP_COMMA 0x0400
/* These are the valid characters for a user-defined function. */
#define MAP_USERFUNC 0x2000
/* This means not only a '$', but skip the variable reference. */
#define MAP_VARIABLE 0x4000
/* The set of characters which are directory separators is OS-specific. */
#define MAP_DIRSEP 0x8000
#define MAP_VMSCOMMA 0x0000
#define MAP_SPACE (MAP_BLANK|MAP_NEWLINE)
/* Handle other OSs.
To overcome an issue parsing paths in a DOS/Windows environment when
built in a unix based environment, override the PATH_SEPARATOR_CHAR
definition unless being built for Cygwin. */
#if defined(HAVE_DOS_PATHS) && !defined(__CYGWIN__)
# undef PATH_SEPARATOR_CHAR
# define PATH_SEPARATOR_CHAR ';'
# define MAP_PATHSEP MAP_SEMI
#elif !defined(PATH_SEPARATOR_CHAR)
# if defined (VMS)
# define PATH_SEPARATOR_CHAR (vms_comma_separator ? ',' : ':')
# define MAP_PATHSEP (vms_comma_separator ? MAP_COMMA : MAP_SEMI)
# else
# define PATH_SEPARATOR_CHAR ':'
# define MAP_PATHSEP MAP_COLON
# endif
#elif PATH_SEPARATOR_CHAR == ':'
# define MAP_PATHSEP MAP_COLON
#elif PATH_SEPARATOR_CHAR == ';'
# define MAP_PATHSEP MAP_SEMI
#elif PATH_SEPARATOR_CHAR == ','
# define MAP_PATHSEP MAP_COMMA
#else
# error "Unknown PATH_SEPARATOR_CHAR"
#endif
#define STOP_SET(_v,_m) ANY_SET(stopchar_map[(unsigned char)(_v)],(_m))
#define ISBLANK(c) STOP_SET((c),MAP_BLANK)
#define ISSPACE(c) STOP_SET((c),MAP_SPACE)
#define NEXT_TOKEN(s) while (ISSPACE (*(s))) ++(s)
#define END_OF_TOKEN(s) while (! STOP_SET (*(s), MAP_SPACE|MAP_NUL)) ++(s)
/* We can't run setrlimit when using posix_spawn. */
extern struct rlimit stack_limit;
#define NILF ((floc *)0)
#define CSTRLEN(_s) (sizeof (_s)-1)
#define STRING_SIZE_TUPLE(_s) (_s), CSTRLEN(_s)
/* The number of bytes needed to represent the largest integer as a string. */
#define INTSTR_LENGTH CSTRLEN ("18446744073709551616")
#define DEFAULT_TTYNAME "true"
#ifdef HAVE_TTYNAME
# define TTYNAME(_f) ttyname (_f)
#else
# define TTYNAME(_f) DEFAULT_TTYNAME
#endif
/* Specify the location of elements read from makefiles. */
typedef struct
{
const char *filenm;
unsigned long lineno;
unsigned long offset;
} floc;
const char *concat (unsigned int, ...);
void message (int prefix, size_t length, const char *fmt, ...)
ATTRIBUTE ((__format__ (__printf__, 3, 4)));
void error (const floc *flocp, size_t length, const char *fmt, ...)
ATTRIBUTE ((__format__ (__printf__, 3, 4)));
void fatal (const floc *flocp, size_t length, const char *fmt, ...)
ATTRIBUTE ((noreturn, __format__ (__printf__, 3, 4)));
void out_of_memory () NORETURN;
/* When adding macros to this list be sure to update the value of
XGETTEXT_OPTIONS in the po/Makevars file. */
#define O(_t,_a,_f) _t((_a), 0, (_f))
#define OS(_t,_a,_f,_s) _t((_a), strlen (_s), (_f), (_s))
#define OSS(_t,_a,_f,_s1,_s2) _t((_a), strlen (_s1) + strlen (_s2), \
(_f), (_s1), (_s2))
#define OSSS(_t,_a,_f,_s1,_s2,_s3) _t((_a), strlen (_s1) + strlen (_s2) + strlen (_s3), \
(_f), (_s1), (_s2), (_s3))
#define ON(_t,_a,_f,_n) _t((_a), INTSTR_LENGTH, (_f), (_n))
#define ONN(_t,_a,_f,_n1,_n2) _t((_a), INTSTR_LENGTH*2, (_f), (_n1), (_n2))
#define OSN(_t,_a,_f,_s,_n) _t((_a), strlen (_s) + INTSTR_LENGTH, \
(_f), (_s), (_n))
#define ONS(_t,_a,_f,_n,_s) _t((_a), INTSTR_LENGTH + strlen (_s), \
(_f), (_n), (_s))
void die (int) NORETURN;
void pfatal_with_name (const char *) NORETURN;
void perror_with_name (const char *, const char *);
#define xstrlen(_s) ((_s)==NULL ? 0 : strlen (_s))
void *xmalloc (size_t);
// void *xcalloc (size_t);
#define xcalloc(size) ((xcalloc)(1, (size)))
void *xrealloc (void *, size_t);
char *xstrdup (const char *);
char *xstrndup (const char *, size_t);
char *find_next_token (const char **, size_t *);
char *next_token (const char *);
char *end_of_token (const char *);
void collapse_continuations (char *);
char *lindex (const char *, const char *, int);
int alpha_compare (const void *, const void *);
void print_spaces (unsigned int);
char *find_percent (char *);
const char *find_percent_cached (const char **);
FILE *get_tmpfile (char **, const char *);
ssize_t writebuf (int, const void *, size_t);
ssize_t readbuf (int, void *, size_t);
#ifndef NO_ARCHIVES
int ar_name (const char *);
void ar_parse_name (const char *, char **, char **);
int ar_touch (const char *);
time_t ar_member_date (const char *);
typedef long int (*ar_member_func_t) (int desc, const char *mem, int truncated,
long int hdrpos, long int datapos,
long int size, long int date, int uid,
int gid, unsigned int mode,
const void *arg);
long int ar_scan (const char *archive, ar_member_func_t function, const void *arg);
int ar_name_equal (const char *name, const char *mem, int truncated);
#ifndef VMS
int ar_member_touch (const char *arname, const char *memname);
#endif
#endif
int dir_file_exists_p (const char *, const char *);
int file_exists_p (const char *);
int file_impossible_p (const char *);
void file_impossible (const char *);
const char *dir_name (const char *);
void print_dir_data_base (void);
void dir_setup_glob (glob_t *);
void hash_init_directories (void);
void define_default_variables (void);
void undefine_default_variables (void);
void set_default_suffixes (void);
void install_default_suffix_rules (void);
void install_default_implicit_rules (void);
void build_vpath_lists (void);
void construct_vpath_list (char *pattern, char *dirpath);
const char *vpath_search (const char *file, FILE_TIMESTAMP *mtime_ptr,
unsigned int* vpath_index, unsigned int* path_index);
int gpath_search (const char *file, size_t len);
void construct_include_path (const char **arg_dirs);
void user_access (void);
void make_access (void);
void child_access (void);
char *strip_whitespace (const char **begpp, const char **endpp);
void show_goal_error (void);
/* String caching */
void strcache_init (void);
void strcache_print_stats (const char *prefix);
int strcache_iscached (const char *str);
const char *strcache_add (const char *str);
const char *strcache_add_len (const char *str, size_t len);
/* Guile support */
int guile_gmake_setup (const floc *flocp);
/* Loadable object support. Sets to the strcached name of the loaded file. */
typedef int (*load_func_t)(const floc *flocp);
int load_file (const floc *flocp, const char **filename, int noerror);
void unload_file (const char *name);
/* Maintainer mode support */
#ifdef MAKE_MAINTAINER_MODE
# define SPIN(_s) spin (_s)
void spin (const char* suffix);
#else
# define SPIN(_s)
#endif
/* We omit these declarations on non-POSIX systems which define _POSIX_VERSION,
because such systems often declare them in header files anyway. */
#if !defined (__GNU_LIBRARY__) && !defined (POSIX) && !defined (_POSIX_VERSION) && !defined(WINDOWS32)
long int atol ();
# ifndef VMS
long int lseek ();
# endif
# ifdef HAVE_GETCWD
# if !defined(VMS) && !defined(__DECC)
char *getcwd ();
# endif
# else
char *getwd ();
# define getcwd(buf, len) getwd (buf)
# endif
#endif /* Not GNU C library or POSIX. */
#if !HAVE_STRCASECMP
# if HAVE_STRICMP
# define strcasecmp stricmp
# elif HAVE_STRCMPI
# define strcasecmp strcmpi
# else
/* Create our own, in misc.c */
int strcasecmp (const char *s1, const char *s2);
# endif
#endif
#if !HAVE_STRNCASECMP
# if HAVE_STRNICMP
# define strncasecmp strnicmp
# elif HAVE_STRNCMPI
# define strncasecmp strncmpi
# else
/* Create our own, in misc.c */
int strncasecmp (const char *s1, const char *s2, int n);
# endif
#endif
#define OUTPUT_SYNC_NONE 0
#define OUTPUT_SYNC_LINE 1
#define OUTPUT_SYNC_TARGET 2
#define OUTPUT_SYNC_RECURSE 3
/* Non-GNU systems may not declare this in unistd.h. */
extern char **environ;
extern const floc *reading_file;
extern const floc **expanding_var;
extern unsigned short stopchar_map[];
extern int just_print_flag, run_silent, ignore_errors_flag, keep_going_flag;
extern int print_data_base_flag, question_flag, touch_flag, always_make_flag;
extern int env_overrides, no_builtin_rules_flag, no_builtin_variables_flag;
extern int print_version_flag, print_directory_flag, check_symlink_flag;
extern int warn_undefined_variables_flag, trace_flag, posix_pedantic;
extern int not_parallel, second_expansion, clock_skew_detected;
extern int rebuilding_makefiles, one_shell, output_sync, verify_flag;
extern const char *default_shell;
/* can we run commands via 'sh -c xxx' or must we use batch files? */
extern int batch_mode_shell;
/* Resetting the command script introduction prefix character. */
#define RECIPEPREFIX_NAME ".RECIPEPREFIX"
#define RECIPEPREFIX_DEFAULT '\t'
extern char cmd_prefix;
extern unsigned int job_slots;
extern double max_load_average;
extern const char *program;
#ifdef VMS
const char *vms_command (const char *argv0);
const char *vms_progname (const char *argv0);
void vms_exit (int);
# define _exit(foo) vms_exit(foo)
# define exit(foo) vms_exit(foo)
extern char *program_name;
void
set_program_name (const char *arv0);
int
need_vms_symbol (void);
int
create_foreign_command (const char *command, const char *image);
int
vms_export_dcl_symbol (const char *name, const char *value);
int
vms_putenv_symbol (const char *string);
void
vms_restore_symbol (const char *string);
#endif
void remote_setup (void);
void remote_cleanup (void);
int start_remote_job_p (int);
int start_remote_job (char **, char **, int, int *, pid_t *, int *);
int remote_status (int *, int *, int *, int);
void block_remote_children (void);
void unblock_remote_children (void);
int remote_kill (pid_t id, int sig);
void print_variable_data_base (void);
void print_vpath_data_base (void);
extern char *starting_directory;
extern unsigned int makelevel;
extern char *version_string, *remote_description, *make_host;
extern unsigned int commands_started;
extern int handling_fatal_signal;
#define MAKE_SUCCESS 0
#define MAKE_TROUBLE 1
#define MAKE_FAILURE 2
/* Set up heap debugging library dmalloc. */
#ifndef initialize_main
# define initialize_main(pargc, pargv)
#endif
/* Some systems (like Solaris, PTX, etc.) do not support the SA_RESTART flag
properly according to POSIX. So, we try to wrap common system calls with
checks for EINTR. Note that there are still plenty of system calls that
can fail with EINTR but this, reportedly, gets the vast majority of
failure cases. If you still experience failures you'll need to either get
a system where SA_RESTART works, or you need to avoid -j. */
#define EINTRLOOP(_v,_c) while (((_v)=_c)==-1 && errno==EINTR)
/* While system calls that return integers are pretty consistent about
returning -1 on failure and setting errno in that case, functions that
return pointers are not always so well behaved. Sometimes they return
NULL for expected behavior: one good example is readdir() which returns
NULL at the end of the directory--and _doesn't_ reset errno. So, we have
to do it ourselves here. */
#define ENULLLOOP(_v,_c) do { errno = 0; (_v) = _c; } \
while((_v)==0 && errno==EINTR)
| 20,153 | 646 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/variable.h | /* clang-format off */
/* Definitions for using variables in GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/hash.h"
/* Codes in a variable definition saying where the definition came from.
Increasing numeric values signify less-overridable definitions. */
enum variable_origin
{
o_default, /* Variable from the default set. */
o_env, /* Variable from environment. */
o_file, /* Variable given in a makefile. */
o_env_override, /* Variable from environment, if -e. */
o_command, /* Variable given by user. */
o_override, /* Variable from an 'override' directive. */
o_automatic, /* Automatic variable -- cannot be set. */
o_invalid /* Core dump time. */
};
enum variable_flavor
{
f_bogus, /* Bogus (error) */
f_simple, /* Simple definition (:= or ::=) */
f_recursive, /* Recursive definition (=) */
f_append, /* Appending definition (+=) */
f_conditional, /* Conditional definition (?=) */
f_shell, /* Shell assignment (!=) */
f_append_value /* Append unexpanded value */
};
/* Structure that represents one variable definition.
Each bucket of the hash table is a chain of these,
chained through 'next'. */
#define EXP_COUNT_BITS 15 /* This gets all the bitfields into 32 bits */
#define EXP_COUNT_MAX ((1<<EXP_COUNT_BITS)-1)
struct variable
{
char *name; /* Variable name. */
char *value; /* Variable value. */
floc fileinfo; /* Where the variable was defined. */
unsigned int length; /* strlen (name) */
unsigned int recursive:1; /* Gets recursively re-evaluated. */
unsigned int append:1; /* Nonzero if an appending target-specific
variable. */
unsigned int conditional:1; /* Nonzero if set with a ?=. */
unsigned int per_target:1; /* Nonzero if a target-specific variable. */
unsigned int special:1; /* Nonzero if this is a special variable. */
unsigned int exportable:1; /* Nonzero if the variable _could_ be
exported. */
unsigned int expanding:1; /* Nonzero if currently being expanded. */
unsigned int private_var:1; /* Nonzero avoids inheritance of this
target-specific variable. */
unsigned int exp_count:EXP_COUNT_BITS;
/* If >1, allow this many self-referential
expansions. */
enum variable_flavor
flavor ENUM_BITFIELD (3); /* Variable flavor. */
enum variable_origin
origin ENUM_BITFIELD (3); /* Variable origin. */
enum variable_export
{
v_export, /* Export this variable. */
v_noexport, /* Don't export this variable. */
v_ifset, /* Export it if it has a non-default value. */
v_default /* Decide in target_environment. */
} export ENUM_BITFIELD (2);
};
/* Structure that represents a variable set. */
struct variable_set
{
struct hash_table table; /* Hash table of variables. */
};
/* Structure that represents a list of variable sets. */
struct variable_set_list
{
struct variable_set_list *next; /* Link in the chain. */
struct variable_set *set; /* Variable set. */
int next_is_parent; /* True if next is a parent target. */
};
/* Structure used for pattern-specific variables. */
struct pattern_var
{
struct pattern_var *next;
const char *suffix;
const char *target;
size_t len;
struct variable variable;
};
extern char *variable_buffer;
extern struct variable_set_list *current_variable_set_list;
extern struct variable *default_goal_var;
extern struct variable shell_var;
/* expand.c */
#ifndef SIZE_MAX
# define SIZE_MAX ((size_t)~(size_t)0)
#endif
char *variable_buffer_output (char *ptr, const char *string, size_t length);
char *variable_expand (const char *line);
char *variable_expand_for_file (const char *line, struct file *file);
char *allocated_variable_expand_for_file (const char *line, struct file *file);
#define allocated_variable_expand(line) \
allocated_variable_expand_for_file (line, (struct file *) 0)
char *expand_argument (const char *str, const char *end);
char *variable_expand_string (char *line, const char *string, size_t length);
void install_variable_buffer (char **bufp, size_t *lenp);
void restore_variable_buffer (char *buf, size_t len);
/* function.c */
int handle_function (char **op, const char **stringp);
int pattern_matches (const char *pattern, const char *percent, const char *str);
char *subst_expand (char *o, const char *text, const char *subst,
const char *replace, size_t slen, size_t rlen,
int by_word);
char *patsubst_expand_pat (char *o, const char *text, const char *pattern,
const char *replace, const char *pattern_percent,
const char *replace_percent);
char *patsubst_expand (char *o, const char *text, char *pattern, char *replace);
char *func_shell_base (char *o, char **argv, int trim_newlines);
void shell_completed (int exit_code, int exit_sig);
/* expand.c */
char *recursively_expand_for_file (struct variable *v, struct file *file);
#define recursively_expand(v) recursively_expand_for_file (v, NULL)
/* variable.c */
struct variable_set_list *create_new_variable_set (void);
void free_variable_set (struct variable_set_list *);
struct variable_set_list *push_new_variable_scope (void);
void pop_variable_scope (void);
void define_automatic_variables (void);
void initialize_file_variables (struct file *file, int reading);
void print_file_variables (const struct file *file);
void print_target_variables (const struct file *file);
void merge_variable_set_lists (struct variable_set_list **to_list,
struct variable_set_list *from_list);
struct variable *do_variable_definition (const floc *flocp,
const char *name, const char *value,
enum variable_origin origin,
enum variable_flavor flavor,
int target_var);
char *parse_variable_definition (const char *line,
struct variable *v);
struct variable *assign_variable_definition (struct variable *v, const char *line);
struct variable *try_variable_definition (const floc *flocp, const char *line,
enum variable_origin origin,
int target_var);
void init_hash_global_variable_set (void);
void hash_init_function_table (void);
void define_new_function(const floc *flocp, const char *name,
unsigned int min, unsigned int max, unsigned int flags,
gmk_func_ptr func);
struct variable *lookup_variable (const char *name, size_t length);
struct variable *lookup_variable_in_set (const char *name, size_t length,
const struct variable_set *set);
struct variable *define_variable_in_set (const char *name, size_t length,
const char *value,
enum variable_origin origin,
int recursive,
struct variable_set *set,
const floc *flocp);
/* Define a variable in the current variable set. */
#define define_variable(n,l,v,o,r) \
define_variable_in_set((n),(l),(v),(o),(r),\
current_variable_set_list->set,NILF)
/* Define a variable with a constant name in the current variable set. */
#define define_variable_cname(n,v,o,r) \
define_variable_in_set((n),(sizeof (n) - 1),(v),(o),(r),\
current_variable_set_list->set,NILF)
/* Define a variable with a location in the current variable set. */
#define define_variable_loc(n,l,v,o,r,f) \
define_variable_in_set((n),(l),(v),(o),(r),\
current_variable_set_list->set,(f))
/* Define a variable with a location in the global variable set. */
#define define_variable_global(n,l,v,o,r,f) \
define_variable_in_set((n),(l),(v),(o),(r),NULL,(f))
/* Define a variable in FILE's variable set. */
#define define_variable_for_file(n,l,v,o,r,f) \
define_variable_in_set((n),(l),(v),(o),(r),(f)->variables->set,NILF)
void undefine_variable_in_set (const char *name, size_t length,
enum variable_origin origin,
struct variable_set *set);
/* Remove variable from the current variable set. */
#define undefine_variable_global(n,l,o) \
undefine_variable_in_set((n),(l),(o),NULL)
/* Warn that NAME is an undefined variable. */
#define warn_undefined(n,l) do{\
if (warn_undefined_variables_flag) \
error (reading_file, (l), \
_("warning: undefined variable '%.*s'"), \
(int)(l), (n)); \
}while(0)
char **target_environment (struct file *file);
struct pattern_var *create_pattern_var (const char *target,
const char *suffix);
extern int export_all_variables;
#define MAKELEVEL_NAME "MAKELEVEL"
#define MAKELEVEL_LENGTH (CSTRLEN (MAKELEVEL_NAME))
| 10,528 | 243 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/job.h | /* clang-format off */
/* Definitions for managing subprocesses in GNU Make.
Copyright (C) 1992-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/output.h"
/* Structure describing a running or dead child process. */
#define VMSCHILD
#define CHILDBASE \
char *cmd_name; /* Alloced copy of command run. */ \
char **environment; /* Environment for commands. */ \
VMSCHILD \
struct output output /* Output for this child. */
struct childbase
{
CHILDBASE;
};
struct child
{
CHILDBASE;
struct child *next; /* Link in the chain. */
struct file *file; /* File being remade. */
char *tmpdir; /* Temporary directory */
char *sh_batch_file; /* Script file for shell commands */
char **command_lines; /* Array of variable-expanded cmd lines. */
char *command_ptr; /* Ptr into command_lines[command_line]. */
unsigned int command_line; /* Index into command_lines. */
pid_t pid; /* Child process's ID number. */
unsigned int remote:1; /* Nonzero if executing remotely. */
unsigned int noerror:1; /* Nonzero if commands contained a '-'. */
unsigned int good_stdin:1; /* Nonzero if this child has a good stdin. */
unsigned int deleted:1; /* Nonzero if targets have been deleted. */
unsigned int recursive:1; /* Nonzero for recursive command ('+' etc.) */
unsigned int jobslot:1; /* Nonzero if it's reserved a job slot. */
unsigned int dontcare:1; /* Saved dontcare flag. */
};
extern struct child *children;
/* A signal handler for SIGCHLD, if needed. */
RETSIGTYPE child_handler (int sig);
int is_bourne_compatible_shell(const char *path);
void new_job (struct file *file);
void reap_children (int block, int err);
void start_waiting_jobs (void);
char **construct_command_argv (char *line, char **restp, struct file *file,
int cmd_flags, char** batch_file);
pid_t child_execute_job (struct childbase *, int, char **, bool);
#ifdef _AMIGA
void exec_command (char **argv) NORETURN;
#elif defined(__EMX__)
int exec_command (char **argv, char **envp);
#else
void exec_command (char **argv, char **envp) NORETURN;
#endif
void unblock_all_sigs (void);
extern unsigned int job_slots_used;
extern unsigned int jobserver_tokens;
void delete_tmpdir (struct child *);
| 3,165 | 90 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/concat-filename.h | /* clang-format off */
/* Construct a full filename from a directory and a relative filename.
Copyright (C) 2001-2004, 2007-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#ifndef _CONCAT_FILENAME_H
#define _CONCAT_FILENAME_H
#ifdef __cplusplus
extern "C" {
#endif
/* Concatenate a directory filename, a relative filename and an optional
suffix. Return a freshly allocated filename. Return NULL and set errno
upon memory allocation failure. */
extern char *concatenated_filename (const char *directory,
const char *filename, const char *suffix);
/* Concatenate a directory filename, a relative filename and an optional
suffix. Return a freshly allocated filename. */
extern char *xconcatenated_filename (const char *directory,
const char *filename, const char *suffix);
#ifdef __cplusplus
}
#endif
#endif /* _CONCAT_FILENAME_H */
| 1,564 | 43 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/file.c | /* Target file management for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* clang-format off */
#include "third_party/make/makeint.inc"
/**/
#include "third_party/make/filedef.h"
#include "third_party/make/dep.h"
#include "third_party/make/job.h"
#include "third_party/make/commands.h"
#include "third_party/make/variable.h"
#include "third_party/make/debug.h"
#include "libc/assert.h"
#include "libc/sysv/consts/clock.h"
#include "third_party/make/hash.h"
/* Remember whether snap_deps has been invoked: we need this to be sure we
don't add new rules (via $(eval ...)) afterwards. In the future it would
be nice to support this, but it means we'd need to re-run snap_deps() or
at least its functionality... it might mean changing snap_deps() to be run
per-file, so we can invoke it after the eval... or remembering which files
in the hash have been snapped (a new boolean flag?) and having snap_deps()
only work on files which have not yet been snapped. */
int snapped_deps = 0;
/* Hash table of files the makefile knows how to make. */
static unsigned long
file_hash_1 (const void *key)
{
return_ISTRING_HASH_1 (((struct file const *) key)->hname);
}
static unsigned long
file_hash_2 (const void *key)
{
return_ISTRING_HASH_2 (((struct file const *) key)->hname);
}
static int
file_hash_cmp (const void *x, const void *y)
{
return_ISTRING_COMPARE (((struct file const *) x)->hname,
((struct file const *) y)->hname);
}
static struct hash_table files;
/* Whether or not .SECONDARY with no prerequisites was given. */
static int all_secondary = 0;
/* Access the hash table of all file records.
lookup_file given a name, return the struct file * for that name,
or nil if there is none.
*/
struct file *
lookup_file (const char *name)
{
struct file *f;
struct file file_key;
assert (*name != '\0');
while (name[0] == '.'
#ifdef HAVE_DOS_PATHS
&& (name[1] == '/' || name[1] == '\\')
#else
&& name[1] == '/'
#endif
&& name[2] != '\0')
{
name += 2;
while (*name == '/'
#ifdef HAVE_DOS_PATHS
|| *name == '\\'
#endif
)
/* Skip following slashes: ".//foo" is "foo", not "/foo". */
++name;
}
if (*name == '\0')
{
/* It was all slashes after a dot. */
name = "./";
}
file_key.hname = name;
f = hash_find_item (&files, &file_key);
return f;
}
/* Look up a file record for file NAME and return it.
Create a new record if one doesn't exist. NAME will be stored in the
new record so it should be constant or in the strcache etc.
*/
struct file *
enter_file (const char *name)
{
struct file *f;
struct file *new;
struct file **file_slot;
struct file file_key;
assert (*name != '\0');
assert (! verify_flag || strcache_iscached (name));
file_key.hname = name;
file_slot = (struct file **) hash_find_slot (&files, &file_key);
f = *file_slot;
if (! HASH_VACANT (f) && !f->double_colon)
{
f->builtin = 0;
return f;
}
new = xcalloc (sizeof (struct file));
new->name = new->hname = name;
new->update_status = us_none;
if (HASH_VACANT (f))
{
new->last = new;
hash_insert_at (&files, new, file_slot);
}
else
{
/* There is already a double-colon entry for this file. */
new->double_colon = f;
f->last->prev = new;
f->last = new;
}
return new;
}
/* Rehash FILE to NAME. This is not as simple as resetting
the 'hname' member, since it must be put in a new hash bucket,
and possibly merged with an existing file called NAME. */
void
rehash_file (struct file *from_file, const char *to_hname)
{
struct file file_key;
struct file **file_slot;
struct file *to_file;
struct file *deleted_file;
struct file *f;
/* If it's already that name, we're done. */
from_file->builtin = 0;
file_key.hname = to_hname;
if (! file_hash_cmp (from_file, &file_key))
return;
/* Find the end of the renamed list for the "from" file. */
file_key.hname = from_file->hname;
while (from_file->renamed != 0)
from_file = from_file->renamed;
if (file_hash_cmp (from_file, &file_key))
/* hname changed unexpectedly!! */
abort ();
/* Remove the "from" file from the hash. */
deleted_file = hash_delete (&files, from_file);
if (deleted_file != from_file)
/* from_file isn't the one stored in files */
abort ();
/* Find where the newly renamed file will go in the hash. */
file_key.hname = to_hname;
file_slot = (struct file **) hash_find_slot (&files, &file_key);
to_file = *file_slot;
/* Change the hash name for this file. */
from_file->hname = to_hname;
for (f = from_file->double_colon; f != 0; f = f->prev)
f->hname = to_hname;
/* If the new name doesn't exist yet just set it to the renamed file. */
if (HASH_VACANT (to_file))
{
hash_insert_at (&files, from_file, file_slot);
return;
}
/* TO_FILE already exists under TO_HNAME.
We must retain TO_FILE and merge FROM_FILE into it. */
if (from_file->cmds != 0)
{
if (to_file->cmds == 0)
to_file->cmds = from_file->cmds;
else if (from_file->cmds != to_file->cmds)
{
size_t l = strlen (from_file->name);
/* We have two sets of commands. We will go with the
one given in the rule explicitly mentioning this name,
but give a message to let the user know what's going on. */
if (to_file->cmds->fileinfo.filenm != 0)
error (&from_file->cmds->fileinfo,
l + strlen (to_file->cmds->fileinfo.filenm) + INTSTR_LENGTH,
_("Recipe was specified for file '%s' at %s:%lu,"),
from_file->name, to_file->cmds->fileinfo.filenm,
to_file->cmds->fileinfo.lineno);
else
error (&from_file->cmds->fileinfo, l,
_("Recipe for file '%s' was found by implicit rule search,"),
from_file->name);
l += strlen (to_hname);
error (&from_file->cmds->fileinfo, l,
_("but '%s' is now considered the same file as '%s'."),
from_file->name, to_hname);
error (&from_file->cmds->fileinfo, l,
_("Recipe for '%s' will be ignored in favor of the one for '%s'."),
to_hname, from_file->name);
}
}
/* Merge the dependencies of the two files. */
if (to_file->deps == 0)
to_file->deps = from_file->deps;
else
{
struct dep *deps = to_file->deps;
while (deps->next != 0)
deps = deps->next;
deps->next = from_file->deps;
}
merge_variable_set_lists (&to_file->variables, from_file->variables);
if (to_file->double_colon && from_file->is_target && !from_file->double_colon)
OSS (fatal, NILF, _("can't rename single-colon '%s' to double-colon '%s'"),
from_file->name, to_hname);
if (!to_file->double_colon && from_file->double_colon)
{
if (to_file->is_target)
OSS (fatal, NILF,
_("can't rename double-colon '%s' to single-colon '%s'"),
from_file->name, to_hname);
else
to_file->double_colon = from_file->double_colon;
}
if (from_file->last_mtime > to_file->last_mtime)
/* %%% Kludge so -W wins on a file that gets vpathized. */
to_file->last_mtime = from_file->last_mtime;
to_file->mtime_before_update = from_file->mtime_before_update;
#define MERGE(field) to_file->field |= from_file->field
MERGE (precious);
MERGE (tried_implicit);
MERGE (updating);
MERGE (updated);
MERGE (is_target);
MERGE (cmd_target);
MERGE (phony);
MERGE (loaded);
MERGE (ignore_vpath);
#undef MERGE
to_file->builtin = 0;
from_file->renamed = to_file;
}
/* Rename FILE to NAME. This is not as simple as resetting
the 'name' member, since it must be put in a new hash bucket,
and possibly merged with an existing file called NAME. */
void
rename_file (struct file *from_file, const char *to_hname)
{
rehash_file (from_file, to_hname);
while (from_file)
{
from_file->name = from_file->hname;
from_file = from_file->prev;
}
}
/* Remove all nonprecious intermediate files.
If SIG is nonzero, this was caused by a fatal signal,
meaning that a different message will be printed, and
the message will go to stderr rather than stdout. */
void
remove_intermediates (int sig)
{
struct file **file_slot;
struct file **file_end;
int doneany = 0;
/* If there's no way we will ever remove anything anyway, punt early. */
if (question_flag || touch_flag || all_secondary)
return;
if (sig && just_print_flag)
return;
file_slot = (struct file **) files.ht_vec;
file_end = file_slot + files.ht_size;
for ( ; file_slot < file_end; file_slot++)
if (! HASH_VACANT (*file_slot))
{
struct file *f = *file_slot;
/* Is this file eligible for automatic deletion?
Yes, IFF: it's marked intermediate, it's not secondary, it wasn't
given on the command line, and it's either a -include makefile or
it's not precious. */
if (f->intermediate && (f->dontcare || !f->precious)
&& !f->secondary && !f->cmd_target)
{
int status;
if (f->update_status == us_none)
/* If nothing would have created this file yet,
don't print an "rm" command for it. */
continue;
if (just_print_flag)
status = 0;
else
{
status = unlink (f->name);
if (status < 0 && errno == ENOENT)
continue;
}
if (!f->dontcare)
{
if (sig)
OS (error, NILF,
_("*** Deleting intermediate file '%s'"), f->name);
else
{
if (! doneany)
DB (DB_BASIC, (_("Removing intermediate files...\n")));
if (!run_silent)
{
if (! doneany)
{
fputs ("rm ", stdout);
doneany = 1;
}
else
putchar (' ');
fputs (f->name, stdout);
fflush (stdout);
}
}
if (status < 0)
perror_with_name ("unlink: ", f->name);
}
}
}
if (doneany && !sig)
{
putchar ('\n');
fflush (stdout);
}
}
/* Given a string containing prerequisites (fully expanded), break it up into
a struct dep list. Enter each of these prereqs into the file database.
*/
struct dep *
split_prereqs (char *p)
{
struct dep *new = PARSE_FILE_SEQ (&p, struct dep, MAP_PIPE, NULL,
PARSEFS_NONE);
if (*p)
{
/* Files that follow '|' are "order-only" prerequisites that satisfy the
dependency by existing: their modification times are irrelevant. */
struct dep *ood;
++p;
ood = PARSE_SIMPLE_SEQ (&p, struct dep);
if (! new)
new = ood;
else
{
struct dep *dp;
for (dp = new; dp->next != NULL; dp = dp->next)
;
dp->next = ood;
}
for (; ood != NULL; ood = ood->next)
ood->ignore_mtime = 1;
}
return new;
}
/* Given a list of prerequisites, enter them into the file database.
If STEM is set then first expand patterns using STEM. */
struct dep *
enter_prereqs (struct dep *deps, const char *stem)
{
struct dep *d1;
if (deps == 0)
return 0;
/* If we have a stem, expand the %'s. We use patsubst_expand to translate
the prerequisites' patterns into plain prerequisite names. */
if (stem)
{
const char *pattern = "%";
char *buffer = variable_expand ("");
struct dep *dp = deps, *dl = 0;
while (dp != 0)
{
char *percent;
size_t nl = strlen (dp->name) + 1;
char *nm = alloca (nl);
memcpy (nm, dp->name, nl);
percent = find_percent (nm);
if (percent)
{
char *o;
/* We have to handle empty stems specially, because that
would be equivalent to $(patsubst %,dp->name,) which
will always be empty. */
if (stem[0] == '\0')
{
memmove (percent, percent+1, strlen (percent));
o = variable_buffer_output (buffer, nm, strlen (nm) + 1);
}
else
o = patsubst_expand_pat (buffer, stem, pattern, nm,
pattern+1, percent+1);
/* If the name expanded to the empty string, ignore it. */
if (buffer[0] == '\0')
{
struct dep *df = dp;
if (dp == deps)
dp = deps = deps->next;
else
dp = dl->next = dp->next;
free_dep (df);
continue;
}
/* Save the name. */
dp->name = strcache_add_len (buffer, o - buffer);
}
dp->stem = stem;
dp->staticpattern = 1;
dl = dp;
dp = dp->next;
}
}
/* Enter them as files, unless they need a 2nd expansion. */
for (d1 = deps; d1 != 0; d1 = d1->next)
{
if (d1->need_2nd_expansion)
continue;
d1->file = lookup_file (d1->name);
if (d1->file == 0)
d1->file = enter_file (d1->name);
d1->staticpattern = 0;
d1->name = 0;
}
return deps;
}
/* Expand and parse each dependency line. */
static void
expand_deps (struct file *f)
{
struct dep *d;
struct dep **dp;
const char *file_stem = f->stem;
int initialized = 0;
f->updating = 0;
/* Walk through the dependencies. For any dependency that needs 2nd
expansion, expand it then insert the result into the list. */
dp = &f->deps;
d = f->deps;
while (d != 0)
{
char *p;
struct dep *new, *next;
char *name = (char *)d->name;
if (! d->name || ! d->need_2nd_expansion)
{
/* This one is all set already. */
dp = &d->next;
d = d->next;
continue;
}
/* If it's from a static pattern rule, convert the patterns into
"$*" so they'll expand properly. */
if (d->staticpattern)
{
char *o = variable_expand ("");
o = subst_expand (o, name, "%", "$*", 1, 2, 0);
*o = '\0';
free (name);
d->name = name = xstrdup (variable_buffer);
d->staticpattern = 0;
}
/* We're going to do second expansion so initialize file variables for
the file. Since the stem for static pattern rules comes from
individual dep lines, we will temporarily set f->stem to d->stem. */
if (!initialized)
{
initialize_file_variables (f, 0);
initialized = 1;
}
if (d->stem != 0)
f->stem = d->stem;
set_file_variables (f);
p = variable_expand_for_file (d->name, f);
if (d->stem != 0)
f->stem = file_stem;
/* At this point we don't need the name anymore: free it. */
free (name);
/* Parse the prerequisites and enter them into the file database. */
new = enter_prereqs (split_prereqs (p), d->stem);
/* If there were no prereqs here (blank!) then throw this one out. */
if (new == 0)
{
*dp = d->next;
free_dep (d);
d = *dp;
continue;
}
/* Add newly parsed prerequisites. */
next = d->next;
*dp = new;
for (dp = &new->next, d = new->next; d != 0; dp = &d->next, d = d->next)
;
*dp = next;
d = *dp;
}
}
/* Add extra prereqs to the file in question. */
struct dep *
expand_extra_prereqs (const struct variable *extra)
{
struct dep *d;
struct dep *prereqs = extra ? split_prereqs (variable_expand (extra->value)) : NULL;
for (d = prereqs; d; d = d->next)
{
d->file = lookup_file (d->name);
if (!d->file)
d->file = enter_file (d->name);
d->name = NULL;
d->ignore_automatic_vars = 1;
}
return prereqs;
}
/* Perform per-file snap operations. */
static void
snap_file (const void *item, void *arg)
{
struct file *f = (struct file*)item;
struct dep *prereqs = NULL;
/* If we're not doing second expansion then reset updating. */
if (!second_expansion)
f->updating = 0;
/* If .SECONDARY is set with no deps, mark all targets as intermediate. */
if (all_secondary)
f->intermediate = 1;
/* If .EXTRA_PREREQS is set, add them as ignored by automatic variables. */
if (f->variables)
prereqs = expand_extra_prereqs (lookup_variable_in_set (STRING_SIZE_TUPLE(".EXTRA_PREREQS"), f->variables->set));
else if (f->is_target)
prereqs = copy_dep_chain (arg);
if (prereqs)
{
struct dep *d;
for (d = prereqs; d; d = d->next)
if (streq (f->name, dep_name (d)))
/* Skip circular dependencies. */
break;
if (d)
/* We broke early: must have found a circular dependency. */
free_dep_chain (prereqs);
else if (!f->deps)
f->deps = prereqs;
else
{
d = f->deps;
while (d->next)
d = d->next;
d->next = prereqs;
}
}
}
/* For each dependency of each file, make the 'struct dep' point
at the appropriate 'struct file' (which may have to be created).
Also mark the files depended on by .PRECIOUS, .PHONY, .SILENT,
and various other special targets. */
void
snap_deps (void)
{
struct file *f;
struct file *f2;
struct dep *d;
/* Remember that we've done this. Once we start snapping deps we can no
longer define new targets. */
snapped_deps = 1;
/* Perform second expansion and enter each dependency name as a file. We
must use hash_dump() here because within these loops we likely add new
files to the table, possibly causing an in-situ table expansion.
We only need to do this if second_expansion has been defined; if it
hasn't then all deps were expanded as the makefile was read in. If we
ever change make to be able to unset .SECONDARY_EXPANSION this will have
to change. */
if (second_expansion)
{
struct file **file_slot_0 = (struct file **) hash_dump (&files, 0, 0);
struct file **file_end = file_slot_0 + files.ht_fill;
struct file **file_slot;
const char *suffixes;
/* Expand .SUFFIXES: its prerequisites are used for $$* calc. */
f = lookup_file (".SUFFIXES");
suffixes = f ? f->name : 0;
for (; f != 0; f = f->prev)
expand_deps (f);
/* For every target that's not .SUFFIXES, expand its prerequisites. */
for (file_slot = file_slot_0; file_slot < file_end; file_slot++)
for (f = *file_slot; f != 0; f = f->prev)
if (f->name != suffixes)
expand_deps (f);
free (file_slot_0);
}
/* Now manage all the special targets. */
for (f = lookup_file (".PRECIOUS"); f != 0; f = f->prev)
for (d = f->deps; d != 0; d = d->next)
for (f2 = d->file; f2 != 0; f2 = f2->prev)
f2->precious = 1;
for (f = lookup_file (".LOW_RESOLUTION_TIME"); f != 0; f = f->prev)
for (d = f->deps; d != 0; d = d->next)
for (f2 = d->file; f2 != 0; f2 = f2->prev)
f2->low_resolution_time = 1;
for (f = lookup_file (".PHONY"); f != 0; f = f->prev)
for (d = f->deps; d != 0; d = d->next)
for (f2 = d->file; f2 != 0; f2 = f2->prev)
{
/* Mark this file as phony nonexistent target. */
f2->phony = 1;
f2->is_target = 1;
f2->last_mtime = NONEXISTENT_MTIME;
f2->mtime_before_update = NONEXISTENT_MTIME;
}
for (f = lookup_file (".INTERMEDIATE"); f != 0; f = f->prev)
/* Mark .INTERMEDIATE deps as intermediate files. */
for (d = f->deps; d != 0; d = d->next)
for (f2 = d->file; f2 != 0; f2 = f2->prev)
f2->intermediate = 1;
/* .INTERMEDIATE with no deps does nothing.
Marking all files as intermediates is useless since the goal targets
would be deleted after they are built. */
for (f = lookup_file (".SECONDARY"); f != 0; f = f->prev)
/* Mark .SECONDARY deps as both intermediate and secondary. */
if (f->deps)
for (d = f->deps; d != 0; d = d->next)
for (f2 = d->file; f2 != 0; f2 = f2->prev)
f2->intermediate = f2->secondary = 1;
/* .SECONDARY with no deps listed marks *all* files that way. */
else
all_secondary = 1;
f = lookup_file (".EXPORT_ALL_VARIABLES");
if (f != 0 && f->is_target)
export_all_variables = 1;
f = lookup_file (".IGNORE");
if (f != 0 && f->is_target)
{
if (f->deps == 0)
ignore_errors_flag = 1;
else
for (d = f->deps; d != 0; d = d->next)
for (f2 = d->file; f2 != 0; f2 = f2->prev)
f2->command_flags |= COMMANDS_NOERROR;
}
f = lookup_file (".SILENT");
if (f != 0 && f->is_target)
{
if (f->deps == 0)
run_silent = 1;
else
for (d = f->deps; d != 0; d = d->next)
for (f2 = d->file; f2 != 0; f2 = f2->prev)
f2->command_flags |= COMMANDS_SILENT;
}
f = lookup_file (".NOTPARALLEL");
if (f != 0 && f->is_target)
not_parallel = 1;
{
struct dep *prereqs = expand_extra_prereqs (lookup_variable (STRING_SIZE_TUPLE(".EXTRA_PREREQS")));
/* Perform per-file snap operations. */
hash_map_arg(&files, snap_file, prereqs);
free_dep_chain (prereqs);
}
#ifndef NO_MINUS_C_MINUS_O
/* If .POSIX was defined, remove OUTPUT_OPTION to comply. */
/* This needs more work: what if the user sets this in the makefile?
if (posix_pedantic)
define_variable_cname ("OUTPUT_OPTION", "", o_default, 1);
*/
#endif
}
/* Set the 'command_state' member of FILE and all its 'also_make's.
Don't decrease the state of also_make's (e.g., don't downgrade a 'running'
also_make to a 'deps_running' also_make). */
void
set_command_state (struct file *file, enum cmd_state state)
{
struct dep *d;
file->command_state = state;
for (d = file->also_make; d != 0; d = d->next)
if (state > d->file->command_state)
d->file->command_state = state;
}
/* Convert an external file timestamp to internal form. */
FILE_TIMESTAMP
file_timestamp_cons (const char *fname, time_t stamp, long int ns)
{
int offset = ORDINARY_MTIME_MIN + (FILE_TIMESTAMP_HI_RES ? ns : 0);
FILE_TIMESTAMP s = stamp;
FILE_TIMESTAMP product = (FILE_TIMESTAMP) s << FILE_TIMESTAMP_LO_BITS;
FILE_TIMESTAMP ts = product + offset;
if (! (s <= FILE_TIMESTAMP_S (ORDINARY_MTIME_MAX)
&& product <= ts && ts <= ORDINARY_MTIME_MAX))
{
char buf[FILE_TIMESTAMP_PRINT_LEN_BOUND + 1];
const char *f = fname ? fname : _("Current time");
ts = s <= OLD_MTIME ? ORDINARY_MTIME_MIN : ORDINARY_MTIME_MAX;
file_timestamp_sprintf (buf, sizeof(buf), ts);
OSS (error, NILF,
_("%s: Timestamp out of range; substituting %s"), f, buf);
}
return ts;
}
/* Return the current time as a file timestamp, setting *RESOLUTION to
its resolution. */
FILE_TIMESTAMP
file_timestamp_now (int *resolution)
{
int r;
time_t s;
int ns;
/* Don't bother with high-resolution clocks if file timestamps have
only one-second resolution. The code below should work, but it's
not worth the hassle of debugging it on hosts where it fails. */
{
struct timespec timespec;
if (clock_gettime (CLOCK_REALTIME, ×pec) == 0)
{
r = 1;
s = timespec.tv_sec;
ns = timespec.tv_nsec;
goto got_time;
}
}
{
struct timeval timeval;
if (gettimeofday (&timeval, 0) == 0)
{
r = 1000;
s = timeval.tv_sec;
ns = timeval.tv_usec * 1000;
goto got_time;
}
}
r = 1000000000;
s = time ((time_t *) 0);
ns = 0;
got_time:
*resolution = r;
return file_timestamp_cons (0, s, ns);
}
/* Place into the buffer P a printable representation of the file
timestamp TS. */
void
file_timestamp_sprintf (char *p, int n, FILE_TIMESTAMP ts)
{
/*
* [jart] patch weakness upstream because buffer can probably overflow
* if integer timestamp is irreguular
*/
int m;
time_t t = FILE_TIMESTAMP_S (ts);
struct tm *tm = localtime (&t);
if (tm)
snprintf (p, n, "%04d-%02d-%02d %02d:%02d:%02d",
tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
else if (t < 0)
snprintf (p, n, "%ld", (long) t);
else
snprintf (p, n, "%lu", (unsigned long) t);
m = strlen (p);
p += m;
n -= m;
if (n <= 0) return;
/* Append nanoseconds as a fraction, but remove trailing zeros. We don't
know the actual timestamp resolution, since clock_getres applies only to
local times, whereas this timestamp might come from a remote filesystem.
So removing trailing zeros is the best guess that we can do. */
snprintf (p, n, ".%09d", FILE_TIMESTAMP_NS (ts));
m = strlen (p) - 1;
p += m;
n += m;
while (*p == '0')
p--;
p += *p != '.';
*p = '\0';
}
/* Print the data base of files. */
void
print_prereqs (const struct dep *deps)
{
const struct dep *ood = 0;
/* Print all normal dependencies; note any order-only deps. */
for (; deps != 0; deps = deps->next)
if (! deps->ignore_mtime)
printf (" %s", dep_name (deps));
else if (! ood)
ood = deps;
/* Print order-only deps, if we have any. */
if (ood)
{
printf (" | %s", dep_name (ood));
for (ood = ood->next; ood != 0; ood = ood->next)
if (ood->ignore_mtime)
printf (" %s", dep_name (ood));
}
putchar ('\n');
}
static void
print_file (const void *item)
{
const struct file *f = item;
/* If we're not using builtin targets, don't show them.
Ideally we'd be able to delete them altogether but currently there's no
facility to ever delete a file once it's been added. */
if (no_builtin_rules_flag && f->builtin)
return;
putchar ('\n');
if (f->cmds && f->cmds->recipe_prefix != cmd_prefix)
{
fputs (".RECIPEPREFIX = ", stdout);
cmd_prefix = f->cmds->recipe_prefix;
if (cmd_prefix != RECIPEPREFIX_DEFAULT)
putchar (cmd_prefix);
putchar ('\n');
}
if (f->variables != 0)
print_target_variables (f);
if (!f->is_target)
puts (_("# Not a target:"));
printf ("%s:%s", f->name, f->double_colon ? ":" : "");
print_prereqs (f->deps);
if (f->precious)
puts (_("# Precious file (prerequisite of .PRECIOUS)."));
if (f->phony)
puts (_("# Phony target (prerequisite of .PHONY)."));
if (f->cmd_target)
puts (_("# Command line target."));
if (f->dontcare)
puts (_("# A default, MAKEFILES, or -include/sinclude makefile."));
if (f->builtin)
puts (_("# Builtin rule"));
puts (f->tried_implicit
? _("# Implicit rule search has been done.")
: _("# Implicit rule search has not been done."));
if (f->stem != 0)
printf (_("# Implicit/static pattern stem: '%s'\n"), f->stem);
if (f->intermediate)
puts (_("# File is an intermediate prerequisite."));
if (f->also_make != 0)
{
const struct dep *d;
fputs (_("# Also makes:"), stdout);
for (d = f->also_make; d != 0; d = d->next)
printf (" %s", dep_name (d));
putchar ('\n');
}
if (f->last_mtime == UNKNOWN_MTIME)
puts (_("# Modification time never checked."));
else if (f->last_mtime == NONEXISTENT_MTIME)
puts (_("# File does not exist."));
else if (f->last_mtime == OLD_MTIME)
puts (_("# File is very old."));
else
{
char buf[FILE_TIMESTAMP_PRINT_LEN_BOUND + 1];
file_timestamp_sprintf (buf, sizeof(buf), f->last_mtime);
printf (_("# Last modified %s\n"), buf);
}
puts (f->updated
? _("# File has been updated.") : _("# File has not been updated."));
switch (f->command_state)
{
case cs_running:
puts (_("# Recipe currently running (THIS IS A BUG)."));
break;
case cs_deps_running:
puts (_("# Dependencies recipe running (THIS IS A BUG)."));
break;
case cs_not_started:
case cs_finished:
switch (f->update_status)
{
case us_none:
break;
case us_success:
puts (_("# Successfully updated."));
break;
case us_question:
assert (question_flag);
puts (_("# Needs to be updated (-q is set)."));
break;
case us_failed:
puts (_("# Failed to be updated."));
break;
}
break;
default:
puts (_("# Invalid value in 'command_state' member!"));
fflush (stdout);
fflush (stderr);
abort ();
}
if (f->variables != 0)
print_file_variables (f);
if (f->cmds != 0)
print_commands (f->cmds);
if (f->prev)
print_file ((const void *) f->prev);
}
void
print_file_data_base (void)
{
puts (_("\n# Files"));
hash_map (&files, print_file);
fputs (_("\n# files hash-table stats:\n# "), stdout);
hash_print_stats (&files, stdout);
}
/* Verify the integrity of the data base of files. */
#define VERIFY_CACHED(_p,_n) \
do{ \
if (_p->_n && _p->_n[0] && !strcache_iscached (_p->_n)) \
error (NULL, strlen (_p->name) + CSTRLEN (# _n) + strlen (_p->_n), \
_("%s: Field '%s' not cached: %s"), _p->name, # _n, _p->_n); \
}while(0)
static void
verify_file (const void *item)
{
const struct file *f = item;
const struct dep *d;
VERIFY_CACHED (f, name);
VERIFY_CACHED (f, hname);
VERIFY_CACHED (f, vpath);
VERIFY_CACHED (f, stem);
/* Check the deps. */
for (d = f->deps; d != 0; d = d->next)
{
if (! d->need_2nd_expansion)
VERIFY_CACHED (d, name);
VERIFY_CACHED (d, stem);
}
}
void
verify_file_data_base (void)
{
hash_map (&files, verify_file);
}
#define EXPANSION_INCREMENT(_l) ((((_l) / 500) + 1) * 500)
char *
build_target_list (char *value)
{
static unsigned long last_targ_count = 0;
if (files.ht_fill != last_targ_count)
{
size_t max = EXPANSION_INCREMENT (strlen (value));
size_t len;
char *p;
struct file **fp = (struct file **) files.ht_vec;
struct file **end = &fp[files.ht_size];
/* Make sure we have at least MAX bytes in the allocated buffer. */
value = xrealloc (value, max);
p = value;
len = 0;
for (; fp < end; ++fp)
if (!HASH_VACANT (*fp) && (*fp)->is_target)
{
struct file *f = *fp;
size_t l = strlen (f->name);
len += l + 1;
if (len > max)
{
size_t off = p - value;
max += EXPANSION_INCREMENT (l + 1);
value = xrealloc (value, max);
p = &value[off];
}
memcpy (p, f->name, l);
p += l;
*(p++) = ' ';
}
*(p-1) = '\0';
last_targ_count = files.ht_fill;
}
return value;
}
void
init_hash_files (void)
{
hash_init (&files, 1000, file_hash_1, file_hash_2, file_hash_cmp);
}
/* EOF */
| 32,561 | 1,146 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/fcntl.c | /* clang-format off */
/* Provide file descriptor control.
Copyright (C) 2009-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* Written by Eric Blake <[email protected]>. */
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/sysv/consts/f.h"
#include "third_party/make/config.h"
/* Specification. */
#include "third_party/make/fcntl.h"
#if defined _WIN32 && !defined __CYGWIN__
/* Get declarations of the native Windows API functions. */
/* Upper bound on getdtablesize(). See lib/getdtablesize.c. */
#define OPEN_MAX_MAX 0x10000
/* Duplicate OLDFD into the first available slot of at least NEWFD,
which must be positive, with FLAGS determining whether the duplicate
will be inheritable. */
static int dupfd(int oldfd, int newfd, int flags) {
/* Mingw has no way to create an arbitrary fd. Iterate until all
file descriptors less than newfd are filled up. */
HANDLE curr_process = GetCurrentProcess();
HANDLE old_handle = (HANDLE)_get_osfhandle(oldfd);
unsigned char fds_to_close[OPEN_MAX_MAX / CHAR_BIT];
unsigned int fds_to_close_bound = 0;
int result;
BOOL inherit = flags & O_CLOEXEC ? FALSE : TRUE;
int mode;
if (newfd < 0 || getdtablesize() <= newfd) {
errno = EINVAL;
return -1;
}
if (old_handle == INVALID_HANDLE_VALUE ||
(mode = setmode(oldfd, O_BINARY)) == -1) {
/* oldfd is not open, or is an unassigned standard file
descriptor. */
errno = EBADF;
return -1;
}
setmode(oldfd, mode);
flags |= mode;
for (;;) {
HANDLE new_handle;
int duplicated_fd;
unsigned int index;
if (!DuplicateHandle(curr_process, /* SourceProcessHandle */
old_handle, /* SourceHandle */
curr_process, /* TargetProcessHandle */
(PHANDLE)&new_handle, /* TargetHandle */
(DWORD)0, /* DesiredAccess */
inherit, /* InheritHandle */
DUPLICATE_SAME_ACCESS)) /* Options */
{
switch (GetLastError()) {
case ERROR_TOO_MANY_OPEN_FILES:
errno = EMFILE;
break;
case ERROR_INVALID_HANDLE:
case ERROR_INVALID_TARGET_HANDLE:
case ERROR_DIRECT_ACCESS_HANDLE:
errno = EBADF;
break;
case ERROR_INVALID_PARAMETER:
case ERROR_INVALID_FUNCTION:
case ERROR_INVALID_ACCESS:
errno = EINVAL;
break;
default:
errno = EACCES;
break;
}
result = -1;
break;
}
duplicated_fd = _open_osfhandle((intptr_t)new_handle, flags);
if (duplicated_fd < 0) {
CloseHandle(new_handle);
result = -1;
break;
}
if (newfd <= duplicated_fd) {
result = duplicated_fd;
break;
}
/* Set the bit duplicated_fd in fds_to_close[]. */
index = (unsigned int)duplicated_fd / CHAR_BIT;
if (fds_to_close_bound <= index) {
if (sizeof fds_to_close <= index) /* Need to increase OPEN_MAX_MAX. */
abort();
memset(fds_to_close + fds_to_close_bound, '\0',
index + 1 - fds_to_close_bound);
fds_to_close_bound = index + 1;
}
fds_to_close[index] |= 1 << ((unsigned int)duplicated_fd % CHAR_BIT);
}
/* Close the previous fds that turned out to be too small. */
{
int saved_errno = errno;
unsigned int duplicated_fd;
for (duplicated_fd = 0; duplicated_fd < fds_to_close_bound * CHAR_BIT;
duplicated_fd++)
if ((fds_to_close[duplicated_fd / CHAR_BIT] >>
(duplicated_fd % CHAR_BIT)) &
1)
close(duplicated_fd);
errno = saved_errno;
}
#if REPLACE_FCHDIR
if (0 <= result) result = _gl_register_dup(oldfd, result);
#endif
return result;
}
#endif /* W32 */
/* Forward declarations, because we '#undef fcntl' in the middle of this
compilation unit. */
/* Our implementation of fcntl (fd, F_DUPFD, target). */
static int rpl_fcntl_DUPFD(int fd, int target);
/* Our implementation of fcntl (fd, F_DUPFD_CLOEXEC, target). */
static int rpl_fcntl_DUPFD_CLOEXEC(int fd, int target);
#ifdef __KLIBC__
/* Adds support for fcntl on directories. */
static int klibc_fcntl(int fd, int action, /* arg */...);
#endif
/* Perform the specified ACTION on the file descriptor FD, possibly
using the argument ARG further described below. This replacement
handles the following actions, and forwards all others on to the
native fcntl. An unrecognized ACTION returns -1 with errno set to
EINVAL.
F_DUPFD - duplicate FD, with int ARG being the minimum target fd.
If successful, return the duplicate, which will be inheritable;
otherwise return -1 and set errno.
F_DUPFD_CLOEXEC - duplicate FD, with int ARG being the minimum
target fd. If successful, return the duplicate, which will not be
inheritable; otherwise return -1 and set errno.
F_GETFD - ARG need not be present. If successful, return a
non-negative value containing the descriptor flags of FD (only
FD_CLOEXEC is portable, but other flags may be present); otherwise
return -1 and set errno. */
int fcntl_(int fd, int action, /* arg */...)
#undef fcntl
#ifdef __KLIBC__
#define fcntl_ klibc_fcntl
#endif
{
va_list arg;
int result = -1;
va_start(arg, action);
if (action == F_DUPFD) {
int target = va_arg(arg, int);
result = rpl_fcntl_DUPFD(fd, target);
}
else if (action == F_DUPFD_CLOEXEC) {
int target = va_arg(arg, int);
result = rpl_fcntl_DUPFD_CLOEXEC(fd, target);
}
#if !HAVE_FCNTL
else if (action == F_GETFD) {
#if defined _WIN32 && !defined __CYGWIN__
HANDLE handle = (HANDLE)_get_osfhandle(fd);
DWORD flags;
if (handle == INVALID_HANDLE_VALUE ||
GetHandleInformation(handle, &flags) == 0)
errno = EBADF;
else
result = (flags & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
#else /* !W32 */
/* Use dup2 to reject invalid file descriptors. No way to
access this information, so punt. */
if (0 <= dup2(fd, fd)) result = 0;
#endif /* !W32 */
} /* F_GETFD */
#endif /* !HAVE_FCNTL */
/* Implementing F_SETFD on mingw is not trivial - there is no
API for changing the O_NOINHERIT bit on an fd, and merely
changing the HANDLE_FLAG_INHERIT bit on the underlying handle
can lead to odd state. It may be possible by duplicating the
handle, using _open_osfhandle with the right flags, then
using dup2 to move the duplicate onto the original, but that
is not supported for now. */
else {
#if 0
switch (action)
{
#ifdef F_BARRIERFSYNC /* macOS */
case F_BARRIERFSYNC:
#endif
#ifdef F_CHKCLEAN /* macOS */
case F_CHKCLEAN:
#endif
#ifdef F_CLOSEM /* NetBSD, HP-UX */
case F_CLOSEM:
#endif
#ifdef F_FLUSH_DATA /* macOS */
case F_FLUSH_DATA:
#endif
#ifdef F_FREEZE_FS /* macOS */
case F_FREEZE_FS:
#endif
#ifdef F_FULLFSYNC /* macOS */
case F_FULLFSYNC:
#endif
#ifdef F_GETCONFINED /* macOS */
case F_GETCONFINED:
#endif
#ifdef F_GETDEFAULTPROTLEVEL /* macOS */
case F_GETDEFAULTPROTLEVEL:
#endif
#ifdef F_GETFD /* POSIX */
case F_GETFD:
#endif
#ifdef F_GETFL /* POSIX */
case F_GETFL:
#endif
#ifdef F_GETLEASE /* Linux */
case F_GETLEASE:
#endif
#ifdef F_GETNOSIGPIPE /* macOS */
case F_GETNOSIGPIPE:
#endif
#ifdef F_GETOWN /* POSIX */
case F_GETOWN:
#endif
#ifdef F_GETPIPE_SZ /* Linux */
case F_GETPIPE_SZ:
#endif
#ifdef F_GETPROTECTIONCLASS /* macOS */
case F_GETPROTECTIONCLASS:
#endif
#ifdef F_GETPROTECTIONLEVEL /* macOS */
case F_GETPROTECTIONLEVEL:
#endif
#ifdef F_GET_SEALS /* Linux */
case F_GET_SEALS:
#endif
#ifdef F_GETSIG /* Linux */
case F_GETSIG:
#endif
#ifdef F_MAXFD /* NetBSD */
case F_MAXFD:
#endif
#ifdef F_RECYCLE /* macOS */
case F_RECYCLE:
#endif
#ifdef F_SETFIFOENH /* HP-UX */
case F_SETFIFOENH:
#endif
#ifdef F_THAW_FS /* macOS */
case F_THAW_FS:
#endif
/* These actions take no argument. */
result = fcntl (fd, action);
break;
#ifdef F_ADD_SEALS /* Linux */
case F_ADD_SEALS:
#endif
#ifdef F_BADFD /* Solaris */
case F_BADFD:
#endif
#ifdef F_CHECK_OPENEVT /* macOS */
case F_CHECK_OPENEVT:
#endif
#ifdef F_DUP2FD /* FreeBSD, AIX, Solaris */
case F_DUP2FD:
#endif
#ifdef F_DUP2FD_CLOEXEC /* FreeBSD, Solaris */
case F_DUP2FD_CLOEXEC:
#endif
#ifdef F_DUP2FD_CLOFORK /* Solaris */
case F_DUP2FD_CLOFORK:
#endif
#ifdef F_DUPFD /* POSIX */
case F_DUPFD:
#endif
#ifdef F_DUPFD_CLOEXEC /* POSIX */
case F_DUPFD_CLOEXEC:
#endif
#ifdef F_DUPFD_CLOFORK /* Solaris */
case F_DUPFD_CLOFORK:
#endif
#ifdef F_GETXFL /* Solaris */
case F_GETXFL:
#endif
#ifdef F_GLOBAL_NOCACHE /* macOS */
case F_GLOBAL_NOCACHE:
#endif
#ifdef F_MAKECOMPRESSED /* macOS */
case F_MAKECOMPRESSED:
#endif
#ifdef F_MOVEDATAEXTENTS /* macOS */
case F_MOVEDATAEXTENTS:
#endif
#ifdef F_NOCACHE /* macOS */
case F_NOCACHE:
#endif
#ifdef F_NODIRECT /* macOS */
case F_NODIRECT:
#endif
#ifdef F_NOTIFY /* Linux */
case F_NOTIFY:
#endif
#ifdef F_OPLKACK /* IRIX */
case F_OPLKACK:
#endif
#ifdef F_OPLKREG /* IRIX */
case F_OPLKREG:
#endif
#ifdef F_RDAHEAD /* macOS */
case F_RDAHEAD:
#endif
#ifdef F_SETBACKINGSTORE /* macOS */
case F_SETBACKINGSTORE:
#endif
#ifdef F_SETCONFINED /* macOS */
case F_SETCONFINED:
#endif
#ifdef F_SETFD /* POSIX */
case F_SETFD:
#endif
#ifdef F_SETFL /* POSIX */
case F_SETFL:
#endif
#ifdef F_SETLEASE /* Linux */
case F_SETLEASE:
#endif
#ifdef F_SETNOSIGPIPE /* macOS */
case F_SETNOSIGPIPE:
#endif
#ifdef F_SETOWN /* POSIX */
case F_SETOWN:
#endif
#ifdef F_SETPIPE_SZ /* Linux */
case F_SETPIPE_SZ:
#endif
#ifdef F_SETPROTECTIONCLASS /* macOS */
case F_SETPROTECTIONCLASS:
#endif
#ifdef F_SETSIG /* Linux */
case F_SETSIG:
#endif
#ifdef F_SINGLE_WRITER /* macOS */
case F_SINGLE_WRITER:
#endif
/* These actions take an 'int' argument. */
{
int x = va_arg (arg, int);
result = fcntl (fd, action, x);
}
break;
default:
/* Other actions take a pointer argument. */
{
void *p = va_arg (arg, void *);
result = fcntl (fd, action, p);
}
break;
}
#else
errno = EINVAL;
#endif
}
va_end(arg);
return result;
}
static int rpl_fcntl_DUPFD(int fd, int target) {
int result;
#if !HAVE_FCNTL
result = dupfd(fd, target, 0);
#elif FCNTL_DUPFD_BUGGY || REPLACE_FCHDIR
/* Detect invalid target; needed for cygwin 1.5.x. */
if (target < 0 || getdtablesize() <= target) {
result = -1;
errno = EINVAL;
} else {
/* Haiku alpha 2 loses fd flags on original. */
int flags = fcntl(fd, F_GETFD);
if (flags < 0)
result = -1;
else {
result = fcntl(fd, F_DUPFD, target);
if (0 <= result && fcntl(fd, F_SETFD, flags) == -1) {
int saved_errno = errno;
close(result);
result = -1;
errno = saved_errno;
}
#if REPLACE_FCHDIR
if (0 <= result) result = _gl_register_dup(fd, result);
#endif
}
}
#else
result = fcntl(fd, F_DUPFD, target);
#endif
return result;
}
static int rpl_fcntl_DUPFD_CLOEXEC(int fd, int target) {
int result;
#if !HAVE_FCNTL
result = dupfd(fd, target, O_CLOEXEC);
#else /* HAVE_FCNTL */
#if defined __HAIKU__
/* On Haiku, the system fcntl (fd, F_DUPFD_CLOEXEC, target) sets
the FD_CLOEXEC flag on fd, not on target. Therefore avoid the
system fcntl in this case. */
#define have_dupfd_cloexec -1
#else
/* Try the system call first, if the headers claim it exists
(that is, if GNULIB_defined_F_DUPFD_CLOEXEC is 0), since we
may be running with a glibc that has the macro but with an
older kernel that does not support it. Cache the
information on whether the system call really works, but
avoid caching failure if the corresponding F_DUPFD fails
for any reason. 0 = unknown, 1 = yes, -1 = no. */
static int have_dupfd_cloexec = GNULIB_defined_F_DUPFD_CLOEXEC ? -1 : 0;
if (0 <= have_dupfd_cloexec) {
result = fcntl(fd, F_DUPFD_CLOEXEC, target);
if (0 <= result || errno != EINVAL) {
have_dupfd_cloexec = 1;
#if REPLACE_FCHDIR
if (0 <= result) result = _gl_register_dup(fd, result);
#endif
} else {
result = rpl_fcntl_DUPFD(fd, target);
if (result >= 0) have_dupfd_cloexec = -1;
}
} else
#endif
result = rpl_fcntl_DUPFD(fd, target);
if (0 <= result && have_dupfd_cloexec == -1) {
int flags = fcntl(result, F_GETFD);
if (flags < 0 || fcntl(result, F_SETFD, flags | FD_CLOEXEC) == -1) {
int saved_errno = errno;
close(result);
errno = saved_errno;
result = -1;
}
}
#endif /* HAVE_FCNTL */
return result;
}
#undef fcntl
#ifdef __KLIBC__
static int klibc_fcntl(int fd, int action, /* arg */...) {
va_list arg_ptr;
int arg;
struct stat sbuf;
int result;
va_start(arg_ptr, action);
arg = va_arg(arg_ptr, int);
result = fcntl(fd, action, arg);
/* EPERM for F_DUPFD, ENOTSUP for others */
if (result == -1 && (errno == EPERM || errno == ENOTSUP) &&
!fstat(fd, &sbuf) && S_ISDIR(sbuf.st_mode)) {
ULONG ulMode;
switch (action) {
case F_DUPFD:
/* Find available fd */
while (fcntl(arg, F_GETFL) != -1 || errno != EBADF) arg++;
result = dup2(fd, arg);
break;
/* Using underlying APIs is right ? */
case F_GETFD:
if (DosQueryFHState(fd, &ulMode)) break;
result = (ulMode & OPEN_FLAGS_NOINHERIT) ? FD_CLOEXEC : 0;
break;
case F_SETFD:
if (arg & ~FD_CLOEXEC) break;
if (DosQueryFHState(fd, &ulMode)) break;
if (arg & FD_CLOEXEC)
ulMode |= OPEN_FLAGS_NOINHERIT;
else
ulMode &= ~OPEN_FLAGS_NOINHERIT;
/* Filter supported flags. */
ulMode &= (OPEN_FLAGS_WRITE_THROUGH | OPEN_FLAGS_FAIL_ON_ERROR |
OPEN_FLAGS_NO_CACHE | OPEN_FLAGS_NOINHERIT);
if (DosSetFHState(fd, ulMode)) break;
result = 0;
break;
case F_GETFL:
result = 0;
break;
case F_SETFL:
if (arg != 0) break;
result = 0;
break;
default:
errno = EINVAL;
break;
}
}
va_end(arg_ptr);
return result;
}
#endif
| 15,443 | 557 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/strcache.c | /* Constant string caching for GNU Make.
Copyright (C) 2006-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* clang-format off */
#include "third_party/make/makeint.inc"
#include "third_party/make/hash.h"
/* A string cached here will never be freed, so we don't need to worry about
reference counting. We just store the string, and then remember it in a
hash so it can be looked up again. */
typedef unsigned short int sc_buflen_t;
struct strcache {
struct strcache *next; /* The next block of strings. Must be first! */
sc_buflen_t end; /* Offset to the beginning of free space. */
sc_buflen_t bytesfree; /* Free space left in this buffer. */
sc_buflen_t count; /* # of strings in this buffer (for stats). */
char buffer[1]; /* The buffer comes after this. */
};
/* The size (in bytes) of each cache buffer.
Try to pick something that will map well into the heap.
This must be able to be represented by a short int (<=65535). */
#define CACHE_BUFFER_BASE (8192)
#define CACHE_BUFFER_ALLOC(_s) ((_s) - (2 * sizeof (size_t)))
#define CACHE_BUFFER_OFFSET (offsetof (struct strcache, buffer))
#define CACHE_BUFFER_SIZE(_s) (CACHE_BUFFER_ALLOC(_s) - CACHE_BUFFER_OFFSET)
#define BUFSIZE CACHE_BUFFER_SIZE (CACHE_BUFFER_BASE)
static struct strcache *strcache = NULL;
static struct strcache *fullcache = NULL;
static unsigned long total_buffers = 0;
static unsigned long total_strings = 0;
static unsigned long total_size = 0;
/* Add a new buffer to the cache. Add it at the front to reduce search time.
This can also increase the overhead, since it's less likely that older
buffers will be filled in. However, GNU make has so many smaller strings
that this doesn't seem to be much of an issue in practice.
*/
static struct strcache *
new_cache (struct strcache **head, sc_buflen_t buflen)
{
struct strcache *new = xmalloc (buflen + CACHE_BUFFER_OFFSET);
new->end = 0;
new->count = 0;
new->bytesfree = buflen;
new->next = *head;
*head = new;
++total_buffers;
return new;
}
static const char *
copy_string (struct strcache *sp, const char *str, sc_buflen_t len)
{
/* Add the string to this cache. */
char *res = &sp->buffer[sp->end];
memmove (res, str, len);
res[len++] = '\0';
sp->end += len;
sp->bytesfree -= len;
++sp->count;
return res;
}
static const char *
add_string (const char *str, sc_buflen_t len)
{
const char *res;
struct strcache *sp;
struct strcache **spp = &strcache;
/* We need space for the nul char. */
sc_buflen_t sz = len + 1;
++total_strings;
total_size += sz;
/* If the string we want is too large to fit into a single buffer, then
no existing cache is large enough. Add it directly to the fullcache. */
if (sz > BUFSIZE)
{
sp = new_cache (&fullcache, sz);
return copy_string (sp, str, len);
}
/* Find the first cache with enough free space. */
for (; *spp != NULL; spp = &(*spp)->next)
if ((*spp)->bytesfree > sz)
break;
sp = *spp;
/* If nothing is big enough, make a new cache at the front. */
if (sp == NULL)
{
sp = new_cache (&strcache, BUFSIZE);
spp = &strcache;
}
/* Add the string to this cache. */
res = copy_string (sp, str, len);
/* If the amount free in this cache is less than the average string size,
consider it full and move it to the full list. */
if (total_strings > 20 && sp->bytesfree < (total_size / total_strings) + 1)
{
*spp = sp->next;
sp->next = fullcache;
fullcache = sp;
}
return res;
}
/* For strings too large for the strcache, we just save them in a list. */
struct hugestring {
struct hugestring *next; /* The next string. */
char buffer[1]; /* The string. */
};
static struct hugestring *hugestrings = NULL;
static const char *
add_hugestring (const char *str, size_t len)
{
struct hugestring *new = xmalloc (sizeof (struct hugestring) + len);
memcpy (new->buffer, str, len);
new->buffer[len] = '\0';
new->next = hugestrings;
hugestrings = new;
return new->buffer;
}
/* Hash table of strings in the cache. */
static unsigned long
str_hash_1 (const void *key)
{
return_ISTRING_HASH_1 ((const char *) key);
}
static unsigned long
str_hash_2 (const void *key)
{
return_ISTRING_HASH_2 ((const char *) key);
}
static int
str_hash_cmp (const void *x, const void *y)
{
return_ISTRING_COMPARE ((const char *) x, (const char *) y);
}
static struct hash_table strings;
static unsigned long total_adds = 0;
static const char *
add_hash (const char *str, size_t len)
{
char *const *slot;
const char *key;
/* If it's too large for the string cache, just copy it.
We don't bother trying to match these. */
if (len > USHRT_MAX - 1)
return add_hugestring (str, len);
/* Look up the string in the hash. If it's there, return it. */
slot = (char *const *) hash_find_slot (&strings, str);
key = *slot;
/* Count the total number of add operations we performed. */
++total_adds;
if (!HASH_VACANT (key))
return key;
/* Not there yet so add it to a buffer, then into the hash table. */
key = add_string (str, (sc_buflen_t)len);
hash_insert_at (&strings, key, slot);
return key;
}
/* Returns true if the string is in the cache; false if not. */
int
strcache_iscached (const char *str)
{
struct strcache *sp;
for (sp = strcache; sp != 0; sp = sp->next)
if (str >= sp->buffer && str < sp->buffer + sp->end)
return 1;
for (sp = fullcache; sp != 0; sp = sp->next)
if (str >= sp->buffer && str < sp->buffer + sp->end)
return 1;
{
struct hugestring *hp;
for (hp = hugestrings; hp != 0; hp = hp->next)
if (str == hp->buffer)
return 1;
}
return 0;
}
/* If the string is already in the cache, return a pointer to the cached
version. If not, add it then return a pointer to the cached version.
Note we do NOT take control of the string passed in. */
const char *
strcache_add (const char *str)
{
return add_hash (str, strlen (str));
}
const char *
strcache_add_len (const char *str, size_t len)
{
/* If we're not given a nul-terminated string we have to create one, because
the hashing functions expect it. */
if (str[len] != '\0')
{
char *key = alloca (len + 1);
memcpy (key, str, len);
key[len] = '\0';
str = key;
}
return add_hash (str, len);
}
void
strcache_init (void)
{
hash_init (&strings, 8000, str_hash_1, str_hash_2, str_hash_cmp);
}
/* Generate some stats output. */
void
strcache_print_stats (const char *prefix)
{
const struct strcache *sp;
unsigned long numbuffs = 0, fullbuffs = 0;
unsigned long totfree = 0, maxfree = 0, minfree = BUFSIZE;
if (! strcache)
{
printf (_("\n%s No strcache buffers\n"), prefix);
return;
}
/* Count the first buffer separately since it's not full. */
for (sp = strcache->next; sp != NULL; sp = sp->next)
{
sc_buflen_t bf = sp->bytesfree;
totfree += bf;
maxfree = (bf > maxfree ? bf : maxfree);
minfree = (bf < minfree ? bf : minfree);
++numbuffs;
}
for (sp = fullcache; sp != NULL; sp = sp->next)
{
sc_buflen_t bf = sp->bytesfree;
totfree += bf;
maxfree = (bf > maxfree ? bf : maxfree);
minfree = (bf < minfree ? bf : minfree);
++numbuffs;
++fullbuffs;
}
/* Make sure we didn't lose any buffers. */
assert (total_buffers == numbuffs + 1);
printf (_("\n%s strcache buffers: %lu (%lu) / strings = %lu / storage = %lu B / avg = %lu B\n"),
prefix, numbuffs + 1, fullbuffs, total_strings, total_size,
(total_size / total_strings));
printf (_("%s current buf: size = %hu B / used = %hu B / count = %hu / avg = %u B\n"),
prefix, (sc_buflen_t)BUFSIZE, strcache->end, strcache->count,
(unsigned int) (strcache->end / strcache->count));
if (numbuffs)
{
/* Show information about non-current buffers. */
unsigned long sz = total_size - strcache->end;
unsigned long cnt = total_strings - strcache->count;
sc_buflen_t avgfree = (sc_buflen_t) (totfree / numbuffs);
printf (_("%s other used: total = %lu B / count = %lu / avg = %lu B\n"),
prefix, sz, cnt, sz / cnt);
printf (_("%s other free: total = %lu B / max = %lu B / min = %lu B / avg = %hu B\n"),
prefix, totfree, maxfree, minfree, avgfree);
}
printf (_("\n%s strcache performance: lookups = %lu / hit rate = %lu%%\n"),
prefix, total_adds, (long unsigned)(100.0 * (total_adds - total_strings) / total_adds));
fputs (_("# hash-table stats:\n# "), stdout);
hash_print_stats (&strings, stdout);
}
| 9,402 | 328 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/README.cosmo | DESCRIPTION
Landlock Make is a fork of GNU Make that adds support for automatic
sandboxing, resource limits, and network access restrictions.
ORIGIN
GNU Make 4.3
http://ftp.gnu.org/gnu/make/make-4.3.tar.gz
LICENSE
GNU GPL version 3 or later
http://gnu.org/licenses/gpl.html
LOCAL CHANGES
- .INTERNET variable to allow internet access
- .PLEDGE variable which restricts system calls
- .UNVEIL variable which controls Landlock LSM
- .STRICT variable to disable implicit unveiling
- .UNSANDBOXED variable to disable pledge / unveil
- .CPU variable which tunes CPU rlimit in seconds
- .MEMORY variable for virtual memory limit, e.g. 512m
- .RSS variable for resident memory limit, e.g. 512m
- .FSIZE variable which tunes max file size, e.g. 1g
- .NPROC variable which tunes fork() / clone() limit
- .NOFILE variable which tunes file descriptor limit
- .MAXCORE variable to set upper limit on core dumps
- Do automatic setup and teardown of TMPDIR per rule
- Remove code that forces slow path if not using /bin/sh
- Remove 200,000 lines of VAX/OS2/DOS/AMIGA/etc. code
| 1,112 | 33 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/main.c | /* Argument parsing and main program of GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
/**/
#include "third_party/make/filedef.h"
#include "third_party/make/os.h"
/**/
#include "third_party/make/dep.h"
#include "third_party/make/job.h"
#include "third_party/make/variable.h"
/**/
#include "third_party/make/commands.h"
#include "third_party/make/debug.h"
#include "third_party/make/rule.h"
/**/
#include "libc/calls/calls.h"
#include "libc/calls/struct/bpf.h"
#include "libc/calls/struct/filter.h"
#include "libc/calls/struct/seccomp.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/dce.h"
#include "libc/limits.h"
#include "libc/macros.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/stack.h"
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/audit.h"
#include "libc/sysv/consts/pr.h"
#include "libc/sysv/consts/sig.h"
#include "third_party/make/getopt.h"
// clang-format off
STATIC_STACK_SIZE(0x00800000); // 8mb stack
#define HAVE_WAIT_NOHANG
static void clean_jobserver (int status);
static void print_data_base (void);
static void print_version (void);
static void decode_switches (int argc, const char **argv, int env);
static void decode_env_switches (const char *envar, size_t len);
static struct variable *define_makeflags (int all, int makefile);
static char *quote_for_env (char *out, const char *in);
static void initialize_global_hash_tables (void);
/* The structure that describes an accepted command switch. */
struct command_switch
{
int c; /* The switch character. */
enum /* Type of the value. */
{
flag, /* Turn int flag on. */
flag_off, /* Turn int flag off. */
string, /* One string per invocation. */
strlist, /* One string per switch. */
filename, /* A string containing a file name. */
positive_int, /* A positive integer. */
floating, /* A floating-point number (double). */
ignore /* Ignored. */
} type;
void *value_ptr; /* Pointer to the value-holding variable. */
unsigned int env:1; /* Can come from MAKEFLAGS. */
unsigned int toenv:1; /* Should be put in MAKEFLAGS. */
unsigned int no_makefile:1; /* Don't propagate when remaking makefiles. */
const void *noarg_value; /* Pointer to value used if no arg given. */
const void *default_value; /* Pointer to default value. */
const char *long_name; /* Long option name. */
};
/* True if C is a switch value that corresponds to a short option. */
#define short_option(c) ((c) <= CHAR_MAX)
/* The structure used to hold the list of strings given
in command switches of a type that takes strlist arguments. */
struct stringlist
{
const char **list; /* Nil-terminated list of strings. */
unsigned int idx; /* Index into above. */
unsigned int max; /* Number of pointers allocated. */
};
/* The recognized command switches. */
/* Nonzero means do extra verification (that may slow things down). */
int verify_flag;
/* Nonzero means do not print commands to be executed (-s). */
static int silent_flag;
static const int default_silent_flag = 0;
/* Nonzero means either -s was given, or .SILENT-with-no-deps was seen. */
int run_silent = 0;
/* Nonzero means just touch the files
that would appear to need remaking (-t) */
int touch_flag;
/* Nonzero means just print what commands would need to be executed,
don't actually execute them (-n). */
int just_print_flag;
/* Print debugging info (--debug). */
static struct stringlist *db_flags = 0;
static int debug_flag = 0;
int db_level = 0;
/* Synchronize output (--output-sync). */
char *output_sync_option = 0;
/* Environment variables override makefile definitions. */
int env_overrides = 0;
/* Nonzero means ignore status codes returned by commands
executed to remake files. Just treat them all as successful (-i). */
int ignore_errors_flag = 0;
/* Nonzero means don't remake anything, just print the data base
that results from reading the makefile (-p). */
int print_data_base_flag = 0;
/* Nonzero means don't remake anything; just return a nonzero status
if the specified targets are not up to date (-q). */
int question_flag = 0;
/* Nonzero means do not use any of the builtin rules (-r) / variables (-R). */
int no_builtin_rules_flag = 0;
int no_builtin_variables_flag = 0;
/* Nonzero means keep going even if remaking some file fails (-k). */
int keep_going_flag;
static const int default_keep_going_flag = 0;
/* Nonzero means check symlink mtimes. */
int check_symlink_flag = 0;
/* Nonzero means print directory before starting and when done (-w). */
int print_directory_flag = 0;
/* Nonzero means ignore print_directory_flag and never print the directory.
This is necessary because print_directory_flag is set implicitly. */
int inhibit_print_directory_flag = 0;
/* Nonzero means print version information. */
int print_version_flag = 0;
/* List of makefiles given with -f switches. */
static struct stringlist *makefiles = 0;
/* Size of the stack when we started. */
struct rlimit stack_limit;
/* Number of job slots for parallelism. */
unsigned int job_slots;
#define INVALID_JOB_SLOTS (-1)
static unsigned int master_job_slots = 0;
static int arg_job_slots = INVALID_JOB_SLOTS;
static const int default_job_slots = INVALID_JOB_SLOTS;
/* Value of job_slots that means no limit. */
static const int inf_jobs = 0;
/* Authorization for the jobserver. */
static char *jobserver_auth = NULL;
/* Handle for the mutex used on Windows to synchronize output of our
children under -O. */
char *sync_mutex = NULL;
/* Maximum load average at which multiple jobs will be run.
Negative values mean unlimited, while zero means limit to
zero load (which could be useful to start infinite jobs remotely
but one at a time locally). */
double max_load_average = -1.0;
double default_load_average = -1.0;
/* List of directories given with -C switches. */
static struct stringlist *directories = 0;
/* List of include directories given with -I switches. */
static struct stringlist *include_directories = 0;
/* List of files given with -o switches. */
static struct stringlist *old_files = 0;
/* List of files given with -W switches. */
static struct stringlist *new_files = 0;
/* List of strings to be eval'd. */
static struct stringlist *eval_strings = 0;
/* If nonzero, we should just print usage and exit. */
static int print_usage_flag = 0;
/* If nonzero, we should print a warning message
for each reference to an undefined variable. */
int warn_undefined_variables_flag;
/* If nonzero, always build all targets, regardless of whether
they appear out of date or not. */
static int always_make_set = 0;
int always_make_flag = 0;
/* If nonzero, we're in the "try to rebuild makefiles" phase. */
int rebuilding_makefiles = 0;
/* Remember the original value of the SHELL variable, from the environment. */
struct variable shell_var;
/* This character introduces a command: it's the first char on the line. */
char cmd_prefix = '\t';
/* The usage output. We write it this way to make life easier for the
translators, especially those trying to translate to right-to-left
languages like Hebrew. */
static const char *const usage[] =
{
N_("Options:\n"),
N_("\
-b, -m Ignored for compatibility.\n"),
N_("\
-B, --always-make Unconditionally make all targets.\n"),
N_("\
-C DIRECTORY, --directory=DIRECTORY\n\
Change to DIRECTORY before doing anything.\n"),
N_("\
-d Print lots of debugging information.\n"),
N_("\
--debug[=FLAGS] Print various types of debugging information.\n"),
N_("\
-e, --environment-overrides\n\
Environment variables override makefiles.\n"),
N_("\
-E STRING, --eval=STRING Evaluate STRING as a makefile statement.\n"),
N_("\
-f FILE, --file=FILE, --makefile=FILE\n\
Read FILE as a makefile.\n"),
N_("\
-h, --help Print this message and exit.\n"),
N_("\
-i, --ignore-errors Ignore errors from recipes.\n"),
N_("\
-I DIRECTORY, --include-dir=DIRECTORY\n\
Search DIRECTORY for included makefiles.\n"),
N_("\
-j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.\n"),
N_("\
-k, --keep-going Keep going when some targets can't be made.\n"),
N_("\
-l [N], --load-average[=N], --max-load[=N]\n\
Don't start multiple jobs unless load is below N.\n"),
N_("\
-L, --check-symlink-times Use the latest mtime between symlinks and target.\n"),
N_("\
-n, --just-print, --dry-run, --recon\n\
Don't actually run any recipe; just print them.\n"),
N_("\
-o FILE, --old-file=FILE, --assume-old=FILE\n\
Consider FILE to be very old and don't remake it.\n"),
N_("\
-O[TYPE], --output-sync[=TYPE]\n\
Synchronize output of parallel jobs by TYPE.\n"),
N_("\
-p, --print-data-base Print make's internal database.\n"),
N_("\
-q, --question Run no recipe; exit status says if up to date.\n"),
N_("\
-r, --no-builtin-rules Disable the built-in implicit rules.\n"),
N_("\
-R, --no-builtin-variables Disable the built-in variable settings.\n"),
N_("\
-s, --silent, --quiet Don't echo recipes.\n"),
N_("\
--no-silent Echo recipes (disable --silent mode).\n"),
N_("\
-S, --no-keep-going, --stop\n\
Turns off -k.\n"),
N_("\
-t, --touch Touch targets instead of remaking them.\n"),
N_("\
--trace Print tracing information.\n"),
N_("\
-v, --version Print the version number of make and exit.\n"),
N_("\
-w, --print-directory Print the current directory.\n"),
N_("\
--no-print-directory Turn off -w, even if it was turned on implicitly.\n"),
N_("\
-W FILE, --what-if=FILE, --new-file=FILE, --assume-new=FILE\n\
Consider FILE to be infinitely new.\n"),
N_("\
--warn-undefined-variables Warn when an undefined variable is referenced.\n"),
N_("\
--strace Log system calls.\n"),
N_("\
--ftrace Log function calls.\n"),
NULL
};
/* The table of command switches.
Order matters here: this is the order MAKEFLAGS will be constructed.
So be sure all simple flags (single char, no argument) come first. */
static const struct command_switch switches[] =
{
{ 'b', ignore, 0, 0, 0, 0, 0, 0, 0 },
{ 'B', flag, &always_make_set, 1, 1, 0, 0, 0, "always-make" },
{ 'd', flag, &debug_flag, 1, 1, 0, 0, 0, 0 },
{ 'e', flag, &env_overrides, 1, 1, 0, 0, 0, "environment-overrides", },
{ 'E', strlist, &eval_strings, 1, 0, 0, 0, 0, "eval" },
{ 'h', flag, &print_usage_flag, 0, 0, 0, 0, 0, "help" },
{ 'i', flag, &ignore_errors_flag, 1, 1, 0, 0, 0, "ignore-errors" },
{ 'k', flag, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
"keep-going" },
{ 'L', flag, &check_symlink_flag, 1, 1, 0, 0, 0, "check-symlink-times" },
{ 'm', ignore, 0, 0, 0, 0, 0, 0, 0 },
{ 'n', flag, &just_print_flag, 1, 1, 1, 0, 0, "just-print" },
{ 'p', flag, &print_data_base_flag, 1, 1, 0, 0, 0, "print-data-base" },
{ 'q', flag, &question_flag, 1, 1, 1, 0, 0, "question" },
{ 'r', flag, &no_builtin_rules_flag, 1, 1, 0, 0, 0, "no-builtin-rules" },
{ 'R', flag, &no_builtin_variables_flag, 1, 1, 0, 0, 0,
"no-builtin-variables" },
{ 's', flag, &silent_flag, 1, 1, 0, 0, &default_silent_flag, "silent" },
{ 'S', flag_off, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
"no-keep-going" },
{ 't', flag, &touch_flag, 1, 1, 1, 0, 0, "touch" },
{ 'v', flag, &print_version_flag, 1, 1, 0, 0, 0, "version" },
{ 'w', flag, &print_directory_flag, 1, 1, 0, 0, 0, "print-directory" },
/* These options take arguments. */
{ 'C', filename, &directories, 0, 0, 0, 0, 0, "directory" },
{ 'f', filename, &makefiles, 0, 0, 0, 0, 0, "file" },
{ 'I', filename, &include_directories, 1, 1, 0, 0, 0,
"include-dir" },
{ 'j', positive_int, &arg_job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
"jobs" },
{ 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,
&default_load_average, "load-average" },
{ 'o', filename, &old_files, 0, 0, 0, 0, 0, "old-file" },
{ 'O', string, &output_sync_option, 1, 1, 0, "target", 0, "output-sync" },
{ 'W', filename, &new_files, 0, 0, 0, 0, 0, "what-if" },
/* These are long-style options. */
{ CHAR_MAX+1, strlist, &db_flags, 1, 1, 0, "basic", 0, "debug" },
{ CHAR_MAX+2, string, &jobserver_auth, 1, 1, 0, 0, 0, "jobserver-auth" },
{ CHAR_MAX+3, flag, &trace_flag, 1, 1, 0, 0, 0, "trace" },
{ CHAR_MAX+4, flag, &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
"no-print-directory" },
{ CHAR_MAX+5, flag, &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
"warn-undefined-variables" },
{ CHAR_MAX+7, string, &sync_mutex, 1, 1, 0, 0, 0, "sync-mutex" },
{ CHAR_MAX+8, flag_off, &silent_flag, 1, 1, 0, 0, &default_silent_flag, "no-silent" },
{ CHAR_MAX+9, string, &jobserver_auth, 1, 0, 0, 0, 0, "jobserver-fds" },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
/* Secondary long names for options. */
static struct option long_option_aliases[] =
{
{ "quiet", no_argument, 0, 's' },
{ "stop", no_argument, 0, 'S' },
{ "new-file", required_argument, 0, 'W' },
{ "assume-new", required_argument, 0, 'W' },
{ "assume-old", required_argument, 0, 'o' },
{ "max-load", optional_argument, 0, 'l' },
{ "dry-run", no_argument, 0, 'n' },
{ "recon", no_argument, 0, 'n' },
{ "makefile", required_argument, 0, 'f' },
};
/* List of goal targets. */
static struct goaldep *goals, *lastgoal;
/* List of variables which were defined on the command line
(or, equivalently, in MAKEFLAGS). */
struct command_variable
{
struct command_variable *next;
struct variable *variable;
};
static struct command_variable *command_variables;
/* The name we were invoked with. */
const char *program;
/* Our current directory before processing any -C options. */
char *directory_before_chdir;
/* Our current directory after processing all -C options. */
char *starting_directory;
/* Value of the MAKELEVEL variable at startup (or 0). */
unsigned int makelevel;
/* Pointer to the value of the .DEFAULT_GOAL special variable.
The value will be the name of the goal to remake if the command line
does not override it. It can be set by the makefile, or else it's
the first target defined in the makefile whose name does not start
with '.'. */
struct variable * default_goal_var;
/* Pointer to structure for the file .DEFAULT
whose commands are used for any file that has none of its own.
This is zero if the makefiles do not define .DEFAULT. */
struct file *default_file;
/* Nonzero if we have seen the magic '.POSIX' target.
This turns on pedantic compliance with POSIX.2. */
int posix_pedantic;
/* Nonzero if we have seen the '.SECONDEXPANSION' target.
This turns on secondary expansion of prerequisites. */
int second_expansion;
/* Nonzero if we have seen the '.ONESHELL' target.
This causes the entire recipe to be handed to SHELL
as a single string, potentially containing newlines. */
int one_shell;
/* One of OUTPUT_SYNC_* if the "--output-sync" option was given. This
attempts to synchronize the output of parallel jobs such that the results
of each job stay together. */
int output_sync = OUTPUT_SYNC_NONE;
/* Nonzero if the "--trace" option was given. */
int trace_flag = 0;
/* Nonzero if we have seen the '.NOTPARALLEL' target.
This turns off parallel builds for this invocation of make. */
int not_parallel;
/* Nonzero if some rule detected clock skew; we keep track so (a) we only
print one warning about it during the run, and (b) we can print a final
warning at the end of the run. */
int clock_skew_detected;
/* Map of possible stop characters for searching strings. */
unsigned short stopchar_map[UCHAR_MAX + 1] = {0};
/* If output-sync is enabled we'll collect all the output generated due to
options, while reading makefiles, etc. */
struct output make_sync;
/* Mask of signals that are being caught with fatal_error_signal. */
sigset_t fatal_signal_set;
typedef RETSIGTYPE (*bsd_signal_ret_t) (int);
static bsd_signal_ret_t
bsd_signal (int sig, bsd_signal_ret_t func)
{
struct sigaction act, oact;
act.sa_handler = func;
act.sa_flags = SA_RESTART;
sigemptyset (&act.sa_mask);
sigaddset (&act.sa_mask, sig);
if (sigaction (sig, &act, &oact) != 0)
return SIG_ERR;
return oact.sa_handler;
}
static void
initialize_global_hash_tables (void)
{
init_hash_global_variable_set ();
strcache_init ();
init_hash_files ();
hash_init_directories ();
hash_init_function_table ();
}
/* This character map locate stop chars when parsing GNU makefiles.
Each element is true if we should stop parsing on that character. */
static void
initialize_stopchar_map (void)
{
int i;
stopchar_map[(int)'\0'] = MAP_NUL;
stopchar_map[(int)'#'] = MAP_COMMENT;
stopchar_map[(int)';'] = MAP_SEMI;
stopchar_map[(int)'='] = MAP_EQUALS;
stopchar_map[(int)':'] = MAP_COLON;
stopchar_map[(int)'|'] = MAP_PIPE;
stopchar_map[(int)'.'] = MAP_DOT | MAP_USERFUNC;
stopchar_map[(int)','] = MAP_COMMA;
stopchar_map[(int)'('] = MAP_VARSEP;
stopchar_map[(int)'{'] = MAP_VARSEP;
stopchar_map[(int)'}'] = MAP_VARSEP;
stopchar_map[(int)')'] = MAP_VARSEP;
stopchar_map[(int)'$'] = MAP_VARIABLE;
stopchar_map[(int)'-'] = MAP_USERFUNC;
stopchar_map[(int)'_'] = MAP_USERFUNC;
stopchar_map[(int)' '] = MAP_BLANK;
stopchar_map[(int)'\t'] = MAP_BLANK;
stopchar_map[(int)'/'] = MAP_DIRSEP;
#if defined(HAVE_DOS_PATHS)
stopchar_map[(int)'\\'] |= MAP_DIRSEP;
#endif
for (i = 1; i <= UCHAR_MAX; ++i)
{
if (isspace (i) && NONE_SET (stopchar_map[i], MAP_BLANK))
/* Don't mark blank characters as newline characters. */
stopchar_map[i] |= MAP_NEWLINE;
else if (isalnum (i))
stopchar_map[i] |= MAP_USERFUNC;
}
}
static const char *
expand_command_line_file (const char *name)
{
const char *cp;
char *expanded = 0;
if (name[0] == '\0')
O (fatal, NILF, _("empty string invalid as file name"));
if (name[0] == '~')
{
expanded = tilde_expand (name);
if (expanded && expanded[0] != '\0')
name = expanded;
}
/* This is also done in parse_file_seq, so this is redundant
for names read from makefiles. It is here for names passed
on the command line. */
while (name[0] == '.' && name[1] == '/')
{
name += 2;
while (name[0] == '/')
/* Skip following slashes: ".//foo" is "foo", not "/foo". */
++name;
}
if (name[0] == '\0')
{
/* Nothing else but one or more "./", maybe plus slashes! */
name = "./";
}
cp = strcache_add (name);
free (expanded);
return cp;
}
/* Toggle -d on receipt of SIGUSR1. */
#ifdef SIGUSR1
static RETSIGTYPE
debug_signal_handler (int sig UNUSED)
{
db_level = db_level ? DB_NONE : DB_BASIC;
}
#endif
static void
decode_debug_flags (void)
{
const char **pp;
if (debug_flag)
db_level = DB_ALL;
if (db_flags)
for (pp=db_flags->list; *pp; ++pp)
{
const char *p = *pp;
while (1)
{
switch (tolower (p[0]))
{
case 'a':
db_level |= DB_ALL;
break;
case 'b':
db_level |= DB_BASIC;
break;
case 'i':
db_level |= DB_BASIC | DB_IMPLICIT;
break;
case 'j':
db_level |= DB_JOBS;
break;
case 'm':
db_level |= DB_BASIC | DB_MAKEFILES;
break;
case 'n':
db_level = 0;
break;
case 'v':
db_level |= DB_BASIC | DB_VERBOSE;
break;
default:
OS (fatal, NILF,
_("unknown debug level specification '%s'"), p);
}
while (*(++p) != '\0')
if (*p == ',' || *p == ' ')
{
++p;
break;
}
if (*p == '\0')
break;
}
}
if (db_level)
verify_flag = 1;
if (! db_level)
debug_flag = 0;
}
static void
decode_output_sync_flags (void)
{
#ifdef NO_OUTPUT_SYNC
output_sync = OUTPUT_SYNC_NONE;
#else
if (output_sync_option)
{
if (streq (output_sync_option, "none"))
output_sync = OUTPUT_SYNC_NONE;
else if (streq (output_sync_option, "line"))
output_sync = OUTPUT_SYNC_LINE;
else if (streq (output_sync_option, "target"))
output_sync = OUTPUT_SYNC_TARGET;
else if (streq (output_sync_option, "recurse"))
output_sync = OUTPUT_SYNC_RECURSE;
else
OS (fatal, NILF,
_("unknown output-sync type '%s'"), output_sync_option);
}
if (sync_mutex)
RECORD_SYNC_MUTEX (sync_mutex);
#endif
}
#ifdef WINDOWS32
#ifndef NO_OUTPUT_SYNC
/* This is called from start_job_command when it detects that
output_sync option is in effect. The handle to the synchronization
mutex is passed, as a string, to sub-makes via the --sync-mutex
command-line argument. */
void
prepare_mutex_handle_string (sync_handle_t handle)
{
if (!sync_mutex)
{
/* Prepare the mutex handle string for our children. */
/* 2 hex digits per byte + 2 characters for "0x" + null. */
sync_mutex = xmalloc ((2 * sizeof (sync_handle_t)) + 2 + 1);
sprintf (sync_mutex, "0x%Ix", handle);
define_makeflags (1, 0);
}
}
#endif /* NO_OUTPUT_SYNC */
/*
* HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
* exception and print it to stderr instead.
*
* If ! DB_VERBOSE, just print a simple message and exit.
* If DB_VERBOSE, print a more verbose message.
* If compiled for DEBUG, let exception pass through to GUI so that
* debuggers can attach.
*/
LONG WINAPI
handle_runtime_exceptions (struct _EXCEPTION_POINTERS *exinfo)
{
PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
LPSTR cmdline = GetCommandLine ();
LPSTR prg = strtok (cmdline, " ");
CHAR errmsg[1024];
#ifdef USE_EVENT_LOG
HANDLE hEventSource;
LPTSTR lpszStrings[1];
#endif
if (! ISDB (DB_VERBOSE))
{
sprintf (errmsg,
_("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\n"),
prg, exrec->ExceptionCode, exrec->ExceptionAddress);
fprintf (stderr, errmsg);
exit (255);
}
sprintf (errmsg,
_("\nUnhandled exception filter called from program %s\nExceptionCode = %lx\nExceptionFlags = %lx\nExceptionAddress = 0x%p\n"),
prg, exrec->ExceptionCode, exrec->ExceptionFlags,
exrec->ExceptionAddress);
if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
&& exrec->NumberParameters >= 2)
sprintf (&errmsg[strlen(errmsg)],
(exrec->ExceptionInformation[0]
? _("Access violation: write operation at address 0x%p\n")
: _("Access violation: read operation at address 0x%p\n")),
(PVOID)exrec->ExceptionInformation[1]);
/* turn this on if we want to put stuff in the event log too */
#ifdef USE_EVENT_LOG
hEventSource = RegisterEventSource (NULL, u"GNU Make");
lpszStrings[0] = errmsg;
if (hEventSource != NULL)
{
ReportEvent (hEventSource, /* handle of event source */
EVENTLOG_ERROR_TYPE, /* event type */
0, /* event category */
0, /* event ID */
NULL, /* current user's SID */
1, /* strings in lpszStrings */
0, /* no bytes of raw data */
lpszStrings, /* array of error strings */
NULL); /* no raw data */
(VOID) DeregisterEventSource (hEventSource);
}
#endif
/* Write the error to stderr too */
fprintf (stderr, errmsg);
#ifdef DEBUG
return EXCEPTION_CONTINUE_SEARCH;
#else
exit (255);
return (255); /* not reached */
#endif
}
/*
* On WIN32 systems we don't have the luxury of a /bin directory that
* is mapped globally to every drive mounted to the system. Since make could
* be invoked from any drive, and we don't want to propagate /bin/sh
* to every single drive. Allow ourselves a chance to search for
* a value for default shell here (if the default path does not exist).
*/
int
find_and_set_default_shell (const char *token)
{
int sh_found = 0;
char *atoken = 0;
const char *search_token;
const char *tokend;
PATH_VAR(sh_path);
extern const char *default_shell;
if (!token)
search_token = default_shell;
else
search_token = atoken = xstrdup (token);
/* If the user explicitly requests the DOS cmd shell, obey that request.
However, make sure that's what they really want by requiring the value
of SHELL either equal, or have a final path element of, "cmd" or
"cmd.exe" case-insensitive. */
tokend = search_token + strlen (search_token) - 3;
if (((tokend == search_token
|| (tokend > search_token
&& (tokend[-1] == '/' || tokend[-1] == '\\')))
&& !strcasecmp (tokend, "cmd"))
|| ((tokend - 4 == search_token
|| (tokend - 4 > search_token
&& (tokend[-5] == '/' || tokend[-5] == '\\')))
&& !strcasecmp (tokend - 4, "cmd.exe")))
{
batch_mode_shell = 1;
unixy_shell = 0;
sprintf (sh_path, "%s", search_token);
default_shell = xstrdup (w32ify (sh_path, 0));
DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
default_shell));
sh_found = 1;
}
else if (!no_default_sh_exe
&& (token == NULL || !strcmp (search_token, default_shell)))
{
/* no new information, path already set or known */
sh_found = 1;
}
else if (_access (search_token, 0) == 0)
{
/* search token path was found */
sprintf (sh_path, "%s", search_token);
default_shell = xstrdup (w32ify (sh_path, 0));
DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
default_shell));
sh_found = 1;
}
else
{
char *p;
struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
/* Search Path for shell */
if (v && v->value)
{
char *ep;
p = v->value;
ep = strchr (p, PATH_SEPARATOR_CHAR);
while (ep && *ep)
{
*ep = '\0';
sprintf (sh_path, "%s/%s", p, search_token);
if (_access (sh_path, 0) == 0)
{
default_shell = xstrdup (w32ify (sh_path, 0));
sh_found = 1;
*ep = PATH_SEPARATOR_CHAR;
/* terminate loop */
p += strlen (p);
}
else
{
*ep = PATH_SEPARATOR_CHAR;
p = ++ep;
}
ep = strchr (p, PATH_SEPARATOR_CHAR);
}
/* be sure to check last element of Path */
if (p && *p)
{
sprintf (sh_path, "%s/%s", p, search_token);
if (_access (sh_path, 0) == 0)
{
default_shell = xstrdup (w32ify (sh_path, 0));
sh_found = 1;
}
}
if (sh_found)
DB (DB_VERBOSE,
(_("find_and_set_shell() path search set default_shell = %s\n"),
default_shell));
}
}
/* naive test */
if (!unixy_shell && sh_found
&& (strstr (default_shell, "sh") || strstr (default_shell, "SH")))
{
unixy_shell = 1;
batch_mode_shell = 0;
}
#ifdef BATCH_MODE_ONLY_SHELL
batch_mode_shell = 1;
#endif
free (atoken);
return (sh_found);
}
#endif /* WINDOWS32 */
static void
reset_jobserver (void)
{
jobserver_clear ();
free (jobserver_auth);
jobserver_auth = NULL;
}
int
main (int argc, char **argv, char **envp)
{
static char *stdin_nm = 0;
int makefile_status = MAKE_SUCCESS;
struct goaldep *read_files;
PATH_VAR (current_directory);
unsigned int restarts = 0;
unsigned int syncing = 0;
int argv_slots;
/* Useful for attaching debuggers, etc. */
SPIN ("main-entry");
output_init (&make_sync);
initialize_stopchar_map();
/* Get rid of any avoidable limit on stack size. */
{
struct rlimit rlim;
/* Set the stack limit huge so that alloca does not fail. */
if (getrlimit (RLIMIT_STACK, &rlim) == 0
&& rlim.rlim_cur > 0 && rlim.rlim_cur < rlim.rlim_max)
{
stack_limit = rlim;
rlim.rlim_cur = rlim.rlim_max;
setrlimit (RLIMIT_STACK, &rlim);
}
else
stack_limit.rlim_cur = 0;
}
/* Needed for OS/2 */
initialize_main (&argc, &argv);
#ifdef MAKE_MAINTAINER_MODE
/* In maintainer mode we always enable verification. */
verify_flag = 1;
#endif
/* Set up gettext/internationalization support. */
setlocale (LC_ALL, "");
/* The cast to void shuts up compiler warnings on systems that
disable NLS. */
(void)bindtextdomain (PACKAGE, LOCALEDIR);
(void)textdomain (PACKAGE);
sigemptyset (&fatal_signal_set);
#define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
#define FATAL_SIG(sig) \
if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \
bsd_signal (sig, SIG_IGN); \
else \
ADD_SIG (sig);
FATAL_SIG (SIGHUP);
FATAL_SIG (SIGQUIT);
FATAL_SIG (SIGINT);
FATAL_SIG (SIGTERM);
FATAL_SIG (SIGXCPU);
FATAL_SIG (SIGXFSZ);
FATAL_SIG (SIGPIPE); /* [jart] handle case of piped into less */
#undef FATAL_SIG
/* Do not ignore the child-death signal. This must be done before
any children could possibly be created; otherwise, the wait
functions won't work on systems with the SVR4 ECHILD brain
damage, if our invoker is ignoring this signal. */
#ifdef HAVE_WAIT_NOHANG
# if defined SIGCHLD
(void) bsd_signal (SIGCHLD, SIG_DFL);
# endif
# if defined SIGCLD && SIGCLD != SIGCHLD
(void) bsd_signal (SIGCLD, SIG_DFL);
# endif
#endif
output_init (NULL);
/* Figure out where this program lives. */
if (argv[0] == 0)
argv[0] = (char *)"";
if (argv[0][0] == '\0')
program = "make";
else
{
#if defined(HAVE_DOS_PATHS)
const char* start = argv[0];
/* Skip an initial drive specifier if present. */
if (isalpha ((unsigned char)start[0]) && start[1] == ':')
start += 2;
if (start[0] == '\0')
program = "make";
else
{
program = start + strlen (start);
while (program > start && ! STOP_SET (program[-1], MAP_DIRSEP))
--program;
/* Remove the .exe extension if present. */
{
size_t len = strlen (program);
if (len > 4 && streq (&program[len - 4], ".exe"))
program = xstrndup (program, len - 4);
}
}
#else
program = strrchr (argv[0], '/');
if (program == 0)
program = argv[0];
else
++program;
#endif
}
/* Set up to access user data (files). */
user_access ();
initialize_global_hash_tables ();
/* Figure out where we are. */
if (getcwd (current_directory, GET_PATH_MAX) == 0)
{
#ifdef HAVE_GETCWD
perror_with_name ("getcwd", "");
#else
OS (error, NILF, "getwd: %s", current_directory);
#endif
current_directory[0] = '\0';
directory_before_chdir = 0;
}
else
directory_before_chdir = xstrdup (current_directory);
/* Initialize the special variables. */
define_variable_cname (".VARIABLES", "", o_default, 0)->special = 1;
/* define_variable_cname (".TARGETS", "", o_default, 0)->special = 1; */
define_variable_cname (".RECIPEPREFIX", "", o_default, 0)->special = 1;
define_variable_cname (".SHELLFLAGS", "-c", o_default, 0);
define_variable_cname (".LOADED", "", o_default, 0);
/* Set up .FEATURES
Use a separate variable because define_variable_cname() is a macro and
some compilers (MSVC) don't like conditionals in macros. */
{
const char *features = "target-specific order-only second-expansion"
" else-if shortest-stem undefine oneshell nocomment"
" grouped-target extra-prereqs"
#ifndef NO_ARCHIVES
" archives"
#endif
#ifdef MAKE_JOBSERVER
" jobserver"
#endif
#ifndef NO_OUTPUT_SYNC
" output-sync"
#endif
#ifdef MAKE_SYMLINKS
" check-symlink"
#endif
#ifdef MAKE_MAINTAINER_MODE
" maintainer"
#endif
;
define_variable_cname (".FEATURES", features, o_default, 0);
}
/* Configure GNU Guile support */
guile_gmake_setup (NILF);
/* Read in variables from the environment. It is important that this be
done before $(MAKE) is figured out so its definitions will not be
from the environment. */
{
unsigned int i;
for (i = 0; envp[i] != 0; ++i)
{
struct variable *v;
const char *ep = envp[i];
/* By default, export all variables culled from the environment. */
enum variable_export export = v_export;
size_t len;
while (! STOP_SET (*ep, MAP_EQUALS))
++ep;
/* If there's no equals sign it's a malformed environment. Ignore. */
if (*ep == '\0')
continue;
#ifdef WINDOWS32
if (!unix_path && strneq (envp[i], "PATH=", 5))
unix_path = ep+1;
else if (!strnicmp (envp[i], "Path=", 5))
{
if (!windows32_path)
windows32_path = ep+1;
/* PATH gets defined after the loop exits. */
continue;
}
#endif
/* Length of the variable name, and skip the '='. */
len = ep++ - envp[i];
/* If this is MAKE_RESTARTS, check to see if the "already printed
the enter statement" flag is set. */
if (len == 13 && strneq (envp[i], "MAKE_RESTARTS", 13))
{
if (*ep == '-')
{
OUTPUT_TRACED ();
++ep;
}
restarts = (unsigned int) atoi (ep);
export = v_noexport;
}
v = define_variable (envp[i], len, ep, o_env, 1);
/* POSIX says the value of SHELL set in the makefile won't change the
value of SHELL given to subprocesses. */
if (streq (v->name, "SHELL"))
{
export = v_noexport;
shell_var.name = xstrdup ("SHELL");
shell_var.length = 5;
shell_var.value = xstrdup (ep);
}
v->export = export;
}
}
#ifdef WINDOWS32
/* If we didn't find a correctly spelled PATH we define PATH as
* either the first misspelled value or an empty string
*/
if (!unix_path)
define_variable_cname ("PATH", windows32_path ? windows32_path : "",
o_env, 1)->export = v_export;
#endif
/* Decode the switches. */
decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
/* Clear GNUMAKEFLAGS to avoid duplication. */
define_variable_cname ("GNUMAKEFLAGS", "", o_env, 0);
decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
#if 0
/* People write things like:
MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
and we set the -p, -i and -e switches. Doesn't seem quite right. */
decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
#endif
/* In output sync mode we need to sync any output generated by reading the
makefiles, such as in $(info ...) or stderr from $(shell ...) etc. */
syncing = make_sync.syncout = (output_sync == OUTPUT_SYNC_LINE
|| output_sync == OUTPUT_SYNC_TARGET);
OUTPUT_SET (&make_sync);
/* Parse the command line options. Remember the job slots set this way. */
{
int env_slots = arg_job_slots;
arg_job_slots = INVALID_JOB_SLOTS;
decode_switches (argc, (const char **)argv, 0);
argv_slots = arg_job_slots;
if (arg_job_slots == INVALID_JOB_SLOTS)
arg_job_slots = env_slots;
}
/* Set a variable specifying whether stdout/stdin is hooked to a TTY. */
#ifdef HAVE_ISATTY
if (isatty (fileno (stdout)))
if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMOUT")))
{
const char *tty = TTYNAME (fileno (stdout));
define_variable_cname ("MAKE_TERMOUT", tty ? tty : DEFAULT_TTYNAME,
o_default, 0)->export = v_export;
}
if (isatty (fileno (stderr)))
if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMERR")))
{
const char *tty = TTYNAME (fileno (stderr));
define_variable_cname ("MAKE_TERMERR", tty ? tty : DEFAULT_TTYNAME,
o_default, 0)->export = v_export;
}
#endif
/* Reset in case the switches changed our minds. */
syncing = (output_sync == OUTPUT_SYNC_LINE
|| output_sync == OUTPUT_SYNC_TARGET);
if (make_sync.syncout && ! syncing)
output_close (&make_sync);
make_sync.syncout = syncing;
OUTPUT_SET (&make_sync);
/* Figure out the level of recursion. */
{
struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
if (v && v->value[0] != '\0' && v->value[0] != '-')
makelevel = (unsigned int) atoi (v->value);
else
makelevel = 0;
}
/* Set always_make_flag if -B was given and we've not restarted already. */
always_make_flag = always_make_set && (restarts == 0);
/* Print version information, and exit. */
if (print_version_flag)
{
print_version ();
die (MAKE_SUCCESS);
}
if (ISDB (DB_BASIC))
print_version ();
/* Set the "MAKE_COMMAND" variable to the name we were invoked with.
(If it is a relative pathname with a slash, prepend our directory name
so the result will run the same program regardless of the current dir.
If it is a name with no slash, we can only hope that PATH did not
find it in the current directory.) */
#ifdef WINDOWS32
/*
* Convert from backslashes to forward slashes for
* programs like sh which don't like them. Shouldn't
* matter if the path is one way or the other for
* CreateProcess().
*/
if (strpbrk (argv[0], "/:\\") || strstr (argv[0], "..")
|| strneq (argv[0], "//", 2))
argv[0] = xstrdup (w32ify (argv[0], 1));
#else /* WINDOWS32 */
if (current_directory[0] != '\0'
&& argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0
#ifdef HAVE_DOS_PATHS
&& (argv[0][0] != '\\' && (!argv[0][0] || argv[0][1] != ':'))
&& strchr (argv[0], '\\') != 0
#endif
)
argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
#endif /* WINDOWS32 */
/* We may move, but until we do, here we are. */
starting_directory = current_directory;
/* Validate the arg_job_slots configuration before we define MAKEFLAGS so
users get an accurate value in their makefiles.
At this point arg_job_slots is the argv setting, if there is one, else
the MAKEFLAGS env setting, if there is one. */
if (jobserver_auth)
{
/* We're a child in an existing jobserver group. */
if (argv_slots == INVALID_JOB_SLOTS)
{
/* There's no -j option on the command line: check authorization. */
if (jobserver_parse_auth (jobserver_auth))
{
/* Success! Use the jobserver. */
goto job_setup_complete;
}
/* Oops: we have jobserver-auth but it's invalid :(. */
O (error, NILF, _("warning: jobserver unavailable: using -j1. Add '+' to parent make rule."));
arg_job_slots = 1;
}
/* The user provided a -j setting on the command line so use it: we're
the master make of a new jobserver group. */
else if (!restarts)
ON (error, NILF,
_("warning: -j%d forced in submake: resetting jobserver mode."),
argv_slots);
/* We can't use our parent's jobserver, so reset. */
reset_jobserver ();
}
job_setup_complete:
/* The extra indirection through $(MAKE_COMMAND) is done
for hysterical raisins. */
define_variable_cname ("MAKE_COMMAND", argv[0], o_default, 0);
define_variable_cname ("MAKE", "$(MAKE_COMMAND)", o_default, 1);
if (command_variables != 0)
{
struct command_variable *cv;
struct variable *v;
size_t len = 0;
char *value, *p;
/* Figure out how much space will be taken up by the command-line
variable definitions. */
for (cv = command_variables; cv != 0; cv = cv->next)
{
v = cv->variable;
len += 2 * strlen (v->name);
if (! v->recursive)
++len;
++len;
len += 2 * strlen (v->value);
++len;
}
/* Now allocate a buffer big enough and fill it. */
p = value = alloca (len);
for (cv = command_variables; cv != 0; cv = cv->next)
{
v = cv->variable;
p = quote_for_env (p, v->name);
if (! v->recursive)
*p++ = ':';
*p++ = '=';
p = quote_for_env (p, v->value);
*p++ = ' ';
}
p[-1] = '\0'; /* Kill the final space and terminate. */
/* Define an unchangeable variable with a name that no POSIX.2
makefile could validly use for its own variable. */
define_variable_cname ("-*-command-variables-*-", value, o_automatic, 0);
/* Define the variable; this will not override any user definition.
Normally a reference to this variable is written into the value of
MAKEFLAGS, allowing the user to override this value to affect the
exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
a reference to this hidden variable is written instead. */
define_variable_cname ("MAKEOVERRIDES", "${-*-command-variables-*-}",
o_env, 1);
}
/* If there were -C flags, move ourselves about. */
if (directories != 0)
{
unsigned int i;
for (i = 0; directories->list[i] != 0; ++i)
{
const char *dir = directories->list[i];
#ifdef WINDOWS32
/* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
But allow -C/ just in case someone wants that. */
{
char *p = (char *)dir + strlen (dir) - 1;
while (p > dir && (p[0] == '/' || p[0] == '\\'))
--p;
p[1] = '\0';
}
#endif
if (chdir (dir) < 0)
pfatal_with_name (dir);
}
}
#ifdef WINDOWS32
/*
* THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
* TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
*
* The functions in dir.c can incorrectly cache information for "."
* before we have changed directory and this can cause file
* lookups to fail because the current directory (.) was pointing
* at the wrong place when it was first evaluated.
*/
no_default_sh_exe = !find_and_set_default_shell (NULL);
#endif /* WINDOWS32 */
/* Except under -s, always do -w in sub-makes and under -C. */
if (!silent_flag && (directories != 0 || makelevel > 0))
print_directory_flag = 1;
/* Let the user disable that with --no-print-directory. */
if (inhibit_print_directory_flag)
print_directory_flag = 0;
/* If -R was given, set -r too (doesn't make sense otherwise!) */
if (no_builtin_variables_flag)
no_builtin_rules_flag = 1;
/* Construct the list of include directories to search. */
construct_include_path (include_directories == 0
? 0 : include_directories->list);
/* If we chdir'ed, figure out where we are now. */
if (directories)
{
#ifdef WINDOWS32
if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
#else
if (getcwd (current_directory, GET_PATH_MAX) == 0)
#endif
{
#ifdef HAVE_GETCWD
perror_with_name ("getcwd", "");
#else
OS (error, NILF, "getwd: %s", current_directory);
#endif
starting_directory = 0;
}
else
starting_directory = current_directory;
}
define_variable_cname ("CURDIR", current_directory, o_file, 0);
/* Read any stdin makefiles into temporary files. */
if (makefiles != 0)
{
unsigned int i;
for (i = 0; i < makefiles->idx; ++i)
if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
{
/* This makefile is standard input. Since we may re-exec
and thus re-read the makefiles, we read standard input
into a temporary file and read from that. */
FILE *outfile;
char *template;
const char *tmpdir;
if (stdin_nm)
O (fatal, NILF,
_("Makefile from standard input specified twice."));
#define DEFAULT_TMPDIR "/tmp"
#define DEFAULT_TMPFILE "GmXXXXXX"
if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
/* These are also used commonly on these platforms. */
&& ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
&& ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
)
tmpdir = DEFAULT_TMPDIR;
template = alloca (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);
strcpy (template, tmpdir);
#ifdef HAVE_DOS_PATHS
if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
strcat (template, "/");
#else
if (template[strlen (template) - 1] != '/')
strcat (template, "/");
#endif /* !HAVE_DOS_PATHS */
strcat (template, DEFAULT_TMPFILE);
outfile = get_tmpfile (&stdin_nm, template);
if (outfile == 0)
pfatal_with_name (_("fopen (temporary file)"));
while (!feof (stdin) && ! ferror (stdin))
{
char buf[2048];
size_t n = fread (buf, 1, sizeof (buf), stdin);
if (n > 0 && fwrite (buf, 1, n, outfile) != n)
pfatal_with_name (_("fwrite (temporary file)"));
}
fclose (outfile);
/* Replace the name that read_all_makefiles will
see with the name of the temporary file. */
makefiles->list[i] = strcache_add (stdin_nm);
/* Make sure the temporary file will not be remade. */
{
struct file *f = enter_file (strcache_add (stdin_nm));
f->updated = 1;
f->update_status = us_success;
f->command_state = cs_finished;
/* Can't be intermediate, or it'll be removed too early for
make re-exec. */
f->intermediate = 0;
f->dontcare = 0;
}
}
}
#ifndef __EMX__ /* Don't use a SIGCHLD handler for OS/2 */
#if !defined(HAVE_WAIT_NOHANG) || defined(MAKE_JOBSERVER)
/* Set up to handle children dying. This must be done before
reading in the makefiles so that 'shell' function calls will work.
If we don't have a hanging wait we have to fall back to old, broken
functionality here and rely on the signal handler and counting
children.
If we're using the jobs pipe we need a signal handler so that SIGCHLD is
not ignored; we need it to interrupt the read(2) of the jobserver pipe if
we're waiting for a token.
If none of these are true, we don't need a signal handler at all. */
{
# if defined SIGCHLD
bsd_signal (SIGCHLD, child_handler);
# endif
# if defined SIGCLD && SIGCLD != SIGCHLD
bsd_signal (SIGCLD, child_handler);
# endif
}
#ifdef HAVE_PSELECT
/* If we have pselect() then we need to block SIGCHLD so it's deferred. */
{
sigset_t block;
sigemptyset (&block);
sigaddset (&block, SIGCHLD);
if (sigprocmask (SIG_SETMASK, &block, NULL) < 0)
pfatal_with_name ("sigprocmask(SIG_SETMASK, SIGCHLD)");
}
#endif
#endif
#endif
/* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
#ifdef SIGUSR1
bsd_signal (SIGUSR1, debug_signal_handler);
#endif
/* Define the initial list of suffixes for old-style rules. */
set_default_suffixes ();
/* Define the file rules for the built-in suffix rules. These will later
be converted into pattern rules. We used to do this in
install_default_implicit_rules, but since that happens after reading
makefiles, it results in the built-in pattern rules taking precedence
over makefile-specified suffix rules, which is wrong. */
install_default_suffix_rules ();
/* Define some internal and special variables. */
define_automatic_variables ();
/* Set up the MAKEFLAGS and MFLAGS variables for makefiles to see.
Initialize it to be exported but allow the makefile to reset it. */
define_makeflags (0, 0)->export = v_export;
/* Define the default variables. */
define_default_variables ();
default_file = enter_file (strcache_add (".DEFAULT"));
default_goal_var = define_variable_cname (".DEFAULT_GOAL", "", o_file, 0);
/* Evaluate all strings provided with --eval.
Also set up the $(-*-eval-flags-*-) variable. */
if (eval_strings)
{
char *p, *value;
unsigned int i;
size_t len = (CSTRLEN ("--eval=") + 1) * eval_strings->idx;
for (i = 0; i < eval_strings->idx; ++i)
{
p = xstrdup (eval_strings->list[i]);
len += 2 * strlen (p);
eval_buffer (p, NULL);
free (p);
}
p = value = alloca (len);
for (i = 0; i < eval_strings->idx; ++i)
{
strcpy (p, "--eval=");
p += CSTRLEN ("--eval=");
p = quote_for_env (p, eval_strings->list[i]);
*(p++) = ' ';
}
p[-1] = '\0';
define_variable_cname ("-*-eval-flags-*-", value, o_automatic, 0);
}
/* Read all the makefiles. */
read_files = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
#ifdef WINDOWS32
/* look one last time after reading all Makefiles */
if (no_default_sh_exe)
no_default_sh_exe = !find_and_set_default_shell (NULL);
#endif /* WINDOWS32 */
{
int old_builtin_rules_flag = no_builtin_rules_flag;
int old_builtin_variables_flag = no_builtin_variables_flag;
int old_arg_job_slots = arg_job_slots;
arg_job_slots = INVALID_JOB_SLOTS;
/* Decode switches again, for variables set by the makefile. */
decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
/* Clear GNUMAKEFLAGS to avoid duplication. */
define_variable_cname ("GNUMAKEFLAGS", "", o_override, 0);
decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
#if 0
decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
#endif
/* If -j is not set in the makefile, or it was set on the command line,
reset to use the previous value. */
if (arg_job_slots == INVALID_JOB_SLOTS || argv_slots != INVALID_JOB_SLOTS)
arg_job_slots = old_arg_job_slots;
else if (jobserver_auth)
{
/* Makefile MAKEFLAGS set -j, but we already have a jobserver.
Make us the master of a new jobserver group. */
if (!restarts)
ON (error, NILF,
_("warning: -j%d forced in makefile: resetting jobserver mode."),
arg_job_slots);
/* We can't use our parent's jobserver, so reset. */
reset_jobserver ();
}
/* Reset in case the switches changed our mind. */
syncing = (output_sync == OUTPUT_SYNC_LINE
|| output_sync == OUTPUT_SYNC_TARGET);
if (make_sync.syncout && ! syncing)
output_close (&make_sync);
make_sync.syncout = syncing;
OUTPUT_SET (&make_sync);
/* If we've disabled builtin rules, get rid of them. */
if (no_builtin_rules_flag && ! old_builtin_rules_flag)
{
if (suffix_file->builtin)
{
free_dep_chain (suffix_file->deps);
suffix_file->deps = 0;
}
define_variable_cname ("SUFFIXES", "", o_default, 0);
}
/* If we've disabled builtin variables, get rid of them. */
if (no_builtin_variables_flag && ! old_builtin_variables_flag)
undefine_default_variables ();
}
/* Final jobserver configuration.
If we have jobserver_auth then we are a client in an existing jobserver
group, that's already been verified OK above. If we don't have
jobserver_auth and jobserver is enabled, then start a new jobserver.
arg_job_slots = INVALID_JOB_SLOTS if we don't want -j in MAKEFLAGS
arg_job_slots = # of jobs of parallelism
job_slots = 0 for no limits on jobs, or when limiting via jobserver.
job_slots = 1 for standard non-parallel mode.
job_slots >1 for old-style parallelism without jobservers. */
if (jobserver_auth)
job_slots = 0;
else if (arg_job_slots == INVALID_JOB_SLOTS)
job_slots = 1;
else
job_slots = arg_job_slots;
/* If we have >1 slot at this point, then we're a top-level make.
Set up the jobserver.
Every make assumes that it always has one job it can run. For the
submakes it's the token they were given by their parent. For the top
make, we just subtract one from the number the user wants. */
if (job_slots > 1 && jobserver_setup (job_slots - 1))
{
/* Fill in the jobserver_auth for our children. */
jobserver_auth = jobserver_get_auth ();
if (jobserver_auth)
{
/* We're using the jobserver so set job_slots to 0. */
master_job_slots = job_slots;
job_slots = 0;
}
}
/* If we're not using parallel jobs, then we don't need output sync.
This is so people can enable output sync in GNUMAKEFLAGS or similar, but
not have it take effect unless parallel builds are enabled. */
if (syncing && job_slots == 1)
{
OUTPUT_UNSET ();
output_close (&make_sync);
syncing = 0;
output_sync = OUTPUT_SYNC_NONE;
}
#ifndef MAKE_SYMLINKS
if (check_symlink_flag)
{
O (error, NILF, _("Symbolic links not supported: disabling -L."));
check_symlink_flag = 0;
}
#endif
/* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
define_makeflags (1, 0);
/* Make each 'struct goaldep' point at the 'struct file' for the file
depended on. Also do magic for special targets. */
snap_deps ();
/* Convert old-style suffix rules to pattern rules. It is important to
do this before installing the built-in pattern rules below, so that
makefile-specified suffix rules take precedence over built-in pattern
rules. */
convert_to_pattern ();
/* Install the default implicit pattern rules.
This used to be done before reading the makefiles.
But in that case, built-in pattern rules were in the chain
before user-defined ones, so they matched first. */
install_default_implicit_rules ();
/* Compute implicit rule limits and do magic for pattern rules. */
snap_implicit_rules ();
/* Construct the listings of directories in VPATH lists. */
build_vpath_lists ();
/* Mark files given with -o flags as very old and as having been updated
already, and files given with -W flags as brand new (time-stamp as far
as possible into the future). If restarts is set we'll do -W later. */
if (old_files != 0)
{
const char **p;
for (p = old_files->list; *p != 0; ++p)
{
struct file *f = enter_file (*p);
f->last_mtime = f->mtime_before_update = OLD_MTIME;
f->updated = 1;
f->update_status = us_success;
f->command_state = cs_finished;
}
}
if (!restarts && new_files != 0)
{
const char **p;
for (p = new_files->list; *p != 0; ++p)
{
struct file *f = enter_file (*p);
f->last_mtime = f->mtime_before_update = NEW_MTIME;
}
}
/* Initialize the remote job module. */
remote_setup ();
/* Dump any output we've collected. */
OUTPUT_UNSET ();
output_close (&make_sync);
if (read_files)
{
/* Update any makefiles if necessary. */
FILE_TIMESTAMP *makefile_mtimes;
char **aargv = NULL;
const char **nargv;
int nargc;
enum update_status status;
DB (DB_BASIC, (_("Updating makefiles....\n")));
{
struct goaldep *d;
unsigned int num_mkfiles = 0;
for (d = read_files; d != NULL; d = d->next)
++num_mkfiles;
makefile_mtimes = alloca (num_mkfiles * sizeof (FILE_TIMESTAMP));
}
/* Remove any makefiles we don't want to try to update. Record the
current modtimes of the others so we can compare them later. */
{
struct goaldep *d = read_files;
struct goaldep *last = NULL;
unsigned int mm_idx = 0;
while (d != 0)
{
struct file *f;
for (f = d->file->double_colon; f != NULL; f = f->prev)
if (f->deps == 0 && f->cmds != 0)
break;
if (f)
{
/* This makefile is a :: target with commands, but no
dependencies. So, it will always be remade. This might
well cause an infinite loop, so don't try to remake it.
(This will only happen if your makefiles are written
exceptionally stupidly; but if you work for Athena, that's
how you write your makefiles.) */
DB (DB_VERBOSE,
(_("Makefile '%s' might loop; not remaking it.\n"),
f->name));
if (last)
last->next = d->next;
else
read_files = d->next;
/* Free the storage. */
free_goaldep (d);
d = last ? last->next : read_files;
}
else
{
makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
last = d;
d = d->next;
}
}
}
/* Set up 'MAKEFLAGS' specially while remaking makefiles. */
define_makeflags (1, 1);
{
int orig_db_level = db_level;
if (! ISDB (DB_MAKEFILES))
db_level = DB_NONE;
rebuilding_makefiles = 1;
status = update_goal_chain (read_files);
rebuilding_makefiles = 0;
db_level = orig_db_level;
}
switch (status)
{
case us_question:
/* The only way this can happen is if the user specified -q and asked
for one of the makefiles to be remade as a target on the command
line. Since we're not actually updating anything with -q we can
treat this as "did nothing". */
case us_none:
/* Did nothing. */
break;
case us_failed:
/* Failed to update. Figure out if we care. */
{
/* Nonzero if any makefile was successfully remade. */
int any_remade = 0;
/* Nonzero if any makefile we care about failed
in updating or could not be found at all. */
int any_failed = 0;
unsigned int i;
struct goaldep *d;
for (i = 0, d = read_files; d != 0; ++i, d = d->next)
{
if (d->file->updated)
{
/* This makefile was updated. */
if (d->file->update_status == us_success)
{
/* It was successfully updated. */
any_remade |= (file_mtime_no_search (d->file)
!= makefile_mtimes[i]);
}
else if (! (d->flags & RM_DONTCARE))
{
FILE_TIMESTAMP mtime;
/* The update failed and this makefile was not
from the MAKEFILES variable, so we care. */
OS (error, NILF, _("Failed to remake makefile '%s'."),
d->file->name);
mtime = file_mtime_no_search (d->file);
any_remade |= (mtime != NONEXISTENT_MTIME
&& mtime != makefile_mtimes[i]);
makefile_status = MAKE_FAILURE;
}
}
else
/* This makefile was not found at all. */
if (! (d->flags & RM_DONTCARE))
{
const char *dnm = dep_name (d);
size_t l = strlen (dnm);
/* This is a makefile we care about. See how much. */
if (d->flags & RM_INCLUDED)
/* An included makefile. We don't need to die, but we
do want to complain. */
error (NILF, l,
_("Included makefile '%s' was not found."), dnm);
else
{
/* A normal makefile. We must die later. */
error (NILF, l,
_("Makefile '%s' was not found"), dnm);
any_failed = 1;
}
}
}
if (any_remade)
goto re_exec;
if (any_failed)
die (MAKE_FAILURE);
break;
}
case us_success:
re_exec:
/* Updated successfully. Re-exec ourselves. */
remove_intermediates (0);
if (print_data_base_flag)
print_data_base ();
clean_jobserver (0);
if (makefiles != 0)
{
/* These names might have changed. */
int i, j = 0;
for (i = 1; i < argc; ++i)
if (strneq (argv[i], "-f", 2)) /* XXX */
{
if (argv[i][2] == '\0')
/* This cast is OK since we never modify argv. */
argv[++i] = (char *) makefiles->list[j];
else
argv[i] = xstrdup (concat (2, "-f", makefiles->list[j]));
++j;
}
}
/* Add -o option for the stdin temporary file, if necessary. */
nargc = argc;
if (stdin_nm)
{
void *m = xmalloc ((nargc + 2) * sizeof (char *));
aargv = m;
memcpy (aargv, argv, argc * sizeof (char *));
aargv[nargc++] = xstrdup (concat (2, "-o", stdin_nm));
aargv[nargc] = 0;
nargv = m;
}
else
nargv = (const char**)argv;
if (directories != 0 && directories->idx > 0)
{
int bad = 1;
if (directory_before_chdir != 0)
{
if (chdir (directory_before_chdir) < 0)
perror_with_name ("chdir", "");
else
bad = 0;
}
if (bad)
O (fatal, NILF,
_("Couldn't change back to original directory."));
}
++restarts;
if (ISDB (DB_BASIC))
{
const char **p;
printf (_("Re-executing[%u]:"), restarts);
for (p = nargv; *p != 0; ++p)
printf (" %s", *p);
putchar ('\n');
fflush (stdout);
}
{
char **p;
for (p = environ; *p != 0; ++p)
{
if (strneq (*p, MAKELEVEL_NAME "=", MAKELEVEL_LENGTH+1))
{
*p = alloca (40);
sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
}
else if (strneq (*p, "MAKE_RESTARTS=", CSTRLEN ("MAKE_RESTARTS=")))
{
*p = alloca (40);
sprintf (*p, "MAKE_RESTARTS=%s%u",
OUTPUT_IS_TRACED () ? "-" : "", restarts);
restarts = 0;
}
}
}
/* If we didn't set the restarts variable yet, add it. */
if (restarts)
{
char *b = alloca (40);
sprintf (b, "MAKE_RESTARTS=%s%u",
OUTPUT_IS_TRACED () ? "-" : "", restarts);
putenv (b);
}
fflush (stdout);
fflush (stderr);
/* The exec'd "child" will be another make, of course. */
jobserver_pre_child(1);
/* Reset limits, if necessary. */
if (stack_limit.rlim_cur)
setrlimit (RLIMIT_STACK, &stack_limit);
exec_command ((char **)nargv, environ);
/* We shouldn't get here but just in case. */
jobserver_post_child(1);
free (aargv);
break;
}
}
/* Set up 'MAKEFLAGS' again for the normal targets. */
define_makeflags (1, 0);
/* Set always_make_flag if -B was given. */
always_make_flag = always_make_set;
/* If restarts is set we haven't set up -W files yet, so do that now. */
if (restarts && new_files != 0)
{
const char **p;
for (p = new_files->list; *p != 0; ++p)
{
struct file *f = enter_file (*p);
f->last_mtime = f->mtime_before_update = NEW_MTIME;
}
}
/* If there is a temp file from reading a makefile from stdin, get rid of
it now. */
if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
perror_with_name (_("unlink (temporary file): "), stdin_nm);
/* If there were no command-line goals, use the default. */
if (goals == 0)
{
char *p;
if (default_goal_var->recursive)
p = variable_expand (default_goal_var->value);
else
{
p = variable_buffer_output (variable_buffer, default_goal_var->value,
strlen (default_goal_var->value));
*p = '\0';
p = variable_buffer;
}
if (*p != '\0')
{
struct file *f = lookup_file (p);
/* If .DEFAULT_GOAL is a non-existent target, enter it into the
table and let the standard logic sort it out. */
if (f == 0)
{
struct nameseq *ns;
ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);
if (ns)
{
/* .DEFAULT_GOAL should contain one target. */
if (ns->next != 0)
O (fatal, NILF,
_(".DEFAULT_GOAL contains more than one target"));
f = enter_file (strcache_add (ns->name));
ns->name = 0; /* It was reused by enter_file(). */
free_ns_chain (ns);
}
}
if (f)
{
goals = alloc_goaldep ();
goals->file = f;
}
}
}
else
lastgoal->next = 0;
if (!goals)
{
struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("MAKEFILE_LIST"));
if (v && v->value && v->value[0] != '\0')
O (fatal, NILF, _("No targets"));
O (fatal, NILF, _("No targets specified and no makefile found"));
}
/* Update the goals. */
DB (DB_BASIC, (_("Updating goal targets....\n")));
{
switch (update_goal_chain (goals))
{
case us_none:
/* Nothing happened. */
/* FALLTHROUGH */
case us_success:
/* Keep the previous result. */
break;
case us_question:
/* We are under -q and would run some commands. */
makefile_status = MAKE_TROUBLE;
break;
case us_failed:
/* Updating failed. POSIX.2 specifies exit status >1 for this; */
makefile_status = MAKE_FAILURE;
break;
}
/* If we detected some clock skew, generate one last warning */
if (clock_skew_detected)
O (error, NILF,
_("warning: Clock skew detected. Your build may be incomplete."));
/* Exit. */
die (makefile_status);
}
/* NOTREACHED */
exit (MAKE_SUCCESS);
}
/* Parsing of arguments, decoding of switches. */
static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
(sizeof (long_option_aliases) /
sizeof (long_option_aliases[0]))];
/* Fill in the string and vector for getopt. */
static void
init_switches (void)
{
char *p;
unsigned int c;
unsigned int i;
if (options[0] != '\0')
/* Already done. */
return;
p = options;
/* Return switch and non-switch args in order, regardless of
POSIXLY_CORRECT. Non-switch args are returned as option 1. */
*p++ = '-';
for (i = 0; switches[i].c != '\0'; ++i)
{
long_options[i].name = (char *) (switches[i].long_name == 0 ? "" :
switches[i].long_name);
long_options[i].flag = 0;
long_options[i].val = switches[i].c;
if (short_option (switches[i].c))
*p++ = (char) switches[i].c;
switch (switches[i].type)
{
case flag:
case flag_off:
case ignore:
long_options[i].has_arg = no_argument;
break;
case string:
case strlist:
case filename:
case positive_int:
case floating:
if (short_option (switches[i].c))
*p++ = ':';
if (switches[i].noarg_value != 0)
{
if (short_option (switches[i].c))
*p++ = ':';
long_options[i].has_arg = optional_argument;
}
else
long_options[i].has_arg = required_argument;
break;
}
}
*p = '\0';
for (c = 0; c < (sizeof (long_option_aliases) /
sizeof (long_option_aliases[0]));
++c)
long_options[i++] = long_option_aliases[c];
long_options[i].name = 0;
}
/* Non-option argument. It might be a variable definition. */
static void
handle_non_switch_argument (const char *arg, int env)
{
struct variable *v;
if (arg[0] == '-' && arg[1] == '\0')
/* Ignore plain '-' for compatibility. */
return;
v = try_variable_definition (0, arg, o_command, 0);
if (v != 0)
{
/* It is indeed a variable definition. If we don't already have this
one, record a pointer to the variable for later use in
define_makeflags. */
struct command_variable *cv;
for (cv = command_variables; cv != 0; cv = cv->next)
if (cv->variable == v)
break;
if (! cv)
{
cv = xmalloc (sizeof (*cv));
cv->variable = v;
cv->next = command_variables;
command_variables = cv;
}
}
else if (! env)
{
/* Not an option or variable definition; it must be a goal
target! Enter it as a file and add it to the dep chain of
goals. */
struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
f->cmd_target = 1;
if (goals == 0)
{
goals = alloc_goaldep ();
lastgoal = goals;
}
else
{
lastgoal->next = alloc_goaldep ();
lastgoal = lastgoal->next;
}
lastgoal->file = f;
{
/* Add this target name to the MAKECMDGOALS variable. */
struct variable *gv;
const char *value;
gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
if (gv == 0)
value = f->name;
else
{
/* Paste the old and new values together */
size_t oldlen, newlen;
char *vp;
oldlen = strlen (gv->value);
newlen = strlen (f->name);
vp = alloca (oldlen + 1 + newlen + 1);
memcpy (vp, gv->value, oldlen);
vp[oldlen] = ' ';
memcpy (&vp[oldlen + 1], f->name, newlen + 1);
value = vp;
}
define_variable_cname ("MAKECMDGOALS", value, o_default, 0);
}
}
}
/* Print a nice usage method. */
static void
print_usage (int bad)
{
const char *const *cpp;
FILE *usageto;
if (print_version_flag)
print_version ();
usageto = bad ? stderr : stdout;
fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
for (cpp = usage; *cpp; ++cpp)
fputs (_(*cpp), usageto);
if (!remote_description || *remote_description == '\0')
fprintf (usageto, _("\nThis program built for %s\n"), make_host);
else
fprintf (usageto, _("\nThis program built for %s (%s)\n"),
make_host, remote_description);
fprintf (usageto, _("Report bugs to <[email protected]>\n"));
}
/* Decode switches from ARGC and ARGV.
They came from the environment if ENV is nonzero. */
static void
decode_switches (int argc, const char **argv, int env)
{
int bad = 0;
const struct command_switch *cs;
struct stringlist *sl;
int c;
/* getopt does most of the parsing for us.
First, get its vectors set up. */
init_switches ();
/* Let getopt produce error messages for the command line,
but not for options from the environment. */
opterr = !env;
/* Reset getopt's state. */
optind = 0;
while (optind < argc)
{
const char *coptarg;
/* Parse the next argument. */
c = getopt_long (argc, (char*const*)argv, options, long_options, NULL);
coptarg = optarg;
if (c == EOF)
/* End of arguments, or "--" marker seen. */
break;
else if (c == 1)
/* An argument not starting with a dash. */
handle_non_switch_argument (coptarg, env);
else if (c == '?')
/* Bad option. We will print a usage message and die later.
But continue to parse the other options so the user can
see all he did wrong. */
bad = 1;
else
for (cs = switches; cs->c != '\0'; ++cs)
if (cs->c == c)
{
/* Whether or not we will actually do anything with
this switch. We test this individually inside the
switch below rather than just once outside it, so that
options which are to be ignored still consume args. */
int doit = !env || cs->env;
switch (cs->type)
{
default:
abort ();
case ignore:
break;
case flag:
case flag_off:
if (doit)
*(int *) cs->value_ptr = cs->type == flag;
break;
case string:
case strlist:
case filename:
if (!doit)
break;
if (! coptarg)
coptarg = xstrdup (cs->noarg_value);
else if (*coptarg == '\0')
{
char opt[2] = "c";
const char *op = opt;
if (short_option (cs->c))
opt[0] = (char) cs->c;
else
op = cs->long_name;
error (NILF, strlen (op),
_("the '%s%s' option requires a non-empty string argument"),
short_option (cs->c) ? "-" : "--", op);
bad = 1;
break;
}
if (cs->type == string)
{
char **val = (char **)cs->value_ptr;
free (*val);
*val = xstrdup (coptarg);
break;
}
sl = *(struct stringlist **) cs->value_ptr;
if (sl == 0)
{
sl = xmalloc (sizeof (struct stringlist));
sl->max = 5;
sl->idx = 0;
sl->list = xmalloc (5 * sizeof (char *));
*(struct stringlist **) cs->value_ptr = sl;
}
else if (sl->idx == sl->max - 1)
{
sl->max += 5;
/* MSVC erroneously warns without a cast here. */
sl->list = xrealloc ((void *)sl->list,
sl->max * sizeof (char *));
}
if (cs->type == filename)
sl->list[sl->idx++] = expand_command_line_file (coptarg);
else
sl->list[sl->idx++] = xstrdup (coptarg);
sl->list[sl->idx] = 0;
break;
case positive_int:
/* See if we have an option argument; if we do require that
it's all digits, not something like "10foo". */
if (coptarg == 0 && argc > optind)
{
const char *cp;
for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
;
if (cp[0] == '\0')
coptarg = argv[optind++];
}
if (!doit)
break;
if (coptarg)
{
int i = atoi (coptarg);
const char *cp;
/* Yes, I realize we're repeating this in some cases. */
for (cp = coptarg; ISDIGIT (cp[0]); ++cp)
;
if (i < 1 || cp[0] != '\0')
{
error (NILF, 0,
_("the '-%c' option requires a positive integer argument"),
cs->c);
bad = 1;
}
else
*(unsigned int *) cs->value_ptr = i;
}
else
*(unsigned int *) cs->value_ptr
= *(unsigned int *) cs->noarg_value;
break;
case floating:
if (coptarg == 0 && optind < argc
&& (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
coptarg = argv[optind++];
if (doit)
*(double *) cs->value_ptr
= (coptarg != 0 ? atof (coptarg)
: *(double *) cs->noarg_value);
break;
}
/* We've found the switch. Stop looking. */
break;
}
}
/* There are no more options according to getting getopt, but there may
be some arguments left. Since we have asked for non-option arguments
to be returned in order, this only happens when there is a "--"
argument to prevent later arguments from being options. */
while (optind < argc)
handle_non_switch_argument (argv[optind++], env);
if (!env && (bad || print_usage_flag))
{
print_usage (bad);
die (bad ? MAKE_FAILURE : MAKE_SUCCESS);
}
/* If there are any options that need to be decoded do it now. */
decode_debug_flags ();
decode_output_sync_flags ();
/* Perform any special switch handling. */
run_silent = silent_flag;
}
/* Decode switches from environment variable ENVAR (which is LEN chars long).
We do this by chopping the value into a vector of words, prepending a
dash to the first word if it lacks one, and passing the vector to
decode_switches. */
static void
decode_env_switches (const char *envar, size_t len)
{
char *varref = alloca (2 + len + 2);
char *value, *p, *buf;
int argc;
const char **argv;
/* Get the variable's value. */
varref[0] = '$';
varref[1] = '(';
memcpy (&varref[2], envar, len);
varref[2 + len] = ')';
varref[2 + len + 1] = '\0';
value = variable_expand (varref);
/* Skip whitespace, and check for an empty value. */
NEXT_TOKEN (value);
len = strlen (value);
if (len == 0)
return;
/* Allocate a vector that is definitely big enough. */
argv = alloca ((1 + len + 1) * sizeof (char *));
/* getopt will look at the arguments starting at ARGV[1].
Prepend a spacer word. */
argv[0] = 0;
argc = 1;
/* We need a buffer to copy the value into while we split it into words
and unquote it. Set up in case we need to prepend a dash later. */
buf = alloca (1 + len + 1);
buf[0] = '-';
p = buf+1;
argv[argc] = p;
while (*value != '\0')
{
if (*value == '\\' && value[1] != '\0')
++value; /* Skip the backslash. */
else if (ISBLANK (*value))
{
/* End of the word. */
*p++ = '\0';
argv[++argc] = p;
do
++value;
while (ISBLANK (*value));
continue;
}
*p++ = *value++;
}
*p = '\0';
argv[++argc] = 0;
assert (p < buf + len + 2);
if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
/* The first word doesn't start with a dash and isn't a variable
definition, so add a dash. */
argv[1] = buf;
/* Parse those words. */
decode_switches (argc, argv, 1);
}
/* Quote the string IN so that it will be interpreted as a single word with
no magic by decode_env_switches; also double dollar signs to avoid
variable expansion in make itself. Write the result into OUT, returning
the address of the next character to be written.
Allocating space for OUT twice the length of IN is always sufficient. */
static char *
quote_for_env (char *out, const char *in)
{
while (*in != '\0')
{
if (*in == '$')
*out++ = '$';
else if (ISBLANK (*in) || *in == '\\')
*out++ = '\\';
*out++ = *in++;
}
return out;
}
/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
command switches. Include options with args if ALL is nonzero.
Don't include options with the 'no_makefile' flag set if MAKEFILE. */
static struct variable *
define_makeflags (int all, int makefile)
{
const char ref[] = "MAKEOVERRIDES";
const char posixref[] = "-*-command-variables-*-";
const char evalref[] = "$(-*-eval-flags-*-)";
const struct command_switch *cs;
char *flagstring;
char *p;
/* We will construct a linked list of 'struct flag's describing
all the flags which need to go in MAKEFLAGS. Then, once we
know how many there are and their lengths, we can put them all
together in a string. */
struct flag
{
struct flag *next;
const struct command_switch *cs;
const char *arg;
};
struct flag *flags = 0;
struct flag *last = 0;
size_t flagslen = 0;
#define ADD_FLAG(ARG, LEN) \
do { \
struct flag *new = alloca (sizeof (struct flag)); \
new->cs = cs; \
new->arg = (ARG); \
new->next = 0; \
if (! flags) \
flags = new; \
else \
last->next = new; \
last = new; \
if (new->arg == 0) \
/* Just a single flag letter: " -x" */ \
flagslen += 3; \
else \
/* " -xfoo", plus space to escape "foo". */ \
flagslen += 1 + 1 + 1 + (3 * (LEN)); \
if (!short_option (cs->c)) \
/* This switch has no single-letter version, so we use the long. */ \
flagslen += 2 + strlen (cs->long_name); \
} while (0)
for (cs = switches; cs->c != '\0'; ++cs)
if (cs->toenv && (!makefile || !cs->no_makefile))
switch (cs->type)
{
case ignore:
break;
case flag:
case flag_off:
if ((!*(int *) cs->value_ptr) == (cs->type == flag_off)
&& (cs->default_value == 0
|| *(int *) cs->value_ptr != *(int *) cs->default_value))
ADD_FLAG (0, 0);
break;
case positive_int:
if (all)
{
if ((cs->default_value != 0
&& (*(unsigned int *) cs->value_ptr
== *(unsigned int *) cs->default_value)))
break;
else if (cs->noarg_value != 0
&& (*(unsigned int *) cs->value_ptr ==
*(unsigned int *) cs->noarg_value))
ADD_FLAG ("", 0); /* Optional value omitted; see below. */
else
{
char *buf = alloca (30);
sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
ADD_FLAG (buf, strlen (buf));
}
}
break;
case floating:
if (all)
{
if (cs->default_value != 0
&& (*(double *) cs->value_ptr
== *(double *) cs->default_value))
break;
else if (cs->noarg_value != 0
&& (*(double *) cs->value_ptr
== *(double *) cs->noarg_value))
ADD_FLAG ("", 0); /* Optional value omitted; see below. */
else
{
char *buf = alloca (100);
sprintf (buf, "%g", *(double *) cs->value_ptr);
ADD_FLAG (buf, strlen (buf));
}
}
break;
case string:
if (all)
{
p = *((char **)cs->value_ptr);
if (p)
ADD_FLAG (p, strlen (p));
}
break;
case filename:
case strlist:
if (all)
{
struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
if (sl != 0)
{
unsigned int i;
for (i = 0; i < sl->idx; ++i)
ADD_FLAG (sl->list[i], strlen (sl->list[i]));
}
}
break;
default:
abort ();
}
#undef ADD_FLAG
/* Four more for the possible " -- ", plus variable references. */
flagslen += 4 + CSTRLEN (posixref) + 4 + CSTRLEN (evalref) + 4;
/* Construct the value in FLAGSTRING.
We allocate enough space for a preceding dash and trailing null. */
flagstring = alloca (1 + flagslen + 1);
memset (flagstring, '\0', 1 + flagslen + 1);
p = flagstring;
/* Start with a dash, for MFLAGS. */
*p++ = '-';
/* Add simple options as a group. */
while (flags != 0 && !flags->arg && short_option (flags->cs->c))
{
*p++ = (char) flags->cs->c;
flags = flags->next;
}
/* Now add more complex flags: ones with options and/or long names. */
while (flags)
{
*p++ = ' ';
*p++ = '-';
/* Add the flag letter or name to the string. */
if (short_option (flags->cs->c))
*p++ = (char) flags->cs->c;
else
{
/* Long options require a double-dash. */
*p++ = '-';
strcpy (p, flags->cs->long_name);
p += strlen (p);
}
/* An omitted optional argument has an ARG of "". */
if (flags->arg && flags->arg[0] != '\0')
{
if (!short_option (flags->cs->c))
/* Long options require '='. */
*p++ = '=';
p = quote_for_env (p, flags->arg);
}
flags = flags->next;
}
/* If no flags at all, get rid of the initial dash. */
if (p == &flagstring[1])
{
flagstring[0] = '\0';
p = flagstring;
}
/* Define MFLAGS before appending variable definitions. Omit an initial
empty dash. Since MFLAGS is not parsed for flags, there is no reason to
override any makefile redefinition. */
define_variable_cname ("MFLAGS",
flagstring + (flagstring[0] == '-' && flagstring[1] == ' ' ? 2 : 0),
o_env, 1);
/* Write a reference to -*-eval-flags-*-, which contains all the --eval
flag options. */
if (eval_strings)
{
*p++ = ' ';
memcpy (p, evalref, CSTRLEN (evalref));
p += CSTRLEN (evalref);
}
if (all)
{
/* If there are any overrides to add, write a reference to
$(MAKEOVERRIDES), which contains command-line variable definitions.
Separate the variables from the switches with a "--" arg. */
const char *r = posix_pedantic ? posixref : ref;
size_t l = strlen (r);
struct variable *v = lookup_variable (r, l);
if (v && v->value && v->value[0] != '\0')
{
strcpy (p, " -- ");
p += 4;
*(p++) = '$';
*(p++) = '(';
memcpy (p, r, l);
p += l;
*(p++) = ')';
}
}
/* If there is a leading dash, omit it. */
if (flagstring[0] == '-')
++flagstring;
/* This used to use o_env, but that lost when a makefile defined MAKEFLAGS.
Makefiles set MAKEFLAGS to add switches, but we still want to redefine
its value with the full set of switches. Then we used o_file, but that
lost when users added -e, causing a previous MAKEFLAGS env. var. to take
precedence over the new one. Of course, an override or command
definition will still take precedence. */
return define_variable_cname ("MAKEFLAGS", flagstring,
env_overrides ? o_env_override : o_file, 1);
}
/* Print version information. */
static void
print_version (void)
{
static int printed_version = 0;
const char *precede = print_data_base_flag ? "# " : "";
if (printed_version)
/* Do it only once. */
return;
printf ("%sLandlock Make " LANDLOCKMAKE_VERSION " (GNU Make %s)\n",
precede, version_string);
if (!remote_description || *remote_description == '\0')
printf (_("%sBuilt for %s\n"), precede, make_host);
else
printf (_("%sBuilt for %s (%s)\n"),
precede, make_host, remote_description);
/* Print this untranslated. The coding standards recommend translating the
(C) to the copyright symbol, but this string is going to change every
year, and none of the rest of it should be translated (including the
word "Copyright"), so it hardly seems worth it. */
printf ("%sCopyright (C) 2022 Justine Alexandra Roberts Tunney\n",
precede);
printf ("%sCopyright (C) 1988-2020 Free Software Foundation, Inc.\n",
precede);
printf (_("%sLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
%sThis is free software: you are free to change and redistribute it.\n\
%sThere is NO WARRANTY, to the extent permitted by law.\n"),
precede, precede, precede);
printed_version = 1;
/* Flush stdout so the user doesn't have to wait to see the
version information while make thinks about things. */
fflush (stdout);
}
/* Print a bunch of information about this and that. */
static void
print_data_base (void)
{
time_t when = time ((time_t *) 0);
print_version ();
printf (_("\n# Make data base, printed on %s"), ctime (&when));
print_variable_data_base ();
print_dir_data_base ();
print_rule_data_base ();
print_file_data_base ();
print_vpath_data_base ();
strcache_print_stats ("#");
when = time ((time_t *) 0);
printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
}
static void
clean_jobserver (int status)
{
/* Sanity: have we written all our jobserver tokens back? If our
exit status is 2 that means some kind of syntax error; we might not
have written all our tokens so do that now. If tokens are left
after any other error code, that's bad. */
if (jobserver_enabled() && jobserver_tokens)
{
if (status != 2)
ON (error, NILF,
"INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
jobserver_tokens);
else
/* Don't write back the "free" token */
while (--jobserver_tokens)
jobserver_release (0);
}
/* Sanity: If we're the master, were all the tokens written back? */
if (master_job_slots)
{
/* We didn't write one for ourself, so start at 1. */
unsigned int tokens = 1 + jobserver_acquire_all ();
if (tokens != master_job_slots)
ONN (error, NILF,
"INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
tokens, master_job_slots);
reset_jobserver ();
}
}
/* Exit with STATUS, cleaning up as necessary. */
void
die (int status)
{
static char dying = 0;
if (!dying)
{
int err;
dying = 1;
if (print_version_flag)
print_version ();
/* Wait for children to die. */
err = (status != 0);
while (job_slots_used > 0)
reap_children (1, err);
/* Let the remote job module clean up its state. */
remote_cleanup ();
/* Remove the intermediate files. */
remove_intermediates (0);
if (print_data_base_flag)
print_data_base ();
if (verify_flag)
verify_file_data_base ();
clean_jobserver (status);
if (output_context)
{
/* die() might be called in a recipe output context due to an
$(error ...) function. */
output_close (output_context);
if (output_context != &make_sync)
output_close (&make_sync);
OUTPUT_UNSET ();
}
output_close (NULL);
/* Try to move back to the original directory. This is essential on
MS-DOS (where there is really only one process), and on Unix it
puts core files in the original directory instead of the -C
directory. Must wait until after remove_intermediates(), or unlinks
of relative pathnames fail. */
if (directory_before_chdir != 0)
{
/* If it fails we don't care: shut up GCC. */
int _x UNUSED;
_x = chdir (directory_before_chdir);
}
}
exit (status);
}
| 97,821 | 3,132 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/xconcat-filename.c | /* clang-format off */
/* Construct a full filename from a directory and a relative filename.
Copyright (C) 2001-2004, 2006-2020 Free Software Foundation, 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; either version 3 of the License, or 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/>. */
/* Written by Bruno Haible <[email protected]>. */
#include "third_party/make/config.h"
/* Specification. */
#include "third_party/make/concat-filename.h"
#include "third_party/make/xalloc.h"
/* Concatenate a directory filename, a relative filename and an optional
suffix. The directory may end with the directory separator. The second
argument may not start with the directory separator (it is relative).
Return a freshly allocated filename. */
char *
xconcatenated_filename (const char *directory, const char *filename,
const char *suffix)
{
char *result;
result = concatenated_filename (directory, filename, suffix);
if (result == NULL)
xalloc_die ();
return result;
}
| 1,527 | 43 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/os.h | /* clang-format off */
/* Declarations for operating system interfaces for GNU Make.
Copyright (C) 2016-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* This section provides OS-specific functions to support the jobserver. */
#ifdef MAKE_JOBSERVER
/* Returns 1 if the jobserver is enabled, else 0. */
unsigned int jobserver_enabled (void);
/* Called in the master instance to set up the jobserver initially. */
unsigned int jobserver_setup (int job_slots);
/* Called in a child instance to connect to the jobserver. */
unsigned int jobserver_parse_auth (const char* auth);
/* Returns an allocated buffer used to pass to child instances. */
char *jobserver_get_auth (void);
/* Clear this instance's jobserver configuration. */
void jobserver_clear (void);
/* Recover all the jobserver tokens and return the number we got. */
unsigned int jobserver_acquire_all (void);
/* Release a jobserver token. If it fails and is_fatal is 1, fatal. */
void jobserver_release (int is_fatal);
/* Notify the jobserver that a child exited. */
void jobserver_signal (void);
/* Get ready to start a non-recursive child. */
void jobserver_pre_child (int);
/* Complete starting a non-recursive child. */
void jobserver_post_child (int);
/* Set up to acquire a new token. */
void jobserver_pre_acquire (void);
/* Wait until we can acquire a jobserver token.
TIMEOUT is 1 if we have other jobs waiting for the load to go down;
in this case we won't wait forever, so we can check the load.
Returns 1 if we got a token, or 0 if we stopped waiting due to a child
exiting or a timeout. */
unsigned int jobserver_acquire (int timeout);
#else
#define jobserver_enabled() (0)
#define jobserver_setup(_slots) (0)
#define jobserver_parse_auth(_auth) (0)
#define jobserver_get_auth() (NULL)
#define jobserver_clear() (void)(0)
#define jobserver_release(_fatal) (void)(0)
#define jobserver_acquire_all() (0)
#define jobserver_signal() (void)(0)
#define jobserver_pre_child(_r) (void)(0)
#define jobserver_post_child(_r) (void)(0)
#define jobserver_pre_acquire() (void)(0)
#define jobserver_acquire(_tmout) (0)
#endif
/* Create a "bad" file descriptor for stdin when parallel jobs are run. */
#if defined(VMS) || defined(WINDOWS32) || defined(_AMIGA) || defined(__MSDOS__)
# define get_bad_stdin() (-1)
#else
int get_bad_stdin (void);
#endif
/* Set a file descriptor to close/not close in a subprocess. */
#if defined(VMS) || defined(_AMIGA) || defined(__MSDOS__)
# define fd_inherit(_i) 0
# define fd_noinherit(_i) 0
#else
void fd_inherit (int);
void fd_noinherit (int);
#endif
| 3,282 | 95 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/xmalloc.c | /* clang-format off */
/* xmalloc.c -- malloc with out of memory checking
Copyright (C) 1990-2000, 2002-2006, 2008-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "third_party/make/config.h"
#define XALLOC_INLINE _GL_EXTERN_INLINE
#include "third_party/make/xalloc.h"
/* 1 if calloc is known to be compatible with GNU calloc. This
matters if we are not also using the calloc module, which defines
HAVE_CALLOC_GNU and supports the GNU API even on non-GNU platforms. */
#if defined HAVE_CALLOC_GNU || (defined __GLIBC__ && !defined __UCLIBC__)
enum { HAVE_GNU_CALLOC = 1 };
#else
enum { HAVE_GNU_CALLOC = 0 };
#endif
/* Allocate N bytes of memory dynamically, with error checking. */
void *
xmalloc (size_t n)
{
void *p = malloc (n);
if (!p && n != 0)
xalloc_die ();
return p;
}
/* Change the size of an allocated block of memory P to N bytes,
with error checking. */
void *
xrealloc (void *p, size_t n)
{
if (!n && p)
{
/* The GNU and C99 realloc behaviors disagree here. Act like
GNU, even if the underlying realloc is C99. */
free (p);
return NULL;
}
p = realloc (p, n);
if (!p && n)
xalloc_die ();
return p;
}
/* If P is null, allocate a block of at least *PN bytes; otherwise,
reallocate P so that it contains more than *PN bytes. *PN must be
nonzero unless P is null. Set *PN to the new block's size, and
return the pointer to the new block. *PN is never set to zero, and
the returned pointer is never null. */
void *
x2realloc (void *p, size_t *pn)
{
return x2nrealloc (p, pn, 1);
}
/* Allocate N bytes of zeroed memory dynamically, with error checking.
There's no need for xnzalloc (N, S), since it would be equivalent
to xcalloc (N, S). */
void *
xzalloc (size_t n)
{
return xcalloc (n, 1);
}
/* Allocate zeroed memory for N elements of S bytes, with error
checking. S must be nonzero. */
void *
xcalloc (size_t n, size_t s)
{
void *p;
/* Test for overflow, since objects with size greater than
PTRDIFF_MAX cause pointer subtraction to go awry. Omit size-zero
tests if HAVE_GNU_CALLOC, since GNU calloc never returns NULL if
successful. */
if (xalloc_oversized (n, s)
|| (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
xalloc_die ();
return p;
}
/* Clone an object P of size S, with error checking. There's no need
for xnmemdup (P, N, S), since xmemdup (P, N * S) works without any
need for an arithmetic overflow check. */
void *
xmemdup (void const *p, size_t s)
{
return memcpy (xmalloc (s), p, s);
}
/* Clone STRING. */
char *
xstrdup (char const *string)
{
return xmemdup (string, strlen (string) + 1);
}
| 3,398 | 124 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/xalloc-die.c | /* clang-format off */
/* Report a memory allocation failure and exit.
Copyright (C) 1997-2000, 2002-2004, 2006, 2009-2020 Free Software
Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#include "libc/runtime/runtime.h"
#include "third_party/make/config.h"
#include "third_party/make/xalloc.h"
#include "third_party/make/error.h"
#include "third_party/make/exitfail.h"
#include "third_party/make/gettext.h"
#define _(msgid) gettext (msgid)
void
xalloc_die (void)
{
error (exit_failure, 0, "%s", _("memory exhausted"));
/* _Noreturn cannot be given to error, since it may return if
its first argument is 0. To help compilers understand the
xalloc_die does not return, call abort. Also, the abort is a
safety feature if exit_failure is 0 (which shouldn't happen). */
abort ();
}
| 1,431 | 43 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/output.h | /* clang-format off */
/* Output to stdout / stderr for GNU make
Copyright (C) 2013-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
struct output
{
int out;
int err;
unsigned int syncout:1; /* True if we want to synchronize output. */
};
extern struct output *output_context;
extern unsigned int stdio_traced;
#define FD_STDIN (fileno (stdin))
#define FD_STDOUT (fileno (stdout))
#define FD_STDERR (fileno (stderr))
#define OUTPUT_SET(_new) do{ output_context = (_new)->syncout ? (_new) : NULL; }while(0)
#define OUTPUT_UNSET() do{ output_context = NULL; }while(0)
#define OUTPUT_TRACED() do{ stdio_traced = 1; }while(0)
#define OUTPUT_IS_TRACED() (!!stdio_traced)
/* Write a buffer directly to the given file descriptor.
This handles errors etc. */
int output_write (int fd, const void *buffer, size_t len);
/* Initialize and close a child output structure: if NULL do this program's
output (this should only be done once). */
void output_init (struct output *out);
void output_close (struct output *out);
/* In situations where output may be about to be displayed but we're not
sure if we've set it up yet, call this. */
void output_start (void);
/* Show a message on stdout or stderr. Will start the output if needed. */
void outputs (int is_err, const char *msg);
#ifdef NO_OUTPUT_SYNC
# define RECORD_SYNC_MUTEX(m) \
O (error, NILF, \
_("-O[TYPE] (--output-sync[=TYPE]) is not configured for this build."));
#else
int output_tmpfd (void);
/* Dump any child output content to stdout, and reset it. */
void output_dump (struct output *out);
# ifdef WINDOWS32
/* For emulations in w32/compat/posixfcn.c. */
# define F_GETFD 1
# define F_SETLKW 2
/* Implementation note: None of the values of l_type below can be zero
-- they are compared with a static instance of the struct, so zero
means unknown/invalid, see w32/compat/posixfcn.c. */
# define F_WRLCK 1
# define F_UNLCK 2
struct flock
{
short l_type;
short l_whence;
off_t l_start;
off_t l_len;
pid_t l_pid;
};
/* This type is actually a HANDLE, but we want to avoid including
windows.h as much as possible. */
typedef intptr_t sync_handle_t;
/* Public functions emulated/provided in posixfcn.c. */
int fcntl (intptr_t fd, int cmd, ...);
intptr_t create_mutex (void);
int same_stream (FILE *f1, FILE *f2);
# define RECORD_SYNC_MUTEX(m) record_sync_mutex(m)
void record_sync_mutex (const char *str);
void prepare_mutex_handle_string (intptr_t hdl);
# else /* !WINDOWS32 */
typedef int sync_handle_t; /* file descriptor */
# define RECORD_SYNC_MUTEX(m) (void)(m)
# endif
#endif /* !NO_OUTPUT_SYNC */
| 3,359 | 102 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/debug.h | /* clang-format off */
/* Debugging macros and interface.
Copyright (C) 1999-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "libc/intrin/likely.h"
#define DB_NONE (0x000)
#define DB_BASIC (0x001)
#define DB_VERBOSE (0x002)
#define DB_JOBS (0x004)
#define DB_IMPLICIT (0x008)
#define DB_MAKEFILES (0x100)
#define DB_ALL (0xfff)
extern int db_level;
#define ISDB(_l) UNLIKELY((_l)&db_level)
/* When adding macros to this list be sure to update the value of
XGETTEXT_OPTIONS in the po/Makevars file. */
#define DBS(_l,_x) do{ if(ISDB(_l)) {print_spaces (depth); \
printf _x; fflush (stdout);} }while(0)
#define DBF(_l,_x) do{ if(ISDB(_l)) {print_spaces (depth); \
printf (_x, file->name); \
fflush (stdout);} }while(0)
#define DB(_l,_x) do{ if(ISDB(_l)) {printf _x; fflush (stdout);} }while(0)
| 1,606 | 43 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/posixos.c | /* POSIX-based operating system interface for GNU Make.
Copyright (C) 2016-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
/**/
#include "libc/sock/select.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/fd.h"
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sig.h"
#include "third_party/make/config.h"
#include "third_party/make/debug.h"
#include "third_party/make/job.h"
#include "third_party/make/os.h"
/* clang-format off */
#ifdef MAKE_JOBSERVER
/* This section provides OS-specific functions to support the jobserver. */
/* These track the state of the jobserver pipe. Passed to child instances. */
static int job_fds[2] = {-1, -1};
/* Used to signal read() that a SIGCHLD happened. Always CLOEXEC.
If we use pselect() this will never be created and always -1.
*/
static int job_rfd = -1;
/* Token written to the pipe (could be any character...) */
static char token = '+';
static int make_job_rfd(void) {
#ifdef HAVE_PSELECT
/* Pretend we succeeded. */
return 0;
#else
EINTRLOOP(job_rfd, dup(job_fds[0]));
if (job_rfd >= 0) fd_noinherit(job_rfd);
return job_rfd;
#endif
}
static void set_blocking(int fd, int blocking) {
/* If we're not using pselect() don't change the blocking. */
#ifdef HAVE_PSELECT
int flags;
EINTRLOOP(flags, fcntl(fd, F_GETFL));
if (flags >= 0) {
int r;
flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
EINTRLOOP(r, fcntl(fd, F_SETFL, flags));
if (r < 0) pfatal_with_name("fcntl(O_NONBLOCK)");
}
#endif
}
unsigned int jobserver_setup(int slots) {
int r;
EINTRLOOP(r, pipe(job_fds));
if (r < 0) pfatal_with_name(_("creating jobs pipe"));
/* By default we don't send the job pipe FDs to our children.
See jobserver_pre_child() and jobserver_post_child(). */
fd_noinherit(job_fds[0]);
fd_noinherit(job_fds[1]);
if (make_job_rfd() < 0) pfatal_with_name(_("duping jobs pipe"));
while (slots--) {
EINTRLOOP(r, write(job_fds[1], &token, 1));
if (r != 1) pfatal_with_name(_("init jobserver pipe"));
}
/* When using pselect() we want the read to be non-blocking. */
set_blocking(job_fds[0], 0);
return 1;
}
unsigned int jobserver_parse_auth(const char *auth) {
/* Given the command-line parameter, parse it. */
if (sscanf(auth, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
OS(fatal, NILF, _("internal error: invalid --jobserver-auth string '%s'"),
auth);
DB(DB_JOBS, (_("Jobserver client (fds %d,%d)\n"), job_fds[0], job_fds[1]));
#ifdef HAVE_FCNTL_H
#define FD_OK(_f) (fcntl((_f), F_GETFD) != -1)
#else
#define FD_OK(_f) 1
#endif
/* Make sure our pipeline is valid, and (possibly) create a duplicate pipe,
that will be closed in the SIGCHLD handler. If this fails with EBADF,
the parent has closed the pipe on us because it didn't think we were a
submake. If so, warn and default to -j1. */
if (!FD_OK(job_fds[0]) || !FD_OK(job_fds[1]) || make_job_rfd() < 0) {
if (errno != EBADF) pfatal_with_name(_("jobserver pipeline"));
job_fds[0] = job_fds[1] = -1;
return 0;
}
/* When using pselect() we want the read to be non-blocking. */
set_blocking(job_fds[0], 0);
return 1;
}
char *jobserver_get_auth(void) {
char *auth = xmalloc((INTSTR_LENGTH * 2) + 2);
sprintf(auth, "%d,%d", job_fds[0], job_fds[1]);
return auth;
}
unsigned int jobserver_enabled(void) {
return job_fds[0] >= 0;
}
void jobserver_clear(void) {
if (job_fds[0] >= 0) close(job_fds[0]);
if (job_fds[1] >= 0) close(job_fds[1]);
if (job_rfd >= 0) close(job_rfd);
job_fds[0] = job_fds[1] = job_rfd = -1;
}
void jobserver_release(int is_fatal) {
int r;
EINTRLOOP(r, write(job_fds[1], &token, 1));
if (r != 1) {
if (is_fatal) pfatal_with_name(_("write jobserver"));
perror_with_name("write", "");
}
}
unsigned int jobserver_acquire_all(void) {
unsigned int tokens = 0;
/* Use blocking reads to wait for all outstanding jobs. */
set_blocking(job_fds[0], 1);
/* Close the write side, so the read() won't hang forever. */
close(job_fds[1]);
job_fds[1] = -1;
while (1) {
char intake;
int r;
EINTRLOOP(r, read(job_fds[0], &intake, 1));
if (r != 1) return tokens;
++tokens;
}
}
/* Prepare the jobserver to start a child process. */
void jobserver_pre_child(int recursive) {
if (recursive && job_fds[0] >= 0) {
fd_inherit(job_fds[0]);
fd_inherit(job_fds[1]);
}
}
/* Reconfigure the jobserver after starting a child process. */
void jobserver_post_child(int recursive) {
if (recursive && job_fds[0] >= 0) {
fd_noinherit(job_fds[0]);
fd_noinherit(job_fds[1]);
}
}
void jobserver_signal(void) {
if (job_rfd >= 0) {
close(job_rfd);
job_rfd = -1;
}
}
void jobserver_pre_acquire(void) {
/* Make sure we have a dup'd FD. */
if (job_rfd < 0 && job_fds[0] >= 0 && make_job_rfd() < 0)
pfatal_with_name(_("duping jobs pipe"));
}
#ifdef HAVE_PSELECT
/* Use pselect() to atomically wait for both a signal and a file descriptor.
It also provides a timeout facility so we don't need to use SIGALRM.
This method relies on the fact that SIGCHLD will be blocked everywhere,
and only unblocked (atomically) within the pselect() call, so we can
never miss a SIGCHLD.
*/
unsigned int jobserver_acquire(int timeout) {
struct timespec spec;
struct timespec *specp = NULL;
sigset_t empty;
sigemptyset(&empty);
if (timeout) {
/* Alarm after one second (is this too granular?) */
spec.tv_sec = 1;
spec.tv_nsec = 0;
specp = &spec;
}
while (1) {
fd_set readfds;
int r;
char intake;
FD_ZERO(&readfds);
FD_SET(job_fds[0], &readfds);
r = pselect(job_fds[0] + 1, &readfds, NULL, NULL, specp, &empty);
if (r < 0)
{
if (errno == EINTR)
/* SIGCHLD will show up as an EINTR. */
return 0;
if (errno == EBADF)
/* Someone closed the jobs pipe.
That shouldn't happen but if it does we're done. */
O(fatal, NILF, _("job server shut down"));
pfatal_with_name(_("pselect jobs pipe"));
}
if (r == 0) /* Timeout. */
return 0;
/* The read FD is ready: read it! This is non-blocking. */
EINTRLOOP(r, read(job_fds[0], &intake, 1));
if (r < 0) {
/* Someone sniped our token! Try again. */
if (errno == EAGAIN) continue;
pfatal_with_name(_("read jobs pipe"));
}
/* read() should never return 0: only the master make can reap all the
tokens and close the write side...?? */
return r > 0;
}
}
#else
/* This method uses a "traditional" UNIX model for waiting on both a signal
and a file descriptor. However, it's complex and since we have a SIGCHLD
handler installed we need to check ALL system calls for EINTR: painful!
Read a token. As long as there's no token available we'll block. We
enable interruptible system calls before the read(2) so that if we get a
SIGCHLD while we're waiting, we'll return with EINTR and we can process the
death(s) and return tokens to the free pool.
Once we return from the read, we immediately reinstate restartable system
calls. This allows us to not worry about checking for EINTR on all the
other system calls in the program.
There is one other twist: there is a span between the time reap_children()
does its last check for dead children and the time the read(2) call is
entered, below, where if a child dies we won't notice. This is extremely
serious as it could cause us to deadlock, given the right set of events.
To avoid this, we do the following: before we reap_children(), we dup(2)
the read FD on the jobserver pipe. The read(2) call below uses that new
FD. In the signal handler, we close that FD. That way, if a child dies
during the section mentioned above, the read(2) will be invoked with an
invalid FD and will return immediately with EBADF. */
static RETSIGTYPE job_noop(int sig UNUSED) {
}
/* Set the child handler action flags to FLAGS. */
static void set_child_handler_action_flags(int set_handler, int set_alarm) {
struct sigaction sa;
memset(&sa, '\0', sizeof sa);
sa.sa_handler = child_handler;
sa.sa_flags = set_handler ? 0 : SA_RESTART;
#if defined SIGCHLD
if (sigaction(SIGCHLD, &sa, NULL) < 0) pfatal_with_name("sigaction: SIGCHLD");
#endif
#if defined SIGCLD && SIGCLD != SIGCHLD
if (sigaction(SIGCLD, &sa, NULL) < 0) pfatal_with_name("sigaction: SIGCLD");
#endif
#if defined SIGALRM
if (set_alarm) {
/* If we're about to enter the read(), set an alarm to wake up in a
second so we can check if the load has dropped and we can start more
work. On the way out, turn off the alarm and set SIG_DFL. */
if (set_handler) {
sa.sa_handler = job_noop;
sa.sa_flags = 0;
if (sigaction(SIGALRM, &sa, NULL) < 0)
pfatal_with_name("sigaction: SIGALRM");
alarm(1);
} else {
alarm(0);
sa.sa_handler = SIG_DFL;
sa.sa_flags = 0;
if (sigaction(SIGALRM, &sa, NULL) < 0)
pfatal_with_name("sigaction: SIGALRM");
}
}
#endif
}
unsigned int jobserver_acquire(int timeout) {
char intake;
int got_token;
int saved_errno;
/* Set interruptible system calls, and read() for a job token. */
set_child_handler_action_flags(1, timeout);
EINTRLOOP(got_token, read(job_rfd, &intake, 1));
saved_errno = errno;
set_child_handler_action_flags(0, timeout);
if (got_token == 1) return 1;
/* If the error _wasn't_ expected (EINTR or EBADF), fatal. Otherwise,
go back and reap_children(), and try again. */
errno = saved_errno;
if (errno != EINTR && errno != EBADF) pfatal_with_name(_("read jobs pipe"));
if (errno == EBADF) DB(DB_JOBS, ("Read returned EBADF.\n"));
return 0;
}
#endif /* HAVE_PSELECT */
#endif /* MAKE_JOBSERVER */
/* Create a "bad" file descriptor for stdin when parallel jobs are run. */
int get_bad_stdin(void) {
static int bad_stdin = -1;
/* Set up a bad standard input that reads from a broken pipe. */
if (bad_stdin == -1) {
/* Make a file descriptor that is the read end of a broken pipe.
This will be used for some children's standard inputs. */
int pd[2];
if (pipe(pd) == 0) {
/* Close the write side. */
(void)close(pd[1]);
/* Save the read side. */
bad_stdin = pd[0];
/* Set the descriptor to close on exec, so it does not litter any
child's descriptor table. When it is dup2'd onto descriptor 0,
that descriptor will not close on exec. */
fd_noinherit(bad_stdin);
}
}
return bad_stdin;
}
/* Set file descriptors to be inherited / not inherited by subprocesses. */
#if !defined(F_SETFD) || !defined(F_GETFD)
void fd_inherit(int fd) {}
void fd_noinherit(int fd) {}
#else
#ifndef FD_CLOEXEC
#define FD_CLOEXEC 1
#endif
void fd_inherit(int fd) {
int flags;
EINTRLOOP(flags, fcntl(fd, F_GETFD));
if (flags >= 0) {
int r;
flags &= ~FD_CLOEXEC;
EINTRLOOP(r, fcntl(fd, F_SETFD, flags));
}
}
void fd_noinherit(int fd) {
int flags;
EINTRLOOP(flags, fcntl(fd, F_GETFD));
if (flags >= 0) {
int r;
flags |= FD_CLOEXEC;
EINTRLOOP(r, fcntl(fd, F_SETFD, flags));
}
}
#endif
| 11,956 | 420 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/error.c | /* clang-format off */
/* Error handler for noninteractive utilities
Copyright (C) 1990-1998, 2000-2007, 2009-2020 Free Software Foundation, Inc.
This file is part of the GNU C Library.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/* Written by David MacKenzie <[email protected]>. */
#include "libc/sysv/consts/f.h"
#include "libc/calls/calls.h"
#include "third_party/make/config.h"
#include "third_party/make/error.h"
#include "libc/stdio/stdio.h"
#include "libc/fmt/fmt.h"
#include "libc/fmt/fmt.h"
#include "libc/str/str.h"
#include "libc/runtime/runtime.h"
#include "third_party/make/stdio.h"
#if !_LIBC && ENABLE_NLS
#include "third_party/make/gettext.h"
# define _(msgid) gettext (msgid)
#endif
#ifdef _LIBC
# define mbsrtowcs __mbsrtowcs
# define USE_UNLOCKED_IO 0
# define _GL_ATTRIBUTE_FORMAT_PRINTF(a, b)
# define _GL_ARG_NONNULL(a)
#else
#include "third_party/make/getprogname.h"
#endif
#ifndef _
# define _(String) String
#endif
/* If NULL, error will flush stdout, then print on stderr the program
name, a colon and a space. Otherwise, error will call this
function without parameters instead. */
void (*error_print_progname) (void);
/* This variable is incremented each time 'error' is called. */
unsigned int error_message_count;
#undef fcntl
#define program_name getprogname ()
#define __strerror_r strerror_r
/* Return non-zero if FD is open. */
static int
is_open (int fd)
{
return 0 <= fcntl (fd, F_GETFL);
}
static void
flush_stdout (void)
{
#if !_LIBC
int stdout_fd;
# if GNULIB_FREOPEN_SAFER
/* Use of gnulib's freopen-safer module normally ensures that
fileno (stdout) == 1
whenever stdout is open. */
stdout_fd = STDOUT_FILENO;
# else
/* POSIX states that fileno (stdout) after fclose is unspecified. But in
practice it is not a problem, because stdout is statically allocated and
the fd of a FILE stream is stored as a field in its allocated memory. */
stdout_fd = fileno (stdout);
# endif
/* POSIX states that fflush (stdout) after fclose is unspecified; it
is safe in glibc, but not on all other platforms. fflush (NULL)
is always defined, but too draconian. */
if (0 <= stdout_fd && is_open (stdout_fd))
#endif
fflush (stdout);
}
static void
print_errno_message (int errnum)
{
char const *s;
s = strerror (errnum);
if (! s)
s = _("Unknown system error");
fprintf (stderr, ": %s", s);
}
static void _GL_ATTRIBUTE_FORMAT_PRINTF (3, 0) _GL_ARG_NONNULL ((3))
error_tail (int status, int errnum, const char *message, va_list args)
{
vfprintf (stderr, message, args);
++error_message_count;
if (errnum)
print_errno_message (errnum);
putc ('\n', stderr);
fflush (stderr);
if (status)
exit (status);
}
/* Print the program name and error message MESSAGE, which is a printf-style
format string with optional args.
If ERRNUM is nonzero, print its corresponding system error message.
Exit with status STATUS if it is nonzero. */
void
error (int status, int errnum, const char *message, ...)
{
va_list args;
flush_stdout ();
if (error_print_progname)
(*error_print_progname) ();
else
{
fprintf (stderr, "%s: ", program_name);
}
va_start (args, message);
error_tail (status, errnum, message, args);
va_end (args);
}
/* Sometimes we want to have at most one error per line. This
variable controls whether this mode is selected or not. */
int error_one_per_line;
void
error_at_line (int status, int errnum, const char *file_name,
unsigned int line_number, const char *message, ...)
{
va_list args;
if (error_one_per_line)
{
static const char *old_file_name;
static unsigned int old_line_number;
if (old_line_number == line_number
&& (file_name == old_file_name
|| (old_file_name != NULL
&& file_name != NULL
&& strcmp (old_file_name, file_name) == 0)))
/* Simply return and print nothing. */
return;
old_file_name = file_name;
old_line_number = line_number;
}
flush_stdout ();
if (error_print_progname)
(*error_print_progname) ();
else
{
fprintf (stderr, "%s:", program_name);
}
fprintf (stderr, file_name != NULL ? "%s:%u: " : " ",
file_name, line_number);
va_start (args, message);
error_tail (status, errnum, message, args);
va_end (args);
}
#ifdef _LIBC
/* Make the weak alias. */
# undef error
# undef error_at_line
weak_alias (__error, error)
weak_alias (__error_at_line, error_at_line)
#endif
| 5,177 | 191 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/function.c | /* Builtin function expansion for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* clang-format off */
#include "third_party/make/makeint.inc"
/**/
#include "third_party/make/filedef.h"
#include "third_party/make/variable.h"
#include "third_party/make/dep.h"
#include "third_party/make/job.h"
#include "third_party/make/os.h"
#include "third_party/make/commands.h"
#include "libc/mem/critbit0.h"
#include "libc/log/rop.h"
#include "libc/runtime/runtime.h"
#include "third_party/make/debug.h"
struct function_table_entry
{
union {
char *(*func_ptr) (char *output, char **argv, const char *fname);
gmk_func_ptr alloc_func_ptr;
} fptr;
const char *name;
unsigned char len;
unsigned char minimum_args;
unsigned char maximum_args;
unsigned int expand_args:1;
unsigned int alloc_fn:1;
};
static unsigned long
function_table_entry_hash_1 (const void *keyv)
{
const struct function_table_entry *key = keyv;
return_STRING_N_HASH_1 (key->name, key->len);
}
static unsigned long
function_table_entry_hash_2 (const void *keyv)
{
const struct function_table_entry *key = keyv;
return_STRING_N_HASH_2 (key->name, key->len);
}
static int
function_table_entry_hash_cmp (const void *xv, const void *yv)
{
const struct function_table_entry *x = xv;
const struct function_table_entry *y = yv;
int result = x->len - y->len;
if (result)
return result;
return_STRING_N_COMPARE (x->name, y->name, x->len);
}
static struct hash_table function_table;
/* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
nonzero, substitutions are done only on matches which are complete
whitespace-delimited words. */
char *
subst_expand (char *o, const char *text, const char *subst, const char *replace,
size_t slen, size_t rlen, int by_word)
{
const char *t = text;
const char *p;
if (slen == 0 && !by_word)
{
/* The first occurrence of "" in any string is its end. */
o = variable_buffer_output (o, t, strlen (t));
if (rlen > 0)
o = variable_buffer_output (o, replace, rlen);
return o;
}
do
{
if (by_word && slen == 0)
/* When matching by words, the empty string should match
the end of each word, rather than the end of the whole text. */
p = end_of_token (next_token (t));
else
{
p = strstr (t, subst);
if (p == 0)
{
/* No more matches. Output everything left on the end. */
o = variable_buffer_output (o, t, strlen (t));
return o;
}
}
/* Output everything before this occurrence of the string to replace. */
if (p > t)
o = variable_buffer_output (o, t, p - t);
/* If we're substituting only by fully matched words,
or only at the ends of words, check that this case qualifies. */
if (by_word
&& ((p > text && !ISSPACE (p[-1]))
|| ! STOP_SET (p[slen], MAP_SPACE|MAP_NUL)))
/* Struck out. Output the rest of the string that is
no longer to be replaced. */
o = variable_buffer_output (o, subst, slen);
else if (rlen > 0)
/* Output the replacement string. */
o = variable_buffer_output (o, replace, rlen);
/* Advance T past the string to be replaced. */
t = p + slen;
} while (*t != '\0');
return o;
}
/* Store into VARIABLE_BUFFER at O the result of scanning TEXT
and replacing strings matching PATTERN with REPLACE.
If PATTERN_PERCENT is not nil, PATTERN has already been
run through find_percent, and PATTERN_PERCENT is the result.
If REPLACE_PERCENT is not nil, REPLACE has already been
run through find_percent, and REPLACE_PERCENT is the result.
Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
character _AFTER_ the %, not to the % itself.
*/
char *
patsubst_expand_pat (char *o, const char *text,
const char *pattern, const char *replace,
const char *pattern_percent, const char *replace_percent)
{
size_t pattern_prepercent_len, pattern_postpercent_len;
size_t replace_prepercent_len, replace_postpercent_len;
const char *t;
size_t len;
int doneany = 0;
/* Record the length of REPLACE before and after the % so we don't have to
compute these lengths more than once. */
if (replace_percent)
{
replace_prepercent_len = replace_percent - replace - 1;
replace_postpercent_len = strlen (replace_percent);
}
else
{
replace_prepercent_len = strlen (replace);
replace_postpercent_len = 0;
}
if (!pattern_percent)
/* With no % in the pattern, this is just a simple substitution. */
return subst_expand (o, text, pattern, replace,
strlen (pattern), strlen (replace), 1);
/* Record the length of PATTERN before and after the %
so we don't have to compute it more than once. */
pattern_prepercent_len = pattern_percent - pattern - 1;
pattern_postpercent_len = strlen (pattern_percent);
while ((t = find_next_token (&text, &len)) != 0)
{
int fail = 0;
/* Is it big enough to match? */
if (len < pattern_prepercent_len + pattern_postpercent_len)
fail = 1;
/* Does the prefix match? */
if (!fail && pattern_prepercent_len > 0
&& (*t != *pattern
|| t[pattern_prepercent_len - 1] != pattern_percent[-2]
|| !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
fail = 1;
/* Does the suffix match? */
if (!fail && pattern_postpercent_len > 0
&& (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
|| t[len - pattern_postpercent_len] != *pattern_percent
|| !strneq (&t[len - pattern_postpercent_len],
pattern_percent, pattern_postpercent_len - 1)))
fail = 1;
if (fail)
/* It didn't match. Output the string. */
o = variable_buffer_output (o, t, len);
else
{
/* It matched. Output the replacement. */
/* Output the part of the replacement before the %. */
o = variable_buffer_output (o, replace, replace_prepercent_len);
if (replace_percent != 0)
{
/* Output the part of the matched string that
matched the % in the pattern. */
o = variable_buffer_output (o, t + pattern_prepercent_len,
len - (pattern_prepercent_len
+ pattern_postpercent_len));
/* Output the part of the replacement after the %. */
o = variable_buffer_output (o, replace_percent,
replace_postpercent_len);
}
}
/* Output a space, but not if the replacement is "". */
if (fail || replace_prepercent_len > 0
|| (replace_percent != 0 && len + replace_postpercent_len > 0))
{
o = variable_buffer_output (o, " ", 1);
doneany = 1;
}
}
if (doneany)
/* Kill the last space. */
--o;
return o;
}
/* Store into VARIABLE_BUFFER at O the result of scanning TEXT
and replacing strings matching PATTERN with REPLACE.
If PATTERN_PERCENT is not nil, PATTERN has already been
run through find_percent, and PATTERN_PERCENT is the result.
If REPLACE_PERCENT is not nil, REPLACE has already been
run through find_percent, and REPLACE_PERCENT is the result.
Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
character _AFTER_ the %, not to the % itself.
*/
char *
patsubst_expand (char *o, const char *text, char *pattern, char *replace)
{
const char *pattern_percent = find_percent (pattern);
const char *replace_percent = find_percent (replace);
/* If there's a percent in the pattern or replacement skip it. */
if (replace_percent)
++replace_percent;
if (pattern_percent)
++pattern_percent;
return patsubst_expand_pat (o, text, pattern, replace,
pattern_percent, replace_percent);
}
/* Look up a function by name. */
static const struct function_table_entry *
lookup_function (const char *s)
{
struct function_table_entry function_table_entry_key;
const char *e = s;
while (STOP_SET (*e, MAP_USERFUNC))
e++;
if (e == s || !STOP_SET(*e, MAP_NUL|MAP_SPACE))
return NULL;
function_table_entry_key.name = s;
function_table_entry_key.len = (unsigned char) (e - s);
return hash_find_item (&function_table, &function_table_entry_key);
}
/* Return 1 if PATTERN matches STR, 0 if not. */
int
pattern_matches (const char *pattern, const char *percent, const char *str)
{
size_t sfxlen, strlength;
if (percent == 0)
{
size_t len = strlen (pattern) + 1;
char *new_chars = alloca (len);
memcpy (new_chars, pattern, len);
percent = find_percent (new_chars);
if (percent == 0)
return streq (new_chars, str);
pattern = new_chars;
}
sfxlen = strlen (percent + 1);
strlength = strlen (str);
if (strlength < (percent - pattern) + sfxlen
|| !strneq (pattern, str, percent - pattern))
return 0;
return !strcmp (percent + 1, str + (strlength - sfxlen));
}
/* Find the next comma or ENDPAREN (counting nested STARTPAREN and
ENDPARENtheses), starting at PTR before END. Return a pointer to
next character.
If no next argument is found, return NULL.
*/
static char *
find_next_argument (char startparen, char endparen,
const char *ptr, const char *end)
{
int count = 0;
for (; ptr < end; ++ptr)
if (!STOP_SET (*ptr, MAP_VARSEP|MAP_COMMA))
continue;
else if (*ptr == startparen)
++count;
else if (*ptr == endparen)
{
--count;
if (count < 0)
return NULL;
}
else if (*ptr == ',' && !count)
return (char *)ptr;
/* We didn't find anything. */
return NULL;
}
/* Glob-expand LINE. The returned pointer is
only good until the next call to string_glob. */
static char *
string_glob (char *line)
{
static char *result = 0;
static size_t length;
struct nameseq *chain;
size_t idx;
chain = PARSE_FILE_SEQ (&line, struct nameseq, MAP_NUL, NULL,
/* We do not want parse_file_seq to strip './'s.
That would break examples like:
$(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
PARSEFS_NOSTRIP|PARSEFS_NOCACHE|PARSEFS_EXISTS);
if (result == 0)
{
length = 100;
result = xmalloc (100);
}
idx = 0;
while (chain != 0)
{
struct nameseq *next = chain->next;
size_t len = strlen (chain->name);
if (idx + len + 1 > length)
{
length += (len + 1) * 2;
result = xrealloc (result, length);
}
memcpy (&result[idx], chain->name, len);
idx += len;
result[idx++] = ' ';
/* Because we used PARSEFS_NOCACHE above, we have to free() NAME. */
free ((char *)chain->name);
free (chain);
chain = next;
}
/* Kill the last space and terminate the string. */
if (idx == 0)
result[0] = '\0';
else
result[idx - 1] = '\0';
return result;
}
/*
Builtin functions
*/
static char *
func_patsubst (char *o, char **argv, const char *funcname UNUSED)
{
o = patsubst_expand (o, argv[2], argv[0], argv[1]);
return o;
}
static char *
func_join (char *o, char **argv, const char *funcname UNUSED)
{
int doneany = 0;
/* Write each word of the first argument directly followed
by the corresponding word of the second argument.
If the two arguments have a different number of words,
the excess words are just output separated by blanks. */
const char *tp;
const char *pp;
const char *list1_iterator = argv[0];
const char *list2_iterator = argv[1];
do
{
size_t len1, len2;
tp = find_next_token (&list1_iterator, &len1);
if (tp != 0)
o = variable_buffer_output (o, tp, len1);
pp = find_next_token (&list2_iterator, &len2);
if (pp != 0)
o = variable_buffer_output (o, pp, len2);
if (tp != 0 || pp != 0)
{
o = variable_buffer_output (o, " ", 1);
doneany = 1;
}
}
while (tp != 0 || pp != 0);
if (doneany)
/* Kill the last blank. */
--o;
return o;
}
static char *
func_origin (char *o, char **argv, const char *funcname UNUSED)
{
/* Expand the argument. */
struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
if (v == 0)
o = variable_buffer_output (o, "undefined", 9);
else
switch (v->origin)
{
default:
case o_invalid:
abort ();
break;
case o_default:
o = variable_buffer_output (o, "default", 7);
break;
case o_env:
o = variable_buffer_output (o, "environment", 11);
break;
case o_file:
o = variable_buffer_output (o, "file", 4);
break;
case o_env_override:
o = variable_buffer_output (o, "environment override", 20);
break;
case o_command:
o = variable_buffer_output (o, "command line", 12);
break;
case o_override:
o = variable_buffer_output (o, "override", 8);
break;
case o_automatic:
o = variable_buffer_output (o, "automatic", 9);
break;
}
return o;
}
static char *
func_flavor (char *o, char **argv, const char *funcname UNUSED)
{
struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
if (v == 0)
o = variable_buffer_output (o, "undefined", 9);
else
if (v->recursive)
o = variable_buffer_output (o, "recursive", 9);
else
o = variable_buffer_output (o, "simple", 6);
return o;
}
static char *
func_notdir_suffix (char *o, char **argv, const char *funcname)
{
/* Expand the argument. */
const char *list_iterator = argv[0];
const char *p2;
int doneany =0;
size_t len=0;
int is_suffix = funcname[0] == 's';
int is_notdir = !is_suffix;
int stop = MAP_DIRSEP | (is_suffix ? MAP_DOT : 0);
while ((p2 = find_next_token (&list_iterator, &len)) != 0)
{
const char *p = p2 + len - 1;
while (p >= p2 && ! STOP_SET (*p, stop))
--p;
if (p >= p2)
{
if (is_notdir)
++p;
else if (*p != '.')
continue;
o = variable_buffer_output (o, p, len - (p - p2));
}
else if (is_notdir)
o = variable_buffer_output (o, p2, len);
if (is_notdir || p >= p2)
{
o = variable_buffer_output (o, " ", 1);
doneany = 1;
}
}
if (doneany)
/* Kill last space. */
--o;
return o;
}
static char *
func_basename_dir (char *o, char **argv, const char *funcname)
{
/* Expand the argument. */
const char *p3 = argv[0];
const char *p2;
int doneany = 0;
size_t len = 0;
int is_basename = funcname[0] == 'b';
int is_dir = !is_basename;
int stop = MAP_DIRSEP | (is_basename ? MAP_DOT : 0) | MAP_NUL;
while ((p2 = find_next_token (&p3, &len)) != 0)
{
const char *p = p2 + len - 1;
while (p >= p2 && ! STOP_SET (*p, stop))
--p;
if (p >= p2 && (is_dir))
o = variable_buffer_output (o, p2, ++p - p2);
else if (p >= p2 && (*p == '.'))
o = variable_buffer_output (o, p2, p - p2);
else if (is_dir)
o = variable_buffer_output (o, "./", 2);
else
/* The entire name is the basename. */
o = variable_buffer_output (o, p2, len);
o = variable_buffer_output (o, " ", 1);
doneany = 1;
}
if (doneany)
/* Kill last space. */
--o;
return o;
}
static char *
func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
{
size_t fixlen = strlen (argv[0]);
const char *list_iterator = argv[1];
int is_addprefix = funcname[3] == 'p';
int is_addsuffix = !is_addprefix;
int doneany = 0;
const char *p;
size_t len;
while ((p = find_next_token (&list_iterator, &len)) != 0)
{
if (is_addprefix)
o = variable_buffer_output (o, argv[0], fixlen);
o = variable_buffer_output (o, p, len);
if (is_addsuffix)
o = variable_buffer_output (o, argv[0], fixlen);
o = variable_buffer_output (o, " ", 1);
doneany = 1;
}
if (doneany)
/* Kill last space. */
--o;
return o;
}
static char *
func_subst (char *o, char **argv, const char *funcname UNUSED)
{
o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
strlen (argv[1]), 0);
return o;
}
static char *
func_firstword (char *o, char **argv, const char *funcname UNUSED)
{
size_t i;
const char *words = argv[0]; /* Use a temp variable for find_next_token */
const char *p = find_next_token (&words, &i);
if (p != 0)
o = variable_buffer_output (o, p, i);
return o;
}
static char *
func_lastword (char *o, char **argv, const char *funcname UNUSED)
{
size_t i;
const char *words = argv[0]; /* Use a temp variable for find_next_token */
const char *p = NULL;
const char *t;
while ((t = find_next_token (&words, &i)) != NULL)
p = t;
if (p != 0)
o = variable_buffer_output (o, p, i);
return o;
}
static char *
func_words (char *o, char **argv, const char *funcname UNUSED)
{
int i = 0;
const char *word_iterator = argv[0];
char buf[20];
while (find_next_token (&word_iterator, NULL) != 0)
++i;
sprintf (buf, "%d", i);
o = variable_buffer_output (o, buf, strlen (buf));
return o;
}
/* Set begpp to point to the first non-whitespace character of the string,
* and endpp to point to the last non-whitespace character of the string.
* If the string is empty or contains nothing but whitespace, endpp will be
* begpp-1.
*/
char *
strip_whitespace (const char **begpp, const char **endpp)
{
while (*begpp <= *endpp && ISSPACE (**begpp))
(*begpp) ++;
while (*endpp >= *begpp && ISSPACE (**endpp))
(*endpp) --;
return (char *)*begpp;
}
static void
check_numeric (const char *s, const char *msg)
{
const char *end = s + strlen (s) - 1;
const char *beg = s;
strip_whitespace (&s, &end);
for (; s <= end; ++s)
if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see makeint.h. */
break;
if (s <= end || end - beg < 0)
OSS (fatal, *expanding_var, "%s: '%s'", msg, beg);
}
static char *
func_word (char *o, char **argv, const char *funcname UNUSED)
{
const char *end_p;
const char *p;
int i;
/* Check the first argument. */
check_numeric (argv[0], _("non-numeric first argument to 'word' function"));
i = atoi (argv[0]);
if (i == 0)
O (fatal, *expanding_var,
_("first argument to 'word' function must be greater than 0"));
end_p = argv[1];
while ((p = find_next_token (&end_p, 0)) != 0)
if (--i == 0)
break;
if (i == 0)
o = variable_buffer_output (o, p, end_p - p);
return o;
}
static char *
func_wordlist (char *o, char **argv, const char *funcname UNUSED)
{
int start, count;
/* Check the arguments. */
check_numeric (argv[0],
_("non-numeric first argument to 'wordlist' function"));
check_numeric (argv[1],
_("non-numeric second argument to 'wordlist' function"));
start = atoi (argv[0]);
if (start < 1)
ON (fatal, *expanding_var,
"invalid first argument to 'wordlist' function: '%d'", start);
count = atoi (argv[1]) - start + 1;
if (count > 0)
{
const char *p;
const char *end_p = argv[2];
/* Find the beginning of the "start"th word. */
while (((p = find_next_token (&end_p, 0)) != 0) && --start)
;
if (p)
{
/* Find the end of the "count"th word from start. */
while (--count && (find_next_token (&end_p, 0) != 0))
;
/* Return the stuff in the middle. */
o = variable_buffer_output (o, p, end_p - p);
}
}
return o;
}
static char *
func_findstring (char *o, char **argv, const char *funcname UNUSED)
{
/* Find the first occurrence of the first string in the second. */
if (strstr (argv[1], argv[0]) != 0)
o = variable_buffer_output (o, argv[0], strlen (argv[0]));
return o;
}
static char *
func_foreach (char *o, char **argv, const char *funcname UNUSED)
{
/* expand only the first two. */
char *varname = expand_argument (argv[0], NULL);
char *list = expand_argument (argv[1], NULL);
const char *body = argv[2];
int doneany = 0;
const char *list_iterator = list;
const char *p;
size_t len;
struct variable *var;
/* Clean up the variable name by removing whitespace. */
char *vp = next_token (varname);
end_of_token (vp)[0] = '\0';
push_new_variable_scope ();
var = define_variable (vp, strlen (vp), "", o_automatic, 0);
/* loop through LIST, put the value in VAR and expand BODY */
while ((p = find_next_token (&list_iterator, &len)) != 0)
{
char *result = 0;
free (var->value);
var->value = xstrndup (p, len);
result = allocated_variable_expand (body);
o = variable_buffer_output (o, result, strlen (result));
o = variable_buffer_output (o, " ", 1);
doneany = 1;
free (result);
}
if (doneany)
/* Kill the last space. */
--o;
pop_variable_scope ();
free (varname);
free (list);
return o;
}
struct a_word
{
struct a_word *next;
struct a_word *chain;
char *str;
size_t length;
int matched;
};
static unsigned long
a_word_hash_1 (const void *key)
{
return_STRING_HASH_1 (((struct a_word const *) key)->str);
}
static unsigned long
a_word_hash_2 (const void *key)
{
return_STRING_HASH_2 (((struct a_word const *) key)->str);
}
static int
a_word_hash_cmp (const void *x, const void *y)
{
int result = (int) ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
if (result)
return result;
return_STRING_COMPARE (((struct a_word const *) x)->str,
((struct a_word const *) y)->str);
}
struct a_pattern
{
struct a_pattern *next;
char *str;
char *percent;
size_t length;
};
static char *
func_filter_filterout (char *o, char **argv, const char *funcname)
{
struct a_word *wordhead;
struct a_word **wordtail;
struct a_word *wp;
struct a_pattern *pathead;
struct a_pattern **pattail;
struct a_pattern *pp;
struct hash_table a_word_table;
int is_filter = funcname[CSTRLEN ("filter")] == '\0';
const char *pat_iterator = argv[0];
const char *word_iterator = argv[1];
int literals = 0;
int words = 0;
int hashing = 0;
char *p;
size_t len;
/* Chop ARGV[0] up into patterns to match against the words.
We don't need to preserve it because our caller frees all the
argument memory anyway. */
pattail = &pathead;
while ((p = find_next_token (&pat_iterator, &len)) != 0)
{
struct a_pattern *pat = alloca (sizeof (struct a_pattern));
*pattail = pat;
pattail = &pat->next;
if (*pat_iterator != '\0')
++pat_iterator;
pat->str = p;
p[len] = '\0';
pat->percent = find_percent (p);
if (pat->percent == 0)
literals++;
/* find_percent() might shorten the string so LEN is wrong. */
pat->length = strlen (pat->str);
}
*pattail = 0;
/* Chop ARGV[1] up into words to match against the patterns. */
wordtail = &wordhead;
while ((p = find_next_token (&word_iterator, &len)) != 0)
{
struct a_word *word = alloca (sizeof (struct a_word));
*wordtail = word;
wordtail = &word->next;
if (*word_iterator != '\0')
++word_iterator;
p[len] = '\0';
word->str = p;
word->length = len;
word->matched = 0;
word->chain = 0;
words++;
}
*wordtail = 0;
/* Only use a hash table if arg list lengths justifies the cost. */
hashing = (literals >= 2 && (literals * words) >= 10);
if (hashing)
{
hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
a_word_hash_cmp);
for (wp = wordhead; wp != 0; wp = wp->next)
{
struct a_word *owp = hash_insert (&a_word_table, wp);
if (owp)
wp->chain = owp;
}
}
if (words)
{
int doneany = 0;
/* Run each pattern through the words, killing words. */
for (pp = pathead; pp != 0; pp = pp->next)
{
if (pp->percent)
for (wp = wordhead; wp != 0; wp = wp->next)
wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
else if (hashing)
{
struct a_word a_word_key;
a_word_key.str = pp->str;
a_word_key.length = pp->length;
wp = hash_find_item (&a_word_table, &a_word_key);
while (wp)
{
wp->matched |= 1;
wp = wp->chain;
}
}
else
for (wp = wordhead; wp != 0; wp = wp->next)
wp->matched |= (wp->length == pp->length
&& strneq (pp->str, wp->str, wp->length));
}
/* Output the words that matched (or didn't, for filter-out). */
for (wp = wordhead; wp != 0; wp = wp->next)
if (is_filter ? wp->matched : !wp->matched)
{
o = variable_buffer_output (o, wp->str, strlen (wp->str));
o = variable_buffer_output (o, " ", 1);
doneany = 1;
}
if (doneany)
/* Kill the last space. */
--o;
}
if (hashing)
hash_free (&a_word_table, 0);
return o;
}
static char *
func_strip (char *o, char **argv, const char *funcname UNUSED)
{
const char *p = argv[0];
int doneany = 0;
while (*p != '\0')
{
int i=0;
const char *word_start;
NEXT_TOKEN (p);
word_start = p;
for (i=0; *p != '\0' && !ISSPACE (*p); ++p, ++i)
{}
if (!i)
break;
o = variable_buffer_output (o, word_start, i);
o = variable_buffer_output (o, " ", 1);
doneany = 1;
}
if (doneany)
/* Kill the last space. */
--o;
return o;
}
/*
Print a warning or fatal message.
*/
static char *
func_error (char *o, char **argv, const char *funcname)
{
char **argvp;
char *msg, *p;
size_t len;
/* The arguments will be broken on commas. Rather than create yet
another special case where function arguments aren't broken up,
just create a format string that puts them back together. */
for (len=0, argvp=argv; *argvp != 0; ++argvp)
len += strlen (*argvp) + 2;
p = msg = alloca (len + 1);
msg[0] = '\0';
for (argvp=argv; argvp[1] != 0; ++argvp)
{
strcpy (p, *argvp);
p += strlen (*argvp);
*(p++) = ',';
*(p++) = ' ';
}
strcpy (p, *argvp);
switch (*funcname)
{
case 'e':
OS (fatal, reading_file, "%s", msg);
case 'w':
OS (error, reading_file, "%s", msg);
break;
case 'i':
outputs (0, msg);
outputs (0, "\n");
break;
default:
OS (fatal, *expanding_var, "Internal error: func_error: '%s'", funcname);
}
/* The warning function expands to the empty string. */
return o;
}
/*
chop argv[0] into words, and sort them.
*/
static char *
func_sort (char *o, char **argv, const char *funcname UNUSED)
{
const char *t;
char **words;
int wordi;
char *p;
size_t len;
/* Find the maximum number of words we'll have. */
t = argv[0];
wordi = 0;
while ((p = find_next_token (&t, NULL)) != 0)
{
++t;
++wordi;
}
words = xmalloc ((wordi == 0 ? 1 : wordi) * sizeof (char *));
/* Now assign pointers to each string in the array. */
t = argv[0];
wordi = 0;
while ((p = find_next_token (&t, &len)) != 0)
{
++t;
p[len] = '\0';
words[wordi++] = p;
}
if (wordi)
{
int i;
/* Now sort the list of words. */
qsort (words, wordi, sizeof (char *), alpha_compare);
/* Now write the sorted list, uniquified. */
for (i = 0; i < wordi; ++i)
{
len = strlen (words[i]);
if (i == wordi - 1 || strlen (words[i + 1]) != len
|| strcmp (words[i], words[i + 1]))
{
o = variable_buffer_output (o, words[i], len);
o = variable_buffer_output (o, " ", 1);
}
}
/* Kill the last space. */
--o;
}
free (words);
return o;
}
/*
chop argv[0] into words, and remove duplicates.
*/
static char *
func_uniq (char *o, char **argv, const char *funcname UNUSED)
{
char *p;
size_t len;
int mutated;
bool once = false;
const char *s = argv[0];
struct critbit0 t = {0};
while ((p = find_next_token (&s, &len)))
{
++s;
p[len] = 0;
RETURN_ON_ERROR ((mutated = critbit0_insert (&t, p)));
if (mutated)
{
if (once)
o = variable_buffer_output (o, " ", 1);
else
once = true;
o = variable_buffer_output (o, p, len);
}
}
critbit0_clear (&t);
return o;
OnError:
critbit0_clear (&t);
OSS (error, NILF, "%s: function failed: %s",
"uniq", strerror (errno));
exit (1);
}
/*
$(if condition,true-part[,false-part])
CONDITION is false iff it evaluates to an empty string. White
space before and after condition are stripped before evaluation.
If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
evaluated (if it exists). Because only one of the two PARTs is evaluated,
you can use $(if ...) to create side-effects (with $(shell ...), for
example).
*/
static char *
func_if (char *o, char **argv, const char *funcname UNUSED)
{
const char *begp = argv[0];
const char *endp = begp + strlen (argv[0]) - 1;
int result = 0;
/* Find the result of the condition: if we have a value, and it's not
empty, the condition is true. If we don't have a value, or it's the
empty string, then it's false. */
strip_whitespace (&begp, &endp);
if (begp <= endp)
{
char *expansion = expand_argument (begp, endp+1);
result = expansion[0] != '\0';
free (expansion);
}
/* If the result is true (1) we want to eval the first argument, and if
it's false (0) we want to eval the second. If the argument doesn't
exist we do nothing, otherwise expand it and add to the buffer. */
argv += 1 + !result;
if (*argv)
{
char *expansion = expand_argument (*argv, NULL);
o = variable_buffer_output (o, expansion, strlen (expansion));
free (expansion);
}
return o;
}
/*
$(or condition1[,condition2[,condition3[...]]])
A CONDITION is false iff it evaluates to an empty string. White
space before and after CONDITION are stripped before evaluation.
CONDITION1 is evaluated. If it's true, then this is the result of
expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
the conditions are true, the expansion is the empty string.
Once a CONDITION is true no further conditions are evaluated
(short-circuiting).
*/
static char *
func_or (char *o, char **argv, const char *funcname UNUSED)
{
for ( ; *argv ; ++argv)
{
const char *begp = *argv;
const char *endp = begp + strlen (*argv) - 1;
char *expansion;
size_t result = 0;
/* Find the result of the condition: if it's false keep going. */
strip_whitespace (&begp, &endp);
if (begp > endp)
continue;
expansion = expand_argument (begp, endp+1);
result = strlen (expansion);
/* If the result is false keep going. */
if (!result)
{
free (expansion);
continue;
}
/* It's true! Keep this result and return. */
o = variable_buffer_output (o, expansion, result);
free (expansion);
break;
}
return o;
}
/*
$(and condition1[,condition2[,condition3[...]]])
A CONDITION is false iff it evaluates to an empty string. White
space before and after CONDITION are stripped before evaluation.
CONDITION1 is evaluated. If it's false, then this is the result of
expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
the conditions are true, the expansion is the result of the last condition.
Once a CONDITION is false no further conditions are evaluated
(short-circuiting).
*/
static char *
func_and (char *o, char **argv, const char *funcname UNUSED)
{
char *expansion;
while (1)
{
const char *begp = *argv;
const char *endp = begp + strlen (*argv) - 1;
size_t result;
/* An empty condition is always false. */
strip_whitespace (&begp, &endp);
if (begp > endp)
return o;
expansion = expand_argument (begp, endp+1);
result = strlen (expansion);
/* If the result is false, stop here: we're done. */
if (!result)
break;
/* Otherwise the result is true. If this is the last one, keep this
result and quit. Otherwise go on to the next one! */
if (*(++argv))
free (expansion);
else
{
o = variable_buffer_output (o, expansion, result);
break;
}
}
free (expansion);
return o;
}
static char *
func_wildcard (char *o, char **argv, const char *funcname UNUSED)
{
char *p = string_glob (argv[0]);
o = variable_buffer_output (o, p, strlen (p));
return o;
}
/*
$(eval <makefile string>)
Always resolves to the empty string.
Treat the arguments as a segment of makefile, and parse them.
*/
static char *
func_eval (char *o, char **argv, const char *funcname UNUSED)
{
char *buf;
size_t len;
/* Eval the buffer. Pop the current variable buffer setting so that the
eval'd code can use its own without conflicting. */
install_variable_buffer (&buf, &len);
eval_buffer (argv[0], NULL);
restore_variable_buffer (buf, len);
return o;
}
static char *
func_value (char *o, char **argv, const char *funcname UNUSED)
{
/* Look up the variable. */
struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
/* Copy its value into the output buffer without expanding it. */
if (v)
o = variable_buffer_output (o, v->value, strlen (v->value));
return o;
}
/*
\r is replaced on UNIX as well. Is this desirable?
*/
static void
fold_newlines (char *buffer, size_t *length, int trim_newlines)
{
char *dst = buffer;
char *src = buffer;
char *last_nonnl = buffer - 1;
src[*length] = 0;
for (; *src != '\0'; ++src)
{
if (src[0] == '\r' && src[1] == '\n')
continue;
if (*src == '\n')
{
*dst++ = ' ';
}
else
{
last_nonnl = dst;
*dst++ = *src;
}
}
if (!trim_newlines && (last_nonnl < (dst - 2)))
last_nonnl = dst - 2;
*(++last_nonnl) = '\0';
*length = last_nonnl - buffer;
}
pid_t shell_function_pid = 0;
static int shell_function_completed;
void
shell_completed (int exit_code, int exit_sig)
{
char buf[256];
shell_function_pid = 0;
if (exit_sig == 0 && exit_code == 127)
shell_function_completed = -1;
else
shell_function_completed = 1;
if (exit_code == 0 && exit_sig > 0)
exit_code = 128 + exit_sig;
sprintf (buf, "%d", exit_code);
define_variable_cname (".SHELLSTATUS", buf, o_override, 0);
}
/*
Do shell spawning, with the naughty bits for different OSes.
*/
char *
func_shell_base (char *o, char **argv, int trim_newlines)
{
char *batch_filename = NULL;
int errfd;
char **command_argv = NULL;
char **envp;
int pipedes[2];
pid_t pid;
/* Construct the argument list. */
command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
&batch_filename);
if (command_argv == 0)
{
return o;
}
/* Using a target environment for 'shell' loses in cases like:
export var = $(shell echo foobie)
bad := $(var)
because target_environment hits a loop trying to expand $(var) to put it
in the environment. This is even more confusing when 'var' was not
explicitly exported, but just appeared in the calling environment.
See Savannah bug #10593.
envp = target_environment (NULL);
*/
envp = environ;
/* Set up the output in case the shell writes something. */
output_start ();
errfd = (output_context && output_context->err >= 0
? output_context->err : FD_STDERR);
if (pipe (pipedes) < 0)
{
OS (error, reading_file, "pipe: %s", strerror (errno));
pid = -1;
goto done;
}
/* Close handles that are unnecessary for the child process. */
fd_noinherit (pipedes[1]);
fd_noinherit (pipedes[0]);
{
struct childbase child;
child.cmd_name = NULL;
child.output.syncout = 1;
child.output.out = pipedes[1];
child.output.err = errfd;
child.environment = envp;
pid = child_execute_job (&child, 1, command_argv, false);
free (child.cmd_name);
}
if (pid < 0)
{
shell_completed (127, 0);
goto done;
}
{
char *buffer;
size_t maxlen, i;
int cc;
/* Record the PID for reap_children. */
shell_function_pid = pid;
shell_function_completed = 0;
/* Close the write side of the pipe. We test for -1, since
pipedes[1] is -1 on MS-Windows, and some versions of MS
libraries barf when 'close' is called with -1. */
if (pipedes[1] >= 0)
close (pipedes[1]);
/* Set up and read from the pipe. */
maxlen = 200;
buffer = xmalloc (maxlen + 1);
/* Read from the pipe until it gets EOF. */
for (i = 0; ; i += cc)
{
if (i == maxlen)
{
maxlen += 512;
buffer = xrealloc (buffer, maxlen + 1);
}
EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
if (cc <= 0)
break;
}
buffer[i] = '\0';
/* Close the read side of the pipe. */
(void) close (pipedes[0]);
/* Loop until child_handler or reap_children() sets
shell_function_completed to the status of our child shell. */
while (shell_function_completed == 0)
reap_children (1, 0);
if (batch_filename)
{
DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
batch_filename));
remove (batch_filename);
free (batch_filename);
}
shell_function_pid = 0;
/* shell_completed() will set shell_function_completed to 1 when the
child dies normally, or to -1 if it dies with status 127, which is
most likely an exec fail. */
if (shell_function_completed == -1)
{
/* This likely means that the execvp failed, so we should just
write the error message in the pipe from the child. */
fputs (buffer, stderr);
fflush (stderr);
}
else
{
/* The child finished normally. Replace all newlines in its output
with spaces, and put that in the variable output buffer. */
fold_newlines (buffer, &i, trim_newlines);
o = variable_buffer_output (o, buffer, i);
}
free (buffer);
}
done:
if (command_argv)
{
/* Free the storage only the child needed. */
free (command_argv[0]);
free (command_argv);
}
return o;
}
static char *
func_shell (char *o, char **argv, const char *funcname UNUSED)
{
return func_shell_base (o, argv, 1);
}
#ifdef EXPERIMENTAL
/*
equality. Return is string-boolean, i.e., the empty string is false.
*/
static char *
func_eq (char *o, char **argv, char *funcname UNUSED)
{
int result = ! strcmp (argv[0], argv[1]);
o = variable_buffer_output (o, result ? "1" : "", result);
return o;
}
/*
string-boolean not operator.
*/
static char *
func_not (char *o, char **argv, char *funcname UNUSED)
{
const char *s = argv[0];
int result = 0;
NEXT_TOKEN (s);
result = ! (*s);
o = variable_buffer_output (o, result ? "1" : "", result);
return o;
}
#endif
#define IS_ABSOLUTE(n) (n[0] == '/')
#define ROOT_LEN 1
/* Return the absolute name of file NAME which does not contain any '.',
'..' components nor any repeated path separators ('/'). */
static char *
abspath (const char *name, char *apath)
{
char *dest;
const char *start, *end, *apath_limit;
unsigned long root_len = ROOT_LEN;
if (name[0] == '\0')
return NULL;
apath_limit = apath + GET_PATH_MAX;
if (!IS_ABSOLUTE(name))
{
/* It is unlikely we would make it until here but just to make sure. */
if (!starting_directory)
return NULL;
strcpy (apath, starting_directory);
dest = strchr (apath, '\0');
}
else
{
memcpy (apath, name, root_len);
apath[root_len] = '\0';
dest = apath + root_len;
/* Get past the root, since we already copied it. */
name += root_len;
}
for (start = end = name; *start != '\0'; start = end)
{
size_t len;
/* Skip sequence of multiple path-separators. */
while (STOP_SET (*start, MAP_DIRSEP))
++start;
/* Find end of path component. */
for (end = start; ! STOP_SET (*end, MAP_DIRSEP|MAP_NUL); ++end)
;
len = end - start;
if (len == 0)
break;
else if (len == 1 && start[0] == '.')
/* nothing */;
else if (len == 2 && start[0] == '.' && start[1] == '.')
{
/* Back up to previous component, ignore if at root already. */
if (dest > apath + root_len)
for (--dest; ! STOP_SET (dest[-1], MAP_DIRSEP); --dest)
;
}
else
{
if (! STOP_SET (dest[-1], MAP_DIRSEP))
*dest++ = '/';
if (dest + len >= apath_limit)
return NULL;
dest = memcpy (dest, start, len);
dest += len;
*dest = '\0';
}
}
/* Unless it is root strip trailing separator. */
if (dest > apath + root_len && STOP_SET (dest[-1], MAP_DIRSEP))
--dest;
*dest = '\0';
return apath;
}
static char *
func_realpath (char *o, char **argv, const char *funcname UNUSED)
{
/* Expand the argument. */
const char *p = argv[0];
const char *path = 0;
int doneany = 0;
size_t len = 0;
while ((path = find_next_token (&p, &len)) != 0)
{
if (len < GET_PATH_MAX)
{
char *rp;
struct stat st;
PATH_VAR (in);
PATH_VAR (out);
strncpy (in, path, len);
in[len] = '\0';
#ifdef HAVE_REALPATH
ENULLLOOP (rp, realpath (in, out));
# if defined _AIX
/* AIX realpath() doesn't remove trailing slashes correctly. */
if (rp)
{
char *ep = rp + strlen (rp) - 1;
while (ep > rp && ep[0] == '/')
*(ep--) = '\0';
}
# endif
#else
rp = abspath (in, out);
#endif
if (rp)
{
int r;
EINTRLOOP (r, stat (out, &st));
if (r == 0)
{
o = variable_buffer_output (o, out, strlen (out));
o = variable_buffer_output (o, " ", 1);
doneany = 1;
}
}
}
}
/* Kill last space. */
if (doneany)
--o;
return o;
}
static char *
func_file (char *o, char **argv, const char *funcname UNUSED)
{
char *fn = argv[0];
if (fn[0] == '>')
{
FILE *fp;
const char *mode = "w";
/* We are writing a file. */
++fn;
if (fn[0] == '>')
{
mode = "a";
++fn;
}
NEXT_TOKEN (fn);
if (fn[0] == '\0')
O (fatal, *expanding_var, _("file: missing filename"));
ENULLLOOP (fp, fopen (fn, mode));
if (fp == NULL)
OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
if (argv[1])
{
size_t l = strlen (argv[1]);
int nl = l == 0 || argv[1][l-1] != '\n';
if (fputs (argv[1], fp) == EOF || (nl && fputc ('\n', fp) == EOF))
OSS (fatal, reading_file, _("write: %s: %s"), fn, strerror (errno));
}
if (fclose (fp))
OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
}
else if (fn[0] == '<')
{
char *preo = o;
FILE *fp;
++fn;
NEXT_TOKEN (fn);
if (fn[0] == '\0')
O (fatal, *expanding_var, _("file: missing filename"));
if (argv[1])
O (fatal, *expanding_var, _("file: too many arguments"));
ENULLLOOP (fp, fopen (fn, "r"));
if (fp == NULL)
{
if (errno == ENOENT)
return o;
OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
}
while (1)
{
char buf[1024];
size_t l = fread (buf, 1, sizeof (buf), fp);
if (l > 0)
o = variable_buffer_output (o, buf, l);
if (ferror (fp))
if (errno != EINTR)
OSS (fatal, reading_file, _("read: %s: %s"), fn, strerror (errno));
if (feof (fp))
break;
}
if (fclose (fp))
OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
/* Remove trailing newline. */
if (o > preo && o[-1] == '\n')
if (--o > preo && o[-1] == '\r')
--o;
}
else
OS (fatal, *expanding_var, _("file: invalid file operation: %s"), fn);
return o;
}
static char *
func_abspath (char *o, char **argv, const char *funcname UNUSED)
{
/* Expand the argument. */
const char *p = argv[0];
const char *path = 0;
int doneany = 0;
size_t len = 0;
while ((path = find_next_token (&p, &len)) != 0)
{
if (len < GET_PATH_MAX)
{
PATH_VAR (in);
PATH_VAR (out);
strncpy (in, path, len);
in[len] = '\0';
if (abspath (in, out))
{
o = variable_buffer_output (o, out, strlen (out));
o = variable_buffer_output (o, " ", 1);
doneany = 1;
}
}
}
/* Kill last space. */
if (doneany)
--o;
return o;
}
/* Lookup table for builtin functions.
This doesn't have to be sorted; we use a straight lookup. We might gain
some efficiency by moving most often used functions to the start of the
table.
If MAXIMUM_ARGS is 0, that means there is no maximum and all
comma-separated values are treated as arguments.
EXPAND_ARGS means that all arguments should be expanded before invocation.
Functions that do namespace tricks (foreach) don't automatically expand. */
static char *func_call (char *o, char **argv, const char *funcname);
#define FT_ENTRY(_name, _min, _max, _exp, _func) \
{ { (_func) }, STRING_SIZE_TUPLE(_name), (_min), (_max), (_exp), 0 }
static struct function_table_entry function_table_init[] =
{
/* Name MIN MAX EXP? Function */
FT_ENTRY ("abspath", 0, 1, 1, func_abspath),
FT_ENTRY ("addprefix", 2, 2, 1, func_addsuffix_addprefix),
FT_ENTRY ("addsuffix", 2, 2, 1, func_addsuffix_addprefix),
FT_ENTRY ("basename", 0, 1, 1, func_basename_dir),
FT_ENTRY ("dir", 0, 1, 1, func_basename_dir),
FT_ENTRY ("notdir", 0, 1, 1, func_notdir_suffix),
FT_ENTRY ("subst", 3, 3, 1, func_subst),
FT_ENTRY ("suffix", 0, 1, 1, func_notdir_suffix),
FT_ENTRY ("filter", 2, 2, 1, func_filter_filterout),
FT_ENTRY ("filter-out", 2, 2, 1, func_filter_filterout),
FT_ENTRY ("findstring", 2, 2, 1, func_findstring),
FT_ENTRY ("firstword", 0, 1, 1, func_firstword),
FT_ENTRY ("flavor", 0, 1, 1, func_flavor),
FT_ENTRY ("join", 2, 2, 1, func_join),
FT_ENTRY ("lastword", 0, 1, 1, func_lastword),
FT_ENTRY ("patsubst", 3, 3, 1, func_patsubst),
FT_ENTRY ("realpath", 0, 1, 1, func_realpath),
FT_ENTRY ("shell", 0, 1, 1, func_shell),
FT_ENTRY ("sort", 0, 1, 1, func_sort),
FT_ENTRY ("strip", 0, 1, 1, func_strip),
FT_ENTRY ("wildcard", 0, 1, 1, func_wildcard),
FT_ENTRY ("word", 2, 2, 1, func_word),
FT_ENTRY ("wordlist", 3, 3, 1, func_wordlist),
FT_ENTRY ("words", 0, 1, 1, func_words),
FT_ENTRY ("origin", 0, 1, 1, func_origin),
FT_ENTRY ("foreach", 3, 3, 0, func_foreach),
FT_ENTRY ("call", 1, 0, 1, func_call),
FT_ENTRY ("info", 0, 1, 1, func_error),
FT_ENTRY ("error", 0, 1, 1, func_error),
FT_ENTRY ("warning", 0, 1, 1, func_error),
FT_ENTRY ("if", 2, 3, 0, func_if),
FT_ENTRY ("or", 1, 0, 0, func_or),
FT_ENTRY ("and", 1, 0, 0, func_and),
FT_ENTRY ("value", 0, 1, 1, func_value),
FT_ENTRY ("eval", 0, 1, 1, func_eval),
FT_ENTRY ("file", 1, 2, 1, func_file),
FT_ENTRY ("uniq", 0, 1, 1, func_uniq),
#ifdef EXPERIMENTAL
FT_ENTRY ("eq", 2, 2, 1, func_eq),
FT_ENTRY ("not", 0, 1, 1, func_not),
#endif
};
#define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
/* These must come after the definition of function_table. */
static char *
expand_builtin_function (char *o, int argc, char **argv,
const struct function_table_entry *entry_p)
{
char *p;
if (argc < (int)entry_p->minimum_args)
fatal (*expanding_var, strlen (entry_p->name),
_("insufficient number of arguments (%d) to function '%s'"),
argc, entry_p->name);
/* I suppose technically some function could do something with no arguments,
but so far no internal ones do, so just test it for all functions here
rather than in each one. We can change it later if necessary. */
if (!argc && !entry_p->alloc_fn)
return o;
if (!entry_p->fptr.func_ptr)
OS (fatal, *expanding_var,
_("unimplemented on this platform: function '%s'"), entry_p->name);
if (!entry_p->alloc_fn)
return entry_p->fptr.func_ptr (o, argv, entry_p->name);
/* This function allocates memory and returns it to us.
Write it to the variable buffer, then free it. */
p = entry_p->fptr.alloc_func_ptr (entry_p->name, argc, argv);
if (p)
{
o = variable_buffer_output (o, p, strlen (p));
free (p);
}
return o;
}
/* Check for a function invocation in *STRINGP. *STRINGP points at the
opening ( or { and is not null-terminated. If a function invocation
is found, expand it into the buffer at *OP, updating *OP, incrementing
*STRINGP past the reference and returning nonzero. If not, return zero. */
int
handle_function (char **op, const char **stringp)
{
const struct function_table_entry *entry_p;
char openparen = (*stringp)[0];
char closeparen = openparen == '(' ? ')' : '}';
const char *beg;
const char *end;
int count = 0;
char *abeg = NULL;
char **argv, **argvp;
int nargs;
beg = *stringp + 1;
entry_p = lookup_function (beg);
if (!entry_p)
return 0;
/* We found a builtin function. Find the beginning of its arguments (skip
whitespace after the name). */
beg += entry_p->len;
NEXT_TOKEN (beg);
/* Find the end of the function invocation, counting nested use of
whichever kind of parens we use. Since we're looking, count commas
to get a rough estimate of how many arguments we might have. The
count might be high, but it'll never be low. */
for (nargs=1, end=beg; *end != '\0'; ++end)
if (!STOP_SET (*end, MAP_VARSEP|MAP_COMMA))
continue;
else if (*end == ',')
++nargs;
else if (*end == openparen)
++count;
else if (*end == closeparen && --count < 0)
break;
if (count >= 0)
fatal (*expanding_var, strlen (entry_p->name),
_("unterminated call to function '%s': missing '%c'"),
entry_p->name, closeparen);
*stringp = end;
/* Get some memory to store the arg pointers. */
argvp = argv = alloca (sizeof (char *) * (nargs + 2));
/* Chop the string into arguments, then a nul. As soon as we hit
MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
last argument.
If we're expanding, store pointers to the expansion of each one. If
not, make a duplicate of the string and point into that, nul-terminating
each argument. */
if (entry_p->expand_args)
{
const char *p;
for (p=beg, nargs=0; p <= end; ++argvp)
{
const char *next;
++nargs;
if (nargs == entry_p->maximum_args
|| ((next = find_next_argument (openparen, closeparen, p, end)) == NULL))
next = end;
*argvp = expand_argument (p, next);
p = next + 1;
}
}
else
{
size_t len = end - beg;
char *p, *aend;
abeg = xmalloc (len+1);
memcpy (abeg, beg, len);
abeg[len] = '\0';
aend = abeg + len;
for (p=abeg, nargs=0; p <= aend; ++argvp)
{
char *next;
++nargs;
if (nargs == entry_p->maximum_args
|| ((next = find_next_argument (openparen, closeparen, p, aend)) == NULL))
next = aend;
*argvp = p;
*next = '\0';
p = next + 1;
}
}
*argvp = NULL;
/* Finally! Run the function... */
*op = expand_builtin_function (*op, nargs, argv, entry_p);
/* Free memory. */
if (entry_p->expand_args)
for (argvp=argv; *argvp != 0; ++argvp)
free (*argvp);
else
free (abeg);
return 1;
}
/* User-defined functions. Expand the first argument as either a builtin
function or a make variable, in the context of the rest of the arguments
assigned to $1, $2, ... $N. $0 is the name of the function. */
static char *
func_call (char *o, char **argv, const char *funcname UNUSED)
{
static int max_args = 0;
char *fname;
char *body;
size_t flen;
int i;
int saved_args;
const struct function_table_entry *entry_p;
struct variable *v;
/* Clean up the name of the variable to be invoked. */
fname = next_token (argv[0]);
end_of_token (fname)[0] = '\0';
/* Calling nothing is a no-op */
if (*fname == '\0')
return o;
/* Are we invoking a builtin function? */
entry_p = lookup_function (fname);
if (entry_p)
{
/* How many arguments do we have? */
for (i=0; argv[i+1]; ++i)
;
return expand_builtin_function (o, i, argv+1, entry_p);
}
/* Not a builtin, so the first argument is the name of a variable to be
expanded and interpreted as a function. Find it. */
flen = strlen (fname);
v = lookup_variable (fname, flen);
if (v == 0)
warn_undefined (fname, flen);
if (v == 0 || *v->value == '\0')
return o;
body = alloca (flen + 4);
body[0] = '$';
body[1] = '(';
memcpy (body + 2, fname, flen);
body[flen+2] = ')';
body[flen+3] = '\0';
/* Set up arguments $(1) .. $(N). $(0) is the function name. */
push_new_variable_scope ();
for (i=0; *argv; ++i, ++argv)
{
char num[11];
sprintf (num, "%d", i);
define_variable (num, strlen (num), *argv, o_automatic, 0);
}
/* If the number of arguments we have is < max_args, it means we're inside
a recursive invocation of $(call ...). Fill in the remaining arguments
in the new scope with the empty value, to hide them from this
invocation. */
for (; i < max_args; ++i)
{
char num[11];
sprintf (num, "%d", i);
define_variable (num, strlen (num), "", o_automatic, 0);
}
/* Expand the body in the context of the arguments, adding the result to
the variable buffer. */
v->exp_count = EXP_COUNT_MAX;
saved_args = max_args;
max_args = i;
o = variable_expand_string (o, body, flen+3);
max_args = saved_args;
v->exp_count = 0;
pop_variable_scope ();
return o + strlen (o);
}
void
define_new_function (const floc *flocp, const char *name,
unsigned int min, unsigned int max, unsigned int flags,
gmk_func_ptr func)
{
const char *e = name;
struct function_table_entry *ent;
size_t len;
while (STOP_SET (*e, MAP_USERFUNC))
e++;
len = e - name;
if (len == 0)
O (fatal, flocp, _("Empty function name"));
if (*name == '.' || *e != '\0')
OS (fatal, flocp, _("Invalid function name: %s"), name);
if (len > 255)
OS (fatal, flocp, _("Function name too long: %s"), name);
if (min > 255)
ONS (fatal, flocp,
_("Invalid minimum argument count (%u) for function %s"), min, name);
if (max > 255 || (max && max < min))
ONS (fatal, flocp,
_("Invalid maximum argument count (%u) for function %s"), max, name);
ent = xmalloc (sizeof (struct function_table_entry));
ent->name = name;
ent->len = (unsigned char) len;
ent->minimum_args = (unsigned char) min;
ent->maximum_args = (unsigned char) max;
ent->expand_args = ANY_SET(flags, GMK_FUNC_NOEXPAND) ? 0 : 1;
ent->alloc_fn = 1;
ent->fptr.alloc_func_ptr = func;
hash_insert (&function_table, ent);
}
void
hash_init_function_table (void)
{
hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
function_table_entry_hash_1, function_table_entry_hash_2,
function_table_entry_hash_cmp);
hash_load (&function_table, function_table_init,
FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
}
| 58,783 | 2,274 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/gettext.h | /* clang-format off */
/* Convenience header for conditional use of GNU <libintl.h>.
Copyright (C) 1995-1998, 2000-2002, 2004-2006, 2009-2020 Free Software
Foundation, 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; either version 3, 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/>. */
#ifndef _LIBGETTEXT_H
#define _LIBGETTEXT_H 1
#include "libc/str/str.h"
/* NLS can be disabled through the configure --disable-nls option
or through "#define ENABLE NLS 0" before including this file. */
#if defined ENABLE_NLS && ENABLE_NLS
/* Get declarations of GNU message catalog functions. */
/* You can set the DEFAULT_TEXT_DOMAIN macro to specify the domain used by
the gettext() and ngettext() macros. This is an alternative to calling
textdomain(), and is useful for libraries. */
# ifdef DEFAULT_TEXT_DOMAIN
# undef gettext
# define gettext(Msgid) \
dgettext (DEFAULT_TEXT_DOMAIN, Msgid)
# undef ngettext
# define ngettext(Msgid1, Msgid2, N) \
dngettext (DEFAULT_TEXT_DOMAIN, Msgid1, Msgid2, N)
# endif
#else
/* Solaris /usr/include/locale.h includes /usr/include/libintl.h, which
chokes if dcgettext is defined as a macro. So include it now, to make
and also including <libintl.h> would fail on SunOS 4, whereas <locale.h>
is OK. */
#if defined(__sun)
#endif
/* Many header files from the libstdc++ coming with g++ 3.3 or newer include
<libintl.h>, which chokes if dcgettext is defined as a macro. So include
it now, to make later inclusions of <libintl.h> a NOP. */
#if defined(__cplusplus) && defined(__GNUG__) && (__GNUC__ >= 3)
# if (__GLIBC__ >= 2 && !defined __UCLIBC__) || _GLIBCXX_HAVE_LIBINTL_H
# endif
#endif
/* Disabled NLS.
The casts to 'const char *' serve the purpose of producing warnings
for invalid uses of the value returned from these functions.
On pre-ANSI systems without 'const', the config.h file is supposed to
contain "#define const". */
# undef gettext
# define gettext(Msgid) ((const char *) (Msgid))
# undef dgettext
# define dgettext(Domainname, Msgid) ((void) (Domainname), gettext (Msgid))
# undef dcgettext
# define dcgettext(Domainname, Msgid, Category) \
((void) (Category), dgettext (Domainname, Msgid))
# undef ngettext
# define ngettext(Msgid1, Msgid2, N) \
((N) == 1 \
? ((void) (Msgid2), (const char *) (Msgid1)) \
: ((void) (Msgid1), (const char *) (Msgid2)))
# undef dngettext
# define dngettext(Domainname, Msgid1, Msgid2, N) \
((void) (Domainname), ngettext (Msgid1, Msgid2, N))
# undef dcngettext
# define dcngettext(Domainname, Msgid1, Msgid2, N, Category) \
((void) (Category), dngettext (Domainname, Msgid1, Msgid2, N))
# undef textdomain
# define textdomain(Domainname) ((const char *) (Domainname))
# undef bindtextdomain
# define bindtextdomain(Domainname, Dirname) \
((void) (Domainname), (const char *) (Dirname))
# undef bind_textdomain_codeset
# define bind_textdomain_codeset(Domainname, Codeset) \
((void) (Domainname), (const char *) (Codeset))
#endif
/* Prefer gnulib's setlocale override over libintl's setlocale override. */
#ifdef GNULIB_defined_setlocale
# undef setlocale
# define setlocale rpl_setlocale
#endif
/* A pseudo function call that serves as a marker for the automated
extraction of messages, but does not call gettext(). The run-time
translation is done at a different place in the code.
The argument, String, should be a literal string. Concatenated strings
and other string expressions won't work.
The macro's expansion is not parenthesized, so that it is suitable as
initializer for static 'char[]' or 'const char[]' variables. */
#define gettext_noop(String) String
/* The separator between msgctxt and msgid in a .mo file. */
#define GETTEXT_CONTEXT_GLUE "\004"
/* Pseudo function calls, taking a MSGCTXT and a MSGID instead of just a
MSGID. MSGCTXT and MSGID must be string literals. MSGCTXT should be
short and rarely need to change.
The letter 'p' stands for 'particular' or 'special'. */
#ifdef DEFAULT_TEXT_DOMAIN
# define pgettext(Msgctxt, Msgid) \
pgettext_aux (DEFAULT_TEXT_DOMAIN, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES)
#else
# define pgettext(Msgctxt, Msgid) \
pgettext_aux (NULL, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES)
#endif
#define dpgettext(Domainname, Msgctxt, Msgid) \
pgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES)
#define dcpgettext(Domainname, Msgctxt, Msgid, Category) \
pgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, Category)
#ifdef DEFAULT_TEXT_DOMAIN
# define npgettext(Msgctxt, Msgid, MsgidPlural, N) \
npgettext_aux (DEFAULT_TEXT_DOMAIN, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES)
#else
# define npgettext(Msgctxt, Msgid, MsgidPlural, N) \
npgettext_aux (NULL, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES)
#endif
#define dnpgettext(Domainname, Msgctxt, Msgid, MsgidPlural, N) \
npgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES)
#define dcnpgettext(Domainname, Msgctxt, Msgid, MsgidPlural, N, Category) \
npgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, Category)
#ifdef __GNUC__
__inline
#else
#ifdef __cplusplus
inline
#endif
#endif
static const char *
pgettext_aux (const char *domain,
const char *msg_ctxt_id, const char *msgid,
int category)
{
const char *translation = dcgettext (domain, msg_ctxt_id, category);
if (translation == msg_ctxt_id)
return msgid;
else
return translation;
}
#ifdef __GNUC__
__inline
#else
#ifdef __cplusplus
inline
#endif
#endif
static const char *
npgettext_aux (const char *domain,
const char *msg_ctxt_id, const char *msgid,
const char *msgid_plural, unsigned long int n,
int category)
{
const char *translation =
dcngettext (domain, msg_ctxt_id, msgid_plural, n, category);
if (translation == msg_ctxt_id || translation == msgid_plural)
return (n == 1 ? msgid : msgid_plural);
else
return translation;
}
/* The same thing extended for non-constant arguments. Here MSGCTXT and MSGID
can be arbitrary expressions. But for string literals these macros are
less efficient than those above. */
/* GNULIB_NO_VLA can be defined to disable use of VLAs even if supported.
This relates to the -Wvla and -Wvla-larger-than warnings, enabled in
the default GCC many warnings set. This allows programs to disable use
of VLAs, which may be unintended, or may be awkward to support portably,
or may have security implications due to non-deterministic stack usage. */
#if (!defined GNULIB_NO_VLA \
&& (((__GNUC__ >= 3 || __GNUG__ >= 2) && !defined __STRICT_ANSI__) \
/* || (__STDC_VERSION__ == 199901L && !defined __HP_cc)
|| (__STDC_VERSION__ >= 201112L && !defined __STDC_NO_VLA__) */ ))
# define _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS 1
#else
# define _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS 0
#endif
#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
#endif
#define pgettext_expr(Msgctxt, Msgid) \
dcpgettext_expr (NULL, Msgctxt, Msgid, LC_MESSAGES)
#define dpgettext_expr(Domainname, Msgctxt, Msgid) \
dcpgettext_expr (Domainname, Msgctxt, Msgid, LC_MESSAGES)
#ifdef __GNUC__
__inline
#else
#ifdef __cplusplus
inline
#endif
#endif
static const char *
dcpgettext_expr (const char *domain,
const char *msgctxt, const char *msgid,
int category)
{
size_t msgctxt_len = strlen (msgctxt) + 1;
size_t msgid_len = strlen (msgid) + 1;
const char *translation;
#if _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
char msg_ctxt_id[msgctxt_len + msgid_len];
#else
char buf[1024];
char *msg_ctxt_id =
(msgctxt_len + msgid_len <= sizeof (buf)
? buf
: (char *) malloc (msgctxt_len + msgid_len));
if (msg_ctxt_id != NULL)
#endif
{
int found_translation;
memcpy (msg_ctxt_id, msgctxt, msgctxt_len - 1);
msg_ctxt_id[msgctxt_len - 1] = '\004';
memcpy (msg_ctxt_id + msgctxt_len, msgid, msgid_len);
translation = dcgettext (domain, msg_ctxt_id, category);
found_translation = (translation != msg_ctxt_id);
#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
if (msg_ctxt_id != buf)
free (msg_ctxt_id);
#endif
if (found_translation)
return translation;
}
return msgid;
}
#define npgettext_expr(Msgctxt, Msgid, MsgidPlural, N) \
dcnpgettext_expr (NULL, Msgctxt, Msgid, MsgidPlural, N, LC_MESSAGES)
#define dnpgettext_expr(Domainname, Msgctxt, Msgid, MsgidPlural, N) \
dcnpgettext_expr (Domainname, Msgctxt, Msgid, MsgidPlural, N, LC_MESSAGES)
#ifdef __GNUC__
__inline
#else
#ifdef __cplusplus
inline
#endif
#endif
static const char *
dcnpgettext_expr (const char *domain,
const char *msgctxt, const char *msgid,
const char *msgid_plural, unsigned long int n,
int category)
{
size_t msgctxt_len = strlen (msgctxt) + 1;
size_t msgid_len = strlen (msgid) + 1;
const char *translation;
#if _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
char msg_ctxt_id[msgctxt_len + msgid_len];
#else
char buf[1024];
char *msg_ctxt_id =
(msgctxt_len + msgid_len <= sizeof (buf)
? buf
: (char *) malloc (msgctxt_len + msgid_len));
if (msg_ctxt_id != NULL)
#endif
{
int found_translation;
memcpy (msg_ctxt_id, msgctxt, msgctxt_len - 1);
msg_ctxt_id[msgctxt_len - 1] = '\004';
memcpy (msg_ctxt_id + msgctxt_len, msgid, msgid_len);
translation = dcngettext (domain, msg_ctxt_id, msgid_plural, n, category);
found_translation = !(translation == msg_ctxt_id || translation == msgid_plural);
#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
if (msg_ctxt_id != buf)
free (msg_ctxt_id);
#endif
if (found_translation)
return translation;
}
return (n == 1 ? msgid : msgid_plural);
}
#endif /* _LIBGETTEXT_H */
| 10,524 | 296 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/loadapi.c | /* clang-format off */
/* API for GNU Make dynamic objects.
Copyright (C) 2013-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
#include "third_party/make/filedef.h"
#include "third_party/make/variable.h"
#include "third_party/make/dep.h"
/* Allocate a buffer in our context, so we can free it. */
char *
gmk_alloc (unsigned int len)
{
return xmalloc (len);
}
/* Free a buffer returned by gmk_expand(). */
void
gmk_free (char *s)
{
free (s);
}
/* Evaluate a buffer as make syntax.
Ideally eval_buffer() will take const char *, but not yet. */
void
gmk_eval (const char *buffer, const gmk_floc *gfloc)
{
/* Preserve existing variable buffer context. */
char *pbuf;
size_t plen;
char *s;
floc fl;
floc *flp;
if (gfloc)
{
fl.filenm = gfloc->filenm;
fl.lineno = gfloc->lineno;
fl.offset = 0;
flp = &fl;
}
else
flp = NULL;
install_variable_buffer (&pbuf, &plen);
s = xstrdup (buffer);
eval_buffer (s, flp);
free (s);
restore_variable_buffer (pbuf, plen);
}
/* Expand a string and return an allocated buffer.
Caller must call gmk_free() with this buffer. */
char *
gmk_expand (const char *ref)
{
return allocated_variable_expand (ref);
}
/* Register a function to be called from makefiles. */
void
gmk_add_function (const char *name, gmk_func_ptr func,
unsigned int min, unsigned int max, unsigned int flags)
{
define_new_function (reading_file, name, min, max, flags, func);
}
| 2,150 | 84 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/gnumake.h | /* clang-format off */
/* External interfaces usable by dynamic objects loaded into GNU Make.
--THIS API IS A "TECHNOLOGY PREVIEW" ONLY. IT IS NOT A STABLE INTERFACE--
Copyright (C) 2013-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#ifndef _GNUMAKE_H_
#define _GNUMAKE_H_
/* Specify the location of elements read from makefiles. */
typedef struct
{
const char *filenm;
unsigned long lineno;
} gmk_floc;
typedef char *(*gmk_func_ptr)(const char *nm, unsigned int argc, char **argv);
#ifdef _WIN32
# ifdef GMK_BUILDING_MAKE
# define GMK_EXPORT __declspec(dllexport)
# else
# define GMK_EXPORT __declspec(dllimport)
# endif
#else
# define GMK_EXPORT
#endif
/* Free memory returned by the gmk_expand() function. */
GMK_EXPORT void gmk_free (char *str);
/* Allocate memory in GNU make's context. */
GMK_EXPORT char *gmk_alloc (unsigned int len);
/* Run $(eval ...) on the provided string BUFFER. */
GMK_EXPORT void gmk_eval (const char *buffer, const gmk_floc *floc);
/* Run GNU make expansion on the provided string STR.
Returns an allocated buffer that the caller must free with gmk_free(). */
GMK_EXPORT char *gmk_expand (const char *str);
/* Register a new GNU make function NAME (maximum of 255 chars long).
When the function is expanded in the makefile, FUNC will be invoked with
the appropriate arguments.
The return value of FUNC must be either NULL, in which case it expands to
the empty string, or a pointer to the result of the expansion in a string
created by gmk_alloc(). GNU make will free the memory when it's done.
MIN_ARGS is the minimum number of arguments the function requires.
MAX_ARGS is the maximum number of arguments (or 0 if there's no maximum).
MIN_ARGS and MAX_ARGS may not exceed 255.
The FLAGS value may be GMK_FUNC_DEFAULT, or one or more of the following
flags OR'd together:
GMK_FUNC_NOEXPAND: the arguments to the function will be not be expanded
before FUNC is called.
*/
GMK_EXPORT void gmk_add_function (const char *name, gmk_func_ptr func,
unsigned int min_args, unsigned int max_args,
unsigned int flags);
#define GMK_FUNC_DEFAULT 0x00
#define GMK_FUNC_NOEXPAND 0x01
#endif /* _GNUMAKE_H_ */
| 2,935 | 81 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/filename.h | /* clang-format off */
/* Basic filename support macros.
Copyright (C) 2001-2004, 2007-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#ifndef _FILENAME_H
#define _FILENAME_H
#ifdef __cplusplus
extern "C" {
#endif
/* Pathname support.
ISSLASH(C) tests whether C is a directory separator character.
IS_ABSOLUTE_PATH(P) tests whether P is an absolute path. If it is not,
it may be concatenated to a directory pathname.
IS_PATH_WITH_DIR(P) tests whether P contains a directory specification.
*/
#if defined _WIN32 || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__
/* Native Windows, Cygwin, OS/2, DOS */
# define ISSLASH(C) ((C) == '/' || (C) == '\\')
# define HAS_DEVICE(P) \
((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) \
&& (P)[1] == ':')
# define IS_ABSOLUTE_PATH(P) (ISSLASH ((P)[0]) || HAS_DEVICE (P))
# define IS_PATH_WITH_DIR(P) \
(strchr (P, '/') != NULL || strchr (P, '\\') != NULL || HAS_DEVICE (P))
# define FILE_SYSTEM_PREFIX_LEN(P) (HAS_DEVICE (P) ? 2 : 0)
#else
/* Unix */
# define ISSLASH(C) ((C) == '/')
# define IS_ABSOLUTE_PATH(P) ISSLASH ((P)[0])
# define IS_PATH_WITH_DIR(P) (strchr (P, '/') != NULL)
# define FILE_SYSTEM_PREFIX_LEN(P) 0
#endif
#ifdef __cplusplus
}
#endif
#endif /* _FILENAME_H */
| 1,965 | 56 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/rule.h | /* clang-format off */
/* Definitions for using pattern rules in GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* Structure used for pattern (implicit) rules. */
struct rule
{
struct rule *next;
const char **targets; /* Targets of the rule. */
unsigned int *lens; /* Lengths of each target. */
const char **suffixes; /* Suffixes (after '%') of each target. */
struct dep *deps; /* Dependencies of the rule. */
struct commands *cmds; /* Commands to execute. */
unsigned short num; /* Number of targets. */
char terminal; /* If terminal (double-colon). */
char in_use; /* If in use by a parent pattern_search. */
};
/* For calling install_pattern_rule. */
struct pspec
{
const char *target, *dep, *commands;
};
extern struct rule *pattern_rules;
extern struct rule *last_pattern_rule;
extern unsigned int num_pattern_rules;
extern unsigned int max_pattern_deps;
extern unsigned int max_pattern_targets;
extern size_t max_pattern_dep_length;
extern struct file *suffix_file;
void snap_implicit_rules (void);
void convert_to_pattern (void);
void install_pattern_rule (struct pspec *p, int terminal);
void create_pattern_rule (const char **targets, const char **target_percents,
unsigned short num, int terminal, struct dep *deps,
struct commands *commands, int override);
void print_rule_data_base (void);
| 2,151 | 59 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/findprog.h | /* clang-format off */
/* clang-format off */
/* Locating a program in PATH.
Copyright (C) 2001-2003, 2009-2020 Free Software Foundation, Inc.
Written by Bruno Haible <[email protected]>, 2001.
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 <https://www.gnu.org/licenses/>. */
#ifndef _FINDPROG_H
#define _FINDPROG_H
#ifdef __cplusplus
extern "C" {
#endif
/* Looks up a program in the PATH.
Attempts to determine the pathname that would be called by execlp/execvp
of PROGNAME. If successful, it returns a pathname containing a slash
(either absolute or relative to the current directory). Otherwise, it
returns PROGNAME unmodified.
Because of the latter case, callers should use execlp/execvp, not
execl/execv on the returned pathname.
The returned string is freshly malloc()ed if it is != PROGNAME. */
extern const char *find_in_path (const char *progname);
/* Looks up a program in the given PATH-like string.
The PATH argument consists of a list of directories, separated by ':' or
(on native Windows) by ';'. An empty PATH element designates the current
directory. A null PATH is equivalent to an empty PATH, that is, to the
singleton list that contains only the current directory.
Determines the pathname that would be called by execlp/execvp of PROGNAME.
- If successful, it returns a pathname containing a slash (either absolute
or relative to the current directory). The returned string can be used
with either execl/execv or execlp/execvp. It is freshly malloc()ed if it
is != PROGNAME.
- Otherwise, it sets errno and returns NULL.
Specific errno values include:
- ENOENT: means that the program's file was not found.
- EACCES: means that the program's file cannot be accessed (due to some
issue with one of the ancestor directories) or lacks the execute
permissions.
If OPTIMIZE_FOR_EXEC is true, the function saves some work, under the
assumption that the resulting pathname will not be accessed directly,
only through execl/execv or execlp/execvp.
Here, a "slash" means:
- On POSIX systems excluding Cygwin: a '/',
- On Windows, OS/2, DOS platforms: a '/' or '\'. */
extern const char *find_in_given_path (const char *progname, const char *path,
bool optimize_for_exec);
#ifdef __cplusplus
}
#endif
#endif /* _FINDPROG_H */
| 2,984 | 72 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/read.c | /* Reading and parsing of makefiles for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* clang-format off */
#include "third_party/make/makeint.inc"
#include "third_party/make/filedef.h"
#include "third_party/make/dep.h"
#include "third_party/make/job.h"
#include "third_party/make/os.h"
#include "third_party/make/commands.h"
#include "third_party/make/variable.h"
#include "third_party/make/rule.h"
#include "third_party/make/debug.h"
#include "third_party/musl/passwd.h"
#include "third_party/make/hash.h"
# define GLOB_ALTDIRFUNC (1 << 9)/* Use gl_opendir et al functions. */
/* A 'struct ebuffer' controls the origin of the makefile we are currently
eval'ing.
*/
struct ebuffer
{
char *buffer; /* Start of the current line in the buffer. */
char *bufnext; /* Start of the next line in the buffer. */
char *bufstart; /* Start of the entire buffer. */
size_t size; /* Malloc'd size of buffer. */
FILE *fp; /* File, or NULL if this is an internal buffer. */
floc floc; /* Info on the file in fp (if any). */
};
/* Track the modifiers we can have on variable assignments */
struct vmodifiers
{
unsigned int assign_v:1;
unsigned int define_v:1;
unsigned int undefine_v:1;
unsigned int export_v:1;
unsigned int override_v:1;
unsigned int private_v:1;
};
/* Types of "words" that can be read in a makefile. */
enum make_word_type
{
w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
w_varassign, w_ampcolon, w_ampdcolon
};
/* A 'struct conditionals' contains the information describing
all the active conditionals in a makefile.
The global variable 'conditionals' contains the conditionals
information for the current makefile. It is initialized from
the static structure 'toplevel_conditionals' and is later changed
to new structures for included makefiles. */
struct conditionals
{
unsigned int if_cmds; /* Depth of conditional nesting. */
unsigned int allocated; /* Elts allocated in following arrays. */
char *ignoring; /* Are we ignoring or interpreting?
0=interpreting, 1=not yet interpreted,
2=already interpreted */
char *seen_else; /* Have we already seen an 'else'? */
};
static struct conditionals toplevel_conditionals;
static struct conditionals *conditionals = &toplevel_conditionals;
/* Default directories to search for include files in */
static const char *default_include_directories[] =
{
#if defined(WINDOWS32) && !defined(INCLUDEDIR)
/* This completely up to the user when they install MSVC or other packages.
This is defined as a placeholder. */
# define INCLUDEDIR "."
#endif
INCLUDEDIR,
#ifndef _AMIGA
"/usr/gnu/include",
"/usr/local/include",
"/usr/include",
#endif
0
};
/* List of directories to search for include files in */
static const char **include_directories;
/* Maximum length of an element of the above. */
static size_t max_incl_len;
/* The filename and pointer to line number of the
makefile currently being read in. */
const floc *reading_file = 0;
/* The chain of files read by read_all_makefiles. */
static struct goaldep *read_files = 0;
static struct goaldep *eval_makefile (const char *filename, unsigned short flags);
static void eval (struct ebuffer *buffer, int flags);
static long readline (struct ebuffer *ebuf);
static void do_undefine (char *name, enum variable_origin origin,
struct ebuffer *ebuf);
static struct variable *do_define (char *name, enum variable_origin origin,
struct ebuffer *ebuf);
static int conditional_line (char *line, size_t len, const floc *flocp);
static void record_files (struct nameseq *filenames, int are_also_makes,
const char *pattern,
const char *pattern_percent, char *depstr,
unsigned int cmds_started, char *commands,
size_t commands_idx, int two_colon,
char prefix, const floc *flocp);
static void record_target_var (struct nameseq *filenames, char *defn,
enum variable_origin origin,
struct vmodifiers *vmod,
const floc *flocp);
static enum make_word_type get_next_mword (char *buffer,
char **startp, size_t *length);
static void remove_comments (char *line);
static char *find_map_unquote (char *string, int map);
static char *find_char_unquote (char *string, int stop);
static char *unescape_char (char *string, int c);
/* Compare a word, both length and contents.
P must point to the word to be tested, and WLEN must be the length.
*/
#define word1eq(s) (wlen == CSTRLEN (s) && strneq (s, p, CSTRLEN (s)))
/* Read in all the makefiles and return a chain of targets to rebuild. */
struct goaldep *
read_all_makefiles (const char **makefiles)
{
unsigned int num_makefiles = 0;
/* Create *_LIST variables, to hold the makefiles, targets, and variables
we will be reading. */
define_variable_cname ("MAKEFILE_LIST", "", o_file, 0);
DB (DB_BASIC, (_("Reading makefiles...\n")));
/* If there's a non-null variable MAKEFILES, its value is a list of
files to read first thing. But don't let it prevent reading the
default makefiles and don't let the default goal come from there. */
{
char *value;
char *name, *p;
size_t length;
{
/* Turn off --warn-undefined-variables while we expand MAKEFILES. */
int save = warn_undefined_variables_flag;
warn_undefined_variables_flag = 0;
value = allocated_variable_expand ("$(MAKEFILES)");
warn_undefined_variables_flag = save;
}
/* Set NAME to the start of next token and LENGTH to its length.
MAKEFILES is updated for finding remaining tokens. */
p = value;
while ((name = find_next_token ((const char **)&p, &length)) != 0)
{
if (*p != '\0')
*p++ = '\0';
eval_makefile (strcache_add (name), RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
}
free (value);
}
/* Read makefiles specified with -f switches. */
if (makefiles != 0)
while (*makefiles != 0)
{
struct goaldep *d = eval_makefile (*makefiles, 0);
if (errno)
perror_with_name ("", *makefiles);
/* Reuse the storage allocated for the read_file. */
*makefiles = dep_name (d);
++num_makefiles;
++makefiles;
}
/* If there were no -f switches, try the default names. */
if (num_makefiles == 0)
{
static const char *default_makefiles[] =
#ifdef VMS
/* all lower case since readdir() (the vms version) 'lowercasifies' */
/* TODO: Above is not always true, this needs more work */
{ "makefile.vms", "gnumakefile", "makefile", 0 };
#else
#ifdef _AMIGA
{ "GNUmakefile", "Makefile", "SMakefile", 0 };
#else /* !Amiga && !VMS */
#ifdef WINDOWS32
{ "GNUmakefile", "makefile", "Makefile", "makefile.mak", 0 };
#else /* !Amiga && !VMS && !WINDOWS32 */
{ "GNUmakefile", "makefile", "Makefile", 0 };
#endif /* !Amiga && !VMS && !WINDOWS32 */
#endif /* AMIGA */
#endif /* VMS */
const char **p = default_makefiles;
while (*p != 0 && !file_exists_p (*p))
++p;
if (*p != 0)
{
eval_makefile (*p, 0);
if (errno)
perror_with_name ("", *p);
}
else
{
/* No default makefile was found. Add the default makefiles to the
'read_files' chain so they will be updated if possible. */
struct goaldep *tail = read_files;
/* Add them to the tail, after any MAKEFILES variable makefiles. */
while (tail != 0 && tail->next != 0)
tail = tail->next;
for (p = default_makefiles; *p != 0; ++p)
{
struct goaldep *d = alloc_goaldep ();
d->file = enter_file (strcache_add (*p));
/* Tell update_goal_chain to bail out as soon as this file is
made, and main not to die if we can't make this file. */
d->flags = RM_DONTCARE;
if (tail == 0)
read_files = d;
else
tail->next = d;
tail = d;
}
if (tail != 0)
tail->next = 0;
}
}
return read_files;
}
/* Install a new conditional and return the previous one. */
static struct conditionals *
install_conditionals (struct conditionals *new)
{
struct conditionals *save = conditionals;
memset (new, '\0', sizeof (*new));
conditionals = new;
return save;
}
/* Free the current conditionals and reinstate a saved one. */
static void
restore_conditionals (struct conditionals *saved)
{
/* Free any space allocated by conditional_line. */
free (conditionals->ignoring);
free (conditionals->seen_else);
/* Restore state. */
conditionals = saved;
}
static struct goaldep *
eval_makefile (const char *filename, unsigned short flags)
{
struct goaldep *deps;
struct ebuffer ebuf;
const floc *curfile;
char *expanded = 0;
/* Create a new goaldep entry. */
deps = alloc_goaldep ();
deps->next = read_files;
read_files = deps;
ebuf.floc.filenm = filename; /* Use the original file name. */
ebuf.floc.lineno = 1;
ebuf.floc.offset = 0;
if (ISDB (DB_VERBOSE))
{
printf (_("Reading makefile '%s'"), filename);
if (flags & RM_NO_DEFAULT_GOAL)
printf (_(" (no default goal)"));
if (flags & RM_INCLUDED)
printf (_(" (search path)"));
if (flags & RM_DONTCARE)
printf (_(" (don't care)"));
if (flags & RM_NO_TILDE)
printf (_(" (no ~ expansion)"));
puts ("...");
}
/* First, get a stream to read. */
/* Expand ~ in FILENAME unless it came from 'include',
in which case it was already done. */
if (!(flags & RM_NO_TILDE) && filename[0] == '~')
{
expanded = tilde_expand (filename);
if (expanded != 0)
filename = expanded;
}
errno = 0;
ENULLLOOP (ebuf.fp, fopen (filename, "r"));
deps->error = errno;
/* Check for unrecoverable errors: out of mem or FILE slots. */
{
if (0 ||
#ifdef EMFILE
deps->error == EMFILE ||
#endif
#ifdef ENFILE
deps->error == ENFILE ||
#endif
deps->error == ENOMEM)
{
const char *err = strerror (deps->error);
OS (fatal, reading_file, "%s", err);
}
}
/* If the makefile wasn't found and it's either a makefile from
the 'MAKEFILES' variable or an included makefile,
search the included makefile search path for this makefile. */
if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
{
unsigned int i;
for (i = 0; include_directories[i] != 0; ++i)
{
const char *included = concat (3, include_directories[i],
"/", filename);
ebuf.fp = fopen (included, "r");
if (ebuf.fp)
{
filename = included;
break;
}
}
}
/* Enter the final name for this makefile as a goaldep. */
filename = strcache_add (filename);
deps->file = lookup_file (filename);
if (deps->file == 0)
deps->file = enter_file (filename);
filename = deps->file->name;
deps->flags = flags;
free (expanded);
if (ebuf.fp == 0)
{
/* The makefile can't be read at all, give up entirely.
If we did some searching errno has the error from the last attempt,
rather from FILENAME itself: recover the more accurate one. */
errno = deps->error;
deps->file->last_mtime = NONEXISTENT_MTIME;
return deps;
}
/* Success; clear errno. */
deps->error = 0;
/* Avoid leaking the makefile to children. */
fd_noinherit (fileno (ebuf.fp));
/* Add this makefile to the list. */
do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
f_append_value, 0);
/* Evaluate the makefile */
ebuf.size = 200;
ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
curfile = reading_file;
reading_file = &ebuf.floc;
eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
reading_file = curfile;
fclose (ebuf.fp);
free (ebuf.bufstart);
/* [jart] breaks gcc11 (also wat) */
void *volatile wat = alloca (0);
errno = 0;
return deps;
}
void
eval_buffer (char *buffer, const floc *flocp)
{
struct ebuffer ebuf;
struct conditionals *saved;
struct conditionals new;
const floc *curfile;
/* Evaluate the buffer */
ebuf.size = strlen (buffer);
ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
ebuf.fp = NULL;
if (flocp)
ebuf.floc = *flocp;
else if (reading_file)
ebuf.floc = *reading_file;
else
{
ebuf.floc.filenm = NULL;
ebuf.floc.lineno = 1;
ebuf.floc.offset = 0;
}
curfile = reading_file;
reading_file = &ebuf.floc;
saved = install_conditionals (&new);
eval (&ebuf, 1);
restore_conditionals (saved);
reading_file = curfile;
/* [jart] breaks gcc11 (also wat) */
void *volatile wat = alloca (0);
}
/* Check LINE to see if it's a variable assignment or undefine.
It might use one of the modifiers "export", "override", "private", or it
might be one of the conditional tokens like "ifdef", "include", etc.
If it's not a variable assignment or undefine, VMOD.V_ASSIGN is 0.
Returns LINE.
Returns a pointer to the first non-modifier character, and sets VMOD
based on the modifiers found if any, plus V_ASSIGN is 1.
*/
static char *
parse_var_assignment (const char *line, struct vmodifiers *vmod)
{
const char *p;
memset (vmod, '\0', sizeof (*vmod));
/* Find the start of the next token. If there isn't one we're done. */
NEXT_TOKEN (line);
if (*line == '\0')
return (char *) line;
p = line;
while (1)
{
size_t wlen;
const char *p2;
struct variable v;
p2 = parse_variable_definition (p, &v);
/* If this is a variable assignment, we're done. */
if (p2)
break;
/* It's not a variable; see if it's a modifier. */
p2 = end_of_token (p);
wlen = p2 - p;
if (word1eq ("export"))
vmod->export_v = 1;
else if (word1eq ("override"))
vmod->override_v = 1;
else if (word1eq ("private"))
vmod->private_v = 1;
else if (word1eq ("define"))
{
/* We can't have modifiers after 'define' */
vmod->define_v = 1;
p = next_token (p2);
break;
}
else if (word1eq ("undefine"))
{
/* We can't have modifiers after 'undefine' */
vmod->undefine_v = 1;
p = next_token (p2);
break;
}
else
/* Not a variable or modifier: this is not a variable assignment. */
return (char *) line;
/* It was a modifier. Try the next word. */
p = next_token (p2);
if (*p == '\0')
return (char *) line;
}
/* Found a variable assignment or undefine. */
vmod->assign_v = 1;
return (char *)p;
}
/* Read file FILENAME as a makefile and add its contents to the data base.
SET_DEFAULT is true if we are allowed to set the default goal. */
static void
eval (struct ebuffer *ebuf, int set_default)
{
char *collapsed = 0;
size_t collapsed_length = 0;
size_t commands_len = 200;
char *commands;
size_t commands_idx = 0;
unsigned int cmds_started, tgts_started;
int ignoring = 0, in_ignored_define = 0;
int no_targets = 0; /* Set when reading a rule without targets. */
int also_make_targets = 0; /* Set when reading grouped targets. */
struct nameseq *filenames = 0;
char *depstr = 0;
long nlines = 0;
int two_colon = 0;
char prefix = cmd_prefix;
const char *pattern = 0;
const char *pattern_percent;
floc *fstart;
floc fi;
#define record_waiting_files() \
do \
{ \
if (filenames != 0) \
{ \
fi.lineno = tgts_started; \
fi.offset = 0; \
record_files (filenames, also_make_targets, pattern, \
pattern_percent, depstr, \
cmds_started, commands, commands_idx, two_colon, \
prefix, &fi); \
filenames = 0; \
} \
commands_idx = 0; \
no_targets = 0; \
pattern = 0; \
also_make_targets = 0; \
} while (0)
pattern_percent = 0;
cmds_started = tgts_started = 1;
fstart = &ebuf->floc;
fi.filenm = ebuf->floc.filenm;
/* Loop over lines in the file.
The strategy is to accumulate target names in FILENAMES, dependencies
in DEPS and commands in COMMANDS. These are used to define a rule
when the start of the next rule (or eof) is encountered.
When you see a "continue" in the loop below, that means we are moving on
to the next line. If you see record_waiting_files(), then the statement
we are parsing also finishes the previous rule. */
commands = xmalloc (200);
while (1)
{
size_t linelen;
char *line;
size_t wlen;
char *p;
char *p2;
struct vmodifiers vmod;
/* At the top of this loop, we are starting a brand new line. */
/* Grab the next line to be evaluated */
ebuf->floc.lineno += nlines;
nlines = readline (ebuf);
/* If there is nothing left to eval, we're done. */
if (nlines < 0)
break;
line = ebuf->buffer;
/* If this is the first line, check for a UTF-8 BOM and skip it. */
if (ebuf->floc.lineno == 1)
{
unsigned char *ul = (unsigned char *) line;
if (ul[0] == 0xEF && ul[1] == 0xBB && ul[2] == 0xBF)
{
line += 3;
if (ISDB(DB_BASIC))
{
if (ebuf->floc.filenm)
printf (_("Skipping UTF-8 BOM in makefile '%s'\n"),
ebuf->floc.filenm);
else
printf (_("Skipping UTF-8 BOM in makefile buffer\n"));
}
}
}
/* If this line is empty, skip it. */
if (line[0] == '\0')
continue;
linelen = strlen (line);
/* Check for a shell command line first.
If it is not one, we can stop treating cmd_prefix specially. */
if (line[0] == cmd_prefix)
{
if (no_targets)
/* Ignore the commands in a rule with no targets. */
continue;
/* If there is no preceding rule line, don't treat this line
as a command, even though it begins with a recipe prefix.
SunOS 4 make appears to behave this way. */
if (filenames != 0)
{
if (ignoring)
/* Yep, this is a shell command, and we don't care. */
continue;
if (commands_idx == 0)
cmds_started = ebuf->floc.lineno;
/* Append this command line to the line being accumulated.
Skip the initial command prefix character. */
if (linelen + commands_idx > commands_len)
{
commands_len = (linelen + commands_idx) * 2;
commands = xrealloc (commands, commands_len);
}
memcpy (&commands[commands_idx], line + 1, linelen - 1);
commands_idx += linelen - 1;
commands[commands_idx++] = '\n';
continue;
}
}
/* This line is not a shell command line. Don't worry about whitespace.
Get more space if we need it; we don't need to preserve the current
contents of the buffer. */
if (collapsed_length < linelen+1)
{
collapsed_length = linelen+1;
free (collapsed);
/* Don't need xrealloc: we don't need to preserve the content. */
collapsed = xmalloc (collapsed_length);
}
strcpy (collapsed, line);
/* Collapse continuation lines. */
collapse_continuations (collapsed);
remove_comments (collapsed);
/* Get rid if starting space (including formfeed, vtab, etc.) */
p = collapsed;
NEXT_TOKEN (p);
/* See if this is a variable assignment. We need to do this early, to
allow variables with names like 'ifdef', 'export', 'private', etc. */
p = parse_var_assignment (p, &vmod);
if (vmod.assign_v)
{
struct variable *v;
enum variable_origin origin = vmod.override_v ? o_override : o_file;
/* If we're ignoring then we're done now. */
if (ignoring)
{
if (vmod.define_v)
in_ignored_define = 1;
continue;
}
/* Variable assignment ends the previous rule. */
record_waiting_files ();
if (vmod.undefine_v)
{
do_undefine (p, origin, ebuf);
continue;
}
else if (vmod.define_v)
v = do_define (p, origin, ebuf);
else
v = try_variable_definition (fstart, p, origin, 0);
assert (v != NULL);
if (vmod.export_v)
v->export = v_export;
if (vmod.private_v)
v->private_var = 1;
/* This line has been dealt with. */
continue;
}
/* If this line is completely empty, ignore it. */
if (*p == '\0')
continue;
p2 = end_of_token (p);
wlen = p2 - p;
NEXT_TOKEN (p2);
/* If we're in an ignored define, skip this line (but maybe get out). */
if (in_ignored_define)
{
/* See if this is an endef line (plus optional comment). */
if (word1eq ("endef") && STOP_SET (*p2, MAP_COMMENT|MAP_NUL))
in_ignored_define = 0;
continue;
}
/* Check for conditional state changes. */
{
int i = conditional_line (p, wlen, fstart);
if (i != -2)
{
if (i == -1)
O (fatal, fstart, _("invalid syntax in conditional"));
ignoring = i;
continue;
}
}
/* Nothing to see here... move along. */
if (ignoring)
continue;
/* Manage the "export" keyword used outside of variable assignment
as well as "unexport". */
if (word1eq ("export") || word1eq ("unexport"))
{
int exporting = *p == 'u' ? 0 : 1;
/* Export/unexport ends the previous rule. */
record_waiting_files ();
/* (un)export by itself causes everything to be (un)exported. */
if (*p2 == '\0')
export_all_variables = exporting;
else
{
size_t l;
const char *cp;
char *ap;
/* Expand the line so we can use indirect and constructed
variable names in an (un)export command. */
cp = ap = allocated_variable_expand (p2);
for (p = find_next_token (&cp, &l); p != 0;
p = find_next_token (&cp, &l))
{
struct variable *v = lookup_variable (p, l);
if (v == 0)
v = define_variable_global (p, l, "", o_file, 0, fstart);
v->export = exporting ? v_export : v_noexport;
}
free (ap);
}
continue;
}
/* Handle the special syntax for vpath. */
if (word1eq ("vpath"))
{
const char *cp;
char *vpat;
size_t l;
/* vpath ends the previous rule. */
record_waiting_files ();
cp = variable_expand (p2);
p = find_next_token (&cp, &l);
if (p != 0)
{
vpat = xstrndup (p, l);
p = find_next_token (&cp, &l);
/* No searchpath means remove all previous
selective VPATH's with the same pattern. */
}
else
/* No pattern means remove all previous selective VPATH's. */
vpat = 0;
construct_vpath_list (vpat, p);
free (vpat);
continue;
}
/* Handle include and variants. */
if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
{
/* We have found an 'include' line specifying a nested
makefile to be read at this point. */
struct conditionals *save;
struct conditionals new_conditionals;
struct nameseq *files;
/* "-include" (vs "include") says no error if the file does not
exist. "sinclude" is an alias for this from SGI. */
int noerror = (p[0] != 'i');
/* Include ends the previous rule. */
record_waiting_files ();
p = allocated_variable_expand (p2);
/* If no filenames, it's a no-op. */
if (*p == '\0')
{
free (p);
continue;
}
/* Parse the list of file names. Don't expand archive references! */
p2 = p;
files = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_NUL, NULL,
PARSEFS_NOAR);
free (p);
/* Save the state of conditionals and start
the included makefile with a clean slate. */
save = install_conditionals (&new_conditionals);
/* Record the rules that are waiting so they will determine
the default goal before those in the included makefile. */
record_waiting_files ();
/* Read each included makefile. */
while (files != 0)
{
struct nameseq *next = files->next;
unsigned short flags = (RM_INCLUDED | RM_NO_TILDE
| (noerror ? RM_DONTCARE : 0)
| (set_default ? 0 : RM_NO_DEFAULT_GOAL));
struct goaldep *d = eval_makefile (files->name, flags);
if (errno)
d->floc = *fstart;
free_ns (files);
files = next;
}
/* Restore conditional state. */
restore_conditionals (save);
continue;
}
/* Handle the load operations. */
if (word1eq ("load") || word1eq ("-load"))
{
/* A 'load' line specifies a dynamic object to load. */
struct nameseq *files;
int noerror = (p[0] == '-');
/* Load ends the previous rule. */
record_waiting_files ();
p = allocated_variable_expand (p2);
/* If no filenames, it's a no-op. */
if (*p == '\0')
{
free (p);
continue;
}
/* Parse the list of file names.
Don't expand archive references or strip "./" */
p2 = p;
files = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_NUL, NULL,
PARSEFS_NOAR);
free (p);
/* Load each file. */
while (files != 0)
{
struct nameseq *next = files->next;
const char *name = files->name;
struct goaldep *deps;
int r;
/* Load the file. 0 means failure. */
r = load_file (&ebuf->floc, &name, noerror);
if (! r && ! noerror)
OS (fatal, &ebuf->floc, _("%s: failed to load"), name);
free_ns (files);
files = next;
/* Return of -1 means a special load: don't rebuild it. */
if (r == -1)
continue;
/* It succeeded, so add it to the list "to be rebuilt". */
deps = alloc_goaldep ();
deps->next = read_files;
read_files = deps;
deps->file = lookup_file (name);
if (deps->file == 0)
deps->file = enter_file (name);
deps->file->loaded = 1;
}
continue;
}
/* This line starts with a tab but was not caught above because there
was no preceding target, and the line might have been usable as a
variable definition. But now we know it is definitely lossage. */
if (line[0] == cmd_prefix)
O (fatal, fstart, _("recipe commences before first target"));
/* This line describes some target files. This is complicated by
the existence of target-specific variables, because we can't
expand the entire line until we know if we have one or not. So
we expand the line word by word until we find the first ':',
then check to see if it's a target-specific variable.
In this algorithm, 'lb_next' will point to the beginning of the
unexpanded parts of the input buffer, while 'p2' points to the
parts of the expanded buffer we haven't searched yet. */
{
enum make_word_type wtype;
char *cmdleft, *semip, *lb_next;
size_t plen = 0;
char *colonp;
const char *end, *beg; /* Helpers for whitespace stripping. */
/* Record the previous rule. */
record_waiting_files ();
tgts_started = fstart->lineno;
/* Search the line for an unquoted ; that is not after an
unquoted #. */
cmdleft = find_map_unquote (line, MAP_SEMI|MAP_COMMENT|MAP_VARIABLE);
if (cmdleft != 0 && *cmdleft == '#')
{
/* We found a comment before a semicolon. */
*cmdleft = '\0';
cmdleft = 0;
}
else if (cmdleft != 0)
/* Found one. Cut the line short there before expanding it. */
*(cmdleft++) = '\0';
semip = cmdleft;
collapse_continuations (line);
/* We can't expand the entire line, since if it's a per-target
variable we don't want to expand it. So, walk from the
beginning, expanding as we go, and looking for "interesting"
chars. The first word is always expandable. */
wtype = get_next_mword (line, &lb_next, &wlen);
switch (wtype)
{
case w_eol:
if (cmdleft != 0)
O (fatal, fstart, _("missing rule before recipe"));
/* This line contained something but turned out to be nothing
but whitespace (a comment?). */
continue;
case w_colon:
case w_dcolon:
case w_ampcolon:
case w_ampdcolon:
/* We accept and ignore rules without targets for
compatibility with SunOS 4 make. */
no_targets = 1;
continue;
default:
break;
}
p2 = variable_expand_string (NULL, lb_next, wlen);
while (1)
{
lb_next += wlen;
if (cmdleft == 0)
{
/* Look for a semicolon in the expanded line. */
cmdleft = find_char_unquote (p2, ';');
if (cmdleft != 0)
{
size_t p2_off = p2 - variable_buffer;
size_t cmd_off = cmdleft - variable_buffer;
char *pend = p2 + strlen (p2);
/* Append any remnants of lb, then cut the line short
at the semicolon. */
*cmdleft = '\0';
/* One school of thought says that you shouldn't expand
here, but merely copy, since now you're beyond a ";"
and into a command script. However, the old parser
expanded the whole line, so we continue that for
backwards-compatibility. Also, it wouldn't be
entirely consistent, since we do an unconditional
expand below once we know we don't have a
target-specific variable. */
variable_expand_string (pend, lb_next, SIZE_MAX);
lb_next += strlen (lb_next);
p2 = variable_buffer + p2_off;
cmdleft = variable_buffer + cmd_off + 1;
}
}
colonp = find_char_unquote (p2, ':');
#ifdef HAVE_DOS_PATHS
if (colonp > p2)
/* The drive spec brain-damage strikes again...
Note that the only separators of targets in this context are
whitespace and a left paren. If others are possible, add them
to the string in the call to strchr. */
while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
isalpha ((unsigned char) colonp[-1]) &&
(colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
colonp = find_char_unquote (colonp + 1, ':');
#endif
if (colonp)
{
/* If the previous character is '&', back up before '&:' */
if (colonp > p2 && colonp[-1] == '&')
--colonp;
break;
}
wtype = get_next_mword (lb_next, &lb_next, &wlen);
if (wtype == w_eol)
break;
p2 += strlen (p2);
*(p2++) = ' ';
p2 = variable_expand_string (p2, lb_next, wlen);
/* We don't need to worry about cmdleft here, because if it was
found in the variable_buffer the entire buffer has already
been expanded... we'll never get here. */
}
p2 = next_token (variable_buffer);
/* If the word we're looking at is EOL, see if there's _anything_
on the line. If not, a variable expanded to nothing, so ignore
it. If so, we can't parse this line so punt. */
if (wtype == w_eol)
{
if (*p2 == '\0')
continue;
/* There's no need to be ivory-tower about this: check for
one of the most common bugs found in makefiles... */
if (cmd_prefix == '\t' && strneq (line, " ", 8))
O (fatal, fstart, _("missing separator (did you mean TAB instead of 8 spaces?)"));
else
O (fatal, fstart, _("missing separator"));
}
{
char save = *colonp;
/* If we have &:, it specifies that the targets are understood to be
updated/created together by a single invocation of the recipe. */
if (save == '&')
also_make_targets = 1;
/* Make the colon the end-of-string so we know where to stop
looking for targets. Start there again once we're done. */
*colonp = '\0';
filenames = PARSE_SIMPLE_SEQ (&p2, struct nameseq);
*colonp = save;
p2 = colonp + (save == '&');
}
if (!filenames)
{
/* We accept and ignore rules without targets for
compatibility with SunOS 4 make. */
no_targets = 1;
continue;
}
/* This should never be possible; we handled it above. */
assert (*p2 != '\0');
++p2;
/* Is this a one-colon or two-colon entry? */
two_colon = *p2 == ':';
if (two_colon)
p2++;
/* Test to see if it's a target-specific variable. Copy the rest
of the buffer over, possibly temporarily (we'll expand it later
if it's not a target-specific variable). PLEN saves the length
of the unparsed section of p2, for later. */
if (*lb_next != '\0')
{
size_t l = p2 - variable_buffer;
plen = strlen (p2);
variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
p2 = variable_buffer + l;
}
p2 = parse_var_assignment (p2, &vmod);
if (vmod.assign_v)
{
/* If there was a semicolon found, add it back, plus anything
after it. */
if (semip)
{
size_t l = p2 - variable_buffer;
*(--semip) = ';';
collapse_continuations (semip);
variable_buffer_output (p2 + strlen (p2),
semip, strlen (semip)+1);
p2 = variable_buffer + l;
}
record_target_var (filenames, p2,
vmod.override_v ? o_override : o_file,
&vmod, fstart);
filenames = 0;
continue;
}
/* This is a normal target, _not_ a target-specific variable.
Unquote any = in the dependency list. */
find_char_unquote (lb_next, '=');
/* Remember the command prefix for this target. */
prefix = cmd_prefix;
/* We have some targets, so don't ignore the following commands. */
no_targets = 0;
/* Expand the dependencies, etc. */
if (*lb_next != '\0')
{
size_t l = p2 - variable_buffer;
variable_expand_string (p2 + plen, lb_next, SIZE_MAX);
p2 = variable_buffer + l;
/* Look for a semicolon in the expanded line. */
if (cmdleft == 0)
{
cmdleft = find_char_unquote (p2, ';');
if (cmdleft != 0)
*(cmdleft++) = '\0';
}
}
/* Is this a static pattern rule: 'target: %targ: %dep; ...'? */
p = strchr (p2, ':');
while (p != 0 && p[-1] == '\\')
{
char *q = &p[-1];
int backslash = 0;
while (*q-- == '\\')
backslash = !backslash;
if (backslash)
p = strchr (p + 1, ':');
else
break;
}
#ifdef _AMIGA
/* Here, the situation is quite complicated. Let's have a look
at a couple of targets:
install: dev:make
dev:make: make
dev:make:: xyz
The rule is that it's only a target, if there are TWO :'s
OR a space around the :.
*/
if (p && !(ISSPACE (p[1]) || !p[1] || ISSPACE (p[-1])))
p = 0;
#endif
#ifdef HAVE_DOS_PATHS
{
int check_again;
do {
check_again = 0;
/* For DOS-style paths, skip a "C:\..." or a "C:/..." */
if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
isalpha ((unsigned char)p[-1]) &&
(p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
p = strchr (p + 1, ':');
check_again = 1;
}
} while (check_again);
}
#endif
if (p != 0)
{
struct nameseq *target;
target = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_COLON, NULL,
PARSEFS_NOGLOB);
++p2;
if (target == 0)
O (fatal, fstart, _("missing target pattern"));
else if (target->next != 0)
O (fatal, fstart, _("multiple target patterns"));
pattern_percent = find_percent_cached (&target->name);
pattern = target->name;
if (pattern_percent == 0)
O (fatal, fstart, _("target pattern contains no '%%'"));
free_ns (target);
}
else
pattern = 0;
/* Strip leading and trailing whitespaces. */
beg = p2;
end = beg + strlen (beg) - 1;
strip_whitespace (&beg, &end);
/* Put all the prerequisites here; they'll be parsed later. */
if (beg <= end && *beg != '\0')
depstr = xstrndup (beg, end - beg + 1);
else
depstr = 0;
commands_idx = 0;
if (cmdleft != 0)
{
/* Semicolon means rest of line is a command. */
size_t l = strlen (cmdleft);
cmds_started = fstart->lineno;
/* Add this command line to the buffer. */
if (l + 2 > commands_len)
{
commands_len = (l + 2) * 2;
commands = xrealloc (commands, commands_len);
}
memcpy (commands, cmdleft, l);
commands_idx += l;
commands[commands_idx++] = '\n';
}
/* Determine if this target should be made default. We used to do
this in record_files() but because of the delayed target recording
and because preprocessor directives are legal in target's commands
it is too late. Consider this fragment for example:
foo:
ifeq ($(.DEFAULT_GOAL),foo)
...
endif
Because the target is not recorded until after ifeq directive is
evaluated the .DEFAULT_GOAL does not contain foo yet as one
would expect. Because of this we have to move the logic here. */
if (set_default && default_goal_var->value[0] == '\0')
{
struct dep *d;
struct nameseq *t = filenames;
for (; t != 0; t = t->next)
{
int reject = 0;
const char *name = t->name;
/* We have nothing to do if this is an implicit rule. */
if (strchr (name, '%') != 0)
break;
/* See if this target's name does not start with a '.',
unless it contains a slash. */
if (*name == '.' && strchr (name, '/') == 0
#ifdef HAVE_DOS_PATHS
&& strchr (name, '\\') == 0
#endif
)
continue;
/* If this file is a suffix, don't let it be
the default goal file. */
for (d = suffix_file->deps; d != 0; d = d->next)
{
struct dep *d2;
if (*dep_name (d) != '.' && streq (name, dep_name (d)))
{
reject = 1;
break;
}
for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
{
size_t l = strlen (dep_name (d2));
if (!strneq (name, dep_name (d2), l))
continue;
if (streq (name + l, dep_name (d)))
{
reject = 1;
break;
}
}
if (reject)
break;
}
if (!reject)
{
define_variable_global (".DEFAULT_GOAL", 13, t->name,
o_file, 0, NILF);
break;
}
}
}
}
}
#undef word1eq
if (conditionals->if_cmds)
O (fatal, fstart, _("missing 'endif'"));
/* At eof, record the last rule. */
record_waiting_files ();
free (collapsed);
free (commands);
}
/* Remove comments from LINE.
This will also remove backslashes that escape things.
It ignores comment characters that appear inside variable references. */
static void
remove_comments (char *line)
{
char *comment;
comment = find_map_unquote (line, MAP_COMMENT|MAP_VARIABLE);
if (comment != 0)
/* Cut off the line at the #. */
*comment = '\0';
}
/* Execute a 'undefine' directive.
The undefine line has already been read, and NAME is the name of
the variable to be undefined. */
static void
do_undefine (char *name, enum variable_origin origin, struct ebuffer *ebuf)
{
char *p, *var;
/* Expand the variable name and find the beginning (NAME) and end. */
var = allocated_variable_expand (name);
name = next_token (var);
if (*name == '\0')
O (fatal, &ebuf->floc, _("empty variable name"));
p = name + strlen (name) - 1;
while (p > name && ISBLANK (*p))
--p;
p[1] = '\0';
undefine_variable_global (name, p - name + 1, origin);
free (var);
}
/* Execute a 'define' directive.
The first line has already been read, and NAME is the name of
the variable to be defined. The following lines remain to be read. */
static struct variable *
do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
{
struct variable *v;
struct variable var;
floc defstart;
int nlevels = 1;
size_t length = 100;
char *definition = xmalloc (length);
size_t idx = 0;
char *p, *n;
defstart = ebuf->floc;
p = parse_variable_definition (name, &var);
if (p == NULL)
/* No assignment token, so assume recursive. */
var.flavor = f_recursive;
else
{
if (var.value[0] != '\0')
O (error, &defstart, _("extraneous text after 'define' directive"));
/* Chop the string before the assignment token to get the name. */
var.name[var.length] = '\0';
}
/* Expand the variable name and find the beginning (NAME) and end. */
n = allocated_variable_expand (name);
name = next_token (n);
if (name[0] == '\0')
O (fatal, &defstart, _("empty variable name"));
p = name + strlen (name) - 1;
while (p > name && ISBLANK (*p))
--p;
p[1] = '\0';
/* Now read the value of the variable. */
while (1)
{
size_t len;
char *line;
long nlines = readline (ebuf);
/* If there is nothing left to be eval'd, there's no 'endef'!! */
if (nlines < 0)
O (fatal, &defstart, _("missing 'endef', unterminated 'define'"));
ebuf->floc.lineno += nlines;
line = ebuf->buffer;
collapse_continuations (line);
/* If the line doesn't begin with a tab, test to see if it introduces
another define, or ends one. Stop if we find an 'endef' */
if (line[0] != cmd_prefix)
{
p = next_token (line);
len = strlen (p);
/* If this is another 'define', increment the level count. */
if ((len == 6 || (len > 6 && ISBLANK (p[6])))
&& strneq (p, "define", 6))
++nlevels;
/* If this is an 'endef', decrement the count. If it's now 0,
we've found the last one. */
else if ((len == 5 || (len > 5 && ISBLANK (p[5])))
&& strneq (p, "endef", 5))
{
p += 5;
remove_comments (p);
if (*(next_token (p)) != '\0')
O (error, &ebuf->floc,
_("extraneous text after 'endef' directive"));
if (--nlevels == 0)
break;
}
}
/* Add this line to the variable definition. */
len = strlen (line);
if (idx + len + 1 > length)
{
length = (idx + len) * 2;
definition = xrealloc (definition, length + 1);
}
memcpy (&definition[idx], line, len);
idx += len;
/* Separate lines with a newline. */
definition[idx++] = '\n';
}
/* We've got what we need; define the variable. */
if (idx == 0)
definition[0] = '\0';
else
definition[idx - 1] = '\0';
v = do_variable_definition (&defstart, name,
definition, origin, var.flavor, 0);
free (definition);
free (n);
return (v);
}
/* Interpret conditional commands "ifdef", "ifndef", "ifeq",
"ifneq", "else" and "endif".
LINE is the input line, with the command as its first word.
FILENAME and LINENO are the filename and line number in the
current makefile. They are used for error messages.
Value is -2 if the line is not a conditional at all,
-1 if the line is an invalid conditional,
0 if following text should be interpreted,
1 if following text should be ignored. */
static int
conditional_line (char *line, size_t len, const floc *flocp)
{
const char *cmdname;
enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
unsigned int i;
unsigned int o;
/* Compare a word, both length and contents. */
#define word1eq(s) (len == CSTRLEN (s) && strneq (s, line, CSTRLEN (s)))
#define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
/* Make sure this line is a conditional. */
chkword ("ifdef", c_ifdef)
else chkword ("ifndef", c_ifndef)
else chkword ("ifeq", c_ifeq)
else chkword ("ifneq", c_ifneq)
else chkword ("else", c_else)
else chkword ("endif", c_endif)
else
return -2;
/* Found one: skip past it and any whitespace after it. */
line += len;
NEXT_TOKEN (line);
#define EXTRATEXT() OS (error, flocp, _("extraneous text after '%s' directive"), cmdname)
#define EXTRACMD() OS (fatal, flocp, _("extraneous '%s'"), cmdname)
/* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
if (cmdtype == c_endif)
{
if (*line != '\0')
EXTRATEXT ();
if (!conditionals->if_cmds)
EXTRACMD ();
--conditionals->if_cmds;
goto DONE;
}
/* An 'else' statement can either be simple, or it can have another
conditional after it. */
if (cmdtype == c_else)
{
const char *p;
if (!conditionals->if_cmds)
EXTRACMD ();
o = conditionals->if_cmds - 1;
if (conditionals->seen_else[o])
O (fatal, flocp, _("only one 'else' per conditional"));
/* Change the state of ignorance. */
switch (conditionals->ignoring[o])
{
case 0:
/* We've just been interpreting. Never do it again. */
conditionals->ignoring[o] = 2;
break;
case 1:
/* We've never interpreted yet. Maybe this time! */
conditionals->ignoring[o] = 0;
break;
}
/* It's a simple 'else'. */
if (*line == '\0')
{
conditionals->seen_else[o] = 1;
goto DONE;
}
/* The 'else' has extra text. That text must be another conditional
and cannot be an 'else' or 'endif'. */
/* Find the length of the next word. */
for (p = line+1; ! STOP_SET (*p, MAP_SPACE|MAP_NUL); ++p)
;
len = p - line;
/* If it's 'else' or 'endif' or an illegal conditional, fail. */
if (word1eq ("else") || word1eq ("endif")
|| conditional_line (line, len, flocp) < 0)
EXTRATEXT ();
else
{
/* conditional_line() created a new level of conditional.
Raise it back to this level. */
if (conditionals->ignoring[o] < 2)
conditionals->ignoring[o] = conditionals->ignoring[o+1];
--conditionals->if_cmds;
}
goto DONE;
}
if (conditionals->allocated == 0)
{
conditionals->allocated = 5;
conditionals->ignoring = xmalloc (conditionals->allocated);
conditionals->seen_else = xmalloc (conditionals->allocated);
}
o = conditionals->if_cmds++;
if (conditionals->if_cmds > conditionals->allocated)
{
conditionals->allocated += 5;
conditionals->ignoring = xrealloc (conditionals->ignoring,
conditionals->allocated);
conditionals->seen_else = xrealloc (conditionals->seen_else,
conditionals->allocated);
}
/* Record that we have seen an 'if...' but no 'else' so far. */
conditionals->seen_else[o] = 0;
/* Search through the stack to see if we're already ignoring. */
for (i = 0; i < o; ++i)
if (conditionals->ignoring[i])
{
/* We are already ignoring, so just push a level to match the next
"else" or "endif", and keep ignoring. We don't want to expand
variables in the condition. */
conditionals->ignoring[o] = 1;
return 1;
}
if (cmdtype == c_ifdef || cmdtype == c_ifndef)
{
size_t l;
char *var;
struct variable *v;
char *p;
/* Expand the thing we're looking up, so we can use indirect and
constructed variable names. */
var = allocated_variable_expand (line);
/* Make sure there's only one variable name to test. */
p = end_of_token (var);
l = p - var;
NEXT_TOKEN (p);
if (*p != '\0')
return -1;
var[l] = '\0';
v = lookup_variable (var, l);
conditionals->ignoring[o] =
((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
free (var);
}
else
{
/* "ifeq" or "ifneq". */
char *s1, *s2;
size_t l;
char termin = *line == '(' ? ',' : *line;
if (termin != ',' && termin != '"' && termin != '\'')
return -1;
s1 = ++line;
/* Find the end of the first string. */
if (termin == ',')
{
int count = 0;
for (; *line != '\0'; ++line)
if (*line == '(')
++count;
else if (*line == ')')
--count;
else if (*line == ',' && count <= 0)
break;
}
else
while (*line != '\0' && *line != termin)
++line;
if (*line == '\0')
return -1;
if (termin == ',')
{
/* Strip blanks after the first string. */
char *p = line++;
while (ISBLANK (p[-1]))
--p;
*p = '\0';
}
else
*line++ = '\0';
s2 = variable_expand (s1);
/* We must allocate a new copy of the expanded string because
variable_expand re-uses the same buffer. */
l = strlen (s2);
s1 = alloca (l + 1);
memcpy (s1, s2, l + 1);
if (termin != ',')
/* Find the start of the second string. */
NEXT_TOKEN (line);
termin = termin == ',' ? ')' : *line;
if (termin != ')' && termin != '"' && termin != '\'')
return -1;
/* Find the end of the second string. */
if (termin == ')')
{
int count = 0;
s2 = next_token (line);
for (line = s2; *line != '\0'; ++line)
{
if (*line == '(')
++count;
else if (*line == ')')
{
if (count <= 0)
break;
else
--count;
}
}
}
else
{
++line;
s2 = line;
while (*line != '\0' && *line != termin)
++line;
}
if (*line == '\0')
return -1;
*(line++) = '\0';
NEXT_TOKEN (line);
if (*line != '\0')
EXTRATEXT ();
s2 = variable_expand (s2);
conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
}
DONE:
/* Search through the stack to see if we're ignoring. */
for (i = 0; i < conditionals->if_cmds; ++i)
if (conditionals->ignoring[i])
return 1;
return 0;
}
/* Record target-specific variable values for files FILENAMES.
TWO_COLON is nonzero if a double colon was used.
The links of FILENAMES are freed, and so are any names in it
that are not incorporated into other data structures.
If the target is a pattern, add the variable to the pattern-specific
variable value list. */
static void
record_target_var (struct nameseq *filenames, char *defn,
enum variable_origin origin, struct vmodifiers *vmod,
const floc *flocp)
{
struct nameseq *nextf;
struct variable_set_list *global;
global = current_variable_set_list;
/* If the variable is an append version, store that but treat it as a
normal recursive variable. */
for (; filenames != 0; filenames = nextf)
{
struct variable *v;
const char *name = filenames->name;
const char *percent;
struct pattern_var *p;
nextf = filenames->next;
free_ns (filenames);
/* If it's a pattern target, then add it to the pattern-specific
variable list. */
percent = find_percent_cached (&name);
if (percent)
{
/* Get a reference for this pattern-specific variable struct. */
p = create_pattern_var (name, percent);
p->variable.fileinfo = *flocp;
/* I don't think this can fail since we already determined it was a
variable definition. */
v = assign_variable_definition (&p->variable, defn);
assert (v != 0);
v->origin = origin;
if (v->flavor == f_simple)
v->value = allocated_variable_expand (v->value);
else
v->value = xstrdup (v->value);
}
else
{
struct file *f;
/* Get a file reference for this file, and initialize it.
We don't want to just call enter_file() because that allocates a
new entry if the file is a double-colon, which we don't want in
this situation. */
f = lookup_file (name);
if (!f)
f = enter_file (strcache_add (name));
else if (f->double_colon)
f = f->double_colon;
initialize_file_variables (f, 1);
current_variable_set_list = f->variables;
v = try_variable_definition (flocp, defn, origin, 1);
if (!v)
O (fatal, flocp, _("Malformed target-specific variable definition"));
current_variable_set_list = global;
}
/* Set up the variable to be *-specific. */
v->per_target = 1;
v->private_var = vmod->private_v;
v->export = vmod->export_v ? v_export : v_default;
/* If it's not an override, check to see if there was a command-line
setting. If so, reset the value. */
if (v->origin != o_override)
{
struct variable *gv;
size_t len = strlen (v->name);
gv = lookup_variable (v->name, len);
if (gv && v != gv
&& (gv->origin == o_env_override || gv->origin == o_command))
{
free (v->value);
v->value = xstrdup (gv->value);
v->origin = gv->origin;
v->recursive = gv->recursive;
v->append = 0;
}
}
}
}
/* Record a description line for files FILENAMES,
with dependencies DEPS, commands to execute described
by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
TWO_COLON is nonzero if a double colon was used.
If not nil, PATTERN is the '%' pattern to make this
a static pattern rule, and PATTERN_PERCENT is a pointer
to the '%' within it.
The links of FILENAMES are freed, and so are any names in it
that are not incorporated into other data structures. */
static void
record_files (struct nameseq *filenames, int are_also_makes,
const char *pattern,
const char *pattern_percent, char *depstr,
unsigned int cmds_started, char *commands,
size_t commands_idx, int two_colon,
char prefix, const floc *flocp)
{
struct commands *cmds;
struct dep *deps;
struct dep *also_make = NULL;
const char *implicit_percent;
const char *name;
/* If we've already snapped deps, that means we're in an eval being
resolved after the makefiles have been read in. We can't add more rules
at this time, since they won't get snapped and we'll get core dumps.
See Savannah bug # 12124. */
if (snapped_deps)
O (fatal, flocp, _("prerequisites cannot be defined in recipes"));
/* Determine if this is a pattern rule or not. */
name = filenames->name;
implicit_percent = find_percent_cached (&name);
/* If there's a recipe, set up a struct for it. */
if (commands_idx > 0)
{
cmds = xmalloc (sizeof (struct commands));
cmds->fileinfo.filenm = flocp->filenm;
cmds->fileinfo.lineno = cmds_started;
cmds->fileinfo.offset = 0;
cmds->commands = xstrndup (commands, commands_idx);
cmds->command_lines = 0;
cmds->recipe_prefix = prefix;
}
else if (are_also_makes)
O (fatal, flocp, _("grouped targets must provide a recipe"));
else
cmds = NULL;
/* If there's a prereq string then parse it--unless it's eligible for 2nd
expansion: if so, snap_deps() will do it. */
if (depstr == 0)
deps = 0;
else
{
depstr = unescape_char (depstr, ':');
if (second_expansion && strchr (depstr, '$'))
{
deps = alloc_dep ();
deps->name = depstr;
deps->need_2nd_expansion = 1;
deps->staticpattern = pattern != 0;
}
else
{
deps = split_prereqs (depstr);
free (depstr);
/* We'll enter static pattern prereqs later when we have the stem.
We don't want to enter pattern rules at all so that we don't
think that they ought to exist (make manual "Implicit Rule Search
Algorithm", item 5c). */
if (! pattern && ! implicit_percent)
deps = enter_prereqs (deps, NULL);
}
}
/* For implicit rules, _all_ the targets must have a pattern. That means we
can test the first one to see if we're working with an implicit rule; if
so we handle it specially. */
if (implicit_percent)
{
struct nameseq *nextf;
const char **targets, **target_pats;
unsigned short c;
if (pattern != 0)
O (fatal, flocp, _("mixed implicit and static pattern rules"));
/* Count the targets to create an array of target names.
We already have the first one. */
nextf = filenames->next;
free_ns (filenames);
filenames = nextf;
for (c = 1; nextf; ++c, nextf = nextf->next)
;
targets = xmalloc (c * sizeof (const char *));
target_pats = xmalloc (c * sizeof (const char *));
targets[0] = name;
target_pats[0] = implicit_percent;
c = 1;
while (filenames)
{
name = filenames->name;
implicit_percent = find_percent_cached (&name);
if (implicit_percent == 0)
O (fatal, flocp, _("mixed implicit and normal rules"));
targets[c] = name;
target_pats[c] = implicit_percent;
++c;
nextf = filenames->next;
free_ns (filenames);
filenames = nextf;
}
create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
return;
}
/* Walk through each target and create it in the database.
We already set up the first target, above. */
while (1)
{
struct nameseq *nextf = filenames->next;
struct file *f;
struct dep *this = 0;
free_ns (filenames);
/* Check for special targets. Do it here instead of, say, snap_deps()
so that we can immediately use the value. */
if (!posix_pedantic && streq (name, ".POSIX"))
{
posix_pedantic = 1;
define_variable_cname (".SHELLFLAGS", "-ec", o_default, 0);
/* These default values are based on IEEE Std 1003.1-2008.
It requires '-O 1' for [CF]FLAGS, but GCC doesn't allow space
between -O and the number so omit it here. */
define_variable_cname ("ARFLAGS", "-rv", o_default, 0);
define_variable_cname ("CC", "c99", o_default, 0);
define_variable_cname ("CFLAGS", "-O1", o_default, 0);
define_variable_cname ("FC", "fort77", o_default, 0);
define_variable_cname ("FFLAGS", "-O1", o_default, 0);
define_variable_cname ("SCCSGETFLAGS", "-s", o_default, 0);
}
else if (!second_expansion && streq (name, ".SECONDEXPANSION"))
second_expansion = 1;
#if !defined (__MSDOS__) && !defined (__EMX__)
else if (!one_shell && streq (name, ".ONESHELL"))
one_shell = 1;
#endif
/* If this is a static pattern rule:
'targets: target%pattern: prereq%pattern; recipe',
make sure the pattern matches this target name. */
if (pattern && !pattern_matches (pattern, pattern_percent, name))
OS (error, flocp,
_("target '%s' doesn't match the target pattern"), name);
else if (deps)
/* If there are multiple targets, copy the chain DEPS for all but the
last one. It is not safe for the same deps to go in more than one
place in the database. */
this = nextf != 0 ? copy_dep_chain (deps) : deps;
/* Find or create an entry in the file database for this target. */
if (!two_colon)
{
/* Single-colon. Combine this rule with the file's existing record,
if any. */
f = enter_file (strcache_add (name));
if (f->double_colon)
OS (fatal, flocp,
_("target file '%s' has both : and :: entries"), f->name);
/* If CMDS == F->CMDS, this target was listed in this rule
more than once. Just give a warning since this is harmless. */
if (cmds != 0 && cmds == f->cmds)
OS (error, flocp,
_("target '%s' given more than once in the same rule"),
f->name);
/* Check for two single-colon entries both with commands.
Check is_target so that we don't lose on files such as .c.o
whose commands were preinitialized. */
else if (cmds != 0 && f->cmds != 0 && f->is_target)
{
size_t l = strlen (f->name);
error (&cmds->fileinfo, l,
_("warning: overriding recipe for target '%s'"),
f->name);
error (&f->cmds->fileinfo, l,
_("warning: ignoring old recipe for target '%s'"),
f->name);
}
/* Defining .DEFAULT with no deps or cmds clears it. */
if (f == default_file && this == 0 && cmds == 0)
f->cmds = 0;
if (cmds != 0)
f->cmds = cmds;
/* Defining .SUFFIXES with no dependencies clears out the list of
suffixes. */
if (f == suffix_file && this == 0)
{
free_dep_chain (f->deps);
f->deps = 0;
}
}
else
{
/* Double-colon. Make a new record even if there already is one. */
f = lookup_file (name);
/* Check for both : and :: rules. Check is_target so we don't lose
on default suffix rules or makefiles. */
if (f != 0 && f->is_target && !f->double_colon)
OS (fatal, flocp,
_("target file '%s' has both : and :: entries"), f->name);
f = enter_file (strcache_add (name));
/* If there was an existing entry and it was a double-colon entry,
enter_file will have returned a new one, making it the prev
pointer of the old one, and setting its double_colon pointer to
the first one. */
if (f->double_colon == 0)
/* This is the first entry for this name, so we must set its
double_colon pointer to itself. */
f->double_colon = f;
f->cmds = cmds;
}
if (are_also_makes)
{
struct dep *also = alloc_dep();
also->name = f->name;
also->file = f;
also->next = also_make;
also_make = also;
}
f->is_target = 1;
/* If this is a static pattern rule, set the stem to the part of its
name that matched the '%' in the pattern, so you can use $* in the
commands. If we didn't do it before, enter the prereqs now. */
if (pattern)
{
static const char *percent = "%";
char *buffer = variable_expand ("");
char *o = patsubst_expand_pat (buffer, name, pattern, percent,
pattern_percent+1, percent+1);
f->stem = strcache_add_len (buffer, o - buffer);
if (this)
{
if (! this->need_2nd_expansion)
this = enter_prereqs (this, f->stem);
else
this->stem = f->stem;
}
}
/* Add the dependencies to this file entry. */
if (this != 0)
{
/* Add the file's old deps and the new ones in THIS together. */
if (f->deps == 0)
f->deps = this;
else if (cmds != 0)
{
struct dep *d = this;
/* If this rule has commands, put these deps first. */
while (d->next != 0)
d = d->next;
d->next = f->deps;
f->deps = this;
}
else
{
struct dep *d = f->deps;
/* A rule without commands: put its prereqs at the end. */
while (d->next != 0)
d = d->next;
d->next = this;
}
}
name = f->name;
/* All done! Set up for the next one. */
if (nextf == 0)
break;
filenames = nextf;
/* Reduce escaped percents. If there are any unescaped it's an error */
name = filenames->name;
if (find_percent_cached (&name))
O (error, flocp,
_("*** mixed implicit and normal rules: deprecated syntax"));
}
/* If there are also-makes, then populate a copy of the also-make list into
each one. For the last file, we take our original also_make list instead
wastefully copying it one more time and freeing it. */
{
struct dep *i;
for (i = also_make; i != NULL; i = i->next)
{
struct file *f = i->file;
struct dep *cpy = i->next ? copy_dep_chain (also_make) : also_make;
if (f->also_make)
{
OS (error, &cmds->fileinfo,
_("warning: overriding group membership for target '%s'"),
f->name);
free_dep_chain (f->also_make);
}
f->also_make = cpy;
}
}
}
/* Search STRING for an unquoted STOPMAP.
Backslashes quote elements from STOPMAP and backslash.
Quoting backslashes are removed from STRING by compacting it into itself.
Returns a pointer to the first unquoted STOPCHAR if there is one, or nil if
there are none.
If MAP_VARIABLE is set, then the complete contents of variable references
are skipped, even if the contain STOPMAP characters. */
static char *
find_map_unquote (char *string, int stopmap)
{
size_t string_len = 0;
char *p = string;
/* Always stop on NUL. */
stopmap |= MAP_NUL;
while (1)
{
while (! STOP_SET (*p, stopmap))
++p;
if (*p == '\0')
break;
/* If we stopped due to a variable reference, skip over its contents. */
if (*p == '$')
{
char openparen = p[1];
/* Check if '$' is the last character in the string. */
if (openparen == '\0')
break;
p += 2;
/* Skip the contents of a non-quoted, multi-char variable ref. */
if (openparen == '(' || openparen == '{')
{
unsigned int pcount = 1;
char closeparen = (openparen == '(' ? ')' : '}');
while (*p)
{
if (*p == openparen)
++pcount;
else if (*p == closeparen)
if (--pcount == 0)
{
++p;
break;
}
++p;
}
}
/* Skipped the variable reference: look for STOPCHARS again. */
continue;
}
if (p > string && p[-1] == '\\')
{
/* Search for more backslashes. */
int i = -2;
while (&p[i] >= string && p[i] == '\\')
--i;
++i;
/* Only compute the length if really needed. */
if (string_len == 0)
string_len = strlen (string);
/* The number of backslashes is now -I.
Copy P over itself to swallow half of them. */
memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
p += i/2;
if (i % 2 == 0)
/* All the backslashes quoted each other; the STOPCHAR was
unquoted. */
return p;
/* The STOPCHAR was quoted by a backslash. Look for another. */
}
else
/* No backslash in sight. */
return p;
}
/* Never hit a STOPCHAR or blank (with BLANK nonzero). */
return 0;
}
static char *
find_char_unquote (char *string, int stop)
{
size_t string_len = 0;
char *p = string;
while (1)
{
p = strchr(p, stop);
if (!p)
return NULL;
if (p > string && p[-1] == '\\')
{
/* Search for more backslashes. */
int i = -2;
while (&p[i] >= string && p[i] == '\\')
--i;
++i;
/* Only compute the length if really needed. */
if (string_len == 0)
string_len = strlen (string);
/* The number of backslashes is now -I.
Copy P over itself to swallow half of them. */
memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
p += i/2;
if (i % 2 == 0)
/* All the backslashes quoted each other; the STOPCHAR was
unquoted. */
return p;
/* The STOPCHAR was quoted by a backslash. Look for another. */
}
else
/* No backslash in sight. */
return p;
}
}
/* Unescape a character in a string. The string is compressed onto itself. */
static char *
unescape_char (char *string, int c)
{
char *p = string;
char *s = string;
while (*s != '\0')
{
if (*s == '\\')
{
char *e = s;
size_t l;
/* We found a backslash. See if it's escaping our character. */
while (*e == '\\')
++e;
l = e - s;
if (*e != c || l%2 == 0)
{
/* It's not; just take it all without unescaping. */
memmove (p, s, l);
p += l;
/* If we hit the end of the string, we're done. */
if (*e == '\0')
break;
}
else if (l > 1)
{
/* It is, and there's >1 backslash. Take half of them. */
l /= 2;
memmove (p, s, l);
p += l;
}
s = e;
}
*(p++) = *(s++);
}
*p = '\0';
return string;
}
/* Search PATTERN for an unquoted % and handle quoting. */
char *
find_percent (char *pattern)
{
return find_char_unquote (pattern, '%');
}
/* Search STRING for an unquoted % and handle quoting. Returns a pointer to
the % or NULL if no % was found.
This version is used with strings in the string cache: if there's a need to
modify the string a new version will be added to the string cache and
*STRING will be set to that. */
const char *
find_percent_cached (const char **string)
{
const char *p = *string;
char *new = 0;
size_t slen = 0;
/* If the first char is a % return now. This lets us avoid extra tests
inside the loop. */
if (*p == '%')
return p;
while (1)
{
p = strchr(p, '%');
if (!p)
break;
/* See if this % is escaped with a backslash; if not we're done. */
if (p[-1] != '\\')
break;
{
/* Search for more backslashes. */
char *pv;
int i = -2;
while (&p[i] >= *string && p[i] == '\\')
--i;
++i;
/* At this point we know we'll need to allocate a new string.
Make a copy if we haven't yet done so. */
if (! new)
{
slen = strlen (*string);
/* [jart] can't prove alloca() isn't returned; let's just leak */
new = malloc (slen + 1);
memcpy (new, *string, slen + 1);
p = new + (p - *string);
*string = new;
}
/* At this point *string, p, and new all point into the same string.
Get a non-const version of p so we can modify new. */
pv = new + (p - *string);
/* The number of backslashes is now -I.
Copy P over itself to swallow half of them. */
memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
p += i/2;
/* If the backslashes quoted each other; the % was unquoted. */
if (i % 2 == 0)
break;
}
}
/* If we had to change STRING, add it to the strcache. */
if (new)
{
*string = strcache_add (*string);
if (p)
p = *string + (p - new);
}
/* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
return p;
}
/* Find the next line of text in an eval buffer, combining continuation lines
into one line.
Return the number of actual lines read (> 1 if continuation lines).
Returns -1 if there's nothing left in the buffer.
After this function, ebuf->buffer points to the first character of the
line we just found.
*/
/* Read a line of text from a STRING.
Since we aren't really reading from a file, don't bother with linenumbers.
*/
static long
readstring (struct ebuffer *ebuf)
{
char *eol;
/* If there is nothing left in this buffer, return 0. */
if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
return -1;
/* Set up a new starting point for the buffer, and find the end of the
next logical line (taking into account backslash/newline pairs). */
eol = ebuf->buffer = ebuf->bufnext;
while (1)
{
int backslash = 0;
const char *bol = eol;
const char *p;
/* Find the next newline. At EOS, stop. */
p = eol = strchr (eol , '\n');
if (!eol)
{
ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
return 0;
}
/* Found a newline; if it's escaped continue; else we're done. */
while (p > bol && *(--p) == '\\')
backslash = !backslash;
if (!backslash)
break;
++eol;
}
/* Overwrite the newline char. */
*eol = '\0';
ebuf->bufnext = eol+1;
return 0;
}
static long
readline (struct ebuffer *ebuf)
{
char *p;
char *end;
char *start;
long nlines = 0;
/* The behaviors between string and stream buffers are different enough to
warrant different functions. Do the Right Thing. */
if (!ebuf->fp)
return readstring (ebuf);
/* When reading from a file, we always start over at the beginning of the
buffer for each new line. */
p = start = ebuf->bufstart;
end = p + ebuf->size;
*p = '\0';
while (fgets (p, (int) (end - p), ebuf->fp) != 0)
{
char *p2;
size_t len;
int backslash;
len = strlen (p);
if (len == 0)
{
/* This only happens when the first thing on the line is a '\0'.
It is a pretty hopeless case, but (wonder of wonders) Athena
lossage strikes again! (xmkmf puts NULs in its makefiles.)
There is nothing really to be done; we synthesize a newline so
the following line doesn't appear to be part of this line. */
O (error, &ebuf->floc,
_("warning: NUL character seen; rest of line ignored"));
p[0] = '\n';
len = 1;
}
/* Jump past the text we just read. */
p += len;
/* If the last char isn't a newline, the whole line didn't fit into the
buffer. Get some more buffer and try again. */
if (p[-1] != '\n')
goto more_buffer;
/* We got a newline, so add one to the count of lines. */
++nlines;
#if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
/* Check to see if the line was really ended with CRLF; if so ignore
the CR. */
if ((p - start) > 1 && p[-2] == '\r')
{
--p;
memmove (p-1, p, strlen (p) + 1);
}
#endif
backslash = 0;
for (p2 = p - 2; p2 >= start; --p2)
{
if (*p2 != '\\')
break;
backslash = !backslash;
}
if (!backslash)
{
p[-1] = '\0';
break;
}
/* It was a backslash/newline combo. If we have more space, read
another line. */
if (end - p >= 80)
continue;
/* We need more space at the end of our buffer, so realloc it.
Make sure to preserve the current offset of p. */
more_buffer:
{
size_t off = p - start;
ebuf->size *= 2;
start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
p = start + off;
end = start + ebuf->size;
*p = '\0';
}
}
if (ferror (ebuf->fp))
pfatal_with_name (ebuf->floc.filenm);
/* If we found some lines, return how many.
If we didn't, but we did find _something_, that indicates we read the last
line of a file with no final newline; return 1.
If we read nothing, we're at EOF; return -1. */
return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
}
/* Parse the next "makefile word" from the input buffer, and return info
about it.
A "makefile word" is one of:
w_bogus Should never happen
w_eol End of input
w_static A static word; cannot be expanded
w_variable A word containing one or more variables/functions
w_colon A colon
w_dcolon A double-colon
w_ampcolon An ampersand-colon (&:) token
w_ampdcolon An ampersand-double-colon (&::) token
w_semicolon A semicolon
w_varassign A variable assignment operator (=, :=, ::=, +=, ?=, or !=)
Note that this function is only used when reading certain parts of the
makefile. Don't use it where special rules hold sway (RHS of a variable,
in a command list, etc.) */
static enum make_word_type
get_next_mword (char *buffer, char **startp, size_t *length)
{
enum make_word_type wtype;
char *p = buffer, *beg;
char c;
/* Skip any leading whitespace. */
while (ISBLANK (*p))
++p;
beg = p;
c = *(p++);
/* Look at the start of the word to see if it's simple. */
switch (c)
{
case '\0':
wtype = w_eol;
goto done;
case ';':
wtype = w_semicolon;
goto done;
case '=':
wtype = w_varassign;
goto done;
case ':':
if (*p == '=')
{
++p;
wtype = w_varassign; /* := */
}
else if (*p == ':')
{
++p;
if (p[1] == '=')
{
++p;
wtype = w_varassign; /* ::= */
}
else
wtype = w_dcolon;
}
else
wtype = w_colon;
goto done;
case '&':
if (*p == ':')
{
++p;
if (*p != ':')
wtype = w_ampcolon; /* &: */
else
{
++p;
wtype = w_ampdcolon; /* &:: */
}
goto done;
}
break;
case '+':
case '?':
case '!':
if (*p == '=')
{
++p;
wtype = w_varassign; /* += or ?= or != */
goto done;
}
break;
default:
break;
}
/* This is some non-operator word. A word consists of the longest
string of characters that doesn't contain whitespace, one of [:=#],
or [?+!]=, or &:. */
/* We start out assuming a static word; if we see a variable we'll
adjust our assumptions then. */
wtype = w_static;
/* We already found the first value of "c", above. */
while (1)
{
char closeparen;
int count;
switch (c)
{
case '\0':
case ' ':
case '\t':
case '=':
goto done_word;
case ':':
#ifdef HAVE_DOS_PATHS
/* A word CAN include a colon in its drive spec. The drive
spec is allowed either at the beginning of a word, or as part
of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
if ((p - beg == 2 || (p - beg > 2 && p[-3] == '('))
&& isalpha ((unsigned char)p[-2]))
break;
#endif
goto done_word;
case '$':
c = *(p++);
if (c == '$')
break;
if (c == '\0')
goto done_word;
/* This is a variable reference, so note that it's expandable.
Then read it to the matching close paren. */
wtype = w_variable;
if (c == '(')
closeparen = ')';
else if (c == '{')
closeparen = '}';
else
/* This is a single-letter variable reference. */
break;
for (count=0; *p != '\0'; ++p)
{
if (*p == c)
++count;
else if (*p == closeparen && --count < 0)
{
++p;
break;
}
}
break;
case '?':
case '+':
if (*p == '=')
goto done_word;
break;
case '\\':
switch (*p)
{
case ':':
case ';':
case '=':
case '\\':
++p;
break;
}
break;
case '&':
if (*p == ':')
goto done_word;
break;
default:
break;
}
c = *(p++);
}
done_word:
--p;
done:
if (startp)
*startp = beg;
if (length)
*length = p - beg;
return wtype;
}
/* Construct the list of include directories
from the arguments and the default list. */
void
construct_include_path (const char **arg_dirs)
{
#ifdef VAXC /* just don't ask ... */
stat_t stbuf;
#else
struct stat stbuf;
#endif
const char **dirs;
const char **cpp;
size_t idx;
/* Compute the number of pointers we need in the table. */
idx = sizeof (default_include_directories) / sizeof (const char *);
if (arg_dirs)
for (cpp = arg_dirs; *cpp != 0; ++cpp)
++idx;
#ifdef __MSDOS__
/* Add one for $DJDIR. */
++idx;
#endif
dirs = xmalloc (idx * sizeof (const char *));
idx = 0;
max_incl_len = 0;
/* First consider any dirs specified with -I switches.
Ignore any that don't exist. Remember the maximum string length. */
if (arg_dirs)
while (*arg_dirs != 0)
{
const char *dir = *(arg_dirs++);
char *expanded = 0;
int e;
if (dir[0] == '~')
{
expanded = tilde_expand (dir);
if (expanded != 0)
dir = expanded;
}
EINTRLOOP (e, stat (dir, &stbuf));
if (e == 0 && S_ISDIR (stbuf.st_mode))
{
size_t len = strlen (dir);
/* If dir name is written with trailing slashes, discard them. */
while (len > 1 && dir[len - 1] == '/')
--len;
if (len > max_incl_len)
max_incl_len = len;
dirs[idx++] = strcache_add_len (dir, len);
}
free (expanded);
}
/* Now add the standard default dirs at the end. */
#ifdef __MSDOS__
{
/* The environment variable $DJDIR holds the root of the DJGPP directory
tree; add ${DJDIR}/include. */
struct variable *djdir = lookup_variable ("DJDIR", 5);
if (djdir)
{
size_t len = strlen (djdir->value) + 8;
char *defdir = alloca (len + 1);
strcat (strcpy (defdir, djdir->value), "/include");
dirs[idx++] = strcache_add (defdir);
if (len > max_incl_len)
max_incl_len = len;
}
}
#endif
for (cpp = default_include_directories; *cpp != 0; ++cpp)
{
int e;
EINTRLOOP (e, stat (*cpp, &stbuf));
if (e == 0 && S_ISDIR (stbuf.st_mode))
{
size_t len = strlen (*cpp);
/* If dir name is written with trailing slashes, discard them. */
while (len > 1 && (*cpp)[len - 1] == '/')
--len;
if (len > max_incl_len)
max_incl_len = len;
dirs[idx++] = strcache_add_len (*cpp, len);
}
}
dirs[idx] = 0;
/* Now add each dir to the .INCLUDE_DIRS variable. */
for (cpp = dirs; *cpp != 0; ++cpp)
do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
o_default, f_append, 0);
include_directories = dirs;
}
/* Expand ~ or ~USER at the beginning of NAME.
Return a newly malloc'd string or 0. */
char *
tilde_expand (const char *name)
{
#ifndef VMS
if (name[1] == '/' || name[1] == '\0')
{
char *home_dir;
int is_variable;
{
/* Turn off --warn-undefined-variables while we expand HOME. */
int save = warn_undefined_variables_flag;
warn_undefined_variables_flag = 0;
home_dir = allocated_variable_expand ("$(HOME)");
warn_undefined_variables_flag = save;
}
is_variable = home_dir[0] != '\0';
if (!is_variable)
{
free (home_dir);
home_dir = getenv ("HOME");
}
# if !defined(_AMIGA) && !defined(WINDOWS32)
if (home_dir == 0 || home_dir[0] == '\0')
{
char *logname = getlogin ();
home_dir = 0;
if (logname != 0)
{
struct passwd *p = getpwnam (logname);
if (p != 0)
home_dir = p->pw_dir;
}
}
# endif /* !AMIGA && !WINDOWS32 */
if (home_dir != 0)
{
char *new = xstrdup (concat (2, home_dir, name + 1));
if (is_variable)
free (home_dir);
return new;
}
}
# if !defined(_AMIGA) && !defined(WINDOWS32)
else
{
struct passwd *pwent;
char *userend = strchr (name + 1, '/');
if (userend != 0)
*userend = '\0';
pwent = getpwnam (name + 1);
if (pwent != 0)
{
if (userend == 0)
return xstrdup (pwent->pw_dir);
else
return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
}
else if (userend != 0)
*userend = '/';
}
# endif /* !AMIGA && !WINDOWS32 */
#endif /* !VMS */
return 0;
}
/* Parse a string into a sequence of filenames represented as a chain of
struct nameseq's and return that chain. Optionally expand the strings via
glob().
The string is passed as STRINGP, the address of a string pointer.
The string pointer is updated to point at the first character
not parsed, which either is a null char or equals STOPMAP.
SIZE is how large (in bytes) each element in the new chain should be.
This is useful if we want them actually to be other structures
that have room for additional info.
STOPMAP is a map of characters that tell us to stop parsing.
PREFIX, if non-null, is added to the beginning of each filename.
FLAGS allows one or more of the following bitflags to be set:
PARSEFS_NOSTRIP - Do no strip './'s off the beginning
PARSEFS_NOAR - Do not check filenames for archive references
PARSEFS_NOGLOB - Do not expand globbing characters
PARSEFS_EXISTS - Only return globbed files that actually exist
(cannot also set NOGLOB)
PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
*/
void *
parse_file_seq (char **stringp, size_t size, int stopmap,
const char *prefix, int flags)
{
/* tmp points to tmpbuf after the prefix, if any.
tp is the end of the buffer. */
static char *tmpbuf = NULL;
int cachep = NONE_SET (flags, PARSEFS_NOCACHE);
struct nameseq *new = 0;
struct nameseq **newp = &new;
#define NEWELT(_n) do { \
const char *__n = (_n); \
*newp = xcalloc (size); \
(*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
newp = &(*newp)->next; \
} while(0)
char *p;
glob_t gl;
char *tp;
int findmap = stopmap|MAP_VMSCOMMA|MAP_NUL;
if (NONE_SET (flags, PARSEFS_ONEWORD))
findmap |= MAP_BLANK;
/* Always stop on NUL. */
stopmap |= MAP_NUL;
if (size < sizeof (struct nameseq))
size = sizeof (struct nameseq);
if (NONE_SET (flags, PARSEFS_NOGLOB))
dir_setup_glob (&gl);
/* Get enough temporary space to construct the largest possible target. */
{
static size_t tmpbuf_len = 0;
size_t l = strlen (*stringp) + 1;
if (l > tmpbuf_len)
{
tmpbuf = xrealloc (tmpbuf, l);
tmpbuf_len = l;
}
}
tp = tmpbuf;
/* Parse STRING. P will always point to the end of the parsed content. */
p = *stringp;
while (1)
{
const char *name;
const char **nlist = 0;
char *tildep = 0;
int globme = 1;
#ifndef NO_ARCHIVES
char *arname = 0;
char *memname = 0;
#endif
char *s;
size_t nlen;
int tot, i;
/* Skip whitespace; at the end of the string or STOPCHAR we're done. */
NEXT_TOKEN (p);
if (STOP_SET (*p, stopmap))
break;
/* There are names left, so find the end of the next name.
Throughout this iteration S points to the start. */
s = p;
p = find_map_unquote (p, findmap);
#ifdef VMS
/* convert comma separated list to space separated */
if (p && *p == ',')
*p =' ';
#endif
#ifdef _AMIGA
/* If we stopped due to a device name, skip it. */
if (p && p != s+1 && p[0] == ':')
p = find_map_unquote (p+1, findmap);
#endif
#ifdef HAVE_DOS_PATHS
/* If we stopped due to a drive specifier, skip it.
Tokens separated by spaces are treated as separate paths since make
doesn't allow path names with spaces. */
if (p && p == s+1 && p[0] == ':'
&& isalpha ((unsigned char)s[0]) && STOP_SET (p[1], MAP_DIRSEP))
p = find_map_unquote (p+1, findmap);
#endif
if (!p)
p = s + strlen (s);
/* Strip leading "this directory" references. */
if (NONE_SET (flags, PARSEFS_NOSTRIP))
#ifdef VMS
/* Skip leading '[]'s. should only be one set or bug somwhere else */
if (p - s > 2 && s[0] == '[' && s[1] == ']')
s += 2;
/* Skip leading '<>'s. should only be one set or bug somwhere else */
if (p - s > 2 && s[0] == '<' && s[1] == '>')
s += 2;
#endif
/* Skip leading './'s. */
while (p - s > 2 && s[0] == '.' && s[1] == '/')
{
/* Skip "./" and all following slashes. */
s += 2;
while (*s == '/')
++s;
}
/* Extract the filename just found, and skip it.
Set NAME to the string, and NLEN to its length. */
if (s == p)
{
/* The name was stripped to empty ("./"). */
#if defined(_AMIGA)
/* PDS-- This cannot be right!! */
tp[0] = '\0';
nlen = 0;
#else
tp[0] = '.';
tp[1] = '/';
tp[2] = '\0';
nlen = 2;
#endif
}
else
{
#ifdef VMS
/* VMS filenames can have a ':' in them but they have to be '\'ed but we need
* to remove this '\' before we can use the filename.
* xstrdup called because S may be read-only string constant.
*/
char *n = tp;
while (s < p)
{
if (s[0] == '\\' && s[1] == ':')
++s;
*(n++) = *(s++);
}
n[0] = '\0';
nlen = strlen (tp);
#else
nlen = p - s;
memcpy (tp, s, nlen);
tp[nlen] = '\0';
#endif
}
/* At this point, TP points to the element and NLEN is its length. */
#ifndef NO_ARCHIVES
/* If this is the start of an archive group that isn't complete, set up
to add the archive prefix for future files. A file list like:
"libf.a(x.o y.o z.o)" needs to be expanded as:
"libf.a(x.o) libf.a(y.o) libf.a(z.o)"
TP == TMP means we're not already in an archive group. Ignore
something starting with '(', as that cannot actually be an
archive-member reference (and treating it as such results in an empty
file name, which causes much lossage). Also if it ends in ")" then
it's a complete reference so we don't need to treat it specially.
Finally, note that archive groups must end with ')' as the last
character, so ensure there's some word ending like that before
considering this an archive group. */
if (NONE_SET (flags, PARSEFS_NOAR)
&& tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
{
char *n = strchr (tp, '(');
if (n)
{
/* This looks like the first element in an open archive group.
A valid group MUST have ')' as the last character. */
const char *e = p;
do
{
const char *o = e;
NEXT_TOKEN (e);
/* Find the end of this word. We don't want to unquote and
we don't care about quoting since we're looking for the
last char in the word. */
while (! STOP_SET (*e, findmap))
++e;
/* If we didn't move, we're done now. */
if (e == o)
break;
if (e[-1] == ')')
{
/* Found the end, so this is the first element in an
open archive group. It looks like "lib(mem".
Reset TP past the open paren. */
nlen -= (n + 1) - tp;
tp = n + 1;
/* We can stop looking now. */
break;
}
}
while (*e != '\0');
/* If we have just "lib(", part of something like "lib( a b)",
go to the next item. */
if (! nlen)
continue;
}
}
/* If we are inside an archive group, make sure it has an end. */
if (tp > tmpbuf)
{
if (tp[nlen-1] == ')')
{
/* This is the natural end; reset TP. */
tp = tmpbuf;
/* This is just ")", something like "lib(a b )": skip it. */
if (nlen == 1)
continue;
}
else
{
/* Not the end, so add a "fake" end. */
tp[nlen++] = ')';
tp[nlen] = '\0';
}
}
#endif
/* If we're not globbing we're done: add it to the end of the chain.
Go to the next item in the string. */
if (ANY_SET (flags, PARSEFS_NOGLOB))
{
NEWELT (concat (2, prefix, tmpbuf));
continue;
}
/* If we get here we know we're doing glob expansion.
TP is a string in tmpbuf. NLEN is no longer used.
We may need to do more work: after this NAME will be set. */
name = tmpbuf;
/* Expand tilde if applicable. */
if (tmpbuf[0] == '~')
{
tildep = tilde_expand (tmpbuf);
if (tildep != 0)
name = tildep;
}
#ifndef NO_ARCHIVES
/* If NAME is an archive member reference replace it with the archive
file name, and save the member name in MEMNAME. We will glob on the
archive name and then reattach MEMNAME later. */
if (NONE_SET (flags, PARSEFS_NOAR) && ar_name (name))
{
ar_parse_name (name, &arname, &memname);
name = arname;
}
#endif /* !NO_ARCHIVES */
/* glob() is expensive: don't call it unless we need to. */
if (NONE_SET (flags, PARSEFS_EXISTS) && strpbrk (name, "?*[") == NULL)
{
globme = 0;
tot = 1;
nlist = &name;
}
else
switch (glob (name, GLOB_ALTDIRFUNC, NULL, &gl))
{
case GLOB_NOSPACE:
out_of_memory ();
case 0:
/* Success. */
tot = gl.gl_pathc;
nlist = (const char **)gl.gl_pathv;
break;
case GLOB_NOMATCH:
/* If we want only existing items, skip this one. */
if (ANY_SET (flags, PARSEFS_EXISTS))
{
tot = 0;
break;
}
/* FALLTHROUGH */
default:
/* By default keep this name. */
tot = 1;
nlist = &name;
break;
}
/* For each matched element, add it to the list. */
for (i = 0; i < tot; ++i)
#ifndef NO_ARCHIVES
if (memname != 0)
{
/* Try to glob on MEMNAME within the archive. */
struct nameseq *found = ar_glob (nlist[i], memname, size);
if (! found)
/* No matches. Use MEMNAME as-is. */
NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
else
{
/* We got a chain of items. Attach them. */
if (*newp)
(*newp)->next = found;
else
*newp = found;
/* Find and set the new end. Massage names if necessary. */
while (1)
{
if (! cachep)
found->name = xstrdup (concat (2, prefix, name));
else if (prefix)
found->name = strcache_add (concat (2, prefix, name));
if (found->next == 0)
break;
found = found->next;
}
newp = &found->next;
}
}
else
#endif /* !NO_ARCHIVES */
NEWELT (concat (2, prefix, nlist[i]));
if (globme)
globfree (&gl);
#ifndef NO_ARCHIVES
free (arname);
#endif
free (tildep);
}
*stringp = p;
return new;
}
| 104,496 | 3,463 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/AUTHORS | -----------------------------------
GNU make development up to version 3.75 by:
Roland McGrath <[email protected]>
Development starting with GNU make 3.76 by:
Paul D. Smith <[email protected]>
Additional development starting with GNU make 3.81 by:
Boris Kolpackov <[email protected]>
GNU Make User's Manual
Written by:
Richard M. Stallman <[email protected]>
Edited by:
Roland McGrath <[email protected]>
Bob Chassell <[email protected]>
Melissa Weisshaus <[email protected]>
Paul D. Smith <[email protected]>
-----------------------------------
GNU make porting efforts:
Port to VMS by:
Klaus Kaempf <[email protected]>
Hartmut Becker <[email protected]>
Archive support/Bug fixes by:
John W. Eaton <[email protected]>
Martin Zinser <[email protected]>
Port to Amiga by:
Aaron Digulla <[email protected]>
Port to MS-DOS (DJGPP), OS/2, and MS-Windows (native/MinGW) by:
DJ Delorie <[email protected]>
Rob Tulloh <[email protected]>
Eli Zaretskii <[email protected]>
Jonathan Grant <[email protected]>
Andreas Beuning <[email protected]>
Earnie Boyd <[email protected]>
Troy Runkel <[email protected]>
-----------------------------------
Other contributors:
Janet Carson <[email protected]>
Howard Chu <[email protected]>
Ludovic Courtès <[email protected]>
Paul Eggert <[email protected]>
Ramon Garcia Fernandez <[email protected]>
Klaus Heinz <[email protected]>
Michael Joosten
Jim Kelton <[email protected]>
David Lubbren <[email protected]>
Tim Magill <[email protected]>
Markus Mauhart <[email protected]>
Greg McGary <[email protected]>
Thien-Thi Nguyen <[email protected]>
Thomas Riedl <[email protected]>
Han-Wen Nienhuys <[email protected]>
Andreas Schwab <[email protected]>
Carl Staelin (Princeton University)
Ian Stewartson (Data Logic Limited)
David A. Wheeler <[email protected]>
David Boyce <[email protected]>
Frank Heckenbach <[email protected]>
Kaz Kylheku <[email protected]>
Christof Warlich <[email protected]>
With suggestions/comments/bug reports from a cast of ... well ...
hundreds, anyway :)
-------------------------------------------------------------------------------
Copyright (C) 1997-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>.
| 3,044 | 91 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/getopt.h | /* Declarations for getopt.
Copyright (C) 1989-2020 Free Software Foundation, Inc.
NOTE: The canonical source of this file is maintained with the GNU C Library.
Bugs can be reported to [email protected].
GNU Make 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.
GNU Make 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/>. */
#include "third_party/getopt/getopt.h"
/* clang-format off */
#ifndef _GETOPT_H
#if 0 && !defined(_GETOPT_H)
#define _GETOPT_H 1
#ifdef __cplusplus
extern "C" {
#endif
/* For communication from `getopt' to the caller.
When `getopt' finds an option that takes an argument,
the argument value is returned here.
Also, when `ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
extern char *optarg;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
and for communication between successive calls to `getopt'.
On entry to `getopt', zero means this is the first call; initialize.
When `getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
Otherwise, `optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
extern int optind;
/* Callers store zero here to inhibit the error message `getopt' prints
for unrecognized options. */
extern int opterr;
/* Set to an option character which was unrecognized. */
extern int optopt;
/* Describe the long-named options requested by the application.
The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector
of `struct option' terminated by an element containing a name which is
zero.
The field `has_arg' is:
no_argument (or 0) if the option does not take an argument,
required_argument (or 1) if the option requires an argument,
optional_argument (or 2) if the option takes an optional argument.
If the field `flag' is not NULL, it points to a variable that is set
to the value given in the field `val' when the option is found, but
left unchanged if the option is not found.
To have a long-named option do something other than set an `int' to
a compiled-in constant, such as set a value from `optarg', set the
option's `flag' field to zero and its `val' field to a nonzero
value (the equivalent single-letter option character, if there is
one). For long options that have a zero `flag' field, `getopt'
returns the contents of the `val' field. */
struct option
{
#if defined (__STDC__) && __STDC__
const char *name;
#else
char *name;
#endif
/* has_arg can't be an enum because some compilers complain about
type mismatches in all the code that assumes it is an int. */
int has_arg;
int *flag;
int val;
};
/* Names for the values of the `has_arg' field of `struct option'. */
#define no_argument 0
#define required_argument 1
#define optional_argument 2
#if defined (__STDC__) && __STDC__
#ifdef __GNU_LIBRARY__
/* Many other libraries have conflicting prototypes for getopt, with
differences in the consts, in stdlib.h. To avoid compilation
errors, only prototype getopt for the GNU C library. */
extern int getopt (int argc, char *const *argv, const char *shortopts);
#else /* not __GNU_LIBRARY__ */
extern int getopt ();
#endif /* __GNU_LIBRARY__ */
extern int getopt_long (int argc, char *const *argv, const char *shortopts,
const struct option *longopts, int *longind);
extern int getopt_long_only (int argc, char *const *argv,
const char *shortopts,
const struct option *longopts, int *longind);
/* Internal only. Users should not call this directly. */
extern int _getopt_internal (int argc, char *const *argv,
const char *shortopts,
const struct option *longopts, int *longind,
int long_only);
#else /* not __STDC__ */
extern int getopt ();
extern int getopt_long ();
extern int getopt_long_only ();
extern int _getopt_internal ();
#endif /* __STDC__ */
#ifdef __cplusplus
}
#endif
#else
extern int _getopt_internal (int argc, char *const *argv,
const char *shortopts,
const struct option *longopts, int *longind,
int long_only);
#endif
#endif /* getopt.h */
| 4,751 | 142 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/misc.c | /* clang-format off */
/* Miscellaneous generic support functions for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
#include "third_party/make/filedef.h"
#include "third_party/make/dep.h"
#include "third_party/make/debug.h"
#include "libc/calls/calls.h"
/* GNU make no longer supports pre-ANSI89 environments. */
/* Compare strings *S1 and *S2.
Return negative if the first is less, positive if it is greater,
zero if they are equal. */
int
alpha_compare (const void *v1, const void *v2)
{
const char *s1 = *((char **)v1);
const char *s2 = *((char **)v2);
if (*s1 != *s2)
return *s1 - *s2;
return strcmp (s1, s2);
}
/* Discard each backslash-newline combination from LINE.
Backslash-backslash-newline combinations become backslash-newlines.
This is done by copying the text at LINE into itself. */
void
collapse_continuations (char *line)
{
char *out = line;
char *in = line;
char *q;
q = strchr(in, '\n');
if (q == 0)
return;
do
{
char *p = q;
int i;
size_t out_line_length;
if (q > line && q[-1] == '\\')
{
/* Search for more backslashes. */
i = -2;
while (&p[i] >= line && p[i] == '\\')
--i;
++i;
}
else
i = 0;
/* The number of backslashes is now -I, keep half of them. */
out_line_length = (p - in) + i - i/2;
if (out != in)
memmove (out, in, out_line_length);
out += out_line_length;
/* When advancing IN, skip the newline too. */
in = q + 1;
if (i & 1)
{
/* Backslash/newline handling:
In traditional GNU make all trailing whitespace, consecutive
backslash/newlines, and any leading non-newline whitespace on the
next line is reduced to a single space.
In POSIX, each backslash/newline and is replaced by a space. */
while (ISBLANK (*in))
++in;
if (! posix_pedantic)
while (out > line && ISBLANK (out[-1]))
--out;
*out++ = ' ';
}
else
{
/* If the newline isn't quoted, put it in the output. */
*out++ = '\n';
}
q = strchr(in, '\n');
}
while (q);
memmove(out, in, strlen(in) + 1);
}
/* Print N spaces (used in debug for target-depth). */
void
print_spaces (unsigned int n)
{
while (n-- > 0)
putchar (' ');
}
/* Return a string whose contents concatenate the NUM strings provided
This string lives in static, re-used memory. */
const char *
concat (unsigned int num, ...)
{
static size_t rlen = 0;
static char *result = NULL;
size_t ri = 0;
va_list args;
va_start (args, num);
while (num-- > 0)
{
const char *s = va_arg (args, const char *);
size_t l = xstrlen (s);
if (l == 0)
continue;
if (ri + l > rlen)
{
rlen = ((rlen ? rlen : 60) + l) * 2;
result = xrealloc (result, rlen);
}
memcpy (result + ri, s, l);
ri += l;
}
va_end (args);
/* Get some more memory if we don't have enough space for the
terminating '\0'. */
if (ri == rlen)
{
rlen = (rlen ? rlen : 60) * 2;
result = xrealloc (result, rlen);
}
result[ri] = '\0';
return result;
}
char *
xstrndup (const char *str, size_t length)
{
char *result;
#ifdef HAVE_STRNDUP
result = strndup (str, length);
if (result == 0)
out_of_memory ();
#else
result = xmalloc (length + 1);
if (length > 0)
strncpy (result, str, length);
result[length] = '\0';
#endif
return result;
}
/* Limited INDEX:
Search through the string STRING, which ends at LIMIT, for the character C.
Returns a pointer to the first occurrence, or nil if none is found.
Like INDEX except that the string searched ends where specified
instead of at the first null. */
char *
lindex (const char *s, const char *limit, int c)
{
while (s < limit)
if (*s++ == c)
return (char *)(s - 1);
return 0;
}
/* Return the address of the first whitespace or null in the string S. */
char *
end_of_token (const char *s)
{
END_OF_TOKEN (s);
return (char *)s;
}
/* Return the address of the first nonwhitespace or null in the string S. */
char *
next_token (const char *s)
{
NEXT_TOKEN (s);
return (char *)s;
}
/* Find the next token in PTR; return the address of it, and store the length
of the token into *LENGTHPTR if LENGTHPTR is not nil. Set *PTR to the end
of the token, so this function can be called repeatedly in a loop. */
char *
find_next_token (const char **ptr, size_t *lengthptr)
{
const char *p = next_token (*ptr);
if (*p == '\0')
return 0;
*ptr = end_of_token (p);
if (lengthptr != 0)
*lengthptr = *ptr - p;
return (char *)p;
}
/* Write a BUFFER of size LEN to file descriptor FD.
Retry short writes from EINTR. Return LEN, or -1 on error. */
ssize_t
writebuf (int fd, const void *buffer, size_t len)
{
const char *msg = buffer;
size_t l = len;
while (l)
{
ssize_t r;
EINTRLOOP (r, write (fd, msg, l));
if (r < 0)
return r;
l -= r;
msg += r;
}
return (ssize_t)len;
}
/* Read until we get LEN bytes from file descriptor FD, into BUFFER.
Retry short reads on EINTR. If we get an error, return it.
Return 0 at EOF. */
ssize_t
readbuf (int fd, void *buffer, size_t len)
{
char *msg = buffer;
while (len)
{
ssize_t r;
EINTRLOOP (r, read (fd, msg, len));
if (r < 0)
return r;
if (r == 0)
break;
len -= r;
msg += r;
}
return (ssize_t)(msg - (char*)buffer);
}
/* Copy a chain of 'struct dep'. For 2nd expansion deps, dup the name. */
struct dep *
copy_dep_chain (const struct dep *d)
{
struct dep *firstnew = 0;
struct dep *lastnew = 0;
while (d != 0)
{
struct dep *c = xmalloc (sizeof (struct dep));
memcpy (c, d, sizeof (struct dep));
if (c->need_2nd_expansion)
c->name = xstrdup (c->name);
c->next = 0;
if (firstnew == 0)
firstnew = lastnew = c;
else
lastnew = lastnew->next = c;
d = d->next;
}
return firstnew;
}
/* Free a chain of struct nameseq.
For struct dep chains use free_dep_chain. */
void
free_ns_chain (struct nameseq *ns)
{
while (ns != 0)
{
struct nameseq *t = ns;
ns = ns->next;
free_ns (t);
}
}
#ifdef MAKE_MAINTAINER_MODE
void
spin (const char* type)
{
char filenm[256];
struct stat dummy;
sprintf (filenm, ".make-spin-%s", type);
if (stat (filenm, &dummy) == 0)
{
fprintf (stderr, "SPIN on %s\n", filenm);
do
sleep (1);
while (stat (filenm, &dummy) == 0);
}
}
#endif
/* Provide support for temporary files. */
#ifndef HAVE_STDLIB_H
# ifdef HAVE_MKSTEMP
int mkstemp (char *template);
# else
char *mktemp (char *template);
# endif
#endif
FILE *
get_tmpfile (char **name, const char *template)
{
FILE *file;
#ifdef HAVE_FDOPEN
int fd;
#endif
/* Preserve the current umask, and set a restrictive one for temp files. */
mode_t mask = umask (0077);
#if defined(HAVE_MKSTEMP) || defined(HAVE_MKTEMP)
# define TEMPLATE_LEN strlen (template)
#else
# define TEMPLATE_LEN L_tmpnam
#endif
*name = xmalloc (TEMPLATE_LEN + 1);
strcpy (*name, template);
#if defined(HAVE_MKSTEMP) && defined(HAVE_FDOPEN)
/* It's safest to use mkstemp(), if we can. */
EINTRLOOP (fd, mkstemp (*name));
if (fd == -1)
file = NULL;
else
file = fdopen (fd, "w");
#else
# ifdef HAVE_MKTEMP
(void) mktemp (*name);
# else
(void) tmpnam (*name);
# endif
# ifdef HAVE_FDOPEN
/* Can't use mkstemp(), but guard against a race condition. */
EINTRLOOP (fd, open (*name, O_CREAT|O_EXCL|O_WRONLY, 0600));
if (fd == -1)
return 0;
file = fdopen (fd, "w");
# else
/* Not secure, but what can we do? */
file = fopen (*name, "w");
# endif
#endif
umask (mask);
return file;
}
#ifdef GETLOADAVG_PRIVILEGED
#ifdef POSIX
/* Hopefully if a system says it's POSIX.1 and has the setuid and setgid
functions, they work as POSIX.1 says. Some systems (Alpha OSF/1 1.2,
for example) which claim to be POSIX.1 also have the BSD setreuid and
setregid functions, but they don't work as in BSD and only the POSIX.1
way works. */
#undef HAVE_SETREUID
#undef HAVE_SETREGID
#else /* Not POSIX. */
/* Some POSIX.1 systems have the seteuid and setegid functions. In a
POSIX-like system, they are the best thing to use. However, some
non-POSIX systems have them too but they do not work in the POSIX style
and we must use setreuid and setregid instead. */
#undef HAVE_SETEUID
#undef HAVE_SETEGID
#endif /* POSIX. */
/* Keep track of the user and group IDs for user- and make- access. */
static int user_uid = -1, user_gid = -1, make_uid = -1, make_gid = -1;
#define access_inited (user_uid != -1)
static enum { make, user } current_access;
/* Under -d, write a message describing the current IDs. */
static void
log_access (const char *flavor)
{
if (! ISDB (DB_JOBS))
return;
/* All the other debugging messages go to stdout,
but we write this one to stderr because it might be
run in a child fork whose stdout is piped. */
fprintf (stderr, _("%s: user %lu (real %lu), group %lu (real %lu)\n"),
flavor, (unsigned long) geteuid (), (unsigned long) getuid (),
(unsigned long) getegid (), (unsigned long) getgid ());
fflush (stderr);
}
static void
init_access (void)
{
user_uid = getuid ();
user_gid = getgid ();
make_uid = geteuid ();
make_gid = getegid ();
/* Do these ever fail? */
if (user_uid == -1 || user_gid == -1 || make_uid == -1 || make_gid == -1)
pfatal_with_name ("get{e}[gu]id");
log_access (_("Initialized access"));
current_access = make;
}
#endif /* GETLOADAVG_PRIVILEGED */
/* Give the process appropriate permissions for access to
user data (i.e., to stat files, or to spawn a child process). */
void
user_access (void)
{
#ifdef GETLOADAVG_PRIVILEGED
if (!access_inited)
init_access ();
if (current_access == user)
return;
/* We are in "make access" mode. This means that the effective user and
group IDs are those of make (if it was installed setuid or setgid).
We now want to set the effective user and group IDs to the real IDs,
which are the IDs of the process that exec'd make. */
#ifdef HAVE_SETEUID
/* Modern systems have the seteuid/setegid calls which set only the
effective IDs, which is ideal. */
if (seteuid (user_uid) < 0)
pfatal_with_name ("user_access: seteuid");
#else /* Not HAVE_SETEUID. */
#ifndef HAVE_SETREUID
/* System V has only the setuid/setgid calls to set user/group IDs.
There is an effective ID, which can be set by setuid/setgid.
It can be set (unless you are root) only to either what it already is
(returned by geteuid/getegid, now in make_uid/make_gid),
the real ID (return by getuid/getgid, now in user_uid/user_gid),
or the saved set ID (what the effective ID was before this set-ID
executable (make) was exec'd). */
if (setuid (user_uid) < 0)
pfatal_with_name ("user_access: setuid");
#else /* HAVE_SETREUID. */
/* In 4BSD, the setreuid/setregid calls set both the real and effective IDs.
They may be set to themselves or each other. So you have two alternatives
at any one time. If you use setuid/setgid, the effective will be set to
the real, leaving only one alternative. Using setreuid/setregid, however,
you can toggle between your two alternatives by swapping the values in a
single setreuid or setregid call. */
if (setreuid (make_uid, user_uid) < 0)
pfatal_with_name ("user_access: setreuid");
#endif /* Not HAVE_SETREUID. */
#endif /* HAVE_SETEUID. */
#ifdef HAVE_SETEGID
if (setegid (user_gid) < 0)
pfatal_with_name ("user_access: setegid");
#else
#ifndef HAVE_SETREGID
if (setgid (user_gid) < 0)
pfatal_with_name ("user_access: setgid");
#else
if (setregid (make_gid, user_gid) < 0)
pfatal_with_name ("user_access: setregid");
#endif
#endif
current_access = user;
log_access (_("User access"));
#endif /* GETLOADAVG_PRIVILEGED */
}
/* Give the process appropriate permissions for access to
make data (i.e., the load average). */
void
make_access (void)
{
#ifdef GETLOADAVG_PRIVILEGED
if (!access_inited)
init_access ();
if (current_access == make)
return;
/* See comments in user_access, above. */
#ifdef HAVE_SETEUID
if (seteuid (make_uid) < 0)
pfatal_with_name ("make_access: seteuid");
#else
#ifndef HAVE_SETREUID
if (setuid (make_uid) < 0)
pfatal_with_name ("make_access: setuid");
#else
if (setreuid (user_uid, make_uid) < 0)
pfatal_with_name ("make_access: setreuid");
#endif
#endif
#ifdef HAVE_SETEGID
if (setegid (make_gid) < 0)
pfatal_with_name ("make_access: setegid");
#else
#ifndef HAVE_SETREGID
if (setgid (make_gid) < 0)
pfatal_with_name ("make_access: setgid");
#else
if (setregid (user_gid, make_gid) < 0)
pfatal_with_name ("make_access: setregid");
#endif
#endif
current_access = make;
log_access (_("Make access"));
#endif /* GETLOADAVG_PRIVILEGED */
}
/* Give the process appropriate permissions for a child process.
This is like user_access, but you can't get back to make_access. */
void
child_access (void)
{
#ifdef GETLOADAVG_PRIVILEGED
if (!access_inited)
abort ();
/* Set both the real and effective UID and GID to the user's.
They cannot be changed back to make's. */
#ifndef HAVE_SETREUID
if (setuid (user_uid) < 0)
pfatal_with_name ("child_access: setuid");
#else
if (setreuid (user_uid, user_uid) < 0)
pfatal_with_name ("child_access: setreuid");
#endif
#ifndef HAVE_SETREGID
if (setgid (user_gid) < 0)
pfatal_with_name ("child_access: setgid");
#else
if (setregid (user_gid, user_gid) < 0)
pfatal_with_name ("child_access: setregid");
#endif
log_access (_("Child access"));
#endif /* GETLOADAVG_PRIVILEGED */
}
#ifdef NEED_GET_PATH_MAX
unsigned int
get_path_max (void)
{
static unsigned int value;
if (value == 0)
{
long int x = pathconf ("/", _PC_PATH_MAX);
if (x > 0)
value = x;
else
return MAXPATHLEN;
}
return value;
}
#endif
| 15,146 | 659 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/stdlib.h | /* clang-format off */
/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* A GNU-like <stdlib.h>.
Copyright (C) 1995, 2001-2004, 2006-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#if __GNUC__ >= 3
#pragma GCC system_header
#endif
#if defined __need_system_stdlib_h || defined __need_malloc_and_calloc
/* Special invocation conventions inside some gnulib header files,
and inside some glibc header files, respectively. */
#else
/* Normal invocation convention. */
#ifndef _GL_STDLIB_H
/* The include_next requires a split double-inclusion guard. */
#ifndef _GL_STDLIB_H
#define _GL_STDLIB_H
/* NetBSD 5.0 mis-defines NULL. */
/* MirBSD 10 defines WEXITSTATUS in <sys/wait.h>, not in <stdlib.h>. */
#if 0 && !defined WEXITSTATUS
#endif
/* Solaris declares getloadavg() in <sys/loadavg.h>. */
#if (1 || defined GNULIB_POSIXCHECK) && 0
/* OpenIndiana has a bug: <sys/time.h> must be included before
<sys/loadavg.h>. */
#endif
/* Native Windows platforms declare mktemp() in <io.h>. */
#if 0 && (defined _WIN32 && ! defined __CYGWIN__)
#endif
#if 0
/* OSF/1 5.1 declares 'struct random_data' in <random.h>, which is included
from <stdlib.h> if _REENTRANT is defined. Include it whenever we need
'struct random_data'. */
# if 1
# endif
# if !1 || 0 || !1
# endif
# if !1
/* Define 'struct random_data'.
But allow multiple gnulib generated <stdlib.h> replacements to coexist. */
# if !GNULIB_defined_struct_random_data
struct random_data
{
int32_t *fptr; /* Front pointer. */
int32_t *rptr; /* Rear pointer. */
int32_t *state; /* Array of state values. */
int rand_type; /* Type of random number generator. */
int rand_deg; /* Degree of random number generator. */
int rand_sep; /* Distance between front and rear. */
int32_t *end_ptr; /* Pointer behind state table. */
};
# define GNULIB_defined_struct_random_data 1
# endif
# endif
#endif
#if (0 || 0 || 0 || 0 || 0 || defined GNULIB_POSIXCHECK) && ! defined __GLIBC__ && !(defined _WIN32 && ! defined __CYGWIN__)
/* On Mac OS X 10.3, only <unistd.h> declares mkstemp. */
/* On Mac OS X 10.5, only <unistd.h> declares mkstemps. */
/* On Mac OS X 10.13, only <unistd.h> declares mkostemp and mkostemps. */
/* On Cygwin 1.7.1, only <unistd.h> declares getsubopt. */
/* But avoid namespace pollution on glibc systems and native Windows. */
#endif
/* The __attribute__ feature is available in gcc versions 2.5 and later.
The attribute __pure__ was added in gcc 2.96. */
#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
# define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
#else
# define _GL_ATTRIBUTE_PURE /* empty */
#endif
/* The definition of _Noreturn is copied here. */
/* A C macro for declaring that a function does not return.
Copyright (C) 2011-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#ifndef _Noreturn
# if (defined __cplusplus \
&& ((201103 <= __cplusplus && !(__GNUC__ == 4 && __GNUC_MINOR__ == 7)) \
|| (defined _MSC_VER && 1900 <= _MSC_VER)) \
&& 0)
/* [[noreturn]] is not practically usable, because with it the syntax
extern _Noreturn void func (...);
would not be valid; such a declaration would only be valid with 'extern'
and '_Noreturn' swapped, or without the 'extern' keyword. However, some
AIX system header files and several gnulib header files use precisely
this syntax with 'extern'. */
# define _Noreturn [[noreturn]]
# elif ((!defined __cplusplus || defined __clang__) \
&& (201112 <= (defined __STDC_VERSION__ ? __STDC_VERSION__ : 0) \
|| 4 < __GNUC__ + (7 <= __GNUC_MINOR__)))
/* _Noreturn works as-is. */
# elif 2 < __GNUC__ + (8 <= __GNUC_MINOR__) || 0x5110 <= __SUNPRO_C
# define _Noreturn __attribute__ ((__noreturn__))
# elif 1200 <= (defined _MSC_VER ? _MSC_VER : 0)
# define _Noreturn __declspec (noreturn)
# else
# define _Noreturn
# endif
#endif
/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
/* C++ compatible function declaration macros.
Copyright (C) 2010-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#ifndef _GL_CXXDEFS_H
#define _GL_CXXDEFS_H
/* Begin/end the GNULIB_NAMESPACE namespace. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_BEGIN_NAMESPACE namespace GNULIB_NAMESPACE {
# define _GL_END_NAMESPACE }
#else
# define _GL_BEGIN_NAMESPACE
# define _GL_END_NAMESPACE
#endif
/* The three most frequent use cases of these macros are:
* For providing a substitute for a function that is missing on some
platforms, but is declared and works fine on the platforms on which
it exists:
#if @GNULIB_FOO@
# if !@HAVE_FOO@
_GL_FUNCDECL_SYS (foo, ...);
# endif
_GL_CXXALIAS_SYS (foo, ...);
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
* For providing a replacement for a function that exists on all platforms,
but is broken/insufficient and needs to be replaced on some platforms:
#if @GNULIB_FOO@
# if @REPLACE_FOO@
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef foo
# define foo rpl_foo
# endif
_GL_FUNCDECL_RPL (foo, ...);
_GL_CXXALIAS_RPL (foo, ...);
# else
_GL_CXXALIAS_SYS (foo, ...);
# endif
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
* For providing a replacement for a function that exists on some platforms
but is broken/insufficient and needs to be replaced on some of them and
is additionally either missing or undeclared on some other platforms:
#if @GNULIB_FOO@
# if @REPLACE_FOO@
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef foo
# define foo rpl_foo
# endif
_GL_FUNCDECL_RPL (foo, ...);
_GL_CXXALIAS_RPL (foo, ...);
# else
# if !@HAVE_FOO@ or if !@HAVE_DECL_FOO@
_GL_FUNCDECL_SYS (foo, ...);
# endif
_GL_CXXALIAS_SYS (foo, ...);
# endif
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
*/
/* _GL_EXTERN_C declaration;
performs the declaration with C linkage. */
#if defined __cplusplus
# define _GL_EXTERN_C extern "C"
#else
# define _GL_EXTERN_C extern
#endif
/* _GL_FUNCDECL_RPL (func, rettype, parameters_and_attributes);
declares a replacement function, named rpl_func, with the given prototype,
consisting of return type, parameters, and attributes.
Example:
_GL_FUNCDECL_RPL (open, int, (const char *filename, int flags, ...)
_GL_ARG_NONNULL ((1)));
*/
#define _GL_FUNCDECL_RPL(func,rettype,parameters_and_attributes) \
_GL_FUNCDECL_RPL_1 (rpl_##func, rettype, parameters_and_attributes)
#define _GL_FUNCDECL_RPL_1(rpl_func,rettype,parameters_and_attributes) \
_GL_EXTERN_C rettype rpl_func parameters_and_attributes
/* _GL_FUNCDECL_SYS (func, rettype, parameters_and_attributes);
declares the system function, named func, with the given prototype,
consisting of return type, parameters, and attributes.
Example:
_GL_FUNCDECL_SYS (open, int, (const char *filename, int flags, ...)
_GL_ARG_NONNULL ((1)));
*/
#define _GL_FUNCDECL_SYS(func,rettype,parameters_and_attributes) \
_GL_EXTERN_C rettype func parameters_and_attributes
/* _GL_CXXALIAS_RPL (func, rettype, parameters);
declares a C++ alias called GNULIB_NAMESPACE::func
that redirects to rpl_func, if GNULIB_NAMESPACE is defined.
Example:
_GL_CXXALIAS_RPL (open, int, (const char *filename, int flags, ...));
Wrapping rpl_func in an object with an inline conversion operator
avoids a reference to rpl_func unless GNULIB_NAMESPACE::func is
actually used in the program. */
#define _GL_CXXALIAS_RPL(func,rettype,parameters) \
_GL_CXXALIAS_RPL_1 (func, rpl_##func, rettype, parameters)
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_RPL_1(func,rpl_func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return ::rpl_func; \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_RPL_1(func,rpl_func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_RPL_CAST_1 (func, rpl_func, rettype, parameters);
is like _GL_CXXALIAS_RPL_1 (func, rpl_func, rettype, parameters);
except that the C function rpl_func may have a slightly different
declaration. A cast is used to silence the "invalid conversion" error
that would otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_RPL_CAST_1(func,rpl_func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return reinterpret_cast<type>(::rpl_func); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_RPL_CAST_1(func,rpl_func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS (func, rettype, parameters);
declares a C++ alias called GNULIB_NAMESPACE::func
that redirects to the system provided function func, if GNULIB_NAMESPACE
is defined.
Example:
_GL_CXXALIAS_SYS (open, int, (const char *filename, int flags, ...));
Wrapping func in an object with an inline conversion operator
avoids a reference to func unless GNULIB_NAMESPACE::func is
actually used in the program. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_SYS(func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return ::func; \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_SYS(func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS_CAST (func, rettype, parameters);
is like _GL_CXXALIAS_SYS (func, rettype, parameters);
except that the C function func may have a slightly different declaration.
A cast is used to silence the "invalid conversion" error that would
otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_SYS_CAST(func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return reinterpret_cast<type>(::func); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_SYS_CAST(func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS_CAST2 (func, rettype, parameters, rettype2, parameters2);
is like _GL_CXXALIAS_SYS (func, rettype, parameters);
except that the C function is picked among a set of overloaded functions,
namely the one with rettype2 and parameters2. Two consecutive casts
are used to silence the "cannot find a match" and "invalid conversion"
errors that would otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
/* The outer cast must be a reinterpret_cast.
The inner cast: When the function is defined as a set of overloaded
functions, it works as a static_cast<>, choosing the designated variant.
When the function is defined as a single variant, it works as a
reinterpret_cast<>. The parenthesized cast syntax works both ways. */
# define _GL_CXXALIAS_SYS_CAST2(func,rettype,parameters,rettype2,parameters2) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return reinterpret_cast<type>((rettype2 (*) parameters2)(::func)); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_SYS_CAST2(func,rettype,parameters,rettype2,parameters2) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIASWARN (func);
causes a warning to be emitted when ::func is used but not when
GNULIB_NAMESPACE::func is used. func must be defined without overloaded
variants. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIASWARN(func) \
_GL_CXXALIASWARN_1 (func, GNULIB_NAMESPACE)
# define _GL_CXXALIASWARN_1(func,namespace) \
_GL_CXXALIASWARN_2 (func, namespace)
/* To work around GCC bug <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=43881>,
we enable the warning only when not optimizing. */
# if !__OPTIMIZE__
# define _GL_CXXALIASWARN_2(func,namespace) \
_GL_WARN_ON_USE (func, \
"The symbol ::" #func " refers to the system function. " \
"Use " #namespace "::" #func " instead.")
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
# define _GL_CXXALIASWARN_2(func,namespace) \
extern __typeof__ (func) func
# else
# define _GL_CXXALIASWARN_2(func,namespace) \
_GL_EXTERN_C int _gl_cxxalias_dummy
# endif
#else
# define _GL_CXXALIASWARN(func) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIASWARN1 (func, rettype, parameters_and_attributes);
causes a warning to be emitted when the given overloaded variant of ::func
is used but not when GNULIB_NAMESPACE::func is used. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIASWARN1(func,rettype,parameters_and_attributes) \
_GL_CXXALIASWARN1_1 (func, rettype, parameters_and_attributes, \
GNULIB_NAMESPACE)
# define _GL_CXXALIASWARN1_1(func,rettype,parameters_and_attributes,namespace) \
_GL_CXXALIASWARN1_2 (func, rettype, parameters_and_attributes, namespace)
/* To work around GCC bug <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=43881>,
we enable the warning only when not optimizing. */
# if !__OPTIMIZE__
# define _GL_CXXALIASWARN1_2(func,rettype,parameters_and_attributes,namespace) \
_GL_WARN_ON_USE_CXX (func, rettype, parameters_and_attributes, \
"The symbol ::" #func " refers to the system function. " \
"Use " #namespace "::" #func " instead.")
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
# define _GL_CXXALIASWARN1_2(func,rettype,parameters_and_attributes,namespace) \
extern __typeof__ (func) func
# else
# define _GL_CXXALIASWARN1_2(func,rettype,parameters_and_attributes,namespace) \
_GL_EXTERN_C int _gl_cxxalias_dummy
# endif
#else
# define _GL_CXXALIASWARN1(func,rettype,parameters_and_attributes) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
#endif /* _GL_CXXDEFS_H */
/* The definition of _GL_ARG_NONNULL is copied here. */
/* A C macro for declaring that specific arguments must not be NULL.
Copyright (C) 2009-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* _GL_ARG_NONNULL((n,...,m)) tells the compiler and static analyzer tools
that the values passed as arguments n, ..., m must be non-NULL pointers.
n = 1 stands for the first argument, n = 2 for the second argument etc. */
#ifndef _GL_ARG_NONNULL
# if (__GNUC__ == 3 && __GNUC_MINOR__ >= 3) || __GNUC__ > 3
# define _GL_ARG_NONNULL(params) __attribute__ ((__nonnull__ params))
# else
# define _GL_ARG_NONNULL(params)
# endif
#endif
/* The definition of _GL_WARN_ON_USE is copied here. */
/* A C macro for emitting warnings if a function is used.
Copyright (C) 2010-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* _GL_WARN_ON_USE (function, "literal string") issues a declaration
for FUNCTION which will then trigger a compiler warning containing
the text of "literal string" anywhere that function is called, if
supported by the compiler. If the compiler does not support this
feature, the macro expands to an unused extern declaration.
_GL_WARN_ON_USE_ATTRIBUTE ("literal string") expands to the
attribute used in _GL_WARN_ON_USE. If the compiler does not support
this feature, it expands to empty.
These macros are useful for marking a function as a potential
portability trap, with the intent that "literal string" include
instructions on the replacement function that should be used
instead.
_GL_WARN_ON_USE is for functions with 'extern' linkage.
_GL_WARN_ON_USE_ATTRIBUTE is for functions with 'static' or 'inline'
linkage.
However, one of the reasons that a function is a portability trap is
if it has the wrong signature. Declaring FUNCTION with a different
signature in C is a compilation error, so this macro must use the
same type as any existing declaration so that programs that avoid
the problematic FUNCTION do not fail to compile merely because they
included a header that poisoned the function. But this implies that
_GL_WARN_ON_USE is only safe to use if FUNCTION is known to already
have a declaration. Use of this macro implies that there must not
be any other macro hiding the declaration of FUNCTION; but
undefining FUNCTION first is part of the poisoning process anyway
(although for symbols that are provided only via a macro, the result
is a compilation error rather than a warning containing
"literal string"). Also note that in C++, it is only safe to use if
FUNCTION has no overloads.
For an example, it is possible to poison 'getline' by:
[getline]) in configure.ac, which potentially defines
HAVE_RAW_DECL_GETLINE
- adding this code to a header that wraps the system <stdio.h>:
#undef getline
#if HAVE_RAW_DECL_GETLINE
_GL_WARN_ON_USE (getline, "getline is required by POSIX 2008, but"
"not universally present; use the gnulib module getline");
#endif
It is not possible to directly poison global variables. But it is
possible to write a wrapper accessor function, and poison that
(less common usage, like &environ, will cause a compilation error
rather than issue the nice warning, but the end result of informing
the developer about their portability problem is still achieved):
#if HAVE_RAW_DECL_ENVIRON
static char ***
rpl_environ (void) { return &environ; }
_GL_WARN_ON_USE (rpl_environ, "environ is not always properly declared");
# undef environ
# define environ (*rpl_environ ())
#endif
or better (avoiding contradictory use of 'static' and 'extern'):
#if HAVE_RAW_DECL_ENVIRON
static char ***
_GL_WARN_ON_USE_ATTRIBUTE ("environ is not always properly declared")
rpl_environ (void) { return &environ; }
# undef environ
# define environ (*rpl_environ ())
#endif
*/
#ifndef _GL_WARN_ON_USE
# if 4 < __GNUC__ || (__GNUC__ == 4 && 3 <= __GNUC_MINOR__)
/* A compiler attribute is available in gcc versions 4.3.0 and later. */
# define _GL_WARN_ON_USE(function, message) \
extern __typeof__ (function) function __attribute__ ((__warning__ (message)))
# define _GL_WARN_ON_USE_ATTRIBUTE(message) \
__attribute__ ((__warning__ (message)))
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
/* Verify the existence of the function. */
# define _GL_WARN_ON_USE(function, message) \
extern __typeof__ (function) function
# define _GL_WARN_ON_USE_ATTRIBUTE(message)
# else /* Unsupported. */
# define _GL_WARN_ON_USE(function, message) \
_GL_WARN_EXTERN_C int _gl_warn_on_use
# define _GL_WARN_ON_USE_ATTRIBUTE(message)
# endif
#endif
/* _GL_WARN_ON_USE_CXX (function, rettype, parameters_and_attributes, "string")
is like _GL_WARN_ON_USE (function, "string"), except that the function is
declared with the given prototype, consisting of return type, parameters,
and attributes.
This variant is useful for overloaded functions in C++. _GL_WARN_ON_USE does
not work in this case. */
#ifndef _GL_WARN_ON_USE_CXX
# if 4 < __GNUC__ || (__GNUC__ == 4 && 3 <= __GNUC_MINOR__)
# define _GL_WARN_ON_USE_CXX(function,rettype,parameters_and_attributes,msg) \
extern rettype function parameters_and_attributes \
__attribute__ ((__warning__ (msg)))
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
/* Verify the existence of the function. */
# define _GL_WARN_ON_USE_CXX(function,rettype,parameters_and_attributes,msg) \
extern rettype function parameters_and_attributes
# else /* Unsupported. */
# define _GL_WARN_ON_USE_CXX(function,rettype,parameters_and_attributes,msg) \
_GL_WARN_EXTERN_C int _gl_warn_on_use
# endif
#endif
/* _GL_WARN_EXTERN_C declaration;
performs the declaration with C linkage. */
#ifndef _GL_WARN_EXTERN_C
# if defined __cplusplus
# define _GL_WARN_EXTERN_C extern "C"
# else
# define _GL_WARN_EXTERN_C extern
# endif
#endif
/* Some systems do not define EXIT_*, despite otherwise supporting C89. */
#ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
#endif
/* Tandem/NSK and other platforms that define EXIT_FAILURE as -1 interfere
with proper operation of xargs. */
#ifndef EXIT_FAILURE
# define EXIT_FAILURE 1
#elif EXIT_FAILURE != 1
# undef EXIT_FAILURE
# define EXIT_FAILURE 1
#endif
#if 0
/* Terminate the current process with the given return code, without running
the 'atexit' handlers. */
# if !1
_GL_FUNCDECL_SYS (_Exit, _Noreturn void, (int status));
# endif
_GL_CXXALIAS_SYS (_Exit, void, (int status));
_GL_CXXALIASWARN (_Exit);
#elif defined GNULIB_POSIXCHECK
# undef _Exit
# if HAVE_RAW_DECL__EXIT
_GL_WARN_ON_USE (_Exit, "_Exit is unportable - "
"use gnulib module _Exit for portability");
# endif
#endif
#if 0
/* Parse a signed decimal integer.
Returns the value of the integer. Errors are not detected. */
# if !1
_GL_FUNCDECL_SYS (atoll, long long, (const char *string)
_GL_ATTRIBUTE_PURE
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (atoll, long long, (const char *string));
_GL_CXXALIASWARN (atoll);
#elif defined GNULIB_POSIXCHECK
# undef atoll
# if HAVE_RAW_DECL_ATOLL
_GL_WARN_ON_USE (atoll, "atoll is unportable - "
"use gnulib module atoll for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef calloc
# define calloc rpl_calloc
# endif
_GL_FUNCDECL_RPL (calloc, void *, (size_t nmemb, size_t size));
_GL_CXXALIAS_RPL (calloc, void *, (size_t nmemb, size_t size));
# else
_GL_CXXALIAS_SYS (calloc, void *, (size_t nmemb, size_t size));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (calloc);
# endif
#elif defined GNULIB_POSIXCHECK
# undef calloc
/* Assume calloc is always declared. */
_GL_WARN_ON_USE (calloc, "calloc is not POSIX compliant everywhere - "
"use gnulib module calloc-posix for portability");
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define canonicalize_file_name rpl_canonicalize_file_name
# endif
_GL_FUNCDECL_RPL (canonicalize_file_name, char *, (const char *name)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (canonicalize_file_name, char *, (const char *name));
# else
# if !1
_GL_FUNCDECL_SYS (canonicalize_file_name, char *, (const char *name)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (canonicalize_file_name, char *, (const char *name));
# endif
_GL_CXXALIASWARN (canonicalize_file_name);
#elif defined GNULIB_POSIXCHECK
# undef canonicalize_file_name
# if HAVE_RAW_DECL_CANONICALIZE_FILE_NAME
_GL_WARN_ON_USE (canonicalize_file_name,
"canonicalize_file_name is unportable - "
"use gnulib module canonicalize-lgpl for portability");
# endif
#endif
#if 1
/* Store max(NELEM,3) load average numbers in LOADAVG[].
The three numbers are the load average of the last 1 minute, the last 5
minutes, and the last 15 minutes, respectively.
LOADAVG is an array of NELEM numbers. */
# if !0
_GL_FUNCDECL_SYS (getloadavg, int, (double loadavg[], int nelem)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (getloadavg, int, (double loadavg[], int nelem));
_GL_CXXALIASWARN (getloadavg);
#elif defined GNULIB_POSIXCHECK
# undef getloadavg
# if HAVE_RAW_DECL_GETLOADAVG
_GL_WARN_ON_USE (getloadavg, "getloadavg is not portable - "
"use gnulib module getloadavg for portability");
# endif
#endif
#if 0
/* Assuming *OPTIONP is a comma separated list of elements of the form
"token" or "token=value", getsubopt parses the first of these elements.
If the first element refers to a "token" that is member of the given
NULL-terminated array of tokens:
- It replaces the comma with a NUL byte, updates *OPTIONP to point past
the first option and the comma, sets *VALUEP to the value of the
element (or NULL if it doesn't contain an "=" sign),
- It returns the index of the "token" in the given array of tokens.
Otherwise it returns -1, and *OPTIONP and *VALUEP are undefined.
For more details see the POSIX specification.
https://pubs.opengroup.org/onlinepubs/9699919799/functions/getsubopt.html */
# if !1
_GL_FUNCDECL_SYS (getsubopt, int,
(char **optionp, char *const *tokens, char **valuep)
_GL_ARG_NONNULL ((1, 2, 3)));
# endif
_GL_CXXALIAS_SYS (getsubopt, int,
(char **optionp, char *const *tokens, char **valuep));
_GL_CXXALIASWARN (getsubopt);
#elif defined GNULIB_POSIXCHECK
# undef getsubopt
# if HAVE_RAW_DECL_GETSUBOPT
_GL_WARN_ON_USE (getsubopt, "getsubopt is unportable - "
"use gnulib module getsubopt for portability");
# endif
#endif
#if 0
/* Change the ownership and access permission of the slave side of the
pseudo-terminal whose master side is specified by FD. */
# if !1
_GL_FUNCDECL_SYS (grantpt, int, (int fd));
# endif
_GL_CXXALIAS_SYS (grantpt, int, (int fd));
_GL_CXXALIASWARN (grantpt);
#elif defined GNULIB_POSIXCHECK
# undef grantpt
# if HAVE_RAW_DECL_GRANTPT
_GL_WARN_ON_USE (grantpt, "grantpt is not portable - "
"use gnulib module grantpt for portability");
# endif
#endif
/* If _GL_USE_STDLIB_ALLOC is nonzero, the including module does not
rely on GNU or POSIX semantics for malloc and realloc (for example,
by never specifying a zero size), so it does not need malloc or
realloc to be redefined. */
#if 1
# if 0
# if !((defined __cplusplus && defined GNULIB_NAMESPACE) \
|| _GL_USE_STDLIB_ALLOC)
# undef malloc
# define malloc rpl_malloc
# endif
_GL_FUNCDECL_RPL (malloc, void *, (size_t size));
_GL_CXXALIAS_RPL (malloc, void *, (size_t size));
# else
_GL_CXXALIAS_SYS (malloc, void *, (size_t size));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (malloc);
# endif
#elif defined GNULIB_POSIXCHECK && !_GL_USE_STDLIB_ALLOC
# undef malloc
/* Assume malloc is always declared. */
_GL_WARN_ON_USE (malloc, "malloc is not POSIX compliant everywhere - "
"use gnulib module malloc-posix for portability");
#endif
/* Convert a multibyte character to a wide character. */
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef mbtowc
# define mbtowc rpl_mbtowc
# endif
_GL_FUNCDECL_RPL (mbtowc, int, (wchar_t *pwc, const char *s, size_t n));
_GL_CXXALIAS_RPL (mbtowc, int, (wchar_t *pwc, const char *s, size_t n));
# else
# if !1
_GL_FUNCDECL_SYS (mbtowc, int, (wchar_t *pwc, const char *s, size_t n));
# endif
_GL_CXXALIAS_SYS (mbtowc, int, (wchar_t *pwc, const char *s, size_t n));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (mbtowc);
# endif
#elif defined GNULIB_POSIXCHECK
# undef mbtowc
# if HAVE_RAW_DECL_MBTOWC
_GL_WARN_ON_USE (mbtowc, "mbtowc is not portable - "
"use gnulib module mbtowc for portability");
# endif
#endif
#if 0
/* Create a unique temporary directory from TEMPLATE.
The last six characters of TEMPLATE must be "XXXXXX";
they are replaced with a string that makes the directory name unique.
Returns TEMPLATE, or a null pointer if it cannot get a unique name.
The directory is created mode 700. */
# if !1
_GL_FUNCDECL_SYS (mkdtemp, char *, (char * /*template*/) _GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (mkdtemp, char *, (char * /*template*/));
_GL_CXXALIASWARN (mkdtemp);
#elif defined GNULIB_POSIXCHECK
# undef mkdtemp
# if HAVE_RAW_DECL_MKDTEMP
_GL_WARN_ON_USE (mkdtemp, "mkdtemp is unportable - "
"use gnulib module mkdtemp for portability");
# endif
#endif
#if 0
/* Create a unique temporary file from TEMPLATE.
The last six characters of TEMPLATE must be "XXXXXX";
they are replaced with a string that makes the file name unique.
The flags are a bitmask, possibly including O_CLOEXEC (defined in <fcntl.h>)
and O_TEXT, O_BINARY (defined in "binary-io.h").
The file is then created, with the specified flags, ensuring it didn't exist
before.
The file is created read-write (mask at least 0600 & ~umask), but it may be
world-readable and world-writable (mask 0666 & ~umask), depending on the
implementation.
Returns the open file descriptor if successful, otherwise -1 and errno
set. */
# if !1
_GL_FUNCDECL_SYS (mkostemp, int, (char * /*template*/, int /*flags*/)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (mkostemp, int, (char * /*template*/, int /*flags*/));
_GL_CXXALIASWARN (mkostemp);
#elif defined GNULIB_POSIXCHECK
# undef mkostemp
# if HAVE_RAW_DECL_MKOSTEMP
_GL_WARN_ON_USE (mkostemp, "mkostemp is unportable - "
"use gnulib module mkostemp for portability");
# endif
#endif
#if 0
/* Create a unique temporary file from TEMPLATE.
The last six characters of TEMPLATE before a suffix of length
SUFFIXLEN must be "XXXXXX";
they are replaced with a string that makes the file name unique.
The flags are a bitmask, possibly including O_CLOEXEC (defined in <fcntl.h>)
and O_TEXT, O_BINARY (defined in "binary-io.h").
The file is then created, with the specified flags, ensuring it didn't exist
before.
The file is created read-write (mask at least 0600 & ~umask), but it may be
world-readable and world-writable (mask 0666 & ~umask), depending on the
implementation.
Returns the open file descriptor if successful, otherwise -1 and errno
set. */
# if !1
_GL_FUNCDECL_SYS (mkostemps, int,
(char * /*template*/, int /*suffixlen*/, int /*flags*/)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (mkostemps, int,
(char * /*template*/, int /*suffixlen*/, int /*flags*/));
_GL_CXXALIASWARN (mkostemps);
#elif defined GNULIB_POSIXCHECK
# undef mkostemps
# if HAVE_RAW_DECL_MKOSTEMPS
_GL_WARN_ON_USE (mkostemps, "mkostemps is unportable - "
"use gnulib module mkostemps for portability");
# endif
#endif
#if 0
/* Create a unique temporary file from TEMPLATE.
The last six characters of TEMPLATE must be "XXXXXX";
they are replaced with a string that makes the file name unique.
The file is then created, ensuring it didn't exist before.
The file is created read-write (mask at least 0600 & ~umask), but it may be
world-readable and world-writable (mask 0666 & ~umask), depending on the
implementation.
Returns the open file descriptor if successful, otherwise -1 and errno
set. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define mkstemp rpl_mkstemp
# endif
_GL_FUNCDECL_RPL (mkstemp, int, (char * /*template*/) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (mkstemp, int, (char * /*template*/));
# else
# if ! 1
_GL_FUNCDECL_SYS (mkstemp, int, (char * /*template*/) _GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (mkstemp, int, (char * /*template*/));
# endif
_GL_CXXALIASWARN (mkstemp);
#elif defined GNULIB_POSIXCHECK
# undef mkstemp
# if HAVE_RAW_DECL_MKSTEMP
_GL_WARN_ON_USE (mkstemp, "mkstemp is unportable - "
"use gnulib module mkstemp for portability");
# endif
#endif
#if 0
/* Create a unique temporary file from TEMPLATE.
The last six characters of TEMPLATE prior to a suffix of length
SUFFIXLEN must be "XXXXXX";
they are replaced with a string that makes the file name unique.
The file is then created, ensuring it didn't exist before.
The file is created read-write (mask at least 0600 & ~umask), but it may be
world-readable and world-writable (mask 0666 & ~umask), depending on the
implementation.
Returns the open file descriptor if successful, otherwise -1 and errno
set. */
# if !1
_GL_FUNCDECL_SYS (mkstemps, int, (char * /*template*/, int /*suffixlen*/)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (mkstemps, int, (char * /*template*/, int /*suffixlen*/));
_GL_CXXALIASWARN (mkstemps);
#elif defined GNULIB_POSIXCHECK
# undef mkstemps
# if HAVE_RAW_DECL_MKSTEMPS
_GL_WARN_ON_USE (mkstemps, "mkstemps is unportable - "
"use gnulib module mkstemps for portability");
# endif
#endif
#if 0
/* Return an FD open to the master side of a pseudo-terminal. Flags should
include O_RDWR, and may also include O_NOCTTY. */
# if !1
_GL_FUNCDECL_SYS (posix_openpt, int, (int flags));
# endif
_GL_CXXALIAS_SYS (posix_openpt, int, (int flags));
_GL_CXXALIASWARN (posix_openpt);
#elif defined GNULIB_POSIXCHECK
# undef posix_openpt
# if HAVE_RAW_DECL_POSIX_OPENPT
_GL_WARN_ON_USE (posix_openpt, "posix_openpt is not portable - "
"use gnulib module posix_openpt for portability");
# endif
#endif
#if 0
/* Return the pathname of the pseudo-terminal slave associated with
the master FD is open on, or NULL on errors. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef ptsname
# define ptsname rpl_ptsname
# endif
_GL_FUNCDECL_RPL (ptsname, char *, (int fd));
_GL_CXXALIAS_RPL (ptsname, char *, (int fd));
# else
# if !1
_GL_FUNCDECL_SYS (ptsname, char *, (int fd));
# endif
_GL_CXXALIAS_SYS (ptsname, char *, (int fd));
# endif
_GL_CXXALIASWARN (ptsname);
#elif defined GNULIB_POSIXCHECK
# undef ptsname
# if HAVE_RAW_DECL_PTSNAME
_GL_WARN_ON_USE (ptsname, "ptsname is not portable - "
"use gnulib module ptsname for portability");
# endif
#endif
#if 0
/* Set the pathname of the pseudo-terminal slave associated with
the master FD is open on and return 0, or set errno and return
non-zero on errors. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef ptsname_r
# define ptsname_r rpl_ptsname_r
# endif
_GL_FUNCDECL_RPL (ptsname_r, int, (int fd, char *buf, size_t len));
_GL_CXXALIAS_RPL (ptsname_r, int, (int fd, char *buf, size_t len));
# else
# if !1
_GL_FUNCDECL_SYS (ptsname_r, int, (int fd, char *buf, size_t len));
# endif
_GL_CXXALIAS_SYS (ptsname_r, int, (int fd, char *buf, size_t len));
# endif
_GL_CXXALIASWARN (ptsname_r);
#elif defined GNULIB_POSIXCHECK
# undef ptsname_r
# if HAVE_RAW_DECL_PTSNAME_R
_GL_WARN_ON_USE (ptsname_r, "ptsname_r is not portable - "
"use gnulib module ptsname_r for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef putenv
# define putenv rpl_putenv
# endif
_GL_FUNCDECL_RPL (putenv, int, (char *string) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (putenv, int, (char *string));
# else
_GL_CXXALIAS_SYS (putenv, int, (char *string));
# endif
_GL_CXXALIASWARN (putenv);
#endif
#if 0
/* Sort an array of NMEMB elements, starting at address BASE, each element
occupying SIZE bytes, in ascending order according to the comparison
function COMPARE. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef qsort_r
# define qsort_r rpl_qsort_r
# endif
_GL_FUNCDECL_RPL (qsort_r, void, (void *base, size_t nmemb, size_t size,
int (*compare) (void const *, void const *,
void *),
void *arg) _GL_ARG_NONNULL ((1, 4)));
_GL_CXXALIAS_RPL (qsort_r, void, (void *base, size_t nmemb, size_t size,
int (*compare) (void const *, void const *,
void *),
void *arg));
# else
# if !1
_GL_FUNCDECL_SYS (qsort_r, void, (void *base, size_t nmemb, size_t size,
int (*compare) (void const *, void const *,
void *),
void *arg) _GL_ARG_NONNULL ((1, 4)));
# endif
_GL_CXXALIAS_SYS (qsort_r, void, (void *base, size_t nmemb, size_t size,
int (*compare) (void const *, void const *,
void *),
void *arg));
# endif
_GL_CXXALIASWARN (qsort_r);
#elif defined GNULIB_POSIXCHECK
# undef qsort_r
# if HAVE_RAW_DECL_QSORT_R
_GL_WARN_ON_USE (qsort_r, "qsort_r is not portable - "
"use gnulib module qsort_r for portability");
# endif
#endif
#if 0
# if !1
# ifndef RAND_MAX
# define RAND_MAX 2147483647
# endif
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef random
# define random rpl_random
# endif
_GL_FUNCDECL_RPL (random, long, (void));
_GL_CXXALIAS_RPL (random, long, (void));
# else
# if !1
_GL_FUNCDECL_SYS (random, long, (void));
# endif
/* Need to cast, because on Haiku, the return type is
int. */
_GL_CXXALIAS_SYS_CAST (random, long, (void));
# endif
_GL_CXXALIASWARN (random);
#elif defined GNULIB_POSIXCHECK
# undef random
# if HAVE_RAW_DECL_RANDOM
_GL_WARN_ON_USE (random, "random is unportable - "
"use gnulib module random for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef srandom
# define srandom rpl_srandom
# endif
_GL_FUNCDECL_RPL (srandom, void, (unsigned int seed));
_GL_CXXALIAS_RPL (srandom, void, (unsigned int seed));
# else
# if !1
_GL_FUNCDECL_SYS (srandom, void, (unsigned int seed));
# endif
/* Need to cast, because on FreeBSD, the first parameter is
unsigned long seed. */
_GL_CXXALIAS_SYS_CAST (srandom, void, (unsigned int seed));
# endif
_GL_CXXALIASWARN (srandom);
#elif defined GNULIB_POSIXCHECK
# undef srandom
# if HAVE_RAW_DECL_SRANDOM
_GL_WARN_ON_USE (srandom, "srandom is unportable - "
"use gnulib module random for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef initstate
# define initstate rpl_initstate
# endif
_GL_FUNCDECL_RPL (initstate, char *,
(unsigned int seed, char *buf, size_t buf_size)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (initstate, char *,
(unsigned int seed, char *buf, size_t buf_size));
# else
# if !1 || !1
_GL_FUNCDECL_SYS (initstate, char *,
(unsigned int seed, char *buf, size_t buf_size)
_GL_ARG_NONNULL ((2)));
# endif
/* Need to cast, because on FreeBSD, the first parameter is
unsigned long seed. */
_GL_CXXALIAS_SYS_CAST (initstate, char *,
(unsigned int seed, char *buf, size_t buf_size));
# endif
_GL_CXXALIASWARN (initstate);
#elif defined GNULIB_POSIXCHECK
# undef initstate
# if HAVE_RAW_DECL_INITSTATE
_GL_WARN_ON_USE (initstate, "initstate is unportable - "
"use gnulib module random for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef setstate
# define setstate rpl_setstate
# endif
_GL_FUNCDECL_RPL (setstate, char *, (char *arg_state) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (setstate, char *, (char *arg_state));
# else
# if !1 || !1
_GL_FUNCDECL_SYS (setstate, char *, (char *arg_state) _GL_ARG_NONNULL ((1)));
# endif
/* Need to cast, because on Mac OS X 10.13, HP-UX, Solaris the first parameter
is const char *arg_state. */
_GL_CXXALIAS_SYS_CAST (setstate, char *, (char *arg_state));
# endif
_GL_CXXALIASWARN (setstate);
#elif defined GNULIB_POSIXCHECK
# undef setstate
# if HAVE_RAW_DECL_SETSTATE
_GL_WARN_ON_USE (setstate, "setstate is unportable - "
"use gnulib module random for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef random_r
# define random_r rpl_random_r
# endif
_GL_FUNCDECL_RPL (random_r, int, (struct random_data *buf, int32_t *result)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (random_r, int, (struct random_data *buf, int32_t *result));
# else
# if !1
_GL_FUNCDECL_SYS (random_r, int, (struct random_data *buf, int32_t *result)
_GL_ARG_NONNULL ((1, 2)));
# endif
_GL_CXXALIAS_SYS (random_r, int, (struct random_data *buf, int32_t *result));
# endif
_GL_CXXALIASWARN (random_r);
#elif defined GNULIB_POSIXCHECK
# undef random_r
# if HAVE_RAW_DECL_RANDOM_R
_GL_WARN_ON_USE (random_r, "random_r is unportable - "
"use gnulib module random_r for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef srandom_r
# define srandom_r rpl_srandom_r
# endif
_GL_FUNCDECL_RPL (srandom_r, int,
(unsigned int seed, struct random_data *rand_state)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (srandom_r, int,
(unsigned int seed, struct random_data *rand_state));
# else
# if !1
_GL_FUNCDECL_SYS (srandom_r, int,
(unsigned int seed, struct random_data *rand_state)
_GL_ARG_NONNULL ((2)));
# endif
_GL_CXXALIAS_SYS (srandom_r, int,
(unsigned int seed, struct random_data *rand_state));
# endif
_GL_CXXALIASWARN (srandom_r);
#elif defined GNULIB_POSIXCHECK
# undef srandom_r
# if HAVE_RAW_DECL_SRANDOM_R
_GL_WARN_ON_USE (srandom_r, "srandom_r is unportable - "
"use gnulib module random_r for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef initstate_r
# define initstate_r rpl_initstate_r
# endif
_GL_FUNCDECL_RPL (initstate_r, int,
(unsigned int seed, char *buf, size_t buf_size,
struct random_data *rand_state)
_GL_ARG_NONNULL ((2, 4)));
_GL_CXXALIAS_RPL (initstate_r, int,
(unsigned int seed, char *buf, size_t buf_size,
struct random_data *rand_state));
# else
# if !1
_GL_FUNCDECL_SYS (initstate_r, int,
(unsigned int seed, char *buf, size_t buf_size,
struct random_data *rand_state)
_GL_ARG_NONNULL ((2, 4)));
# endif
/* Need to cast, because on Haiku, the third parameter is
unsigned long buf_size. */
_GL_CXXALIAS_SYS_CAST (initstate_r, int,
(unsigned int seed, char *buf, size_t buf_size,
struct random_data *rand_state));
# endif
_GL_CXXALIASWARN (initstate_r);
#elif defined GNULIB_POSIXCHECK
# undef initstate_r
# if HAVE_RAW_DECL_INITSTATE_R
_GL_WARN_ON_USE (initstate_r, "initstate_r is unportable - "
"use gnulib module random_r for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef setstate_r
# define setstate_r rpl_setstate_r
# endif
_GL_FUNCDECL_RPL (setstate_r, int,
(char *arg_state, struct random_data *rand_state)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (setstate_r, int,
(char *arg_state, struct random_data *rand_state));
# else
# if !1
_GL_FUNCDECL_SYS (setstate_r, int,
(char *arg_state, struct random_data *rand_state)
_GL_ARG_NONNULL ((1, 2)));
# endif
/* Need to cast, because on Haiku, the first parameter is
void *arg_state. */
_GL_CXXALIAS_SYS_CAST (setstate_r, int,
(char *arg_state, struct random_data *rand_state));
# endif
_GL_CXXALIASWARN (setstate_r);
#elif defined GNULIB_POSIXCHECK
# undef setstate_r
# if HAVE_RAW_DECL_SETSTATE_R
_GL_WARN_ON_USE (setstate_r, "setstate_r is unportable - "
"use gnulib module random_r for portability");
# endif
#endif
#if 0
# if 0
# if !((defined __cplusplus && defined GNULIB_NAMESPACE) \
|| _GL_USE_STDLIB_ALLOC)
# undef realloc
# define realloc rpl_realloc
# endif
_GL_FUNCDECL_RPL (realloc, void *, (void *ptr, size_t size));
_GL_CXXALIAS_RPL (realloc, void *, (void *ptr, size_t size));
# else
_GL_CXXALIAS_SYS (realloc, void *, (void *ptr, size_t size));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (realloc);
# endif
#elif defined GNULIB_POSIXCHECK && !_GL_USE_STDLIB_ALLOC
# undef realloc
/* Assume realloc is always declared. */
_GL_WARN_ON_USE (realloc, "realloc is not POSIX compliant everywhere - "
"use gnulib module realloc-posix for portability");
#endif
#if 0
# if ! 1
_GL_FUNCDECL_SYS (reallocarray, void *,
(void *ptr, size_t nmemb, size_t size));
# endif
_GL_CXXALIAS_SYS (reallocarray, void *,
(void *ptr, size_t nmemb, size_t size));
_GL_CXXALIASWARN (reallocarray);
#elif defined GNULIB_POSIXCHECK
# undef reallocarray
# if HAVE_RAW_DECL_REALLOCARRAY
_GL_WARN_ON_USE (reallocarray, "reallocarray is not portable - "
"use gnulib module reallocarray for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define realpath rpl_realpath
# endif
_GL_FUNCDECL_RPL (realpath, char *, (const char *name, char *resolved)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (realpath, char *, (const char *name, char *resolved));
# else
# if !1
_GL_FUNCDECL_SYS (realpath, char *, (const char *name, char *resolved)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (realpath, char *, (const char *name, char *resolved));
# endif
_GL_CXXALIASWARN (realpath);
#elif defined GNULIB_POSIXCHECK
# undef realpath
# if HAVE_RAW_DECL_REALPATH
_GL_WARN_ON_USE (realpath, "realpath is unportable - use gnulib module "
"canonicalize or canonicalize-lgpl for portability");
# endif
#endif
#if 0
/* Test a user response to a question.
Return 1 if it is affirmative, 0 if it is negative, or -1 if not clear. */
# if !1
_GL_FUNCDECL_SYS (rpmatch, int, (const char *response) _GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (rpmatch, int, (const char *response));
_GL_CXXALIASWARN (rpmatch);
#elif defined GNULIB_POSIXCHECK
# undef rpmatch
# if HAVE_RAW_DECL_RPMATCH
_GL_WARN_ON_USE (rpmatch, "rpmatch is unportable - "
"use gnulib module rpmatch for portability");
# endif
#endif
#if 0
/* Look up NAME in the environment, returning 0 in insecure situations. */
# if !1
_GL_FUNCDECL_SYS (secure_getenv, char *,
(char const *name) _GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (secure_getenv, char *, (char const *name));
_GL_CXXALIASWARN (secure_getenv);
#elif defined GNULIB_POSIXCHECK
# undef secure_getenv
# if HAVE_RAW_DECL_SECURE_GETENV
_GL_WARN_ON_USE (secure_getenv, "secure_getenv is unportable - "
"use gnulib module secure_getenv for portability");
# endif
#endif
#if 0
/* Set NAME to VALUE in the environment.
If REPLACE is nonzero, overwrite an existing value. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef setenv
# define setenv rpl_setenv
# endif
_GL_FUNCDECL_RPL (setenv, int,
(const char *name, const char *value, int replace)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (setenv, int,
(const char *name, const char *value, int replace));
# else
# if !1
_GL_FUNCDECL_SYS (setenv, int,
(const char *name, const char *value, int replace)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (setenv, int,
(const char *name, const char *value, int replace));
# endif
# if !(0 && !1)
_GL_CXXALIASWARN (setenv);
# endif
#elif defined GNULIB_POSIXCHECK
# undef setenv
# if HAVE_RAW_DECL_SETENV
_GL_WARN_ON_USE (setenv, "setenv is unportable - "
"use gnulib module setenv for portability");
# endif
#endif
#if 0
/* Parse a double from STRING, updating ENDP if appropriate. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define strtod rpl_strtod
# endif
# define GNULIB_defined_strtod_function 1
_GL_FUNCDECL_RPL (strtod, double, (const char *str, char **endp)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (strtod, double, (const char *str, char **endp));
# else
# if !1
_GL_FUNCDECL_SYS (strtod, double, (const char *str, char **endp)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (strtod, double, (const char *str, char **endp));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (strtod);
# endif
#elif defined GNULIB_POSIXCHECK
# undef strtod
# if HAVE_RAW_DECL_STRTOD
_GL_WARN_ON_USE (strtod, "strtod is unportable - "
"use gnulib module strtod for portability");
# endif
#endif
#if 0
/* Parse a 'long double' from STRING, updating ENDP if appropriate. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define strtold rpl_strtold
# endif
# define GNULIB_defined_strtold_function 1
_GL_FUNCDECL_RPL (strtold, long double, (const char *str, char **endp)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (strtold, long double, (const char *str, char **endp));
# else
# if !1
_GL_FUNCDECL_SYS (strtold, long double, (const char *str, char **endp)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (strtold, long double, (const char *str, char **endp));
# endif
_GL_CXXALIASWARN (strtold);
#elif defined GNULIB_POSIXCHECK
# undef strtold
# if HAVE_RAW_DECL_STRTOLD
_GL_WARN_ON_USE (strtold, "strtold is unportable - "
"use gnulib module strtold for portability");
# endif
#endif
#if 0
/* Parse a signed integer whose textual representation starts at STRING.
The integer is expected to be in base BASE (2 <= BASE <= 36); if BASE == 0,
it may be decimal or octal (with prefix "0") or hexadecimal (with prefix
"0x").
If ENDPTR is not NULL, the address of the first byte after the integer is
stored in *ENDPTR.
Upon overflow, the return value is LLONG_MAX or LLONG_MIN, and errno is set
to ERANGE. */
# if !1
_GL_FUNCDECL_SYS (strtoll, long long,
(const char *string, char **endptr, int base)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (strtoll, long long,
(const char *string, char **endptr, int base));
_GL_CXXALIASWARN (strtoll);
#elif defined GNULIB_POSIXCHECK
# undef strtoll
# if HAVE_RAW_DECL_STRTOLL
_GL_WARN_ON_USE (strtoll, "strtoll is unportable - "
"use gnulib module strtoll for portability");
# endif
#endif
#if 0
/* Parse an unsigned integer whose textual representation starts at STRING.
The integer is expected to be in base BASE (2 <= BASE <= 36); if BASE == 0,
it may be decimal or octal (with prefix "0") or hexadecimal (with prefix
"0x").
If ENDPTR is not NULL, the address of the first byte after the integer is
stored in *ENDPTR.
Upon overflow, the return value is ULLONG_MAX, and errno is set to
ERANGE. */
# if !1
_GL_FUNCDECL_SYS (strtoull, unsigned long long,
(const char *string, char **endptr, int base)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (strtoull, unsigned long long,
(const char *string, char **endptr, int base));
_GL_CXXALIASWARN (strtoull);
#elif defined GNULIB_POSIXCHECK
# undef strtoull
# if HAVE_RAW_DECL_STRTOULL
_GL_WARN_ON_USE (strtoull, "strtoull is unportable - "
"use gnulib module strtoull for portability");
# endif
#endif
#if 0
/* Unlock the slave side of the pseudo-terminal whose master side is specified
by FD, so that it can be opened. */
# if !1
_GL_FUNCDECL_SYS (unlockpt, int, (int fd));
# endif
_GL_CXXALIAS_SYS (unlockpt, int, (int fd));
_GL_CXXALIASWARN (unlockpt);
#elif defined GNULIB_POSIXCHECK
# undef unlockpt
# if HAVE_RAW_DECL_UNLOCKPT
_GL_WARN_ON_USE (unlockpt, "unlockpt is not portable - "
"use gnulib module unlockpt for portability");
# endif
#endif
#if 0
/* Remove the variable NAME from the environment. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef unsetenv
# define unsetenv rpl_unsetenv
# endif
_GL_FUNCDECL_RPL (unsetenv, int, (const char *name) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (unsetenv, int, (const char *name));
# else
# if !1
_GL_FUNCDECL_SYS (unsetenv, int, (const char *name) _GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (unsetenv, int, (const char *name));
# endif
# if !(0 && !1)
_GL_CXXALIASWARN (unsetenv);
# endif
#elif defined GNULIB_POSIXCHECK
# undef unsetenv
# if HAVE_RAW_DECL_UNSETENV
_GL_WARN_ON_USE (unsetenv, "unsetenv is unportable - "
"use gnulib module unsetenv for portability");
# endif
#endif
/* Convert a wide character to a multibyte character. */
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef wctomb
# define wctomb rpl_wctomb
# endif
_GL_FUNCDECL_RPL (wctomb, int, (char *s, wchar_t wc));
_GL_CXXALIAS_RPL (wctomb, int, (char *s, wchar_t wc));
# else
_GL_CXXALIAS_SYS (wctomb, int, (char *s, wchar_t wc));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (wctomb);
# endif
#endif
#endif /* _GL_STDLIB_H */
#endif /* _GL_STDLIB_H */
#endif
| 60,189 | 1,617 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/getopt1.c | /* getopt_long and getopt_long_only entry points for GNU getopt.
Copyright (C) 1987-1994, 1996-2020 Free Software Foundation, Inc.
NOTE: The canonical source of this file is maintained with the GNU C Library.
Bugs can be reported to [email protected].
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/getopt.h"
/* clang-format off */
#ifdef HAVE_CONFIG_H
#include "third_party/make/config.h"
#endif
/* Comment out all this code if we are using the GNU C Library, and are not
actually compiling the library itself. This code is part of the GNU C
Library, but also included in many other GNU distributions. Compiling
and linking in this code is a waste when using the GNU C library
(especially if it is a shared library). Rather than having every GNU
program understand `configure --with-gnu-libc' and omit the object files,
it is simpler to just do this in the source for each such file. */
#define GETOPT_INTERFACE_VERSION 2
#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
#if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
#define ELIDE_CODE
#endif
#endif
#ifndef ELIDE_CODE
int
getopt_long (int argc, char *const *argv, const char *options,
const struct option *long_options, int *opt_index)
{
return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
}
/* Like getopt_long, but '-' as well as '--' can indicate a long option.
If an option that starts with '-' (not '--') doesn't match a long option,
but does match a short option, it is parsed as a short option
instead. */
int
getopt_long_only (int argc, char *const *argv, const char *options,
const struct option *long_options, int *opt_index)
{
return _getopt_internal (argc, argv, options, long_options, opt_index, 1);
}
#endif /* Not ELIDE_CODE. */
#ifdef TEST
int
main (int argc, char **argv)
{
int c;
int digit_optind = 0;
while (1)
{
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] =
{
{"add", 1, 0, 0},
{"append", 0, 0, 0},
{"delete", 1, 0, 0},
{"verbose", 0, 0, 0},
{"create", 0, 0, 0},
{"file", 1, 0, 0},
{0, 0, 0, 0}
};
c = getopt_long (argc, argv, "abc:d:0123456789",
long_options, &option_index);
if (c == -1)
break;
switch (c)
{
case 0:
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf ("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf ("option %c\n", c);
break;
case 'a':
printf ("option a\n");
break;
case 'b':
printf ("option b\n");
break;
case 'c':
printf ("option c with value '%s'\n", optarg);
break;
case 'd':
printf ("option d with value '%s'\n", optarg);
break;
case '?':
break;
default:
printf ("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
printf ("\n");
}
exit (0);
}
#endif /* TEST */
| 3,943 | 154 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/make.mk | #-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-â
#âââvi: set et ft=make ts=8 tw=8 fenc=utf-8 :viââââââââââââââââââââââââ
PKGS += THIRD_PARTY_MAKE
THIRD_PARTY_MAKE_COMS = \
o/$(MODE)/third_party/make/make.com
THIRD_PARTY_MAKE_BINS = \
$(THIRD_PARTY_MAKE_COMS) \
$(THIRD_PARTY_MAKE_COMS:%=%.dbg)
THIRD_PARTY_MAKE_A = \
o/$(MODE)/third_party/make/make.a
THIRD_PARTY_MAKE_HDRS = \
third_party/make/filename.h \
third_party/make/dirname.h \
third_party/make/stddef.h \
third_party/make/error.h \
third_party/make/gnumake.h \
third_party/make/gettext.h \
third_party/make/stdlib.h \
third_party/make/xalloc.h \
third_party/make/xalloc-oversized.h \
third_party/make/os.h \
third_party/make/stdint.h \
third_party/make/fd-hook.h \
third_party/make/job.h \
third_party/make/unistd.h \
third_party/make/getprogname.h \
third_party/make/dosname.h \
third_party/make/config.h \
third_party/make/concat-filename.h \
third_party/make/findprog.h \
third_party/make/intprops.h \
third_party/make/exitfail.h \
third_party/make/alloca.h \
third_party/make/hash.h \
third_party/make/rule.h \
third_party/make/filedef.h \
third_party/make/fcntl.h \
third_party/make/stdio.h \
third_party/make/variable.h \
third_party/make/debug.h \
third_party/make/output.h \
third_party/make/getopt.h \
third_party/make/dep.h \
third_party/make/commands.h
THIRD_PARTY_MAKE_INCS = \
third_party/make/makeint.inc
THIRD_PARTY_MAKE_CHECKS = \
$(THIRD_PARTY_MAKE_A).pkg
# libgnu.a recipe
THIRD_PARTY_MAKE_SRCS_LIB = \
third_party/make/basename-lgpl.c \
third_party/make/concat-filename.c \
third_party/make/dirname-lgpl.c \
third_party/make/error.c \
third_party/make/exitfail.c \
third_party/make/fcntl.c \
third_party/make/fd-hook.c \
third_party/make/findprog-in.c \
third_party/make/getprogname.c \
third_party/make/stripslash.c \
third_party/make/unistd.c \
third_party/make/xalloc-die.c \
third_party/make/xconcat-filename.c \
third_party/make/xmalloc.c
THIRD_PARTY_MAKE_SRCS_BASE = \
third_party/make/commands.c \
third_party/make/default.c \
third_party/make/dir.c \
third_party/make/expand.c \
third_party/make/file.c \
third_party/make/function.c \
third_party/make/getopt.c \
third_party/make/getopt1.c \
third_party/make/guile.c \
third_party/make/hash.c \
third_party/make/implicit.c \
third_party/make/job.c \
third_party/make/load.c \
third_party/make/loadapi.c \
third_party/make/main.c \
third_party/make/misc.c \
third_party/make/output.c \
third_party/make/posixos.c \
third_party/make/read.c \
third_party/make/remake.c \
third_party/make/remote-stub.c \
third_party/make/rule.c \
third_party/make/strcache.c \
third_party/make/variable.c \
third_party/make/version.c \
third_party/make/vpath.c
THIRD_PARTY_MAKE_SRCS = \
$(THIRD_PARTY_MAKE_SRCS_BASE) \
$(THIRD_PARTY_MAKE_SRCS_LIB)
THIRD_PARTY_MAKE_OBJS = \
$(THIRD_PARTY_MAKE_SRCS:%.c=o/$(MODE)/%.o)
THIRD_PARTY_MAKE_DIRECTDEPS = \
LIBC_CALLS \
LIBC_ELF \
LIBC_FMT \
LIBC_INTRIN \
LIBC_LOG \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_RUNTIME \
LIBC_STDIO \
LIBC_STR \
LIBC_SOCK \
LIBC_NT_KERNEL32 \
LIBC_SYSV \
LIBC_SYSV_CALLS \
LIBC_TIME \
LIBC_TINYMATH \
LIBC_X \
THIRD_PARTY_COMPILER_RT \
THIRD_PARTY_MUSL \
THIRD_PARTY_GDTOA
THIRD_PARTY_MAKE_DEPS := \
$(call uniq,$(foreach x,$(THIRD_PARTY_MAKE_DIRECTDEPS),$($(x))))
$(THIRD_PARTY_MAKE_A).pkg: \
$(THIRD_PARTY_MAKE_OBJS) \
$(foreach x,$(THIRD_PARTY_MAKE_DIRECTDEPS),$($(x)_A).pkg)
$(THIRD_PARTY_MAKE_A): \
third_party/make/ \
$(THIRD_PARTY_MAKE_A).pkg \
$(filter-out %main.o,$(THIRD_PARTY_MAKE_OBJS))
o/$(MODE)/third_party/make/make.com.dbg: \
$(THIRD_PARTY_MAKE_DEPS) \
$(THIRD_PARTY_MAKE_A) \
$(THIRD_PARTY_MAKE_A).pkg \
o/$(MODE)/third_party/make/main.o \
$(CRT) \
$(APE_NO_MODIFY_SELF)
@$(APELINK)
o/$(MODE)/third_party/make/make.com: \
o/$(MODE)/third_party/make/make.com.dbg \
o/$(MODE)/third_party/zip/zip.com \
o/$(MODE)/tool/build/symtab.com \
$(VM)
@$(MAKE_OBJCOPY)
@$(MAKE_SYMTAB_CREATE)
@$(MAKE_SYMTAB_ZIP)
o/$(MODE)/third_party/make/strcache.o \
o/$(MODE)/third_party/make/expand.o \
o/$(MODE)/third_party/make/read.o: private \
OVERRIDE_CFLAGS += \
-O2
o/$(MODE)/third_party/make/hash.o: private \
OVERRIDE_CFLAGS += \
-O3
$(THIRD_PARTY_MAKE_OBJS): private \
OVERRIDE_CFLAGS += \
-DNO_ARCHIVES \
-DHAVE_CONFIG_H \
-DSTACK_FRAME_UNLIMITED \
-DINCLUDEDIR=\".\" \
-DLIBDIR=\".\" \
-DLOCALEDIR=\".\"
.PHONY: o/$(MODE)/third_party/make
o/$(MODE)/third_party/make: \
$(THIRD_PARTY_MAKE_BINS) \
$(THIRD_PARTY_MAKE_CHECKS)
| 4,996 | 185 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/ar.c | /* Interface to 'ar' archives for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
/**/
#include "libc/mem/alg.h"
#include "third_party/make/dep.h"
#include "third_party/make/filedef.h"
#include "third_party/musl/fnmatch.h"
/* clang-format off */
/* Return nonzero if NAME is an archive-member reference, zero if not. An
archive-member reference is a name like 'lib(member)' where member is a
non-empty string.
If a name like 'lib((entry))' is used, a fatal error is signaled at
the attempt to use this unsupported feature. */
int
ar_name (const char *name)
{
const char *p = strchr (name, '(');
const char *end;
if (p == 0 || p == name)
return 0;
end = p + strlen (p) - 1;
if (*end != ')' || end == p + 1)
return 0;
if (p[1] == '(' && end[-1] == ')')
OS (fatal, NILF, _("attempt to use unsupported feature: '%s'"), name);
return 1;
}
/* Parse the archive-member reference NAME into the archive and member names.
Creates one allocated string containing both names, pointed to by ARNAME_P.
MEMNAME_P points to the member. */
void
ar_parse_name (const char *name, char **arname_p, char **memname_p)
{
char *p;
*arname_p = xstrdup (name);
p = strchr (*arname_p, '(');
*(p++) = '\0';
p[strlen (p) - 1] = '\0';
*memname_p = p;
}
/* This function is called by 'ar_scan' to find which member to look at. */
/* ARGSUSED */
static long int
ar_member_date_1 (int desc UNUSED, const char *mem, int truncated,
long int hdrpos UNUSED, long int datapos UNUSED,
long int size UNUSED, long int date,
int uid UNUSED, int gid UNUSED, unsigned int mode UNUSED,
const void *name)
{
return ar_name_equal (name, mem, truncated) ? date : 0;
}
/* Return the modtime of NAME. */
time_t
ar_member_date (const char *name)
{
char *arname;
char *memname;
long int val;
ar_parse_name (name, &arname, &memname);
/* Make sure we know the modtime of the archive itself because we are
likely to be called just before commands to remake a member are run,
and they will change the archive itself.
But we must be careful not to enter_file the archive itself if it does
not exist, because pattern_search assumes that files found in the data
base exist or can be made. */
{
struct file *arfile;
arfile = lookup_file (arname);
if (arfile == 0 && file_exists_p (arname))
arfile = enter_file (strcache_add (arname));
if (arfile != 0)
(void) f_mtime (arfile, 0);
}
val = ar_scan (arname, ar_member_date_1, memname);
free (arname);
return (val <= 0 ? (time_t) -1 : (time_t) val);
}
/* Set the archive-member NAME's modtime to now. */
int
ar_touch (const char *name)
{
char *arname, *memname;
int val;
ar_parse_name (name, &arname, &memname);
/* Make sure we know the modtime of the archive itself before we
touch the member, since this will change the archive modtime. */
{
struct file *arfile;
arfile = enter_file (strcache_add (arname));
f_mtime (arfile, 0);
}
val = 1;
switch (ar_member_touch (arname, memname))
{
case -1:
OS (error, NILF, _("touch: Archive '%s' does not exist"), arname);
break;
case -2:
OS (error, NILF, _("touch: '%s' is not a valid archive"), arname);
break;
case -3:
perror_with_name ("touch: ", arname);
break;
case 1:
OSS (error, NILF,
_("touch: Member '%s' does not exist in '%s'"), memname, arname);
break;
case 0:
val = 0;
break;
default:
OS (error, NILF,
_("touch: Bad return code from ar_member_touch on '%s'"), name);
}
free (arname);
return val;
}
/* State of an 'ar_glob' run, passed to 'ar_glob_match'. */
/* On VMS, (object) modules in libraries do not have suffixes. That is, to
find a match for a pattern, the pattern must not have any suffix. So the
suffix of the pattern is saved and the pattern is stripped (ar_glob).
If there is a match and the match, which is a module name, is added to
the chain, the saved suffix is added back to construct a source filename
(ar_glob_match). */
struct ar_glob_state
{
const char *arname;
const char *pattern;
size_t size;
struct nameseq *chain;
unsigned int n;
};
/* This function is called by 'ar_scan' to match one archive
element against the pattern in STATE. */
static long int
ar_glob_match (int desc UNUSED, const char *mem, int truncated UNUSED,
long int hdrpos UNUSED, long int datapos UNUSED,
long int size UNUSED, long int date UNUSED, int uid UNUSED,
int gid UNUSED, unsigned int mode UNUSED, const void *arg)
{
struct ar_glob_state *state = (struct ar_glob_state *)arg;
if (fnmatch (state->pattern, mem, FNM_PATHNAME|FNM_PERIOD) == 0)
{
/* We have a match. Add it to the chain. */
struct nameseq *new = xcalloc (state->size);
new->name = strcache_add(concat(4, state->arname, "(", mem, ")"));
new->next = state->chain;
state->chain = new;
++state->n;
}
return 0L;
}
/* Return nonzero if PATTERN contains any metacharacters.
Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
static int
ar_glob_pattern_p (const char *pattern, int quote)
{
const char *p;
int opened = 0;
for (p = pattern; *p != '\0'; ++p)
switch (*p)
{
case '?':
case '*':
return 1;
case '\\':
if (quote)
++p;
break;
case '[':
opened = 1;
break;
case ']':
if (opened)
return 1;
break;
}
return 0;
}
/* Glob for MEMBER_PATTERN in archive ARNAME.
Return a malloc'd chain of matching elements (or nil if none). */
struct nameseq *
ar_glob (const char *arname, const char *member_pattern, size_t size)
{
struct ar_glob_state state;
struct nameseq *n;
const char **names;
unsigned int i;
if (! ar_glob_pattern_p (member_pattern, 1))
return 0;
/* Scan the archive for matches.
ar_glob_match will accumulate them in STATE.chain. */
state.arname = arname;
state.pattern = member_pattern;
state.size = size;
state.chain = 0;
state.n = 0;
ar_scan (arname, ar_glob_match, &state);
if (state.chain == 0)
return 0;
/* Now put the names into a vector for sorting. */
names = alloca (state.n * sizeof (const char *));
i = 0;
for (n = state.chain; n != 0; n = n->next)
names[i++] = n->name;
/* Sort them alphabetically. */
/* MSVC erroneously warns without a cast here. */
qsort ((void *)names, i, sizeof (*names), alpha_compare);
/* Put them back into the chain in the sorted order. */
i = 0;
for (n = state.chain; n != 0; n = n->next)
n->name = names[i++];
return state.chain;
}
| 7,571 | 282 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/dir.c | /* Directory hashing for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
/**/
#include "libc/calls/struct/dirent.h"
#include "third_party/make/dep.h"
#include "third_party/make/filedef.h"
#include "third_party/make/hash.h"
#include "third_party/musl/glob.h"
/* clang-format off */
#ifndef __ptr_t
#define __ptr_t void *
#endif
#define gl_readdir __dummy2[1]
#define gl_opendir __dummy2[2]
#define gl_closedir __dummy2[0]
#define gl_lstat __dummy2[3]
#define gl_stat __dummy2[4]
#ifdef HAVE_DIRENT_H
#define NAMLEN(dirent) strlen((dirent)->d_name)
#else
#define dirent direct
#define NAMLEN(dirent) (dirent)->d_namlen
#endif
/* In GNU systems, <dirent.h> defines this macro for us. */
#ifdef _D_NAMLEN
#undef NAMLEN
#define NAMLEN(d) _D_NAMLEN(d)
#endif
#if (defined(POSIX) || defined(VMS) || defined(WINDOWS32)) && \
!defined(__GNU_LIBRARY__)
/* Posix does not require that the d_ino field be present, and some
systems do not provide it. */
#define REAL_DIR_ENTRY(dp) 1
#define FAKE_DIR_ENTRY(dp)
#else
#define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
#define FAKE_DIR_ENTRY(dp) (dp->d_ino = 1)
#endif /* POSIX */
#ifdef HAVE_CASE_INSENSITIVE_FS
static const char *downcase(const char *filename) {
static PATH_VAR(new_filename);
char *df;
if (filename == 0) return 0;
df = new_filename;
while (*filename != '\0') {
*df++ = tolower((unsigned char)*filename);
++filename;
}
*df = 0;
return new_filename;
}
#endif /* HAVE_CASE_INSENSITIVE_FS */
/* Hash table of directories. */
#ifndef DIRECTORY_BUCKETS
#define DIRECTORY_BUCKETS 199
#endif
struct directory_contents {
dev_t dev; /* Device and inode numbers of this dir. */
#ifdef WINDOWS32
/* Inode means nothing on WINDOWS32. Even file key information is
* unreliable because it is random per file open and undefined for remote
* filesystems. The most unique attribute I can come up with is the fully
* qualified name of the directory. Beware though, this is also
* unreliable. I'm open to suggestion on a better way to emulate inode. */
char *path_key;
time_t ctime;
time_t mtime; /* controls check for stale directory cache */
int fs_flags; /* FS_FAT, FS_NTFS, ... */
#define FS_FAT 0x1
#define FS_NTFS 0x2
#define FS_UNKNOWN 0x4
#else
ino_t ino;
#endif /* WINDOWS32 */
struct hash_table dirfiles; /* Files in this directory. */
DIR *dirstream; /* Stream reading this directory. */
};
static unsigned long directory_contents_hash_1(const void *key_0) {
const struct directory_contents *key = key_0;
unsigned long hash;
#ifdef WINDOWS32
hash = 0;
ISTRING_HASH_1(key->path_key, hash);
hash ^= ((unsigned int)key->dev << 4) ^ (unsigned int)key->ctime;
#else
hash = ((unsigned int)key->dev << 4) ^ (unsigned int)key->ino;
#endif /* WINDOWS32 */
return hash;
}
static unsigned long directory_contents_hash_2(const void *key_0) {
const struct directory_contents *key = key_0;
unsigned long hash;
#ifdef WINDOWS32
hash = 0;
ISTRING_HASH_2(key->path_key, hash);
hash ^= ((unsigned int)key->dev << 4) ^ (unsigned int)~key->ctime;
#else
hash = ((unsigned int)key->dev << 4) ^ (unsigned int)~key->ino;
#endif /* WINDOWS32 */
return hash;
}
/* Sometimes it's OK to use subtraction to get this value:
result = X - Y;
But, if we're not sure of the type of X and Y they may be too large for an
int (on a 64-bit system for example). So, use ?: instead.
See Savannah bug #15534.
NOTE! This macro has side-effects!
*/
#define MAKECMP(_x, _y) ((_x) < (_y) ? -1 : ((_x) == (_y) ? 0 : 1))
static int directory_contents_hash_cmp(const void *xv, const void *yv) {
const struct directory_contents *x = xv;
const struct directory_contents *y = yv;
int result;
#ifdef WINDOWS32
ISTRING_COMPARE(x->path_key, y->path_key, result);
if (result) return result;
result = MAKECMP(x->ctime, y->ctime);
if (result) return result;
#else
result = MAKECMP(x->ino, y->ino);
if (result) return result;
#endif /* WINDOWS32 */
return MAKECMP(x->dev, y->dev);
}
/* Table of directory contents hashed by device and inode number. */
static struct hash_table directory_contents;
struct directory {
const char *name; /* Name of the directory. */
/* The directory's contents. This data may be shared by several
entries in the hash table, which refer to the same directory
(identified uniquely by 'dev' and 'ino') under different names. */
struct directory_contents *contents;
};
static unsigned long directory_hash_1(const void *key) {
return_ISTRING_HASH_1(((const struct directory *)key)->name);
}
static unsigned long directory_hash_2(const void *key) {
return_ISTRING_HASH_2(((const struct directory *)key)->name);
}
static int directory_hash_cmp(const void *x, const void *y) {
return_ISTRING_COMPARE(((const struct directory *)x)->name,
((const struct directory *)y)->name);
}
/* Table of directories hashed by name. */
static struct hash_table directories;
/* Never have more than this many directories open at once. */
#define MAX_OPEN_DIRECTORIES 10
static unsigned int open_directories = 0;
/* Hash table of files in each directory. */
struct dirfile {
const char *name; /* Name of the file. */
size_t length;
short impossible; /* This file is impossible. */
unsigned char type;
};
static unsigned long dirfile_hash_1(const void *key) {
return_ISTRING_HASH_1(((struct dirfile const *)key)->name);
}
static unsigned long dirfile_hash_2(const void *key) {
return_ISTRING_HASH_2(((struct dirfile const *)key)->name);
}
static int dirfile_hash_cmp(const void *xv, const void *yv) {
const struct dirfile *x = xv;
const struct dirfile *y = yv;
int result = (int)(x->length - y->length);
if (result) return result;
return_ISTRING_COMPARE(x->name, y->name);
}
#ifndef DIRFILE_BUCKETS
#define DIRFILE_BUCKETS 107
#endif
static int dir_contents_file_exists_p(struct directory_contents *dir,
const char *filename);
static struct directory *find_directory(const char *name);
/* Find the directory named NAME and return its 'struct directory'. */
static struct directory *find_directory(const char *name) {
struct directory *dir;
struct directory **dir_slot;
struct directory dir_key;
dir_key.name = name;
dir_slot = (struct directory **)hash_find_slot(&directories, &dir_key);
dir = *dir_slot;
if (HASH_VACANT(dir)) {
/* The directory was not found. Create a new entry for it. */
const char *p = name + strlen(name);
struct stat st;
int r;
dir = xmalloc(sizeof(struct directory));
#if defined(HAVE_CASE_INSENSITIVE_FS) && defined(VMS)
/* Todo: Why is this only needed on VMS? */
{
char *lname = downcase_inplace(xstrdup(name));
dir->name = strcache_add_len(lname, p - name);
free(lname);
}
#else
dir->name = strcache_add_len(name, p - name);
#endif
hash_insert_at(&directories, dir, dir_slot);
/* The directory is not in the name hash table.
Find its device and inode numbers, and look it up by them. */
#if defined(WINDOWS32)
{
char tem[MAXPATHLEN], *tstart, *tend;
/* Remove any trailing slashes. Windows32 stat fails even on
valid directories if they end in a slash. */
memcpy(tem, name, p - name + 1);
tstart = tem;
if (tstart[1] == ':') tstart += 2;
for (tend = tem + (p - name - 1);
tend > tstart && (*tend == '/' || *tend == '\\'); tend--)
*tend = '\0';
r = stat(tem, &st);
}
#else
EINTRLOOP(r, stat(name, &st));
#endif
if (r < 0) {
/* Couldn't stat the directory. Mark this by
setting the 'contents' member to a nil pointer. */
dir->contents = 0;
} else {
/* Search the contents hash table; device and inode are the key. */
#ifdef WINDOWS32
char *w32_path;
#endif
struct directory_contents *dc;
struct directory_contents **dc_slot;
struct directory_contents dc_key;
dc_key.dev = st.st_dev;
#ifdef WINDOWS32
dc_key.path_key = w32_path = w32ify(name, 1);
dc_key.ctime = st.st_ctime;
#else
dc_key.ino = st.st_ino;
#endif
dc_slot = (struct directory_contents **)hash_find_slot(
&directory_contents, &dc_key);
dc = *dc_slot;
if (HASH_VACANT(dc)) {
/* Nope; this really is a directory we haven't seen before. */
#ifdef WINDOWS32
char fs_label[BUFSIZ];
char fs_type[BUFSIZ];
unsigned long fs_serno;
unsigned long fs_flags;
unsigned long fs_len;
#endif
dc = (struct directory_contents *)xmalloc(
sizeof(struct directory_contents));
/* Enter it in the contents hash table. */
dc->dev = st.st_dev;
#ifdef WINDOWS32
dc->path_key = xstrdup(w32_path);
dc->ctime = st.st_ctime;
dc->mtime = st.st_mtime;
/* NTFS is the only WINDOWS32 filesystem that bumps mtime on a
directory when files are added/deleted from a directory. */
w32_path[3] = '\0';
if (GetVolumeInformation(w32_path, fs_label, sizeof(fs_label),
&fs_serno, &fs_len, &fs_flags, fs_type,
sizeof(fs_type)) == FALSE)
dc->fs_flags = FS_UNKNOWN;
else if (!strcmp(fs_type, "FAT"))
dc->fs_flags = FS_FAT;
else if (!strcmp(fs_type, "NTFS"))
dc->fs_flags = FS_NTFS;
else
dc->fs_flags = FS_UNKNOWN;
#else
dc->ino = st.st_ino;
#endif /* WINDOWS32 */
hash_insert_at(&directory_contents, dc, dc_slot);
ENULLLOOP(dc->dirstream, opendir(name));
if (dc->dirstream == 0)
/* Couldn't open the directory. Mark this by setting the
'files' member to a nil pointer. */
dc->dirfiles.ht_vec = 0;
else {
hash_init(&dc->dirfiles, DIRFILE_BUCKETS, dirfile_hash_1,
dirfile_hash_2, dirfile_hash_cmp);
/* Keep track of how many directories are open. */
++open_directories;
if (open_directories == MAX_OPEN_DIRECTORIES)
/* We have too many directories open already.
Read the entire directory and then close it. */
dir_contents_file_exists_p(dc, 0);
}
}
/* Point the name-hashed entry for DIR at its contents data. */
dir->contents = dc;
}
}
return dir;
}
/* Return 1 if the name FILENAME is entered in DIR's hash table.
FILENAME must contain no slashes. */
static int dir_contents_file_exists_p(struct directory_contents *dir,
const char *filename) {
struct dirfile *df;
struct dirent *d;
#ifdef WINDOWS32
struct stat st;
int rehash = 0;
#endif
if (dir == 0 || dir->dirfiles.ht_vec == 0)
/* The directory could not be stat'd or opened. */
return 0;
#ifdef HAVE_CASE_INSENSITIVE_FS
filename = downcase(filename);
#endif
if (filename != 0) {
struct dirfile dirfile_key;
if (*filename == '\0') {
/* Checking if the directory exists. */
return 1;
}
dirfile_key.name = filename;
dirfile_key.length = strlen(filename);
df = hash_find_item(&dir->dirfiles, &dirfile_key);
if (df) return !df->impossible;
}
/* The file was not found in the hashed list.
Try to read the directory further. */
if (dir->dirstream == 0) {
#ifdef WINDOWS32
/*
* Check to see if directory has changed since last read. FAT
* filesystems force a rehash always as mtime does not change
* on directories (ugh!).
*/
if (dir->path_key) {
if ((dir->fs_flags & FS_FAT) != 0) {
dir->mtime = time((time_t *)0);
rehash = 1;
} else if (stat(dir->path_key, &st) == 0 && st.st_mtime > dir->mtime) {
/* reset date stamp to show most recent re-process. */
dir->mtime = st.st_mtime;
rehash = 1;
}
/* If it has been already read in, all done. */
if (!rehash) return 0;
/* make sure directory can still be opened; if not return. */
dir->dirstream = opendir(dir->path_key);
if (!dir->dirstream) return 0;
} else
#endif
/* The directory has been all read in. */
return 0;
}
while (1) {
/* Enter the file in the hash table. */
size_t len;
struct dirfile dirfile_key;
struct dirfile **dirfile_slot;
ENULLLOOP(d, readdir(dir->dirstream));
if (d == 0) {
if (errno) pfatal_with_name("INTERNAL: readdir");
break;
}
if (!REAL_DIR_ENTRY(d)) continue;
len = NAMLEN(d);
dirfile_key.name = d->d_name;
dirfile_key.length = len;
dirfile_slot =
(struct dirfile **)hash_find_slot(&dir->dirfiles, &dirfile_key);
#ifdef WINDOWS32
/*
* If re-reading a directory, don't cache files that have
* already been discovered.
*/
if (!rehash || HASH_VACANT(*dirfile_slot))
#endif
{
df = xmalloc(sizeof(struct dirfile));
#if defined(HAVE_CASE_INSENSITIVE_FS) && defined(VMS)
/* TODO: Why is this only needed on VMS? */
df->name = strcache_add_len(downcase_inplace(d->d_name), len);
#else
df->name = strcache_add_len(d->d_name, len);
#endif
#ifdef HAVE_STRUCT_DIRENT_D_TYPE
df->type = d->d_type;
#endif
df->length = len;
df->impossible = 0;
hash_insert_at(&dir->dirfiles, df, dirfile_slot);
}
/* Check if the name matches the one we're searching for. */
if (filename != 0 && patheq(d->d_name, filename)) return 1;
}
/* If the directory has been completely read in,
close the stream and reset the pointer to nil. */
if (d == 0) {
--open_directories;
closedir(dir->dirstream);
dir->dirstream = 0;
}
return 0;
}
/* Return 1 if the name FILENAME in directory DIRNAME
is entered in the dir hash table.
FILENAME must contain no slashes. */
int dir_file_exists_p(const char *dirname, const char *filename) {
return dir_contents_file_exists_p(find_directory(dirname)->contents,
filename);
}
/* Return 1 if the file named NAME exists. */
int file_exists_p(const char *name) {
const char *dirend;
const char *dirname;
const char *slash;
#ifndef NO_ARCHIVES
if (ar_name(name)) return ar_member_date(name) != (time_t)-1;
#endif
dirend = strrchr(name, '/');
#ifdef HAVE_DOS_PATHS
/* Forward and backslashes might be mixed. We need the rightmost one. */
{
const char *bslash = strrchr(name, '\\');
if (!dirend || bslash > dirend) dirend = bslash;
/* The case of "d:file". */
if (!dirend && name[0] && name[1] == ':') dirend = name + 1;
}
#endif /* HAVE_DOS_PATHS */
if (dirend == 0) return dir_file_exists_p(".", name);
slash = dirend;
if (dirend == name)
dirname = "/";
else {
char *p;
#ifdef HAVE_DOS_PATHS
/* d:/ and d: are *very* different... */
if (dirend < name + 3 && name[1] == ':' &&
(*dirend == '/' || *dirend == '\\' || *dirend == ':'))
dirend++;
#endif
p = alloca(dirend - name + 1);
memcpy(p, name, dirend - name);
p[dirend - name] = '\0';
dirname = p;
}
slash++;
return dir_file_exists_p(dirname, slash);
}
/* Mark FILENAME as 'impossible' for 'file_impossible_p'.
This means an attempt has been made to search for FILENAME
as an intermediate file, and it has failed. */
void file_impossible(const char *filename) {
const char *dirend;
const char *p = filename;
struct directory *dir;
struct dirfile *new;
dirend = strrchr(p, '/');
#ifdef HAVE_DOS_PATHS
/* Forward and backslashes might be mixed. We need the rightmost one. */
{
const char *bslash = strrchr(p, '\\');
if (!dirend || bslash > dirend) dirend = bslash;
/* The case of "d:file". */
if (!dirend && p[0] && p[1] == ':') dirend = p + 1;
}
#endif /* HAVE_DOS_PATHS */
if (dirend == 0)
dir = find_directory(".");
else {
const char *dirname;
const char *slash = dirend;
if (dirend == p)
dirname = "/";
else {
char *cp;
#ifdef HAVE_DOS_PATHS
/* d:/ and d: are *very* different... */
if (dirend < p + 3 && p[1] == ':' &&
(*dirend == '/' || *dirend == '\\' || *dirend == ':'))
dirend++;
#endif
cp = alloca(dirend - p + 1);
memcpy(cp, p, dirend - p);
cp[dirend - p] = '\0';
dirname = cp;
}
dir = find_directory(dirname);
filename = p = slash + 1;
}
if (dir->contents == 0)
/* The directory could not be stat'd. We allocate a contents
structure for it, but leave it out of the contents hash table. */
dir->contents = xcalloc(sizeof(struct directory_contents));
if (dir->contents->dirfiles.ht_vec == 0) {
hash_init(&dir->contents->dirfiles, DIRFILE_BUCKETS, dirfile_hash_1,
dirfile_hash_2, dirfile_hash_cmp);
}
/* Make a new entry and put it in the table. */
new = xmalloc(sizeof(struct dirfile));
new->length = strlen(filename);
#if defined(HAVE_CASE_INSENSITIVE_FS) && defined(VMS)
/* todo: Why is this only needed on VMS? */
new->name = strcache_add_len(downcase(filename), new->length);
#else
new->name = strcache_add_len(filename, new->length);
#endif
new->impossible = 1;
hash_insert(&dir->contents->dirfiles, new);
}
/* Return nonzero if FILENAME has been marked impossible. */
int file_impossible_p(const char *filename) {
const char *dirend;
struct directory_contents *dir;
struct dirfile *dirfile;
struct dirfile dirfile_key;
dirend = strrchr(filename, '/');
#ifdef HAVE_DOS_PATHS
/* Forward and backslashes might be mixed. We need the rightmost one. */
{
const char *bslash = strrchr(filename, '\\');
if (!dirend || bslash > dirend) dirend = bslash;
/* The case of "d:file". */
if (!dirend && filename[0] && filename[1] == ':') dirend = filename + 1;
}
#endif /* HAVE_DOS_PATHS */
if (dirend == 0)
dir = find_directory(".")->contents;
else {
const char *dirname;
const char *slash = dirend;
if (dirend == filename)
dirname = "/";
else {
char *cp;
#ifdef HAVE_DOS_PATHS
/* d:/ and d: are *very* different... */
if (dirend < filename + 3 && filename[1] == ':' &&
(*dirend == '/' || *dirend == '\\' || *dirend == ':'))
dirend++;
#endif
cp = alloca(dirend - filename + 1);
memcpy(cp, filename, dirend - filename);
cp[dirend - filename] = '\0';
dirname = cp;
}
dir = find_directory(dirname)->contents;
filename = slash + 1;
}
if (dir == 0 || dir->dirfiles.ht_vec == 0)
/* There are no files entered for this directory. */
return 0;
#ifdef HAVE_CASE_INSENSITIVE_FS
filename = downcase(filename);
#endif
dirfile_key.name = filename;
dirfile_key.length = strlen(filename);
dirfile = hash_find_item(&dir->dirfiles, &dirfile_key);
if (dirfile) return dirfile->impossible;
return 0;
}
/* Return the already allocated name in the
directory hash table that matches DIR. */
const char *dir_name(const char *dir) {
return find_directory(dir)->name;
}
/* Print the data base of directories. */
void print_dir_data_base(void) {
unsigned int files;
unsigned int impossible;
struct directory **dir_slot;
struct directory **dir_end;
puts(_("\n# Directories\n"));
files = impossible = 0;
dir_slot = (struct directory **)directories.ht_vec;
dir_end = dir_slot + directories.ht_size;
for (; dir_slot < dir_end; dir_slot++) {
struct directory *dir = *dir_slot;
if (!HASH_VACANT(dir)) {
if (dir->contents == 0)
printf(_("# %s: could not be stat'd.\n"), dir->name);
else if (dir->contents->dirfiles.ht_vec == 0) {
printf(_("# %s (device %ld, inode %ld): could not be opened.\n"),
dir->name, (long int)dir->contents->dev,
(long int)dir->contents->ino);
} else {
unsigned int f = 0;
unsigned int im = 0;
struct dirfile **files_slot;
struct dirfile **files_end;
files_slot = (struct dirfile **)dir->contents->dirfiles.ht_vec;
files_end = files_slot + dir->contents->dirfiles.ht_size;
for (; files_slot < files_end; files_slot++) {
struct dirfile *df = *files_slot;
if (!HASH_VACANT(df)) {
if (df->impossible)
++im;
else
++f;
}
}
printf(_("# %s (device %ld, inode %ld): "), dir->name,
(long)dir->contents->dev, (long)dir->contents->ino);
if (f == 0)
fputs(_("No"), stdout);
else
printf("%u", f);
fputs(_(" files, "), stdout);
if (im == 0)
fputs(_("no"), stdout);
else
printf("%u", im);
fputs(_(" impossibilities"), stdout);
if (dir->contents->dirstream == 0)
puts(".");
else
puts(_(" so far."));
files += f;
impossible += im;
}
}
}
fputs("\n# ", stdout);
if (files == 0)
fputs(_("No"), stdout);
else
printf("%u", files);
fputs(_(" files, "), stdout);
if (impossible == 0)
fputs(_("no"), stdout);
else
printf("%u", impossible);
printf(_(" impossibilities in %lu directories.\n"), directories.ht_fill);
}
/* Hooks for globbing. */
/* Structure describing state of iterating through a directory hash table. */
struct dirstream {
struct directory_contents *contents; /* The directory being read. */
struct dirfile **dirfile_slot; /* Current slot in table. */
};
/* Forward declarations. */
static __ptr_t open_dirstream(const char *);
static struct dirent *read_dirstream(__ptr_t);
static __ptr_t open_dirstream(const char *directory) {
struct dirstream *new;
struct directory *dir = find_directory(directory);
if (dir->contents == 0 || dir->contents->dirfiles.ht_vec == 0)
/* DIR->contents is nil if the directory could not be stat'd.
DIR->contents->dirfiles is nil if it could not be opened. */
return 0;
/* Read all the contents of the directory now. There is no benefit
in being lazy, since glob will want to see every file anyway. */
dir_contents_file_exists_p(dir->contents, 0);
new = xmalloc(sizeof(struct dirstream));
new->contents = dir->contents;
new->dirfile_slot = (struct dirfile **)new->contents->dirfiles.ht_vec;
return (__ptr_t) new;
}
static struct dirent *read_dirstream(__ptr_t stream) {
static char *buf;
static size_t bufsz;
struct dirstream *const ds = (struct dirstream *)stream;
struct directory_contents *dc = ds->contents;
struct dirfile **dirfile_end =
(struct dirfile **)dc->dirfiles.ht_vec + dc->dirfiles.ht_size;
while (ds->dirfile_slot < dirfile_end) {
struct dirfile *df = *ds->dirfile_slot++;
if (!HASH_VACANT(df) && !df->impossible) {
/* The glob interface wants a 'struct dirent', so mock one up. */
struct dirent *d;
size_t len = df->length + 1;
size_t sz = sizeof(*d) - sizeof(d->d_name) + len;
if (sz > bufsz) {
bufsz *= 2;
if (sz > bufsz) bufsz = sz;
buf = xrealloc(buf, bufsz);
}
d = (struct dirent *)buf;
#ifdef __MINGW32__
#if __MINGW32_MAJOR_VERSION < 3 || \
(__MINGW32_MAJOR_VERSION == 3 && __MINGW32_MINOR_VERSION == 0)
d->d_name = xmalloc(len);
#endif
#endif
FAKE_DIR_ENTRY(d);
#ifdef _DIRENT_HAVE_D_NAMLEN
d->d_namlen = len - 1;
#endif
d->d_type = df->type;
memcpy(d->d_name, df->name, len);
return d;
}
}
return 0;
}
/* On 64 bit ReliantUNIX (5.44 and above) in LFS mode, stat() is actually a
* macro for stat64(). If stat is a macro, make a local wrapper function to
* invoke it.
*
* On MS-Windows, stat() "succeeds" for foo/bar/. where foo/bar is a
* regular file; fix that here.
*/
#if !defined(stat) && !defined(WINDOWS32) || defined(VMS)
#define local_stat stat
#else
static int local_stat(const char *path, struct stat *buf) {
int e;
#ifdef WINDOWS32
size_t plen = strlen(path);
/* Make sure the parent of "." exists and is a directory, not a
file. This is because 'stat' on Windows normalizes the argument
foo/. => foo without checking first that foo is a directory. */
if (plen > 1 && path[plen - 1] == '.' &&
(path[plen - 2] == '/' || path[plen - 2] == '\\')) {
char parent[MAXPATHLEN];
strncpy(parent, path, plen - 2);
parent[plen - 2] = '\0';
if (stat(parent, buf) < 0 || !_S_ISDIR(buf->st_mode)) return -1;
}
#endif
EINTRLOOP(e, stat(path, buf));
return e;
}
#endif
/* Similarly for lstat. */
#if !defined(lstat) && !defined(WINDOWS32) || defined(VMS)
#define local_lstat lstat
#elif defined(WINDOWS32)
/* Windows doesn't support lstat(). */
#define local_lstat local_stat
#else
static int local_lstat(const char *path, struct stat *buf) {
int e;
EINTRLOOP(e, lstat(path, buf));
return e;
}
#endif
void dir_setup_glob(glob_t *gl) {
gl->gl_offs = 0;
gl->gl_opendir = open_dirstream;
gl->gl_readdir = read_dirstream;
gl->gl_closedir = free;
gl->gl_lstat = local_lstat;
gl->gl_stat = local_stat;
}
void hash_init_directories(void) {
hash_init(&directories, DIRECTORY_BUCKETS, directory_hash_1, directory_hash_2,
directory_hash_cmp);
hash_init(&directory_contents, DIRECTORY_BUCKETS, directory_contents_hash_1,
directory_contents_hash_2, directory_contents_hash_cmp);
}
| 26,172 | 885 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/exitfail.c | /* clang-format off */
/* Failure exit status
Copyright (C) 2002-2003, 2005-2007, 2009-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
int volatile exit_failure = 1; /*TODO: this should be EXIT_FAILURE; */
| 847 | 20 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/job.c | /* Job execution and handling for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
/**/
#include "third_party/make/debug.h"
#include "third_party/make/filedef.h"
#include "third_party/make/job.h"
/**/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/pledge.h"
#include "libc/calls/pledge.internal.h"
#include "libc/calls/struct/bpf.h"
#include "libc/calls/struct/filter.h"
#include "libc/calls/struct/seccomp.h"
#include "libc/calls/struct/sysinfo.h"
#include "libc/calls/struct/timeval.h"
#include "libc/dce.h"
#include "libc/elf/def.h"
#include "libc/elf/elf.h"
#include "libc/elf/struct/ehdr.h"
#include "libc/elf/struct/phdr.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/fmt.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/promises.internal.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/log/backtrace.internal.h"
#include "libc/log/log.h"
#include "libc/log/rop.h"
#include "libc/macros.internal.h"
#include "libc/nexgen32e/kcpuids.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/audit.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/nrlinux.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/pr.h"
#include "libc/sysv/consts/prot.h"
#include "libc/sysv/consts/rlimit.h"
#include "libc/sysv/errfuns.h"
#include "libc/time/time.h"
#include "libc/x/x.h"
#include "third_party/libcxx/math.h"
#include "third_party/make/commands.h"
#include "third_party/make/dep.h"
#include "third_party/make/os.h"
#include "third_party/make/variable.h"
// clang-format off
#ifdef WINDOWS32
const char *default_shell = "sh.exe";
int no_default_sh_exe = 1;
int batch_mode_shell = 1;
HANDLE main_thread;
#else
const char *default_shell = "/bin/sh";
int batch_mode_shell = 0;
#endif
#define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
#define WAIT_T int
/* Different systems have different requirements for pid_t.
Plus we have to support gettext string translation... Argh. */
static const char *
pid2str (pid_t pid)
{
static char pidstring[100];
sprintf (pidstring, "%lu", (unsigned long) pid);
return pidstring;
}
static void free_child (struct child *);
static void start_job_command (struct child *child);
static int load_too_high (void);
static int job_next_command (struct child *);
static int start_waiting_job (struct child *);
/* Chain of all live (or recently deceased) children. */
struct child *children = 0;
/* Number of children currently running. */
unsigned int job_slots_used = 0;
/* Nonzero if the 'good' standard input is in use. */
static int good_stdin_used = 0;
/* Chain of children waiting to run until the load average goes down. */
static struct child *waiting_jobs = 0;
/* Non-zero if we use a *real* shell (always so on Unix). */
int unixy_shell = 1;
/* Number of jobs started in the current second. */
unsigned long job_counter = 0;
/* Number of jobserver tokens this instance is currently using. */
unsigned int jobserver_tokens = 0;
#ifdef WINDOWS32
/*
* The macro which references this function is defined in makeint.h.
*/
int
w32_kill (pid_t pid, int sig)
{
return ((process_kill ((HANDLE)pid, sig) == TRUE) ? 0 : -1);
}
/* This function creates a temporary file name with an extension specified
* by the unixy arg.
* Return an xmalloc'ed string of a newly created temp file and its
* file descriptor, or die. */
static char *
create_batch_file (char const *base, int unixy, int *fd)
{
const char *const ext = unixy ? "sh" : "bat";
const char *error_string = NULL;
char temp_path[MAXPATHLEN]; /* need to know its length */
unsigned path_size = GetTempPath (sizeof temp_path, temp_path);
int path_is_dot = 0;
/* The following variable is static so we won't try to reuse a name
that was generated a little while ago, because that file might
not be on disk yet, since we use FILE_ATTRIBUTE_TEMPORARY below,
which tells the OS it doesn't need to flush the cache to disk.
If the file is not yet on disk, we might think the name is
available, while it really isn't. This happens in parallel
builds, where Make doesn't wait for one job to finish before it
launches the next one. */
static unsigned uniq = 0;
static int second_loop = 0;
const size_t sizemax = strlen (base) + strlen (ext) + 10;
if (path_size == 0)
{
path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
path_is_dot = 1;
}
++uniq;
if (uniq >= 0x10000 && !second_loop)
{
/* If we already had 64K batch files in this
process, make a second loop through the numbers,
looking for free slots, i.e. files that were
deleted in the meantime. */
second_loop = 1;
uniq = 1;
}
while (path_size > 0 &&
path_size + sizemax < sizeof temp_path &&
!(uniq >= 0x10000 && second_loop))
{
unsigned size = sprintf (temp_path + path_size,
"%s%s-%x.%s",
temp_path[path_size - 1] == '\\' ? "" : "\\",
base, uniq, ext);
HANDLE h = CreateFile (temp_path, /* file name */
GENERIC_READ | GENERIC_WRITE, /* desired access */
0, /* no share mode */
NULL, /* default security attributes */
CREATE_NEW, /* creation disposition */
FILE_ATTRIBUTE_NORMAL | /* flags and attributes */
FILE_ATTRIBUTE_TEMPORARY, /* we'll delete it */
NULL); /* no template file */
if (h == INVALID_HANDLE_VALUE)
{
const DWORD er = GetLastError ();
if (er == ERROR_FILE_EXISTS || er == ERROR_ALREADY_EXISTS)
{
++uniq;
if (uniq == 0x10000 && !second_loop)
{
second_loop = 1;
uniq = 1;
}
}
/* the temporary path is not guaranteed to exist */
else if (path_is_dot == 0)
{
path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
path_is_dot = 1;
}
else
{
error_string = map_windows32_error_to_string (er);
break;
}
}
else
{
const unsigned final_size = path_size + size + 1;
char *const path = xmalloc (final_size);
memcpy (path, temp_path, final_size);
*fd = _open_osfhandle ((intptr_t)h, 0);
if (unixy)
{
char *p;
int ch;
for (p = path; (ch = *p) != 0; ++p)
if (ch == '\\')
*p = '/';
}
return path; /* good return */
}
}
*fd = -1;
if (error_string == NULL)
error_string = _("Cannot create a temporary file\n");
O (fatal, NILF, error_string);
/* not reached */
return NULL;
}
#endif /* WINDOWS32 */
/* determines whether path looks to be a Bourne-like shell. */
int
is_bourne_compatible_shell (const char *path)
{
/* List of known POSIX (or POSIX-ish) shells. */
static const char *unix_shells[] = {
"build/bootstrap/cocmd.com",
"false",
"dash",
"sh",
"bash",
"ksh",
"rksh",
"zsh",
"ash",
"dash",
NULL
};
const char **s;
/* find the rightmost '/' or '\\' */
const char *name = strrchr (path, '/');
char *p = strrchr (path, '\\');
if (name && p) /* take the max */
name = (name > p) ? name : p;
else if (p) /* name must be 0 */
name = p;
else if (!name) /* name and p must be 0 */
name = path;
if (*name == '/' || *name == '\\')
++name;
/* this should be able to deal with extensions on Windows-like systems */
for (s = unix_shells; *s != NULL; ++s)
{
#if defined(WINDOWS32) || defined(__MSDOS__)
size_t len = strlen (*s);
if ((strlen (name) >= len && STOP_SET (name[len], MAP_DOT|MAP_NUL))
&& strncasecmp (name, *s, len) == 0)
#else
if (strcmp (name, *s) == 0)
#endif
return 1; /* a known unix-style shell */
}
/* if not on the list, assume it's not a Bourne-like shell */
return 0;
}
extern sigset_t fatal_signal_set;
static void
block_sigs ()
{
sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
}
static void
unblock_sigs ()
{
sigprocmask (SIG_UNBLOCK, &fatal_signal_set, (sigset_t *) 0);
}
void
unblock_all_sigs ()
{
sigset_t empty;
sigemptyset (&empty);
sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
}
/* Write an error message describing the exit status given in
EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
Append "(ignored)" if IGNORED is nonzero. */
static void
child_error (struct child *child,
int exit_code, int exit_sig, int coredump, int ignored)
{
const char *pre = "*** ";
const char *post = "";
const char *dump = "";
const struct file *f = child->file;
const floc *flocp = &f->cmds->fileinfo;
const char *nm;
size_t l;
if (ignored && run_silent)
return;
if (exit_sig && coredump)
dump = _(" (core dumped)");
if (ignored)
{
pre = "";
post = _(" (ignored)");
}
if (! flocp->filenm)
nm = _("<builtin>");
else
{
char *a = alloca (strlen (flocp->filenm) + 6 + INTSTR_LENGTH + 1);
sprintf (a, "%s:%lu", flocp->filenm, flocp->lineno + flocp->offset);
nm = a;
}
l = strlen (pre) + strlen (nm) + strlen (f->name) + strlen (post);
OUTPUT_SET (&child->output);
show_goal_error ();
if (exit_sig == 0)
error (NILF, l + INTSTR_LENGTH,
_("%s[%s: %s] Error %d%s"), pre, nm, f->name, exit_code, post);
else
{
const char *s = strsignal (exit_sig);
error (NILF, l + strlen (s) + strlen (dump),
"%s[%s: %s] %s%s%s", pre, nm, f->name, s, dump, post);
}
OUTPUT_UNSET ();
}
/* [jart] manage temporary directories per rule */
bool
parse_bool (const char *s)
{
while (isspace (*s))
++s;
if (isdigit (*s))
return !! atoi (s);
return _startswithi (s, "true");
}
const char *
get_target_variable (const char *name,
size_t length,
struct file *file,
const char *dflt)
{
const struct variable *var;
if ((file &&
((var = lookup_variable_in_set (name, length,
file->variables->set)) ||
(file->pat_variables &&
(var = lookup_variable_in_set (name, length,
file->pat_variables->set))))) ||
(var = lookup_variable (name, length)))
return variable_expand (var->value);
else
return dflt;
}
const char *
get_tmpdir (struct file *file)
{
return get_target_variable (STRING_SIZE_TUPLE ("TMPDIR"), file, 0);
}
char *
new_tmpdir (const char *tmp, struct file *file)
{
const char *s;
int c, e, i, j;
char *dir, *tmpdir;
char cwd[PATH_MAX];
char path[PATH_MAX];
/* create temporary directory in tmp */
i = 0;
/* ensure tmpdir will be absolute */
if (tmp[0] != '/')
{
if (getcwd(cwd, sizeof(cwd)))
{
for (j = 0; cwd[j]; ++j)
if (i < PATH_MAX)
path[i++] = cwd[j];
if (i && path[i - 1] != '/')
if (i < PATH_MAX)
path[i++] = '/';
}
else
DB (DB_JOBS, (_("Failed to get current directory\n")));
}
/* copy old tmpdir */
for (j = 0; tmp[j]; ++j)
if (i < PATH_MAX)
path[i++] = tmp[j];
/* append slash */
if (i && path[i - 1] != '/')
if (i < PATH_MAX)
path[i++] = '/';
/* append target name safely */
for (j = 0; (c = file->name[j]); ++j)
{
if (isalnum(c))
c = tolower(c);
else
c = '_';
if (i < PATH_MAX)
path[i++] = c;
}
/* copy random template */
s = ".XXXXXX";
for (j = 0; s[j]; ++j)
if (i < PATH_MAX)
path[i++] = s[j];
/* add nul terminator */
if (i + 11 < PATH_MAX)
path[i] = 0;
else
{
DB (DB_JOBS, (_("Creating TMPDIR in %s for %s is too long\n"),
tmp, file->name));
return 0;
}
/* create temp directory with random data */
e = errno;
if (!(tmpdir = mkdtemp (path)) && errno == ENOENT)
{
/* create parent directories if necessary */
char *dir;
errno = e;
dir = xstrdup (path);
if (!makedirs (dirname (dir), 0700))
tmpdir = mkdtemp (path);
free (dir);
}
/* returned string must be free'd */
if (tmpdir)
{
tmpdir = xstrdup (tmpdir);
DB (DB_JOBS, (_("Created TMPDIR %s\n"), path));
}
else
DB (DB_JOBS, (_("Creating TMPDIR %s failed %s\n"),
path, strerror (errno)));
return tmpdir;
}
bool
get_file_timestamp (struct file *file)
{
int e;
struct stat st;
EINTRLOOP (e, stat (file->name, &st));
if (e == 0)
return FILE_TIMESTAMP_STAT_MODTIME (file->name, st);
else
return NONEXISTENT_MTIME;
}
void
delete_tmpdir (struct child *c)
{
if (!c->tmpdir) return;
DB (DB_JOBS, (_("Deleting TMPDIR %s\n"), c->tmpdir));
if (!isdirectory (c->tmpdir))
DB (DB_JOBS, (_("Warning TMPDIR %s doesn't exist\n"), c->tmpdir));
errno = 0;
if (rmrf (c->tmpdir))
DB (DB_JOBS, (_("Deleting TMPDIR %s failed %s\n"),
c->tmpdir, strerror(errno)));
free (c->tmpdir);
c->tmpdir = 0;
}
/* Handle a dead child. This handler may or may not ever be installed.
If we're using the jobserver feature without pselect(), we need it.
First, installing it ensures the read will interrupt on SIGCHLD. Second,
we close the dup'd read FD to ensure we don't enter another blocking read
without reaping all the dead children. In this case we don't need the
dead_children count.
If we don't have either waitpid or wait3, then make is unreliable, but we
use the dead_children count to reap children as best we can. */
static unsigned int dead_children = 0;
RETSIGTYPE
child_handler (int sig UNUSED)
{
++dead_children;
jobserver_signal ();
}
extern pid_t shell_function_pid;
/* Reap all dead children, storing the returned status and the new command
state ('cs_finished') in the 'file' member of the 'struct child' for the
dead child, and removing the child from the chain. In addition, if BLOCK
nonzero, we block in this function until we've reaped at least one
complete child, waiting for it to die if necessary. If ERR is nonzero,
print an error message first. */
void
reap_children (int block, int err)
{
WAIT_T status;
/* Initially, assume we have some. */
int reap_more = 1;
/* As long as:
We have at least one child outstanding OR a shell function in progress,
AND
We're blocking for a complete child OR there are more children to reap
we'll keep reaping children. */
while ((children != 0 || shell_function_pid != 0)
&& (block || reap_more))
{
unsigned int remote = 0;
pid_t pid;
int exit_code, exit_sig, coredump;
struct child *lastc, *c;
int child_failed;
int any_remote, any_local;
int dontcare;
if (err && block)
{
static int printed = 0;
/* We might block for a while, so let the user know why.
Only print this message once no matter how many jobs are left. */
fflush (stdout);
if (!printed)
O (error, NILF, _("*** Waiting for unfinished jobs...."));
printed = 1;
}
/* We have one less dead child to reap. As noted in
child_handler() above, this count is completely unimportant for
all modern, POSIX-y systems that support wait3() or waitpid().
The rest of this comment below applies only to early, broken
pre-POSIX systems. We keep the count only because... it's there...
The test and decrement are not atomic; if it is compiled into:
register = dead_children - 1;
dead_children = register;
a SIGCHLD could come between the two instructions.
child_handler increments dead_children.
The second instruction here would lose that increment. But the
only effect of dead_children being wrong is that we might wait
longer than necessary to reap a child, and lose some parallelism;
and we might print the "Waiting for unfinished jobs" message above
when not necessary. */
if (dead_children > 0)
--dead_children;
any_remote = 0;
any_local = shell_function_pid != 0;
lastc = 0;
for (c = children; c != 0; lastc = c, c = c->next)
{
any_remote |= c->remote;
any_local |= ! c->remote;
/* If pid < 0, this child never even started. Handle it. */
if (c->pid < 0)
{
exit_sig = 0;
coredump = 0;
/* According to POSIX, 127 is used for command not found. */
exit_code = 127;
goto process_child;
}
DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
c, c->file->name, pid2str (c->pid),
c->remote ? _(" (remote)") : ""));
}
/* First, check for remote children. */
if (any_remote)
pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
else
pid = 0;
if (pid > 0)
/* We got a remote child. */
remote = 1;
else if (pid < 0)
{
/* A remote status command failed miserably. Punt. */
remote_status_lose:
pfatal_with_name ("remote_status");
}
else
{
/* No remote children. Check for local children. */
if (any_local)
{
if (!block)
pid = WAIT_NOHANG (&status);
else
EINTRLOOP (pid, wait (&status));
}
else
pid = 0;
if (pid < 0)
{
/* The wait*() failed miserably. Punt. */
pfatal_with_name ("wait");
}
else if (pid > 0)
{
/* We got a child exit; chop the status word up. */
exit_code = WEXITSTATUS (status);
exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
coredump = WCOREDUMP (status);
}
else
{
/* No local children are dead. */
reap_more = 0;
if (!block || !any_remote)
break;
/* Now try a blocking wait for a remote child. */
pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
if (pid < 0)
goto remote_status_lose;
else if (pid == 0)
/* No remote children either. Finally give up. */
break;
/* We got a remote child. */
remote = 1;
}
}
/* Check if this is the child of the 'shell' function. */
if (!remote && pid == shell_function_pid)
{
shell_completed (exit_code, exit_sig);
break;
}
/* Search for a child matching the deceased one. */
lastc = 0;
for (c = children; c != 0; lastc = c, c = c->next)
if (c->pid == pid && c->remote == remote)
break;
if (c == 0)
/* An unknown child died.
Ignore it; it was inherited from our invoker. */
continue;
DB (DB_JOBS, (exit_sig == 0 && exit_code == 0
? _("Reaping winning child %p PID %s %s\n")
: _("Reaping losing child %p PID %s %s\n"),
c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
/* If we have started jobs in this second, remove one. */
if (job_counter)
--job_counter;
process_child:
/* Determine the failure status: 0 for success, 1 for updating target in
question mode, 2 for anything else. */
if (exit_sig == 0 && exit_code == 0)
child_failed = MAKE_SUCCESS;
else if (exit_sig == 0 && exit_code == 1 && question_flag && c->recursive)
child_failed = MAKE_TROUBLE;
else
child_failed = MAKE_FAILURE;
if (c->sh_batch_file)
{
int rm_status;
DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
c->sh_batch_file));
errno = 0;
rm_status = remove (c->sh_batch_file);
if (rm_status)
DB (DB_JOBS, (_("Cleaning up temp batch file %s failed (%d)\n"),
c->sh_batch_file, errno));
/* all done with memory */
free (c->sh_batch_file);
c->sh_batch_file = NULL;
}
/* If this child had the good stdin, say it is now free. */
if (c->good_stdin)
good_stdin_used = 0;
dontcare = c->dontcare;
if (child_failed && !c->noerror && !ignore_errors_flag)
{
/* The commands failed. Write an error message,
delete non-precious targets, and abort. */
static int delete_on_error = -1;
if (!dontcare && child_failed == MAKE_FAILURE)
child_error (c, exit_code, exit_sig, coredump, 0);
c->file->update_status = child_failed == MAKE_FAILURE ? us_failed : us_question;
if (delete_on_error == -1)
{
struct file *f = lookup_file (".DELETE_ON_ERROR");
delete_on_error = f != 0 && f->is_target;
}
if (exit_sig != 0 || delete_on_error)
{
delete_child_targets (c);
delete_tmpdir (c);
}
else if (c->file->touched &&
c->file->touched != get_file_timestamp (c->file))
/* If file was created just so it could be sandboxed, then
delete that file even if .DELETE_ON_ERROR isn't used,
but only if the command hasn't modified it. */
unlink (c->file->name);
}
else
{
if (child_failed)
{
/* The commands failed, but we don't care. */
child_error (c, exit_code, exit_sig, coredump, 1);
child_failed = 0;
}
/* If there are more commands to run, try to start them. */
if (job_next_command (c))
{
if (handling_fatal_signal)
{
/* Never start new commands while we are dying.
Since there are more commands that wanted to be run,
the target was not completely remade. So we treat
this as if a command had failed. */
c->file->update_status = us_failed;
}
else
{
#ifndef NO_OUTPUT_SYNC
/* If we're sync'ing per line, write the previous line's
output before starting the next one. */
if (output_sync == OUTPUT_SYNC_LINE)
output_dump (&c->output);
#endif
/* Check again whether to start remotely.
Whether or not we want to changes over time.
Also, start_remote_job may need state set up
by start_remote_job_p. */
c->remote = start_remote_job_p (0);
start_job_command (c);
/* Fatal signals are left blocked in case we were
about to put that child on the chain. But it is
already there, so it is safe for a fatal signal to
arrive now; it will clean up this child's targets. */
unblock_sigs ();
if (c->file->command_state == cs_running)
/* We successfully started the new command.
Loop to reap more children. */
continue;
}
if (c->file->update_status != us_success)
{
/* We failed to start the commands. */
delete_child_targets (c);
delete_tmpdir (c);
}
}
else
{
/* There are no more commands. We got through them all
without an unignored error. Now the target has been
successfully updated. */
c->file->update_status = us_success;
delete_tmpdir (c);
}
}
/* When we get here, all the commands for c->file are finished. */
#ifndef NO_OUTPUT_SYNC
/* Synchronize any remaining parallel output. */
output_dump (&c->output);
#endif
/* At this point c->file->update_status is success or failed. But
c->file->command_state is still cs_running if all the commands
ran; notice_finished_file looks for cs_running to tell it that
it's interesting to check the file's modtime again now. */
if (! handling_fatal_signal)
/* Notice if the target of the commands has been changed.
This also propagates its values for command_state and
update_status to its also_make files. */
notice_finished_file (c->file);
/* Block fatal signals while frobnicating the list, so that
children and job_slots_used are always consistent. Otherwise
a fatal signal arriving after the child is off the chain and
before job_slots_used is decremented would believe a child was
live and call reap_children again. */
block_sigs ();
if (c->pid > 0)
{
DB (DB_JOBS, (_("Removing child %p PID %s%s from chain.\n"),
c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
}
/* There is now another slot open. */
if (job_slots_used > 0)
job_slots_used -= c->jobslot;
/* Remove the child from the chain and free it. */
if (lastc == 0)
children = c->next;
else
lastc->next = c->next;
free_child (c);
unblock_sigs ();
/* If the job failed, and the -k flag was not given, die,
unless we are already in the process of dying. */
if (!err && child_failed && !dontcare && !keep_going_flag &&
/* fatal_error_signal will die with the right signal. */
!handling_fatal_signal)
die (child_failed);
/* Only block for one child. */
block = 0;
}
return;
}
/* Free the storage allocated for CHILD. */
static void
free_child (struct child *child)
{
output_close (&child->output);
if (!jobserver_tokens)
ONS (fatal, NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
child, child->file->name);
/* If we're using the jobserver and this child is not the only outstanding
job, put a token back into the pipe for it. */
if (jobserver_enabled () && jobserver_tokens > 1)
{
jobserver_release (1);
DB (DB_JOBS, (_("Released token for child %p (%s).\n"),
child, child->file->name));
}
--jobserver_tokens;
if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
return;
if (child->command_lines != 0)
{
unsigned int i;
for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
free (child->command_lines[i]);
free (child->command_lines);
}
if (child->environment != 0)
{
char **ep = child->environment;
while (*ep != 0)
free (*ep++);
free (child->environment);
}
free (child->tmpdir);
free (child->cmd_name);
free (child);
}
/* Start a job to run the commands specified in CHILD.
CHILD is updated to reflect the commands and ID of the child process.
NOTE: On return fatal signals are blocked! The caller is responsible
for calling 'unblock_sigs', once the new child is safely on the chain so
it can be cleaned up in the event of a fatal signal. */
static void
start_job_command (struct child *child)
{
int flags;
char *p;
# define FREE_ARGV(_a) do{ if (_a) { free ((_a)[0]); free (_a); } }while(0)
char **argv;
/* If we have a completely empty commandset, stop now. */
if (!child->command_ptr)
goto next_command;
/* Combine the flags parsed for the line itself with
the flags specified globally for this target. */
flags = (child->file->command_flags
| child->file->cmds->lines_flags[child->command_line - 1]);
p = child->command_ptr;
child->noerror = ((flags & COMMANDS_NOERROR) != 0);
while (*p != '\0')
{
if (*p == '@')
flags |= COMMANDS_SILENT;
else if (*p == '+')
flags |= COMMANDS_RECURSE;
else if (*p == '-')
child->noerror = 1;
/* Don't skip newlines. */
else if (!ISBLANK (*p))
break;
++p;
}
child->recursive = ((flags & COMMANDS_RECURSE) != 0);
/* Update the file's command flags with any new ones we found. We only
keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
now marking more commands recursive than should be in the case of
multiline define/endef scripts where only one line is marked "+". In
order to really fix this, we'll have to keep a lines_flags for every
actual line, after expansion. */
child->file->cmds->lines_flags[child->command_line - 1] |= flags & COMMANDS_RECURSE;
/* POSIX requires that a recipe prefix after a backslash-newline should
be ignored. Remove it now so the output is correct. */
{
char prefix = child->file->cmds->recipe_prefix;
char *p1, *p2;
p1 = p2 = p;
while (*p1 != '\0')
{
*(p2++) = *p1;
if (p1[0] == '\n' && p1[1] == prefix)
++p1;
++p1;
}
*p2 = *p1;
}
/* Figure out an argument list from this command line. */
{
char *end = 0;
argv = construct_command_argv (p, &end, child->file,
child->file->cmds->lines_flags[child->command_line - 1],
&child->sh_batch_file);
if (end == NULL)
child->command_ptr = NULL;
else
{
*end++ = '\0';
child->command_ptr = end;
}
}
/* If -q was given, say that updating 'failed' if there was any text on the
command line, or 'succeeded' otherwise. The exit status of 1 tells the
user that -q is saying 'something to do'; the exit status for a random
error is 2. */
if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
{
FREE_ARGV (argv);
child->file->update_status = us_question;
notice_finished_file (child->file);
return;
}
if (touch_flag && !(flags & COMMANDS_RECURSE))
{
/* Go on to the next command. It might be the recursive one.
We construct ARGV only to find the end of the command line. */
FREE_ARGV (argv);
argv = 0;
}
if (argv == 0)
{
next_command:
/* This line has no commands. Go to the next. */
if (job_next_command (child))
start_job_command (child);
else
{
/* No more commands. Make sure we're "running"; we might not be if
(e.g.) all commands were skipped due to -n. */
set_command_state (child->file, cs_running);
child->file->update_status = us_success;
notice_finished_file (child->file);
}
OUTPUT_UNSET();
return;
}
/* Are we going to synchronize this command's output? Do so if either we're
in SYNC_RECURSE mode or this command is not recursive. We'll also check
output_sync separately below in case it changes due to error. */
child->output.syncout = output_sync && (output_sync == OUTPUT_SYNC_RECURSE
|| !(flags & COMMANDS_RECURSE));
OUTPUT_SET (&child->output);
#ifndef NO_OUTPUT_SYNC
if (! child->output.syncout)
/* We don't want to sync this command: to avoid misordered
output ensure any already-synced content is written. */
output_dump (&child->output);
#endif
/* Print the command if appropriate. */
if (just_print_flag || trace_flag
|| (!(flags & COMMANDS_SILENT) && !run_silent))
OS (message, 0, "%s", p);
/* Tell update_goal_chain that a command has been started on behalf of
this target. It is important that this happens here and not in
reap_children (where we used to do it), because reap_children might be
reaping children from a different target. We want this increment to
guaranteedly indicate that a command was started for the dependency
chain (i.e., update_file recursion chain) we are processing. */
++commands_started;
/* Optimize an empty command. People use this for timestamp rules,
so avoid forking a useless shell. Do this after we increment
commands_started so make still treats this special case as if it
performed some action (makes a difference as to what messages are
printed, etc. */
if (
(argv[0] && is_bourne_compatible_shell (argv[0]))
&& (argv[1] && argv[1][0] == '-'
&&
((argv[1][1] == 'c' && argv[1][2] == '\0')
||
(argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
&& (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
&& argv[3] == NULL)
{
FREE_ARGV (argv);
goto next_command;
}
/* If -n was given, recurse to get the next line in the sequence. */
if (just_print_flag && !(flags & COMMANDS_RECURSE))
{
FREE_ARGV (argv);
goto next_command;
}
/* We're sure we're going to invoke a command: set up the output. */
output_start ();
/* Flush the output streams so they won't have things written twice. */
fflush (stdout);
fflush (stderr);
/* Decide whether to give this child the 'good' standard input
(one that points to the terminal or whatever), or the 'bad' one
that points to the read side of a broken pipe. */
child->good_stdin = !good_stdin_used;
if (child->good_stdin)
good_stdin_used = 1;
child->deleted = 0;
/* Set up the environment for the child. */
if (child->environment == 0)
child->environment = target_environment (child->file);
/* start_waiting_job has set CHILD->remote if we can start a remote job. */
if (child->remote)
{
int is_remote, used_stdin;
pid_t id;
if (start_remote_job (argv, child->environment,
child->good_stdin ? 0 : get_bad_stdin (),
&is_remote, &id, &used_stdin))
/* Don't give up; remote execution may fail for various reasons. If
so, simply run the job locally. */
goto run_local;
else
{
if (child->good_stdin && !used_stdin)
{
child->good_stdin = 0;
good_stdin_used = 0;
}
child->remote = is_remote;
child->pid = id;
}
}
else
{
/* Fork the child process. */
char **parent_environ;
run_local:
block_sigs ();
child->remote = 0;
parent_environ = environ;
jobserver_pre_child (flags & COMMANDS_RECURSE);
child->pid = child_execute_job ((struct childbase *)child,
child->good_stdin, argv, true);
environ = parent_environ; /* Restore value child may have clobbered. */
jobserver_post_child (flags & COMMANDS_RECURSE);
}
/* Bump the number of jobs started in this second. */
if (child->pid >= 0)
++job_counter;
/* Set the state to running. */
set_command_state (child->file, cs_running);
/* Free the storage used by the child's argument list. */
FREE_ARGV (argv);
OUTPUT_UNSET();
#undef FREE_ARGV
}
/* Try to start a child running.
Returns nonzero if the child was started (and maybe finished), or zero if
the load was too high and the child was put on the 'waiting_jobs' chain. */
static int
start_waiting_job (struct child *c)
{
struct file *f = c->file;
/* If we can start a job remotely, we always want to, and don't care about
the local load average. We record that the job should be started
remotely in C->remote for start_job_command to test. */
c->remote = start_remote_job_p (1);
/* If we are running at least one job already and the load average
is too high, make this one wait. */
if (!c->remote
&& ((job_slots_used > 0 && load_too_high ())
#ifdef WINDOWS32
|| process_table_full ()
#endif
))
{
/* Put this child on the chain of children waiting for the load average
to go down. */
set_command_state (f, cs_running);
c->next = waiting_jobs;
waiting_jobs = c;
return 0;
}
/* Start the first command; reap_children will run later command lines. */
start_job_command (c);
switch (f->command_state)
{
case cs_running:
c->next = children;
if (c->pid > 0)
{
DB (DB_JOBS, (_("Putting child %p (%s) PID %s%s on the chain.\n"),
c, c->file->name, pid2str (c->pid),
c->remote ? _(" (remote)") : ""));
/* One more job slot is in use. */
++job_slots_used;
assert (c->jobslot == 0);
c->jobslot = 1;
}
children = c;
unblock_sigs ();
break;
case cs_not_started:
/* All the command lines turned out to be empty. */
f->update_status = us_success;
/* FALLTHROUGH */
case cs_finished:
notice_finished_file (f);
free_child (c);
break;
default:
assert (f->command_state == cs_finished);
break;
}
return 1;
}
/* Create a 'struct child' for FILE and start its commands running. */
void
new_job (struct file *file)
{
struct commands *cmds = file->cmds;
struct variable *var;
struct child *c;
unsigned int i;
char **lines;
/* Let any previously decided-upon jobs that are waiting
for the load to go down start before this new one. */
start_waiting_jobs ();
/* Reap any children that might have finished recently. */
reap_children (0, 0);
/* Chop the commands up into lines if they aren't already. */
chop_commands (cmds);
/* Start the command sequence, record it in a new
'struct child', and add that to the chain. */
c = xcalloc (sizeof (struct child));
output_init (&c->output);
c->file = file;
c->sh_batch_file = NULL;
/* [jart] manage temporary directories per rule */
if ((c->tmpdir = get_tmpdir (file)) &&
(c->tmpdir = new_tmpdir (c->tmpdir, file)))
{
var = define_variable_for_file ("TMPDIR", 6, c->tmpdir,
o_override, 0, file);
var->export = v_export;
}
/* Cache dontcare flag because file->dontcare can be changed once we
return. Check dontcare inheritance mechanism for details. */
c->dontcare = file->dontcare;
/* Start saving output in case the expansion uses $(info ...) etc. */
OUTPUT_SET (&c->output);
/* Expand the command lines and store the results in LINES. */
lines = xmalloc (cmds->ncommand_lines * sizeof (char *));
for (i = 0; i < cmds->ncommand_lines; ++i)
{
/* Collapse backslash-newline combinations that are inside variable
or function references. These are left alone by the parser so
that they will appear in the echoing of commands (where they look
nice); and collapsed by construct_command_argv when it tokenizes.
But letting them survive inside function invocations loses because
we don't want the functions to see them as part of the text. */
char *in, *out, *ref;
/* IN points to where in the line we are scanning.
OUT points to where in the line we are writing.
When we collapse a backslash-newline combination,
IN gets ahead of OUT. */
in = out = cmds->command_lines[i];
while ((ref = strchr (in, '$')) != 0)
{
++ref; /* Move past the $. */
if (out != in)
/* Copy the text between the end of the last chunk
we processed (where IN points) and the new chunk
we are about to process (where REF points). */
memmove (out, in, ref - in);
/* Move both pointers past the boring stuff. */
out += ref - in;
in = ref;
if (*ref == '(' || *ref == '{')
{
char openparen = *ref;
char closeparen = openparen == '(' ? ')' : '}';
char *outref;
int count;
char *p;
*out++ = *in++; /* Copy OPENPAREN. */
outref = out;
/* IN now points past the opening paren or brace.
Count parens or braces until it is matched. */
count = 0;
while (*in != '\0')
{
if (*in == closeparen && --count < 0)
break;
else if (*in == '\\' && in[1] == '\n')
{
/* We have found a backslash-newline inside a
variable or function reference. Eat it and
any following whitespace. */
int quoted = 0;
for (p = in - 1; p > ref && *p == '\\'; --p)
quoted = !quoted;
if (quoted)
/* There were two or more backslashes, so this is
not really a continuation line. We don't collapse
the quoting backslashes here as is done in
collapse_continuations, because the line will
be collapsed again after expansion. */
*out++ = *in++;
else
{
/* Skip the backslash, newline, and whitespace. */
in += 2;
NEXT_TOKEN (in);
/* Discard any preceding whitespace that has
already been written to the output. */
while (out > outref && ISBLANK (out[-1]))
--out;
/* Replace it all with a single space. */
*out++ = ' ';
}
}
else
{
if (*in == openparen)
++count;
*out++ = *in++;
}
}
}
}
/* There are no more references in this line to worry about.
Copy the remaining uninteresting text to the output. */
if (out != in)
memmove (out, in, strlen (in) + 1);
/* Finally, expand the line. */
cmds->fileinfo.offset = i;
lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
file);
}
cmds->fileinfo.offset = 0;
c->command_lines = lines;
/* Fetch the first command line to be run. */
job_next_command (c);
/* Wait for a job slot to be freed up. If we allow an infinite number
don't bother; also job_slots will == 0 if we're using the jobserver. */
if (job_slots != 0)
while (job_slots_used == job_slots)
reap_children (1, 0);
#ifdef MAKE_JOBSERVER
/* If we are controlling multiple jobs make sure we have a token before
starting the child. */
/* This can be inefficient. There's a decent chance that this job won't
actually have to run any subprocesses: the command script may be empty
or otherwise optimized away. It would be nice if we could defer
obtaining a token until just before we need it, in start_job_command.
To do that we'd need to keep track of whether we'd already obtained a
token (since start_job_command is called for each line of the job, not
just once). Also more thought needs to go into the entire algorithm;
this is where the old parallel job code waits, so... */
else if (jobserver_enabled ())
while (1)
{
int got_token;
DB (DB_JOBS, ("Need a job token; we %shave children\n",
children ? "" : "don't "));
/* If we don't already have a job started, use our "free" token. */
if (!jobserver_tokens)
break;
/* Prepare for jobserver token acquisition. */
jobserver_pre_acquire ();
/* Reap anything that's currently waiting. */
reap_children (0, 0);
/* Kick off any jobs we have waiting for an opportunity that
can run now (i.e., waiting for load). */
start_waiting_jobs ();
/* If our "free" slot is available, use it; we don't need a token. */
if (!jobserver_tokens)
break;
/* There must be at least one child already, or we have no business
waiting for a token. */
if (!children)
O (fatal, NILF, "INTERNAL: no children as we go to sleep on read\n");
/* Get a token. */
got_token = jobserver_acquire (waiting_jobs != NULL);
/* If we got one, we're done here. */
if (got_token == 1)
{
DB (DB_JOBS, (_("Obtained token for child %p (%s).\n"),
c, c->file->name));
break;
}
}
#endif
++jobserver_tokens;
/* Trace the build.
Use message here so that changes to working directories are logged. */
if (trace_flag)
{
char *newer = allocated_variable_expand_for_file ("$?", c->file);
const char *nm;
if (! cmds->fileinfo.filenm)
nm = _("<builtin>");
else
{
char *n = alloca (strlen (cmds->fileinfo.filenm) + 1 + 11 + 1);
sprintf (n, "%s:%lu", cmds->fileinfo.filenm, cmds->fileinfo.lineno);
nm = n;
}
if (newer[0] == '\0')
OSS (message, 0,
_("%s: target '%s' does not exist"), nm, c->file->name);
else
OSSS (message, 0,
_("%s: update target '%s' due to: %s"), nm, c->file->name, newer);
free (newer);
}
/* The job is now primed. Start it running.
(This will notice if there is in fact no recipe.) */
start_waiting_job (c);
if (job_slots == 1 || not_parallel)
/* Since there is only one job slot, make things run linearly.
Wait for the child to die, setting the state to 'cs_finished'. */
while (file->command_state == cs_running)
reap_children (1, 0);
OUTPUT_UNSET ();
return;
}
/* Move CHILD's pointers to the next command for it to execute.
Returns nonzero if there is another command. */
static int
job_next_command (struct child *child)
{
while (child->command_ptr == 0 || *child->command_ptr == '\0')
{
/* There are no more lines in the expansion of this line. */
if (child->command_line == child->file->cmds->ncommand_lines)
{
/* There are no more lines to be expanded. */
child->command_ptr = 0;
child->file->cmds->fileinfo.offset = 0;
return 0;
}
else
/* Get the next line to run. */
child->command_ptr = child->command_lines[child->command_line++];
}
child->file->cmds->fileinfo.offset = child->command_line - 1;
return 1;
}
/* Determine if the load average on the system is too high to start a new job.
On systems which provide /proc/loadavg (e.g., Linux), we use an idea
provided by Sven C. Dack <[email protected]>: retrieve the current number
of processes the kernel is running and, if it's greater than the requested
load we don't allow another job to start. We allow a job to start with
equal processes since one of those will be for make itself, which will then
pause waiting for jobs to clear.
Otherwise, we obtain the system load average and compare that.
The system load average is only recomputed once every N (N>=1) seconds.
However, a very parallel make can easily start tens or even hundreds of
jobs in a second, which brings the system to its knees for a while until
that first batch of jobs clears out.
To avoid this we use a weighted algorithm to try to account for jobs which
have been started since the last second, and guess what the load average
would be now if it were computed.
This algorithm was provided by Thomas Riedl <[email protected]>,
based on load average being recomputed once per second, which is
(apparently) how Solaris operates. Linux recomputes only once every 5
seconds, but Linux is handled by the /proc/loadavg algorithm above.
Thomas writes:
! calculate something load-oid and add to the observed sys.load,
! so that latter can catch up:
! - every job started increases jobctr;
! - every dying job decreases a positive jobctr;
! - the jobctr value gets zeroed every change of seconds,
! after its value*weight_b is stored into the 'backlog' value last_sec
! - weight_a times the sum of jobctr and last_sec gets
! added to the observed sys.load.
!
! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
! sub-shelled commands (rm, echo, sed...) for tests.
! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
! resulted in significant excession of the load limit, raising it
! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
! reach the limit in most test cases.
!
! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
! exceeding the limit for longer-running stuff (compile jobs in
! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
! small jobs' effects.
*/
#define LOAD_WEIGHT_A 0.25
#define LOAD_WEIGHT_B 0.25
static int
load_too_high (void)
{
static double last_sec;
static time_t last_now;
/* This is disabled by default for now, because it will behave badly if the
user gives a value > the number of cores; in that situation the load will
never be exceeded, this function always returns false, and we'll start
all the jobs. Also, it's not quite right to limit jobs to the number of
cores not busy since a job takes some time to start etc. Maybe that's
OK, I'm not sure exactly how to handle that, but for sure we need to
clamp this value at the number of cores before this can be enabled.
*/
double load, guess;
time_t now;
if (max_load_average < 0)
return 0;
/* Find the real system load average. */
make_access ();
if (getloadavg (&load, 1) != 1)
{
static int lossage = -1;
/* Complain only once for the same error. */
if (lossage == -1 || errno != lossage)
{
if (errno == 0)
/* An errno value of zero means getloadavg is just unsupported. */
O (error, NILF,
_("cannot enforce load limits on this operating system"));
else
perror_with_name (_("cannot enforce load limit: "), "getloadavg");
}
lossage = errno;
load = 0;
}
user_access ();
/* If we're in a new second zero the counter and correct the backlog
value. Only keep the backlog for one extra second; after that it's 0. */
now = time (NULL);
if (last_now < now)
{
if (last_now == now - 1)
last_sec = LOAD_WEIGHT_B * job_counter;
else
last_sec = 0.0;
job_counter = 0;
last_now = now;
}
/* Try to guess what the load would be right now. */
guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
guess, load, max_load_average));
return guess >= max_load_average;
}
/* Start jobs that are waiting for the load to be lower. */
void
start_waiting_jobs (void)
{
struct child *job;
if (waiting_jobs == 0)
return;
do
{
/* Check for recently deceased descendants. */
reap_children (0, 0);
/* Take a job off the waiting list. */
job = waiting_jobs;
waiting_jobs = job->next;
/* Try to start that job. We break out of the loop as soon
as start_waiting_job puts one back on the waiting list. */
}
while (start_waiting_job (job) && waiting_jobs != 0);
return;
}
bool
get_perm_prefix (const char *path, char out_perm[5], const char **out_path)
{
int c, n;
for (n = 0;;)
switch ((c = *path++)) {
case 'r':
case 'w':
case 'c':
case 'x':
out_perm[n++] = c;
out_perm[n] = 0;
break;
case ':':
if (n)
{
*out_path = path;
return true;
}
else
return false;
default:
return false;
}
}
/* Adds path to sandbox, returning true if found. */
int
Unveil (const char *path, const char *perm)
{
int e;
char *fp[2];
char permprefix[5];
/* if path is like `rwcx:o/tmp` then `rwcx` will override perm */
if (path && get_perm_prefix (path, permprefix, &path))
perm = permprefix;
fp[0] = 0;
fp[1] = 0;
if (path && path[0] == '~' &&
(fp[1] = tilde_expand ((fp[0] = xstrdup (path)))))
path = fp[1];
DB (DB_JOBS, (_("Unveiling %s with permissions %s\n"), path, perm));
e = errno;
if (unveil (path, perm) != -1)
{
free(fp[0]);
free(fp[1]);
return 0;
}
/* path not found isn't really much of an error */
if (errno == ENOENT)
{
free(fp[0]);
free(fp[1]);
errno = e;
return 0;
}
/* otherwise fail */
OSS (error, NILF, "%s: unveil() failed %s", path, strerror (errno));
free(fp[0]);
free(fp[1]);
return -1;
}
int
unveil_variable (const struct variable *var)
{
char *val, *tok, *state, *start;
if (!var) return 0;
start = val = xstrdup (variable_expand (var->value));
while ((tok = strtok_r (start, " \t\r\n", &state)))
{
RETURN_ON_ERROR (Unveil (tok, "r"));
start = 0;
}
free(val);
return 0;
OnError:
return -1;
}
static int
get_base_cpu_freq_mhz (void)
{
return KCPUIDS(16H, EAX) & 0x7fff;
}
int
set_limit (int r, long lo, long hi)
{
struct rlimit old;
struct rlimit lim = {lo, hi};
if (!setrlimit (r, &lim))
return 0;
if (getrlimit (r, &old))
return -1;
lim.rlim_cur = MIN (lim.rlim_cur, old.rlim_max);
lim.rlim_max = MIN (lim.rlim_max, old.rlim_max);
return setrlimit (r, &lim);
}
static int
set_cpu_limit (int secs)
{
int mhz, lim;
if (secs <= 0) return 0;
if (!(mhz = get_base_cpu_freq_mhz())) return eopnotsupp();
lim = ceil(3100. / mhz * secs);
return set_limit (RLIMIT_CPU, lim, lim + 1);
}
static struct sysinfo g_sysinfo;
__attribute__((__constructor__)) static void
get_sysinfo (void)
{
int e = errno;
sysinfo (&g_sysinfo);
errno = e;
}
static bool internet;
static char *promises;
/* POSIX:
Create a child process executing the command in ARGV.
Returns the PID or -1. */
pid_t
child_execute_job (struct childbase *child,
int good_stdin,
char **argv,
bool is_build_rule)
{
const int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
struct dep *d;
bool strict;
bool sandboxed;
bool unsandboxed;
struct child *c;
unsigned long ipromises;
char pathbuf[PATH_MAX];
char outpathbuf[PATH_MAX];
int fdout = FD_STDOUT;
int fderr = FD_STDERR;
pid_t pid;
int e, r;
char *s;
/* Divert child output if we want to capture it. */
if (child->output.syncout)
{
if (child->output.out >= 0)
fdout = child->output.out;
if (child->output.err >= 0)
fderr = child->output.err;
}
pid = fork();
if (pid != 0)
return pid;
/* We are the child. */
unblock_all_sigs ();
/* Reset limits, if necessary. */
if (stack_limit.rlim_cur)
setrlimit (RLIMIT_STACK, &stack_limit);
/* Tell build rules apart from $(shell foo). */
if (is_build_rule) {
c = (struct child *)child;
} else {
c = 0;
}
if (c)
{
strict = parse_bool (get_target_variable
(STRING_SIZE_TUPLE (".STRICT"),
c->file, "0"));
internet = !strict ||
parse_bool (get_target_variable
(STRING_SIZE_TUPLE (".INTERNET"),
c->file, "0"));
unsandboxed = !strict ||
parse_bool (get_target_variable
(STRING_SIZE_TUPLE (".UNSANDBOXED"),
c->file, "0"));
}
else
{
strict = false;
internet = true;
unsandboxed = true;
}
sandboxed = !unsandboxed;
if (sandboxed)
{
promises = emptytonull (get_target_variable
(STRING_SIZE_TUPLE (".PLEDGE"),
c ? c->file : 0, 0));
if (promises)
promises = xstrdup (promises);
if (ParsePromises (promises, &ipromises))
{
OSS (error, NILF, "%s: invalid .PLEDGE string: %s",
argv[0], strerror (errno));
_Exit (127);
}
}
else
{
promises = NULL;
ipromises = 0;
}
DB (DB_JOBS,
(_("Executing %s for %s%s%s%s\n"),
argv[0], c ? c->file->name : "$(shell)",
sandboxed ? " with sandboxing" : " without sandboxing",
strict ? " in .STRICT mode" : "",
internet ? " with internet access" : ""));
#ifdef __x86_64__
/* [jart] Set cpu seconds quota. */
if (RLIMIT_CPU < RLIM_NLIMITS &&
(s = get_target_variable (STRING_SIZE_TUPLE (".CPU"),
c ? c->file : 0, 0)))
{
int secs;
secs = atoi (s);
if (!set_cpu_limit (secs))
DB (DB_JOBS, (_("Set cpu limit of %d seconds\n"), secs));
else
DB (DB_JOBS, (_("Failed to set CPU limit: %s\n"), strerror (errno)));
}
#endif /* __x86_64__ */
/* [jart] Set virtual memory quota. */
if (RLIMIT_AS < RLIM_NLIMITS &&
(s = get_target_variable (STRING_SIZE_TUPLE (".MEMORY"),
c ? c->file : 0, 0)))
{
long bytes;
char buf[16];
errno = 0;
if (!strchr (s, '%'))
bytes = sizetol (s, 1024);
else
bytes = strtod (s, 0) / 100. * g_sysinfo.totalram;
if (bytes > 0)
{
if (!set_limit (RLIMIT_AS, bytes, bytes))
DB (DB_JOBS, (_("Set virtual memory limit of %sb\n"),
(sizefmt (buf, bytes, 1024), buf)));
else
DB (DB_JOBS, (_("Failed to set virtual memory: %s\n"),
strerror (errno)));
}
else if (errno)
{
OSS (error, NILF, "%s: .MEMORY invalid: %s",
argv[0], strerror (errno));
_Exit (127);
}
}
/* [jart] Set resident memory quota. */
if (RLIMIT_RSS < RLIM_NLIMITS &&
(s = get_target_variable (STRING_SIZE_TUPLE (".RSS"),
c ? c->file : 0, 0)))
{
long bytes;
char buf[16];
errno = 0;
if (!strchr (s, '%'))
bytes = sizetol (s, 1024);
else
bytes = strtod (s, 0) / 100. * g_sysinfo.totalram;
if (bytes > 0)
{
if (!set_limit (RLIMIT_RSS, bytes, bytes))
DB (DB_JOBS, (_("Set resident memory limit of %sb\n"),
(sizefmt (buf, bytes, 1024), buf)));
else
DB (DB_JOBS, (_("Failed to set resident memory: %s\n"),
strerror (errno)));
}
else if (errno)
{
OSS (error, NILF, "%s: .RSS invalid: %s",
argv[0], strerror (errno));
_Exit (127);
}
}
/* [jart] Set file size limit. */
if (RLIMIT_FSIZE < RLIM_NLIMITS &&
(s = get_target_variable (STRING_SIZE_TUPLE (".FSIZE"),
c ? c->file : 0, 0)))
{
long bytes;
char buf[16];
errno = 0;
if ((bytes = sizetol (s, 1000)) > 0)
{
if (!set_limit (RLIMIT_FSIZE, bytes, bytes * 1.5))
DB (DB_JOBS, (_("Set file size limit of %sb\n"),
(sizefmt (buf, bytes, 1000), buf)));
else
DB (DB_JOBS, (_("Failed to set file size limit: %s\n"),
strerror (errno)));
}
else if (errno)
{
OSS (error, NILF, "%s: .FSIZE invalid: %s",
argv[0], strerror (errno));
_Exit (127);
}
}
/* [jart] Set core dump limit. */
if (RLIMIT_CORE < RLIM_NLIMITS &&
(s = get_target_variable (STRING_SIZE_TUPLE (".MAXCORE"),
c ? c->file : 0, 0)))
{
long bytes;
char buf[16];
errno = 0;
if ((bytes = sizetol (s, 1000)) > 0)
{
if (!set_limit (RLIMIT_CORE, bytes, bytes))
DB (DB_JOBS, (_("Set core dump limit of %sb\n"),
(sizefmt (buf, bytes, 1000), buf)));
else
DB (DB_JOBS, (_("Failed to set core dump limit: %s\n"),
strerror (errno)));
}
else if (errno)
{
OSS (error, NILF, "%s: .MAXCORE invalid: %s",
argv[0], strerror (errno));
_Exit (127);
}
}
/* [jart] Set process limit. */
if (RLIMIT_NPROC < RLIM_NLIMITS &&
(s = get_target_variable (STRING_SIZE_TUPLE (".NPROC"),
c ? c->file : 0, 0)))
{
int procs;
if ((procs = atoi (s)) > 0)
{
if (!set_limit (RLIMIT_NPROC,
procs + g_sysinfo.procs,
procs + g_sysinfo.procs))
DB (DB_JOBS, (_("Set process limit to %d + %d preexisting\n"),
procs, g_sysinfo.procs));
else
DB (DB_JOBS, (_("Failed to set process limit: %s\n"),
strerror (errno)));
}
}
/* [jart] Set file descriptor limit. */
if (RLIMIT_NOFILE < RLIM_NLIMITS &&
(s = get_target_variable (STRING_SIZE_TUPLE (".NOFILE"),
c ? c->file : 0, 0)))
{
int fds;
if ((fds = atoi (s)) > 0)
{
if (!set_limit (RLIMIT_NOFILE, fds, fds))
DB (DB_JOBS, (_("Set file descriptor limit to %d\n"), fds));
else
DB (DB_JOBS, (_("Failed to set process limit: %s\n"),
strerror (errno)));
}
}
/* [jart] Prevent builds from talking to the Internet. */
if (internet)
DB (DB_JOBS, (_("Allowing Internet access\n")));
else if (!(~ipromises & (1ul << PROMISE_INET)) &&
!(~ipromises & (1ul << PROMISE_DNS)))
DB (DB_JOBS, (_("Internet access will be blocked by pledge\n")));
#ifdef __x86_64__
else
{
e = errno;
if (!nointernet())
DB (DB_JOBS, (_("Blocked Internet access with seccomp ptrace\n")));
else
{
if (errno = EPERM)
{
errno = e;
DB (DB_JOBS, (_("Can't block Internet if already traced\n")));
}
else if (errno == ENOSYS)
{
errno = e;
DB (DB_JOBS, (_("Need SECCOMP ptrace() to block Internet\n")));
}
else
{
OSS (error, NILF, "%s: failed to block internet access: %s",
argv[0], strerror (errno));
_Exit (127);
}
}
}
#endif
/* [jart] Resolve command into executable path. */
if (!strict || !sandboxed)
{
if ((s = commandv (argv[0], pathbuf, sizeof (pathbuf))))
argv[0] = s;
else
{
OSS (error, NILF, "%s: command not found on $PATH: %s",
argv[0], strerror (errno));
_Exit (127);
}
}
/* [jart] Sandbox build rule commands based on prerequisites. */
if (c)
{
errno = 0;
if (sandboxed)
{
/*
* permit launching actually portable executables
*
* we assume launching make.com already did the expensive
* work of extracting the ape loader program, via /bin/sh
* and we won't need to do that again, since sys_execve()
* will pass ape binaries directly to the ape loader, but
* only if the ape loader exists on a well-known path.
*/
e = errno;
DB (DB_JOBS, (_("Unveiling %s with permissions %s\n"),
"/usr/bin/ape", "rx"));
if (unveil ("/usr/bin/ape", "rx") == -1)
{
char *s, *t;
errno = e;
if ((s = getenv ("TMPDIR")))
{
t = xjoinpaths (s, ".ape");
RETURN_ON_ERROR (Unveil (t, "rx"));
free (t);
}
if ((s = getenv ("HOME")))
{
t = xjoinpaths (s, ".ape");
RETURN_ON_ERROR (Unveil (t, "rx"));
free (t);
}
}
/* Unveil executable. */
RETURN_ON_ERROR (Unveil (argv[0], "rx"));
/* Unveil temporary directory. */
if (c->tmpdir)
RETURN_ON_ERROR (Unveil (c->tmpdir, "rwcx"));
/* Unveil .PLEDGE = vminfo. */
if (promises && (~ipromises & (1ul << PROMISE_VMINFO)))
{
RETURN_ON_ERROR (Unveil ("/proc/stat", "r"));
RETURN_ON_ERROR (Unveil ("/proc/meminfo", "r"));
RETURN_ON_ERROR (Unveil ("/proc/cpuinfo", "r"));
RETURN_ON_ERROR (Unveil ("/proc/diskstats", "r"));
RETURN_ON_ERROR (Unveil ("/proc/self/maps", "r"));
RETURN_ON_ERROR (Unveil ("/sys/devices/system/cpu", "r"));
}
/* Unveil .PLEDGE = tty. */
if (promises && (~ipromises & (1ul << PROMISE_TTY)))
{
RETURN_ON_ERROR (Unveil (ttyname(0), "rw"));
RETURN_ON_ERROR (Unveil ("/dev/tty", "rw"));
RETURN_ON_ERROR (Unveil ("/dev/console", "rw"));
RETURN_ON_ERROR (Unveil ("/etc/terminfo", "r"));
RETURN_ON_ERROR (Unveil ("/usr/lib/terminfo", "r"));
RETURN_ON_ERROR (Unveil ("/usr/share/terminfo", "r"));
}
/* Unveil .PLEDGE = dns. */
if (promises && (~ipromises & (1ul << PROMISE_DNS)))
{
RETURN_ON_ERROR (Unveil ("/etc/hosts", "r"));
RETURN_ON_ERROR (Unveil ("/etc/hostname", "r"));
RETURN_ON_ERROR (Unveil ("/etc/services", "r"));
RETURN_ON_ERROR (Unveil ("/etc/protocols", "r"));
RETURN_ON_ERROR (Unveil ("/etc/resolv.conf", "r"));
}
/* Unveil .PLEDGE = inet. */
if (promises && (~ipromises & (1ul << PROMISE_INET)))
RETURN_ON_ERROR (Unveil ("/etc/ssl/certs/ca-certificates.crt", "r"));
/* Unveil .PLEDGE = rpath. */
if (promises && (~ipromises & (1ul << PROMISE_RPATH)))
RETURN_ON_ERROR (Unveil ("/proc/filesystems", "r"));
/*
* unveils target output file
*
* landlock operates per inode so it can't whitelist missing
* paths. so we create the output file manually, and prevent
* creation so that it can't be deleted by the command which
* must truncate when writing its output.
*/
if (!c->file->phony &&
strlen(c->file->name) < PATH_MAX)
{
int fd, rc, err;
if (c->file->last_mtime == NONEXISTENT_MTIME)
{
strcpy (outpathbuf, c->file->name);
err = errno;
if (makedirs (dirname (outpathbuf), 0777) == -1)
errno = err;
fd = open (c->file->name, O_RDWR | O_CREAT, 0777);
if (fd != -1)
close (fd);
else if (errno == EEXIST)
errno = err;
else
{
OSS (error, NILF, "%s: touch target failed %s",
c->file->name, strerror (errno));
_Exit (127);
}
c->file->touched = get_file_timestamp (c->file);
}
DB (DB_JOBS, (_("Unveiling %s with permissions %s\n"),
c->file->name, "rwx"));
if (unveil (c->file->name, "rwx") && errno != ENOSYS)
{
OSS (error, NILF, "%s: unveil target failed %s",
c->file->name, strerror (errno));
_Exit (127);
}
}
/*
* unveil target prerequisites
*
* directories get special treatment:
*
* - libc/nt
* shall unveil everything beneath dir
*
* - libc/nt/
* no sandboxing due to trailing slash
* intended to be timestamp check only
*/
for (d = c->file->deps; d; d = d->next)
{
size_t n;
n = strlen (d->file->name);
if (n && d->file->name[n - 1] == '/')
continue;
RETURN_ON_ERROR (Unveil (d->file->name, "rx"));
if (n > 4 && READ32LE(d->file->name + n - 4) == READ32LE(".com"))
{
s = xstrcat (d->file->name, ".dbg");
RETURN_ON_ERROR (Unveil (s, "rx"));
free (s);
}
}
/* unveil explicit .UNVEIL entries */
RETURN_ON_ERROR
(unveil_variable
(lookup_variable
(STRING_SIZE_TUPLE (".UNVEIL"))));
RETURN_ON_ERROR
(unveil_variable
(lookup_variable_in_set
(STRING_SIZE_TUPLE (".UNVEIL"),
c->file->variables->set)));
if (c->file->pat_variables)
RETURN_ON_ERROR
(unveil_variable
(lookup_variable_in_set
(STRING_SIZE_TUPLE (".UNVEIL"),
c->file->pat_variables->set)));
/* commit sandbox */
RETURN_ON_ERROR (Unveil (0, 0));
}
}
/* For any redirected FD, dup2() it to the standard FD.
They are all marked close-on-exec already. */
if (fdin >= 0 && fdin != FD_STDIN)
EINTRLOOP (r, dup2 (fdin, FD_STDIN));
if (fdout != FD_STDOUT)
EINTRLOOP (r, dup2 (fdout, FD_STDOUT));
if (fderr != FD_STDERR)
EINTRLOOP (r, dup2 (fderr, FD_STDERR));
/* Run the command. */
exec_command (argv, child->environment);
OnError:
_Exit (127);
}
/* Replace the current process with one running the command in ARGV,
with environment ENVP. This function does not return. */
void
exec_command (char **argv, char **envp)
{
/* Be the user, permanently. */
child_access ();
/* Restrict system calls. */
if (promises)
{
__pledge_mode = PLEDGE_PENALTY_RETURN_EPERM;
DB (DB_JOBS, (_("Pledging %s\n"), promises));
promises = xstrcat (promises, " prot_exec exec");
if (pledge (promises, promises))
{
OSS (error, NILF, "pledge(%s) failed: %s",
promises, strerror (errno));
_Exit (127);
}
}
/* Run the program. */
environ = envp;
execv (argv[0], argv);
if(errno == ENOENT)
OSS (error, NILF, "%s: command doesn't exist: %s",
argv[0], strerror (errno));
else if(errno == ENOEXEC)
{
/* The file was not a program. Try it as a shell script. */
const char *shell;
char **new_argv;
int argc;
int i=1;
shell = getenv ("SHELL");
if (shell == 0)
shell = default_shell;
argc = 1;
while (argv[argc] != 0)
++argc;
new_argv = alloca ((1 + argc + 1) * sizeof (char *));
new_argv[0] = (char *)shell;
new_argv[i] = argv[0];
while (argc > 0)
{
new_argv[i + argc] = argv[argc];
--argc;
}
execvp (shell, new_argv);
OSS (error, NILF, "%s: execvp shell failed: %s",
new_argv[0], strerror (errno));
}
OSS (error, NILF, "%s: execv failed: %s",
argv[0], strerror (errno));
_Exit (127);
}
/* Figure out the argument list necessary to run LINE as a command. Try to
avoid using a shell. This routine handles only ' quoting, and " quoting
when no backslash, $ or ' characters are seen in the quotes. Starting
quotes may be escaped with a backslash. If any of the characters in
sh_chars is seen, or any of the builtin commands listed in sh_cmds
is the first word of a line, the shell is used.
If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
If *RESTP is NULL, newlines will be ignored.
SHELL is the shell to use, or nil to use the default shell.
IFS is the value of $IFS, or nil (meaning the default).
FLAGS is the value of lines_flags for this command line. It is
used in the WINDOWS32 port to check whether + or $(MAKE) were found
in this command line, in which case the effect of just_print_flag
is overridden. */
static char **
construct_command_argv_internal (char *line, char **restp, const char *shell,
const char *shellflags, const char *ifs,
int flags, char **batch_filename UNUSED)
{
static const char *sh_chars = "#;\"*?[]&|<>(){}$`^~!";
static const char *sh_cmds[] =
{ ".", ":", "alias", "bg", "break", "case", "cd", "command", "continue",
"eval", "exec", "exit", "export", "fc", "fg", "for", "getopts", "hash",
"if", "jobs", "login", "logout", "read", "readonly", "return", "set",
"shift", "test", "times", "trap", "type", "ulimit", "umask", "unalias",
"unset", "wait", "while", 0 };
size_t i;
char *p;
#ifndef NDEBUG
char *end;
#endif
char *ap;
const char *cap;
const char *cp;
int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
char **new_argv = 0;
char *argstr = 0;
if (restp != NULL)
*restp = NULL;
/* Make sure not to bother processing an empty line but stop at newline. */
while (ISBLANK (*line))
++line;
if (*line == '\0')
return 0;
if (shellflags == 0)
shellflags = posix_pedantic ? "-ec" : "-c";
/* See if it is safe to parse commands internally. */
if (shell == 0)
shell = default_shell;
/* [jart] remove code that forces slow path if not using /bin/sh */
if (ifs)
for (cap = ifs; *cap != '\0'; ++cap)
if (*cap != ' ' && *cap != '\t' && *cap != '\n')
goto slow;
if (shellflags)
if (shellflags[0] != '-'
|| ((shellflags[1] != 'c' || shellflags[2] != '\0')
&& (shellflags[1] != 'e' || shellflags[2] != 'c' || shellflags[3] != '\0')))
goto slow;
i = strlen (line) + 1;
/* More than 1 arg per character is impossible. */
new_argv = xmalloc (i * sizeof (char *));
/* All the args can fit in a buffer as big as LINE is. */
ap = new_argv[0] = argstr = xmalloc (i);
#ifndef NDEBUG
end = ap + i;
#endif
/* I is how many complete arguments have been found. */
i = 0;
instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
for (p = line; *p != '\0'; ++p)
{
// assert (ap <= end);
if (instring)
{
/* Inside a string, just copy any char except a closing quote
or a backslash-newline combination. */
if (*p == instring)
{
instring = 0;
if (ap == new_argv[0] || *(ap-1) == '\0')
last_argument_was_empty = 1;
}
else if (*p == '\\' && p[1] == '\n')
{
/* Backslash-newline is handled differently depending on what
kind of string we're in: inside single-quoted strings you
keep them; in double-quoted strings they disappear. For
DOS/Windows/OS2, if we don't have a POSIX shell, we keep the
pre-POSIX behavior of removing the backslash-newline. */
if (instring == '"'
#if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
|| !unixy_shell
#endif
)
++p;
else
{
*(ap++) = *(p++);
*(ap++) = *p;
}
}
else if (*p == '\n' && restp != NULL)
{
/* End of the command line. */
*restp = p;
goto end_of_line;
}
/* Backslash, $, and ` are special inside double quotes.
If we see any of those, punt.
But on MSDOS, if we use COMMAND.COM, double and single
quotes have the same effect. */
else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
goto slow;
else
*ap++ = *p;
}
else if (strchr (sh_chars, *p) != 0)
/* Not inside a string, but it's a special char. */
goto slow;
else if (one_shell && *p == '\n')
/* In .ONESHELL mode \n is a separator like ; or && */
goto slow;
else
/* Not a special char. */
switch (*p)
{
case '=':
/* Equals is a special character in leading words before the
first word with no equals sign in it. This is not the case
with sh -k, but we never get here when using nonstandard
shell flags. */
if (! seen_nonequals && unixy_shell)
goto slow;
word_has_equals = 1;
*ap++ = '=';
break;
case '\\':
/* Backslash-newline has special case handling, ref POSIX.
We're in the fastpath, so emulate what the shell would do. */
if (p[1] == '\n')
{
/* Throw out the backslash and newline. */
++p;
/* At the beginning of the argument, skip any whitespace other
than newline before the start of the next word. */
if (ap == new_argv[i])
while (ISBLANK (p[1]))
++p;
}
else if (p[1] != '\0')
{
/* Copy and skip the following char. */
*ap++ = *++p;
}
break;
case '\'':
case '"':
instring = *p;
break;
case '\n':
if (restp != NULL)
{
/* End of the command line. */
*restp = p;
goto end_of_line;
}
else
/* Newlines are not special. */
*ap++ = '\n';
break;
case ' ':
case '\t':
/* We have the end of an argument.
Terminate the text of the argument. */
*ap++ = '\0';
new_argv[++i] = ap;
last_argument_was_empty = 0;
/* Update SEEN_NONEQUALS, which tells us if every word
heretofore has contained an '='. */
seen_nonequals |= ! word_has_equals;
if (word_has_equals && ! seen_nonequals)
/* An '=' in a word before the first
word without one is magical. */
goto slow;
word_has_equals = 0; /* Prepare for the next word. */
/* If this argument is the command name,
see if it is a built-in shell command.
If so, have the shell handle it. */
if (i == 1)
{
int j;
for (j = 0; sh_cmds[j] != 0; ++j)
{
if (streq (sh_cmds[j], new_argv[0]))
goto slow;
}
}
/* Skip whitespace chars, but not newlines. */
while (ISBLANK (p[1]))
++p;
break;
default:
*ap++ = *p;
break;
}
}
end_of_line:
if (instring)
/* Let the shell deal with an unterminated quote. */
goto slow;
/* Terminate the last argument and the argument list. */
*ap = '\0';
if (new_argv[i][0] != '\0' || last_argument_was_empty)
++i;
new_argv[i] = 0;
if (i == 1)
{
int j;
for (j = 0; sh_cmds[j] != 0; ++j)
if (streq (sh_cmds[j], new_argv[0]))
goto slow;
}
if (new_argv[0] == 0)
{
/* Line was empty. */
free (argstr);
free (new_argv);
return 0;
}
return new_argv;
slow:;
/* We must use the shell. */
if (new_argv != 0)
{
/* Free the old argument list we were working on. */
free (argstr);
free (new_argv);
}
{
/* SHELL may be a multi-word command. Construct a command line
"$(SHELL) $(.SHELLFLAGS) LINE", with all special chars in LINE escaped.
Then recurse, expanding this command line to get the final
argument list. */
char *new_line;
size_t shell_len = strlen (shell);
size_t line_len = strlen (line);
size_t sflags_len = shellflags ? strlen (shellflags) : 0;
/* In .ONESHELL mode we are allowed to throw the entire current
recipe string at a single shell and trust that the user
has configured the shell and shell flags, and formatted
the string, appropriately. */
if (one_shell)
{
/* If the shell is Bourne compatible, we must remove and ignore
interior special chars [@+-] because they're meaningless to
the shell itself. If, however, we're in .ONESHELL mode and
have changed SHELL to something non-standard, we should
leave those alone because they could be part of the
script. In this case we must also leave in place
any leading [@+-] for the same reason. */
/* Remove and ignore interior prefix chars [@+-] because they're
meaningless given a single shell. */
if (is_bourne_compatible_shell (shell))
{
const char *f = line;
char *t = line;
/* Copy the recipe, removing and ignoring interior prefix chars
[@+-]: they're meaningless in .ONESHELL mode. */
while (f[0] != '\0')
{
int esc = 0;
/* This is the start of a new recipe line. Skip whitespace
and prefix characters but not newlines. */
while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
++f;
/* Copy until we get to the next logical recipe line. */
while (*f != '\0')
{
*(t++) = *(f++);
if (f[-1] == '\\')
esc = !esc;
else
{
/* On unescaped newline, we're done with this line. */
if (f[-1] == '\n' && ! esc)
break;
/* Something else: reset the escape sequence. */
esc = 0;
}
}
}
*t = '\0';
}
/* Create an argv list for the shell command line. */
{
int n = 0;
new_argv = xmalloc ((4 + sflags_len/2) * sizeof (char *));
new_argv[n++] = xstrdup (shell);
/* Chop up the shellflags (if any) and assign them. */
if (! shellflags)
new_argv[n++] = xstrdup ("");
else
{
const char *s = shellflags;
char *t;
size_t len;
while ((t = find_next_token (&s, &len)) != 0)
new_argv[n++] = xstrndup (t, len);
}
/* Set the command to invoke. */
new_argv[n++] = line;
new_argv[n++] = NULL;
}
return new_argv;
}
new_line = xmalloc ((shell_len*2) + 1 + sflags_len + 1
+ (line_len*2) + 1);
ap = new_line;
/* Copy SHELL, escaping any characters special to the shell. If
we don't escape them, construct_command_argv_internal will
recursively call itself ad nauseam, or until stack overflow,
whichever happens first. */
for (cp = shell; *cp != '\0'; ++cp)
{
if (strchr (sh_chars, *cp) != 0)
*(ap++) = '\\';
*(ap++) = *cp;
}
*(ap++) = ' ';
if (shellflags)
memcpy (ap, shellflags, sflags_len);
ap += sflags_len;
*(ap++) = ' ';
#ifdef WINDOWS32
command_ptr = ap;
#endif
for (p = line; *p != '\0'; ++p)
{
if (restp != NULL && *p == '\n')
{
*restp = p;
break;
}
else if (*p == '\\' && p[1] == '\n')
{
/* POSIX says we keep the backslash-newline. If we don't have a
POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
and remove the backslash/newline. */
#if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
# define PRESERVE_BSNL unixy_shell
#else
# define PRESERVE_BSNL 1
#endif
if (PRESERVE_BSNL)
{
*(ap++) = '\\';
/* Only non-batch execution needs another backslash,
because it will be passed through a recursive
invocation of this function. */
if (!batch_mode_shell)
*(ap++) = '\\';
*(ap++) = '\n';
}
++p;
continue;
}
/* DOS shells don't know about backslash-escaping. */
if (unixy_shell && !batch_mode_shell &&
(*p == '\\' || *p == '\'' || *p == '"'
|| ISSPACE (*p)
|| strchr (sh_chars, *p) != 0))
*ap++ = '\\';
*ap++ = *p;
}
if (ap == new_line + shell_len + sflags_len + 2)
{
/* Line was empty. */
free (new_line);
return 0;
}
*ap = '\0';
#ifdef WINDOWS32
/* Some shells do not work well when invoked as 'sh -c xxx' to run a
command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
cases, run commands via a script file. */
if (just_print_flag && !(flags & COMMANDS_RECURSE))
{
/* Need to allocate new_argv, although it's unused, because
start_job_command will want to free it and its 0'th element. */
new_argv = xmalloc (2 * sizeof (char *));
new_argv[0] = xstrdup ("");
new_argv[1] = NULL;
}
else if ((no_default_sh_exe || batch_mode_shell) && batch_filename)
{
int temp_fd;
FILE* batch = NULL;
int id = GetCurrentProcessId ();
PATH_VAR (fbuf);
/* create a file name */
sprintf (fbuf, "make%d", id);
*batch_filename = create_batch_file (fbuf, unixy_shell, &temp_fd);
DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
*batch_filename));
/* Create a FILE object for the batch file, and write to it the
commands to be executed. Put the batch file in TEXT mode. */
_setmode (temp_fd, _O_TEXT);
batch = _fdopen (temp_fd, "wt");
if (!unixy_shell)
fputs ("@echo off\n", batch);
fputs (command_ptr, batch);
fputc ('\n', batch);
fclose (batch);
DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
!unixy_shell ? "\n\t@echo off" : "", command_ptr));
/* create argv */
new_argv = xmalloc (3 * sizeof (char *));
if (unixy_shell)
{
new_argv[0] = xstrdup (shell);
new_argv[1] = *batch_filename; /* only argv[0] gets freed later */
}
else
{
new_argv[0] = xstrdup (*batch_filename);
new_argv[1] = NULL;
}
new_argv[2] = NULL;
}
else
#endif /* WINDOWS32 */
if (unixy_shell)
new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0,
flags, 0);
else
fatal (NILF, CSTRLEN (__FILE__) + INTSTR_LENGTH,
_("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
__FILE__, __LINE__);
free (new_line);
}
return new_argv;
}
/* Figure out the argument list necessary to run LINE as a command. Try to
avoid using a shell. This routine handles only ' quoting, and " quoting
when no backslash, $ or ' characters are seen in the quotes. Starting
quotes may be escaped with a backslash. If any of the characters in
sh_chars is seen, or any of the builtin commands listed in sh_cmds
is the first word of a line, the shell is used.
If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
If *RESTP is NULL, newlines will be ignored.
FILE is the target whose commands these are. It is used for
variable expansion for $(SHELL) and $(IFS). */
char **
construct_command_argv (char *line, char **restp, struct file *file,
int cmd_flags, char **batch_filename)
{
char *shell, *ifs, *shellflags;
char **argv;
{
/* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
int save = warn_undefined_variables_flag;
warn_undefined_variables_flag = 0;
shell = allocated_variable_expand_for_file ("$(SHELL)", file);
#ifdef WINDOWS32
/*
* Convert to forward slashes so that construct_command_argv_internal()
* is not confused.
*/
if (shell)
{
char *p = w32ify (shell, 0);
strcpy (shell, p);
}
#endif
shellflags = allocated_variable_expand_for_file ("$(.SHELLFLAGS)", file);
ifs = allocated_variable_expand_for_file ("$(IFS)", file);
warn_undefined_variables_flag = save;
}
argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
cmd_flags, batch_filename);
free (shell);
free (shellflags);
free (ifs);
return argv;
}
| 91,972 | 2,967 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/dirname-lgpl.c | /* clang-format off */
/* dirname.c -- return all but the last element in a file name
Copyright (C) 1990, 1998, 2000-2001, 2003-2006, 2009-2020 Free Software
Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#include "third_party/make/config.h"
/**/
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "third_party/make/dirname.h"
/* clang-format off */
/* Return the length of the prefix of FILE that will be used by
dir_name. If FILE is in the working directory, this returns zero
even though 'dir_name (FILE)' will return ".". Works properly even
if there are trailing slashes (by effectively ignoring them). */
size_t
dir_len (char const *file)
{
size_t prefix_length = FILE_SYSTEM_PREFIX_LEN (file);
size_t length;
/* Advance prefix_length beyond important leading slashes. */
prefix_length += (prefix_length != 0
? (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
&& ISSLASH (file[prefix_length]))
: (ISSLASH (file[0])
? ((DOUBLE_SLASH_IS_DISTINCT_ROOT
&& ISSLASH (file[1]) && ! ISSLASH (file[2])
? 2 : 1))
: 0));
/* Strip the basename and any redundant slashes before it. */
for (length = last_component (file) - file;
prefix_length < length; length--)
if (! ISSLASH (file[length - 1]))
break;
return length;
}
/* In general, we can't use the builtin 'dirname' function if available,
since it has different meanings in different environments.
In some environments the builtin 'dirname' modifies its argument.
Return the leading directories part of FILE, allocated with malloc.
Works properly even if there are trailing slashes (by effectively
ignoring them). Return NULL on failure.
If lstat (FILE) would succeed, then { chdir (dir_name (FILE));
lstat (base_name (FILE)); } will access the same file. Likewise,
if the sequence { chdir (dir_name (FILE));
rename (base_name (FILE), "foo"); } succeeds, you have renamed FILE
to "foo" in the same directory FILE was in. */
char *
mdir_name (char const *file)
{
size_t length = dir_len (file);
bool append_dot = (length == 0
|| (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
&& length == FILE_SYSTEM_PREFIX_LEN (file)
&& file[2] != '\0' && ! ISSLASH (file[2])));
char *dir = malloc (length + append_dot + 1);
if (!dir)
return NULL;
memcpy (dir, file, length);
if (append_dot)
dir[length++] = '.';
dir[length] = '\0';
return dir;
}
| 3,248 | 88 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/filedef.h | /* Definition of target file data structures for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* Structure that represents the info on one file
that the makefile says how to make.
All of these are chained together through 'next'. */
#include "third_party/make/hash.h"
/* clang-format off */
struct commands;
struct dep;
struct variable;
struct variable_set_list;
struct file
{
const char *name;
const char *hname; /* Hashed filename */
const char *vpath; /* VPATH/vpath pathname */
struct dep *deps; /* all dependencies, including duplicates */
struct commands *cmds; /* Commands to execute for this target. */
const char *stem; /* Implicit stem, if an implicit
rule has been used */
struct dep *also_make; /* Targets that are made by making this. */
struct file *prev; /* Previous entry for same file name;
used when there are multiple double-colon
entries for the same file. */
struct file *last; /* Last entry for the same file name. */
/* File that this file was renamed to. After any time that a
file could be renamed, call 'check_renamed' (below). */
struct file *renamed;
/* List of variable sets used for this file. */
struct variable_set_list *variables;
/* Pattern-specific variable reference for this target, or null if there
isn't one. Also see the pat_searched flag, below. */
struct variable_set_list *pat_variables;
/* Immediate dependent that caused this target to be remade,
or nil if there isn't one. */
struct file *parent;
/* For a double-colon entry, this is the first double-colon entry for
the same file. Otherwise this is null. */
struct file *double_colon;
FILE_TIMESTAMP last_mtime; /* File's modtime, if already known. */
FILE_TIMESTAMP mtime_before_update; /* File's modtime before any updating
has been performed. */
FILE_TIMESTAMP touched; /* Set if file was created in order for
Landlock LSM to sandbox it. */
unsigned int considered; /* equal to 'considered' if file has been
considered on current scan of goal chain */
int command_flags; /* Flags OR'd in for cmds; see commands.h. */
enum update_status /* Status of the last attempt to update. */
{
us_success = 0, /* Successfully updated. Must be 0! */
us_none, /* No attempt to update has been made. */
us_question, /* Needs to be updated (-q is is set). */
us_failed /* Update failed. */
} update_status ENUM_BITFIELD (2);
enum cmd_state /* State of commands. ORDER IS IMPORTANT! */
{
cs_not_started = 0, /* Not yet started. Must be 0! */
cs_deps_running, /* Dep commands running. */
cs_running, /* Commands running. */
cs_finished /* Commands finished. */
} command_state ENUM_BITFIELD (2);
unsigned int builtin:1; /* True if the file is a builtin rule. */
unsigned int precious:1; /* Non-0 means don't delete file on quit */
unsigned int loaded:1; /* True if the file is a loaded object. */
unsigned int low_resolution_time:1; /* Nonzero if this file's time stamp
has only one-second resolution. */
unsigned int tried_implicit:1; /* Nonzero if have searched
for implicit rule for making
this file; don't search again. */
unsigned int updating:1; /* Nonzero while updating deps of this file */
unsigned int updated:1; /* Nonzero if this file has been remade. */
unsigned int is_target:1; /* Nonzero if file is described as target. */
unsigned int cmd_target:1; /* Nonzero if file was given on cmd line. */
unsigned int phony:1; /* Nonzero if this is a phony file
i.e., a prerequisite of .PHONY. */
unsigned int intermediate:1;/* Nonzero if this is an intermediate file. */
unsigned int secondary:1; /* Nonzero means remove_intermediates should
not delete it. */
unsigned int dontcare:1; /* Nonzero if no complaint is to be made if
this target cannot be remade. */
unsigned int ignore_vpath:1;/* Nonzero if we threw out VPATH name. */
unsigned int pat_searched:1;/* Nonzero if we already searched for
pattern-specific variables. */
unsigned int no_diag:1; /* True if the file failed to update and no
diagnostics has been issued (dontcare). */
};
extern struct file *default_file;
struct file *lookup_file (const char *name);
struct file *enter_file (const char *name);
struct dep *split_prereqs (char *prereqstr);
struct dep *enter_prereqs (struct dep *prereqs, const char *stem);
struct dep *expand_extra_prereqs (const struct variable *extra);
void remove_intermediates (int sig);
void snap_deps (void);
void rename_file (struct file *file, const char *name);
void rehash_file (struct file *file, const char *name);
void set_command_state (struct file *file, enum cmd_state state);
void notice_finished_file (struct file *file);
void init_hash_files (void);
void verify_file_data_base (void);
char *build_target_list (char *old_list);
void print_prereqs (const struct dep *deps);
void print_file_data_base (void);
int try_implicit_rule (struct file *file, unsigned int depth);
int stemlen_compare (const void *v1, const void *v2);
#if FILE_TIMESTAMP_HI_RES
# define FILE_TIMESTAMP_STAT_MODTIME(fname, st) \
file_timestamp_cons (fname, (st).st_mtime, (st).ST_MTIM_NSEC)
#else
# define FILE_TIMESTAMP_STAT_MODTIME(fname, st) \
file_timestamp_cons (fname, (st).st_mtime, 0)
#endif
/* If FILE_TIMESTAMP is 64 bits (or more), use nanosecond resolution.
(Multiply by 2**30 instead of by 10**9 to save time at the cost of
slightly decreasing the number of available timestamps.) With
64-bit FILE_TIMESTAMP, this stops working on 2514-05-30 01:53:04
UTC, but by then uintmax_t should be larger than 64 bits. */
#define FILE_TIMESTAMPS_PER_S (FILE_TIMESTAMP_HI_RES ? 1000000000 : 1)
#define FILE_TIMESTAMP_LO_BITS (FILE_TIMESTAMP_HI_RES ? 30 : 0)
#define FILE_TIMESTAMP_S(ts) (((ts) - ORDINARY_MTIME_MIN) \
>> FILE_TIMESTAMP_LO_BITS)
#define FILE_TIMESTAMP_NS(ts) ((int) (((ts) - ORDINARY_MTIME_MIN) \
& ((1 << FILE_TIMESTAMP_LO_BITS) - 1)))
/* Upper bound on length of string "YYYY-MM-DD HH:MM:SS.NNNNNNNNN"
representing a file timestamp. The upper bound is not necessarily 29,
since the year might be less than -999 or greater than 9999.
Subtract one for the sign bit if in case file timestamps can be negative;
subtract FLOOR_LOG2_SECONDS_PER_YEAR to yield an upper bound on how many
file timestamp bits might affect the year;
302 / 1000 is log10 (2) rounded up;
add one for integer division truncation;
add one more for a minus sign if file timestamps can be negative;
add 4 to allow for any 4-digit epoch year (e.g. 1970);
add 25 to allow for "-MM-DD HH:MM:SS.NNNNNNNNN". */
#define FLOOR_LOG2_SECONDS_PER_YEAR 24
#define FILE_TIMESTAMP_PRINT_LEN_BOUND /* 62 */ \
(((sizeof (FILE_TIMESTAMP) * CHAR_BIT - 1 - FLOOR_LOG2_SECONDS_PER_YEAR) \
* 302 / 1000) \
+ 1 + 1 + 4 + 25)
FILE_TIMESTAMP file_timestamp_cons (char const *, time_t, long int);
FILE_TIMESTAMP file_timestamp_now (int *);
void file_timestamp_sprintf (char *, int, FILE_TIMESTAMP );
/* Return the mtime of file F (a struct file *), caching it.
The value is NONEXISTENT_MTIME if the file does not exist. */
#define file_mtime(f) file_mtime_1 ((f), 1)
/* Return the mtime of file F (a struct file *), caching it.
Don't search using vpath for the file--if it doesn't actually exist,
we don't find it.
The value is NONEXISTENT_MTIME if the file does not exist. */
#define file_mtime_no_search(f) file_mtime_1 ((f), 0)
FILE_TIMESTAMP f_mtime (struct file *file, int search);
#define file_mtime_1(f, v) \
((f)->last_mtime == UNKNOWN_MTIME ? f_mtime ((f), v) : (f)->last_mtime)
/* Special timestamp values. */
/* The file's timestamp is not yet known. */
#define UNKNOWN_MTIME 0
/* The file does not exist. */
#define NONEXISTENT_MTIME 1
/* The file does not exist, and we assume that it is older than any
actual file. */
#define OLD_MTIME 2
/* The smallest and largest ordinary timestamps. */
#define ORDINARY_MTIME_MIN (OLD_MTIME + 1)
#define ORDINARY_MTIME_MAX ((FILE_TIMESTAMP_S (NEW_MTIME) \
<< FILE_TIMESTAMP_LO_BITS) \
+ ORDINARY_MTIME_MIN + FILE_TIMESTAMPS_PER_S - 1)
/* Modtime value to use for 'infinitely new'. We used to get the current time
from the system and use that whenever we wanted 'new'. But that causes
trouble when the machine running make and the machine holding a file have
different ideas about what time it is; and can also lose for 'force'
targets, which need to be considered newer than anything that depends on
them, even if said dependents' modtimes are in the future. */
#define NEW_MTIME INTEGER_TYPE_MAXIMUM (FILE_TIMESTAMP)
#define check_renamed(file) \
while ((file)->renamed != 0) (file) = (file)->renamed /* No ; here. */
/* Have we snapped deps yet? */
extern int snapped_deps;
| 10,479 | 221 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/commands.c | /* Command processing for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
/**/
#include "third_party/make/dep.h"
#include "third_party/make/filedef.h"
#include "third_party/make/job.h"
#include "third_party/make/variable.h"
/**/
#include "third_party/make/commands.h"
/* clang-format off */
#define FILE_LIST_SEPARATOR ' '
static unsigned long
dep_hash_1 (const void *key)
{
const struct dep *d = key;
return_STRING_HASH_1 (dep_name (d));
}
static unsigned long
dep_hash_2 (const void *key)
{
const struct dep *d = key;
return_STRING_HASH_2 (dep_name (d));
}
static int
dep_hash_cmp (const void *x, const void *y)
{
const struct dep *dx = x;
const struct dep *dy = y;
return strcmp (dep_name (dx), dep_name (dy));
}
/* Set FILE's automatic variables up. */
void
set_file_variables (struct file *file)
{
struct dep *d;
const char *at, *percent, *star, *less;
#ifndef NO_ARCHIVES
/* If the target is an archive member 'lib(member)',
then $@ is 'lib' and $% is 'member'. */
if (ar_name (file->name))
{
size_t len;
const char *cp;
char *p;
cp = strchr (file->name, '(');
p = alloca (cp - file->name + 1);
memcpy (p, file->name, cp - file->name);
p[cp - file->name] = '\0';
at = p;
len = strlen (cp + 1);
p = alloca (len);
memcpy (p, cp + 1, len - 1);
p[len - 1] = '\0';
percent = p;
}
else
#endif /* NO_ARCHIVES. */
{
at = file->name;
percent = "";
}
/* $* is the stem from an implicit or static pattern rule. */
if (file->stem == 0)
{
/* In Unix make, $* is set to the target name with
any suffix in the .SUFFIXES list stripped off for
explicit rules. We store this in the 'stem' member. */
const char *name;
size_t len;
#ifndef NO_ARCHIVES
if (ar_name (file->name))
{
name = strchr (file->name, '(') + 1;
len = strlen (name) - 1;
}
else
#endif
{
name = file->name;
len = strlen (name);
}
for (d = enter_file (strcache_add (".SUFFIXES"))->deps; d ; d = d->next)
{
size_t slen = strlen (dep_name (d));
if (len > slen && strneq (dep_name (d), name + (len - slen), slen))
{
file->stem = strcache_add_len (name, len - slen);
break;
}
}
if (d == 0)
file->stem = "";
}
star = file->stem;
/* $< is the first not order-only dependency. */
less = "";
for (d = file->deps; d != 0; d = d->next)
if (!d->ignore_mtime && !d->ignore_automatic_vars)
{
if (!d->need_2nd_expansion)
less = dep_name (d);
break;
}
if (file->cmds != 0 && file->cmds == default_file->cmds)
/* This file got its commands from .DEFAULT.
In this case $< is the same as $@. */
less = at;
#define DEFINE_VARIABLE(name, len, value) \
(void) define_variable_for_file (name,len,value,o_automatic,0,file)
/* Define the variables. */
DEFINE_VARIABLE ("<", 1, less);
DEFINE_VARIABLE ("*", 1, star);
DEFINE_VARIABLE ("@", 1, at);
DEFINE_VARIABLE ("%", 1, percent);
/* Compute the values for $^, $+, $?, and $|. */
{
static char *plus_value=0, *bar_value=0, *qmark_value=0;
static size_t plus_max=0, bar_max=0, qmark_max=0;
size_t qmark_len, plus_len, bar_len;
char *cp;
char *caret_value;
char *qp;
char *bp;
size_t len;
struct hash_table dep_hash;
void **slot;
/* Compute first the value for $+, which is supposed to contain
duplicate dependencies as they were listed in the makefile. */
plus_len = 0;
bar_len = 0;
for (d = file->deps; d != 0; d = d->next)
{
if (!d->need_2nd_expansion && !d->ignore_automatic_vars)
{
if (d->ignore_mtime)
bar_len += strlen (dep_name (d)) + 1;
else
plus_len += strlen (dep_name (d)) + 1;
}
}
if (bar_len == 0)
bar_len++;
if (plus_len == 0)
plus_len++;
if (plus_len > plus_max)
plus_value = xrealloc (plus_value, plus_max = plus_len);
cp = plus_value;
qmark_len = plus_len + 1; /* Will be this or less. */
for (d = file->deps; d != 0; d = d->next)
if (! d->ignore_mtime && ! d->need_2nd_expansion && ! d->ignore_automatic_vars)
{
const char *c = dep_name (d);
#ifndef NO_ARCHIVES
if (ar_name (c))
{
c = strchr (c, '(') + 1;
len = strlen (c) - 1;
}
else
#endif
len = strlen (c);
memcpy (cp, c, len);
cp += len;
*cp++ = FILE_LIST_SEPARATOR;
if (! (d->changed || always_make_flag))
qmark_len -= len + 1; /* Don't space in $? for this one. */
}
/* Kill the last space and define the variable. */
cp[cp > plus_value ? -1 : 0] = '\0';
DEFINE_VARIABLE ("+", 1, plus_value);
/* Compute the values for $^, $?, and $|. */
cp = caret_value = plus_value; /* Reuse the buffer; it's big enough. */
if (qmark_len > qmark_max)
qmark_value = xrealloc (qmark_value, qmark_max = qmark_len);
qp = qmark_value;
if (bar_len > bar_max)
bar_value = xrealloc (bar_value, bar_max = bar_len);
bp = bar_value;
/* Make sure that no dependencies are repeated in $^, $?, and $|. It
would be natural to combine the next two loops but we can't do it
because of a situation where we have two dep entries, the first
is order-only and the second is normal (see below). */
hash_init (&dep_hash, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
for (d = file->deps; d != 0; d = d->next)
{
if (d->need_2nd_expansion || d->ignore_automatic_vars)
continue;
slot = hash_find_slot (&dep_hash, d);
if (HASH_VACANT (*slot))
hash_insert_at (&dep_hash, d, slot);
else
{
/* Check if the two prerequisites have different ignore_mtime.
If so then we need to "upgrade" one that is order-only. */
struct dep* hd = (struct dep*) *slot;
if (d->ignore_mtime != hd->ignore_mtime)
d->ignore_mtime = hd->ignore_mtime = 0;
}
}
for (d = file->deps; d != 0; d = d->next)
{
const char *c;
if (d->need_2nd_expansion || d->ignore_automatic_vars || hash_find_item (&dep_hash, d) != d)
continue;
c = dep_name (d);
#ifndef NO_ARCHIVES
if (ar_name (c))
{
c = strchr (c, '(') + 1;
len = strlen (c) - 1;
}
else
#endif
len = strlen (c);
if (d->ignore_mtime)
{
memcpy (bp, c, len);
bp += len;
*bp++ = FILE_LIST_SEPARATOR;
}
else
{
memcpy (cp, c, len);
cp += len;
*cp++ = FILE_LIST_SEPARATOR;
if (d->changed || always_make_flag)
{
memcpy (qp, c, len);
qp += len;
*qp++ = FILE_LIST_SEPARATOR;
}
}
}
hash_free (&dep_hash, 0);
/* Kill the last spaces and define the variables. */
cp[cp > caret_value ? -1 : 0] = '\0';
DEFINE_VARIABLE ("^", 1, caret_value);
qp[qp > qmark_value ? -1 : 0] = '\0';
DEFINE_VARIABLE ("?", 1, qmark_value);
bp[bp > bar_value ? -1 : 0] = '\0';
DEFINE_VARIABLE ("|", 1, bar_value);
}
#undef DEFINE_VARIABLE
}
/* Chop CMDS up into individual command lines if necessary.
Also set the 'lines_flags' and 'any_recurse' members. */
void
chop_commands (struct commands *cmds)
{
unsigned int nlines;
unsigned short idx;
char **lines;
/* If we don't have any commands,
or we already parsed them, never mind. */
if (!cmds || cmds->command_lines != 0)
return;
/* Chop CMDS->commands up into lines in CMDS->command_lines. */
if (one_shell)
{
size_t l = strlen (cmds->commands);
nlines = 1;
lines = xmalloc (nlines * sizeof (char *));
lines[0] = xstrdup (cmds->commands);
/* Strip the trailing newline. */
if (l > 0 && lines[0][l-1] == '\n')
lines[0][l-1] = '\0';
}
else
{
const char *p;
nlines = 5;
lines = xmalloc (nlines * sizeof (char *));
idx = 0;
p = cmds->commands;
while (*p != '\0')
{
const char *end = p;
find_end:;
end = strchr (end, '\n');
if (end == 0)
end = p + strlen (p);
else if (end > p && end[-1] == '\\')
{
int backslash = 1;
const char *b;
for (b = end - 2; b >= p && *b == '\\'; --b)
backslash = !backslash;
if (backslash)
{
++end;
goto find_end;
}
}
if (idx == nlines)
{
nlines += 2;
lines = xrealloc (lines, nlines * sizeof (char *));
}
lines[idx++] = xstrndup (p, (size_t) (end - p));
p = end;
if (*p != '\0')
++p;
}
if (idx != nlines)
{
nlines = idx;
lines = xrealloc (lines, nlines * sizeof (char *));
}
}
/* Finally, set the corresponding CMDS->lines_flags elements and the
CMDS->any_recurse flag. */
if (nlines > USHRT_MAX)
ON (fatal, &cmds->fileinfo, _("Recipe has too many lines (%ud)"), nlines);
cmds->ncommand_lines = (unsigned short)nlines;
cmds->command_lines = lines;
cmds->any_recurse = 0;
cmds->lines_flags = xmalloc (nlines);
for (idx = 0; idx < nlines; ++idx)
{
unsigned char flags = 0;
const char *p = lines[idx];
while (ISBLANK (*p) || *p == '-' || *p == '@' || *p == '+')
switch (*(p++))
{
case '+':
flags |= COMMANDS_RECURSE;
break;
case '@':
flags |= COMMANDS_SILENT;
break;
case '-':
flags |= COMMANDS_NOERROR;
break;
}
/* If no explicit '+' was given, look for MAKE variable references. */
if (!(flags & COMMANDS_RECURSE)
&& (strstr (p, "$(MAKE)") != 0 || strstr (p, "${MAKE}") != 0))
flags |= COMMANDS_RECURSE;
cmds->lines_flags[idx] = flags;
cmds->any_recurse |= flags & COMMANDS_RECURSE ? 1 : 0;
}
}
/* Execute the commands to remake FILE. If they are currently executing,
return or have already finished executing, just return. Otherwise,
fork off a child process to run the first command line in the sequence. */
void
execute_file_commands (struct file *file)
{
const char *p;
/* Don't go through all the preparations if
the commands are nothing but whitespace. */
for (p = file->cmds->commands; *p != '\0'; ++p)
if (!ISSPACE (*p) && *p != '-' && *p != '@' && *p != '+')
break;
if (*p == '\0')
{
/* If there are no commands, assume everything worked. */
set_command_state (file, cs_running);
file->update_status = us_success;
notice_finished_file (file);
return;
}
/* First set the automatic variables according to this file. */
initialize_file_variables (file, 0);
set_file_variables (file);
/* If this is a loaded dynamic object, unload it before remaking.
Some systems don't support overwriting a loaded object. */
if (file->loaded)
unload_file (file->name);
/* Start the commands running. */
new_job (file);
}
/* This is set while we are inside fatal_error_signal,
so things can avoid nonreentrant operations. */
int handling_fatal_signal = 0;
/* Handle fatal signals. */
RETSIGTYPE
fatal_error_signal (int sig)
{
#ifdef WINDOWS32
extern HANDLE main_thread;
/* Windows creates a sperate thread for handling Ctrl+C, so we need
to suspend the main thread, or else we will have race conditions
when both threads call reap_children. */
if (main_thread)
{
DWORD susp_count = SuspendThread (main_thread);
if (susp_count != 0)
fprintf (stderr, "SuspendThread: suspend count = %ld\n", susp_count);
else if (susp_count == (DWORD)-1)
{
DWORD ierr = GetLastError ();
fprintf (stderr, "SuspendThread: error %ld: %s\n",
ierr, map_windows32_error_to_string (ierr));
}
}
#endif
handling_fatal_signal = 1;
/* Set the handling for this signal to the default.
It is blocked now while we run this handler. */
signal (sig, SIG_DFL);
/* A termination signal won't be sent to the entire
process group, but it means we want to kill the children. */
if (sig == SIGTERM)
{
struct child *c;
for (c = children; c != 0; c = c->next)
if (!c->remote && c->pid > 0)
(void) kill (c->pid, SIGTERM);
}
/* If we got a signal that means the user
wanted to kill make, remove pending targets. */
if (sig == SIGTERM || sig == SIGINT
|| sig == SIGHUP
|| sig == SIGQUIT
|| sig == SIGPIPE
)
{
struct child *c;
/* Remote children won't automatically get signals sent
to the process group, so we must send them. */
for (c = children; c != 0; c = c->next)
if (c->remote && c->pid > 0)
(void) remote_kill (c->pid, sig);
for (c = children; c != 0; c = c->next)
{
delete_child_targets (c);
delete_tmpdir (c);
}
/* Clean up the children. We don't just use the call below because
we don't want to print the "Waiting for children" message. */
while (job_slots_used > 0)
reap_children (1, 0);
}
else
/* Wait for our children to die. */
while (job_slots_used > 0)
reap_children (1, 1);
/* Delete any non-precious intermediate files that were made. */
remove_intermediates (1);
if (sig == SIGQUIT)
/* We don't want to send ourselves SIGQUIT, because it will
cause a core dump. Just exit instead. */
exit (MAKE_TROUBLE);
#ifdef WINDOWS32
if (main_thread)
CloseHandle (main_thread);
/* Cannot call W32_kill with a pid (it needs a handle). The exit
status of 130 emulates what happens in Bash. */
exit (130);
#else
/* Signal the same code; this time it will really be fatal. The signal
will be unblocked when we return and arrive then to kill us. */
if (kill (getpid (), sig) < 0)
pfatal_with_name ("kill");
#endif /* not WINDOWS32 */
}
/* Delete FILE unless it's precious or not actually a file (phony),
and it has changed on disk since we last stat'd it. */
static void
delete_target (struct file *file, const char *on_behalf_of)
{
struct stat st;
int e;
if (file->precious || file->phony)
return;
#ifndef NO_ARCHIVES
if (ar_name (file->name))
{
time_t file_date = (file->last_mtime == NONEXISTENT_MTIME
? (time_t) -1
: (time_t) FILE_TIMESTAMP_S (file->last_mtime));
if (ar_member_date (file->name) != file_date)
{
if (on_behalf_of)
OSS (error, NILF,
_("*** [%s] Archive member '%s' may be bogus; not deleted"),
on_behalf_of, file->name);
else
OS (error, NILF,
_("*** Archive member '%s' may be bogus; not deleted"),
file->name);
}
return;
}
#endif
EINTRLOOP (e, stat (file->name, &st));
if (e == 0
&& S_ISREG (st.st_mode)
&& FILE_TIMESTAMP_STAT_MODTIME (file->name, st) != file->last_mtime)
{
if (on_behalf_of)
OSS (error, NILF,
_("*** [%s] Deleting file '%s'"), on_behalf_of, file->name);
else
OS (error, NILF, _("*** Deleting file '%s'"), file->name);
if (unlink (file->name) < 0
&& errno != ENOENT) /* It disappeared; so what. */
perror_with_name ("unlink: ", file->name);
}
}
/* Delete all non-precious targets of CHILD unless they were already deleted.
Set the flag in CHILD to say they've been deleted. */
void
delete_child_targets (struct child *child)
{
struct dep *d;
if (child->deleted || child->pid < 0)
return;
/* Delete the target file if it changed. */
delete_target (child->file, NULL);
/* Also remove any non-precious targets listed in the 'also_make' member. */
for (d = child->file->also_make; d != 0; d = d->next)
delete_target (d->file, child->file->name);
child->deleted = 1;
}
/* Print out the commands in CMDS. */
void
print_commands (const struct commands *cmds)
{
const char *s;
fputs (_("# recipe to execute"), stdout);
if (cmds->fileinfo.filenm == 0)
puts (_(" (built-in):"));
else
printf (_(" (from '%s', line %lu):\n"),
cmds->fileinfo.filenm, cmds->fileinfo.lineno);
s = cmds->commands;
while (*s != '\0')
{
const char *end;
int bs;
/* Print one full logical recipe line: find a non-escaped newline. */
for (end = s, bs = 0; *end != '\0'; ++end)
{
if (*end == '\n' && !bs)
break;
bs = *end == '\\' ? !bs : 0;
}
printf ("%c%.*s\n", cmd_prefix, (int) (end - s), s);
s = end + (end[0] == '\n');
}
}
| 18,213 | 679 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/version.c | /* clang-format off */
/* Record version and build host architecture for GNU make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* We use <config.h> instead of "config.h" so that a compilation
using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
(which it would do because makeint.h was found in $srcdir). */
#include "third_party/make/config.h"
#ifndef MAKE_HOST
# define MAKE_HOST "unknown"
#endif
const char *version_string = VERSION;
const char *make_host = MAKE_HOST;
/*
Local variables:
version-control: never
End:
*/
| 1,209 | 35 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/expand.c | /* Variable expansion functions for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
/* clang-format off */
#include "third_party/make/makeint.inc"
/**/
#include "third_party/make/filedef.h"
#include "third_party/make/job.h"
#include "third_party/make/commands.h"
#include "third_party/make/variable.h"
#include "third_party/make/rule.h"
/* Initially, any errors reported when expanding strings will be reported
against the file where the error appears. */
const floc **expanding_var = &reading_file;
/* The next two describe the variable output buffer.
This buffer is used to hold the variable-expansion of a line of the
makefile. It is made bigger with realloc whenever it is too small.
variable_buffer_length is the size currently allocated.
variable_buffer is the address of the buffer.
For efficiency, it's guaranteed that the buffer will always have
VARIABLE_BUFFER_ZONE extra bytes allocated. This allows you to add a few
extra chars without having to call a function. Note you should never use
these bytes unless you're _sure_ you have room (you know when the buffer
length was last checked. */
#define VARIABLE_BUFFER_ZONE 5
static size_t variable_buffer_length;
char *variable_buffer;
/* Subroutine of variable_expand and friends:
The text to add is LENGTH chars starting at STRING to the variable_buffer.
The text is added to the buffer at PTR, and the updated pointer into
the buffer is returned as the value. Thus, the value returned by
each call to variable_buffer_output should be the first argument to
the following call. */
char *
variable_buffer_output (char *ptr, const char *string, size_t length)
{
size_t newlen = length + (ptr - variable_buffer);
if ((newlen + VARIABLE_BUFFER_ZONE) > variable_buffer_length)
{
size_t offset = ptr - variable_buffer;
variable_buffer_length = (newlen + 100 > 2 * variable_buffer_length
? newlen + 100
: 2 * variable_buffer_length);
variable_buffer = xrealloc (variable_buffer, variable_buffer_length);
ptr = variable_buffer + offset;
}
memcpy (ptr, string, length);
return ptr + length;
}
/* Return a pointer to the beginning of the variable buffer. */
static char *
initialize_variable_output (void)
{
/* If we don't have a variable output buffer yet, get one. */
if (variable_buffer == 0)
{
variable_buffer_length = 200;
variable_buffer = xmalloc (variable_buffer_length);
variable_buffer[0] = '\0';
}
return variable_buffer;
}
/* Recursively expand V. The returned string is malloc'd. */
static char *allocated_variable_append (const struct variable *v);
char *
recursively_expand_for_file (struct variable *v, struct file *file)
{
char *value;
const floc *this_var;
const floc **saved_varp;
struct variable_set_list *save = 0;
int set_reading = 0;
/* Don't install a new location if this location is empty.
This can happen for command-line variables, builtin variables, etc. */
saved_varp = expanding_var;
if (v->fileinfo.filenm)
{
this_var = &v->fileinfo;
expanding_var = &this_var;
}
/* If we have no other file-reading context, use the variable's context. */
if (!reading_file)
{
set_reading = 1;
reading_file = &v->fileinfo;
}
if (v->expanding)
{
if (!v->exp_count)
/* Expanding V causes infinite recursion. Lose. */
OS (fatal, *expanding_var,
_("Recursive variable '%s' references itself (eventually)"),
v->name);
--v->exp_count;
}
if (file)
{
save = current_variable_set_list;
current_variable_set_list = file->variables;
}
v->expanding = 1;
if (v->append)
value = allocated_variable_append (v);
else
value = allocated_variable_expand (v->value);
v->expanding = 0;
if (set_reading)
reading_file = 0;
if (file)
current_variable_set_list = save;
expanding_var = saved_varp;
return value;
}
/* Expand a simple reference to variable NAME, which is LENGTH chars long. */
static inline char *
reference_variable (char *o, const char *name, size_t length)
{
struct variable *v;
char *value;
v = lookup_variable (name, length);
if (v == 0)
warn_undefined (name, length);
/* If there's no variable by that name or it has no value, stop now. */
if (v == 0 || (*v->value == '\0' && !v->append))
return o;
value = (v->recursive ? recursively_expand (v) : v->value);
o = variable_buffer_output (o, value, strlen (value));
if (v->recursive)
free (value);
return o;
}
/* Scan STRING for variable references and expansion-function calls. Only
LENGTH bytes of STRING are actually scanned. If LENGTH is -1, scan until
a null byte is found.
Write the results to LINE, which must point into 'variable_buffer'. If
LINE is NULL, start at the beginning of the buffer.
Return a pointer to LINE, or to the beginning of the buffer if LINE is
NULL.
*/
char *
variable_expand_string (char *line, const char *string, size_t length)
{
struct variable *v;
const char *p, *p1;
char *save;
char *o;
size_t line_offset;
if (!line)
line = initialize_variable_output ();
o = line;
line_offset = line - variable_buffer;
if (length == 0)
{
variable_buffer_output (o, "", 1);
return (variable_buffer);
}
/* We need a copy of STRING: due to eval, it's possible that it will get
freed as we process it (it might be the value of a variable that's reset
for example). Also having a nil-terminated string is handy. */
save = length == SIZE_MAX ? xstrdup (string) : xstrndup (string, length);
p = save;
while (1)
{
/* Copy all following uninteresting chars all at once to the
variable output buffer, and skip them. Uninteresting chars end
at the next $ or the end of the input. */
p1 = strchr (p, '$');
o = variable_buffer_output (o, p, p1 != 0 ? (size_t) (p1 - p) : strlen (p) + 1);
if (p1 == 0)
break;
p = p1 + 1;
/* Dispatch on the char that follows the $. */
switch (*p)
{
case '$':
case '\0':
/* $$ or $ at the end of the string means output one $ to the
variable output buffer. */
o = variable_buffer_output (o, p1, 1);
break;
case '(':
case '{':
/* $(...) or ${...} is the general case of substitution. */
{
char openparen = *p;
char closeparen = (openparen == '(') ? ')' : '}';
const char *begp;
const char *beg = p + 1;
char *op;
char *abeg = NULL;
const char *end, *colon;
op = o;
begp = p;
if (handle_function (&op, &begp))
{
o = op;
p = begp;
break;
}
/* Is there a variable reference inside the parens or braces?
If so, expand it before expanding the entire reference. */
end = strchr (beg, closeparen);
if (end == 0)
/* Unterminated variable reference. */
O (fatal, *expanding_var, _("unterminated variable reference"));
p1 = lindex (beg, end, '$');
if (p1 != 0)
{
/* BEG now points past the opening paren or brace.
Count parens or braces until it is matched. */
int count = 0;
for (p = beg; *p != '\0'; ++p)
{
if (*p == openparen)
++count;
else if (*p == closeparen && --count < 0)
break;
}
/* If COUNT is >= 0, there were unmatched opening parens
or braces, so we go to the simple case of a variable name
such as '$($(a)'. */
if (count < 0)
{
abeg = expand_argument (beg, p); /* Expand the name. */
beg = abeg;
end = strchr (beg, '\0');
}
}
else
/* Advance P to the end of this reference. After we are
finished expanding this one, P will be incremented to
continue the scan. */
p = end;
/* This is not a reference to a built-in function and
any variable references inside are now expanded.
Is the resultant text a substitution reference? */
colon = lindex (beg, end, ':');
if (colon)
{
/* This looks like a substitution reference: $(FOO:A=B). */
const char *subst_beg = colon + 1;
const char *subst_end = lindex (subst_beg, end, '=');
if (subst_end == 0)
/* There is no = in sight. Punt on the substitution
reference and treat this as a variable name containing
a colon, in the code below. */
colon = 0;
else
{
const char *replace_beg = subst_end + 1;
const char *replace_end = end;
/* Extract the variable name before the colon
and look up that variable. */
v = lookup_variable (beg, colon - beg);
if (v == 0)
warn_undefined (beg, colon - beg);
/* If the variable is not empty, perform the
substitution. */
if (v != 0 && *v->value != '\0')
{
char *pattern, *replace, *ppercent, *rpercent;
char *value = (v->recursive
? recursively_expand (v)
: v->value);
/* Copy the pattern and the replacement. Add in an
extra % at the beginning to use in case there
isn't one in the pattern. */
pattern = alloca (subst_end - subst_beg + 2);
*(pattern++) = '%';
memcpy (pattern, subst_beg, subst_end - subst_beg);
pattern[subst_end - subst_beg] = '\0';
replace = alloca (replace_end - replace_beg + 2);
*(replace++) = '%';
memcpy (replace, replace_beg,
replace_end - replace_beg);
replace[replace_end - replace_beg] = '\0';
/* Look for %. Set the percent pointers properly
based on whether we find one or not. */
ppercent = find_percent (pattern);
if (ppercent)
{
++ppercent;
rpercent = find_percent (replace);
if (rpercent)
++rpercent;
}
else
{
ppercent = pattern;
rpercent = replace;
--pattern;
--replace;
}
o = patsubst_expand_pat (o, value, pattern, replace,
ppercent, rpercent);
if (v->recursive)
free (value);
}
}
}
if (colon == 0)
/* This is an ordinary variable reference.
Look up the value of the variable. */
o = reference_variable (o, beg, end - beg);
free (abeg);
}
break;
default:
if (ISSPACE (p[-1]))
break;
/* A $ followed by a random char is a variable reference:
$a is equivalent to $(a). */
o = reference_variable (o, p, 1);
break;
}
if (*p == '\0')
break;
++p;
}
free (save);
variable_buffer_output (o, "", 1);
return (variable_buffer + line_offset);
}
/* Scan LINE for variable references and expansion-function calls.
Build in 'variable_buffer' the result of expanding the references and calls.
Return the address of the resulting string, which is null-terminated
and is valid only until the next time this function is called. */
char *
variable_expand (const char *line)
{
return variable_expand_string (NULL, line, SIZE_MAX);
}
/* Expand an argument for an expansion function.
The text starting at STR and ending at END is variable-expanded
into a null-terminated string that is returned as the value.
This is done without clobbering 'variable_buffer' or the current
variable-expansion that is in progress. */
char *
expand_argument (const char *str, const char *end)
{
char *tmp, *alloc = NULL;
char *r;
if (str == end)
return xstrdup ("");
if (!end || *end == '\0')
return allocated_variable_expand (str);
if (end - str + 1 > 1000)
tmp = alloc = xmalloc (end - str + 1);
else
tmp = alloca (end - str + 1);
memcpy (tmp, str, end - str);
tmp[end - str] = '\0';
r = allocated_variable_expand (tmp);
if (alloc)
free (alloc);
return r;
}
/* Expand LINE for FILE. Error messages refer to the file and line where
FILE's commands were found. Expansion uses FILE's variable set list. */
char *
variable_expand_for_file (const char *line, struct file *file)
{
char *result;
struct variable_set_list *savev;
const floc *savef;
if (file == 0)
return variable_expand (line);
savev = current_variable_set_list;
current_variable_set_list = file->variables;
savef = reading_file;
if (file->cmds && file->cmds->fileinfo.filenm)
reading_file = &file->cmds->fileinfo;
else
reading_file = 0;
result = variable_expand (line);
current_variable_set_list = savev;
reading_file = savef;
return result;
}
/* Like allocated_variable_expand, but for += target-specific variables.
First recursively construct the variable value from its appended parts in
any upper variable sets. Then expand the resulting value. */
static char *
variable_append (const char *name, size_t length,
const struct variable_set_list *set, int local)
{
const struct variable *v;
char *buf = 0;
int nextlocal;
/* If there's nothing left to check, return the empty buffer. */
if (!set)
return initialize_variable_output ();
/* If this set is local and the next is not a parent, then next is local. */
nextlocal = local && set->next_is_parent == 0;
/* Try to find the variable in this variable set. */
v = lookup_variable_in_set (name, length, set->set);
/* If there isn't one, or this one is private, try the set above us. */
if (!v || (!local && v->private_var))
return variable_append (name, length, set->next, nextlocal);
/* If this variable type is append, first get any upper values.
If not, initialize the buffer. */
if (v->append)
buf = variable_append (name, length, set->next, nextlocal);
else
buf = initialize_variable_output ();
/* Append this value to the buffer, and return it.
If we already have a value, first add a space. */
if (buf > variable_buffer)
buf = variable_buffer_output (buf, " ", 1);
/* Either expand it or copy it, depending. */
if (! v->recursive)
return variable_buffer_output (buf, v->value, strlen (v->value));
buf = variable_expand_string (buf, v->value, strlen (v->value));
return (buf + strlen (buf));
}
static char *
allocated_variable_append (const struct variable *v)
{
char *val;
/* Construct the appended variable value. */
char *obuf = variable_buffer;
size_t olen = variable_buffer_length;
variable_buffer = 0;
val = variable_append (v->name, strlen (v->name),
current_variable_set_list, 1);
variable_buffer_output (val, "", 1);
val = variable_buffer;
variable_buffer = obuf;
variable_buffer_length = olen;
return val;
}
/* Like variable_expand_for_file, but the returned string is malloc'd.
This function is called a lot. It wants to be efficient. */
char *
allocated_variable_expand_for_file (const char *line, struct file *file)
{
char *value;
char *obuf = variable_buffer;
size_t olen = variable_buffer_length;
variable_buffer = 0;
value = variable_expand_for_file (line, file);
variable_buffer = obuf;
variable_buffer_length = olen;
return value;
}
/* Install a new variable_buffer context, returning the current one for
safe-keeping. */
void
install_variable_buffer (char **bufp, size_t *lenp)
{
*bufp = variable_buffer;
*lenp = variable_buffer_length;
variable_buffer = 0;
initialize_variable_output ();
}
/* Restore a previously-saved variable_buffer setting (free the current one).
*/
void
restore_variable_buffer (char *buf, size_t len)
{
free (variable_buffer);
variable_buffer = buf;
variable_buffer_length = len;
}
| 18,144 | 595 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/findprog-in.c | /* clang-format off */
/* Locating a program in a given path.
Copyright (C) 2001-2004, 2006-2020 Free Software Foundation, Inc.
Written by Bruno Haible <[email protected]>, 2001, 2019.
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 <https://www.gnu.org/licenses/>. */
#include "libc/errno.h"
#include "libc/str/str.h"
#include "libc/mem/mem.h"
#include "third_party/make/config.h"
/* Specification. */
#include "third_party/make/findprog.h"
#include "libc/sysv/consts/ok.h"
#include "third_party/make/filename.h"
#include "third_party/make/concat-filename.h"
#include "third_party/make/xalloc.h"
#if (defined _WIN32 && !defined __CYGWIN__) || defined __EMX__ || defined __DJGPP__
/* Native Windows, OS/2, DOS */
# define NATIVE_SLASH '\\'
#else
/* Unix */
# define NATIVE_SLASH '/'
#endif
/* Separator in PATH like lists of pathnames. */
#if (defined _WIN32 && !defined __CYGWIN__) || defined __EMX__ || defined __DJGPP__
/* Native Windows, OS/2, DOS */
# define PATH_SEPARATOR ';'
#else
/* Unix */
# define PATH_SEPARATOR ':'
#endif
/* The list of suffixes that the execlp/execvp function tries when searching
for the program. */
static const char * const suffixes[] =
{
#if defined _WIN32 && !defined __CYGWIN__ /* Native Windows */
"", ".com", ".exe", ".bat", ".cmd"
/* Note: Files without any suffix are not considered executable. */
/* Note: The cmd.exe program does a different lookup: It searches according
to the PATHEXT environment variable.
See <https://stackoverflow.com/questions/7839150/>.
Also, it executes files ending .bat and .cmd directly without letting the
kernel interpret the program file. */
#elif defined __CYGWIN__
"", ".exe", ".com"
#elif defined __EMX__
"", ".exe"
#elif defined __DJGPP__
"", ".com", ".exe", ".bat"
#else /* Unix */
""
#endif
};
const char *
find_in_given_path (const char *progname, const char *path,
bool optimize_for_exec)
{
{
bool has_slash = false;
{
const char *p;
for (p = progname; *p != '\0'; p++)
if (ISSLASH (*p))
{
has_slash = true;
break;
}
}
if (has_slash)
{
/* If progname contains a slash, it is either absolute or relative to
the current directory. PATH is not used. */
if (optimize_for_exec)
/* The execl/execv/execlp/execvp functions will try the various
suffixes anyway and fail if no executable is found. */
return progname;
else
{
/* Try the various suffixes and see whether one of the files
with such a suffix is actually executable. */
int failure_errno;
size_t i;
#if defined _WIN32 && !defined __CYGWIN__ /* Native Windows */
const char *progbasename;
{
const char *p;
progbasename = progname;
for (p = progname; *p != '\0'; p++)
if (ISSLASH (*p))
progbasename = p + 1;
}
#endif
/* Try all platform-dependent suffixes. */
failure_errno = ENOENT;
for (i = 0; i < sizeof (suffixes) / sizeof (suffixes[0]); i++)
{
const char *suffix = suffixes[i];
#if defined _WIN32 && !defined __CYGWIN__ /* Native Windows */
/* File names without a '.' are not considered executable, and
for file names with a '.' no additional suffix is tried. */
if ((*suffix != '\0') != (strchr (progbasename, '.') != NULL))
#endif
{
/* Concatenate progname and suffix. */
char *progpathname =
xconcatenated_filename ("", progname, suffix);
/* On systems which have the eaccess() system call, let's
use it. On other systems, let's hope that this program
is not installed setuid or setgid, so that it is ok to
call access() despite its design flaw. */
if (eaccess (progpathname, X_OK) == 0)
{
/* Found! */
if (strcmp (progpathname, progname) == 0)
{
free (progpathname);
return progname;
}
else
return progpathname;
}
if (errno != ENOENT)
failure_errno = errno;
free (progpathname);
}
}
errno = failure_errno;
return NULL;
}
}
}
if (path == NULL)
/* If PATH is not set, the default search path is implementation dependent.
In practice, it is treated like an empty PATH. */
path = "";
{
int failure_errno;
/* Make a copy, to prepare for destructive modifications. */
char *path_copy = xstrdup (path);
char *path_rest;
char *cp;
failure_errno = ENOENT;
for (path_rest = path_copy; ; path_rest = cp + 1)
{
const char *dir;
bool last;
size_t i;
/* Extract next directory in PATH. */
dir = path_rest;
for (cp = path_rest; *cp != '\0' && *cp != PATH_SEPARATOR; cp++)
;
last = (*cp == '\0');
*cp = '\0';
/* Empty PATH components designate the current directory. */
if (dir == cp)
dir = ".";
/* Try all platform-dependent suffixes. */
for (i = 0; i < sizeof (suffixes) / sizeof (suffixes[0]); i++)
{
const char *suffix = suffixes[i];
#if defined _WIN32 && !defined __CYGWIN__ /* Native Windows */
/* File names without a '.' are not considered executable, and
for file names with a '.' no additional suffix is tried. */
if ((*suffix != '\0') != (strchr (progname, '.') != NULL))
#endif
{
/* Concatenate dir, progname, and suffix. */
char *progpathname =
xconcatenated_filename (dir, progname, suffix);
/* On systems which have the eaccess() system call, let's
use it. On other systems, let's hope that this program
is not installed setuid or setgid, so that it is ok to
call access() despite its design flaw. */
if (eaccess (progpathname, X_OK) == 0)
{
/* Found! */
if (strcmp (progpathname, progname) == 0)
{
free (progpathname);
/* Add the "./" prefix for real, that
xconcatenated_filename() optimized away. This
avoids a second PATH search when the caller uses
execl/execv/execlp/execvp. */
progpathname =
XNMALLOC (2 + strlen (progname) + 1, char);
progpathname[0] = '.';
progpathname[1] = NATIVE_SLASH;
memcpy (progpathname + 2, progname,
strlen (progname) + 1);
}
free (path_copy);
return progpathname;
}
if (errno != ENOENT)
failure_errno = errno;
free (progpathname);
}
}
if (last)
break;
}
/* Not found in PATH. */
free (path_copy);
errno = failure_errno;
return NULL;
}
}
| 8,506 | 252 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/stddef.h | /* clang-format off */
/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* A substitute for POSIX 2008 <stddef.h>, for platforms that have issues.
Copyright (C) 2009-2020 Free Software Foundation, 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; either version 3, 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/>. */
/* Written by Eric Blake. */
/*
* POSIX 2008 <stddef.h> for platforms that have issues.
* <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/stddef.h.html>
*/
#if __GNUC__ >= 3
#pragma GCC system_header
#endif
#if defined __need_wchar_t || defined __need_size_t \
|| defined __need_ptrdiff_t || defined __need_NULL \
|| defined __need_wint_t
/* Special invocation convention inside gcc header files. In
particular, gcc provides a version of <stddef.h> that blindly
redefines NULL even when __need_wint_t was defined, even though
wint_t is not normally provided by <stddef.h>. Hence, we must
remember if special invocation has ever been used to obtain wint_t,
in which case we need to clean up NULL yet again. */
# if !(defined _GL_STDDEF_H && defined _GL_STDDEF_WINT_T)
# ifdef __need_wint_t
# define _GL_STDDEF_WINT_T
# endif
# endif
#else
/* Normal invocation convention. */
# ifndef _GL_STDDEF_H
/* The include_next requires a split double-inclusion guard. */
/* On NetBSD 5.0, the definition of NULL lacks proper parentheses. */
# if (0 \
&& (!defined _GL_STDDEF_H || defined _GL_STDDEF_WINT_T))
# undef NULL
# ifdef __cplusplus
/* ISO C++ says that the macro NULL must expand to an integer constant
expression, hence '((void *) 0)' is not allowed in C++. */
# if __GNUG__ >= 3
/* GNU C++ has a __null macro that behaves like an integer ('int' or
'long') but has the same size as a pointer. Use that, to avoid
warnings. */
# define NULL __null
# else
# define NULL 0L
# endif
# else
# define NULL ((void *) 0)
# endif
# endif
# ifndef _GL_STDDEF_H
# define _GL_STDDEF_H
/* Some platforms lack wchar_t. */
#if !1
# define wchar_t int
#endif
/* Some platforms lack max_align_t. The check for _GCC_MAX_ALIGN_T is
a hack in case the configure-time test was done with g++ even though
we are currently compiling with gcc.
On MSVC, max_align_t is defined only in C++ mode, after <cstddef> was
included. Its definition is good since it has an alignment of 8 (on x86
and x86_64). */
#if defined _MSC_VER && defined __cplusplus
#else
# if ! (0 || defined _GCC_MAX_ALIGN_T)
# if !GNULIB_defined_max_align_t
/* On the x86, the maximum storage alignment of double, long, etc. is 4,
but GCC's C11 ABI for x86 says that max_align_t has an alignment of 8,
and the C11 standard allows this. Work around this problem by
using __alignof__ (which returns 8 for double) rather than _Alignof
(which returns 4), and align each union member accordingly. */
# ifdef __GNUC__
# define _GL_STDDEF_ALIGNAS(type) \
__attribute__ ((__aligned__ (__alignof__ (type))))
# else
# define _GL_STDDEF_ALIGNAS(type) /* */
# endif
typedef union
{
char *__p _GL_STDDEF_ALIGNAS (char *);
double __d _GL_STDDEF_ALIGNAS (double);
long double __ld _GL_STDDEF_ALIGNAS (long double);
long int __i _GL_STDDEF_ALIGNAS (long int);
} rpl_max_align_t;
# define max_align_t rpl_max_align_t
# define GNULIB_defined_max_align_t 1
# endif
# endif
#endif
# endif /* _GL_STDDEF_H */
# endif /* _GL_STDDEF_H */
#endif /* __need_XXX */
| 4,008 | 121 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/hash.c | /* hash.c -- hash table maintenance
Copyright (C) 1995, 1999, 2002, 2010 Free Software Foundation, Inc.
Written by Greg McGary <[email protected]> <[email protected]>
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
/**/
#include "libc/assert.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/bsr.h"
#include "libc/intrin/likely.h"
#include "libc/log/check.h"
#include "third_party/make/hash.h"
/* clang-format off */
#define CALLOC(t, n) ((t *) xcalloc (sizeof (t) * (n)))
#define MALLOC(t, n) ((t *) xmalloc (sizeof (t) * (n)))
#define REALLOC(o, t, n) ((t *) xrealloc ((o), sizeof (t) * (n)))
#define CLONE(o, t, n) ((t *) memcpy (MALLOC (t, (n)), (o), sizeof (t) * (n)))
static void hash_rehash __P((struct hash_table* ht));
static unsigned long round_up_2 __P((unsigned long rough));
/* Implement double hashing with open addressing. The table size is
always a power of two. The secondary ('increment') hash function
is forced to return an odd-value, in order to be relatively prime
to the table size. This guarantees that the increment can
potentially hit every slot in the table during collision
resolution. */
void *hash_deleted_item = &hash_deleted_item;
/* Force the table size to be a power of two, possibly rounding up the
given size. */
void
hash_init (struct hash_table *ht, unsigned long size,
hash_func_t hash_1, hash_func_t hash_2, hash_cmp_func_t hash_cmp)
{
ht->ht_size = round_up_2 (size);
ht->ht_empty_slots = ht->ht_size;
ht->ht_vec = (void**) CALLOC (struct token *, ht->ht_size);
if (ht->ht_vec == 0)
{
fprintf (stderr, _("can't allocate %lu bytes for hash table: memory exhausted"),
ht->ht_size * (unsigned long) sizeof (struct token *));
exit (MAKE_TROUBLE);
}
ht->ht_capacity = ht->ht_size - (ht->ht_size / 16); /* 93.75% loading factor */
ht->ht_fill = 0;
ht->ht_collisions = 0;
ht->ht_lookups = 0;
ht->ht_rehashes = 0;
ht->ht_hash_1 = hash_1;
ht->ht_hash_2 = hash_2;
ht->ht_compare = hash_cmp;
}
/* Load an array of items into 'ht'. */
void
hash_load (struct hash_table *ht, void *item_table,
unsigned long cardinality, unsigned long size)
{
char *items = (char *) item_table;
while (cardinality--)
{
hash_insert (ht, items);
items += size;
}
}
/* Returns the address of the table slot matching 'key'. If 'key' is
not found, return the address of an empty slot suitable for
inserting 'key'. The caller is responsible for incrementing
ht_fill on insertion. */
void **
hash_find_slot (struct hash_table *ht, const void *key)
{
void **slot;
void **deleted_slot = 0;
unsigned int hash_2 = 0;
unsigned int hash_1 = (*ht->ht_hash_1) (key);
ht->ht_lookups++;
for (;;)
{
hash_1 &= (ht->ht_size - 1);
slot = &ht->ht_vec[hash_1];
if (*slot == 0)
return (deleted_slot ? deleted_slot : slot);
if (*slot == hash_deleted_item)
{
if (deleted_slot == 0)
deleted_slot = slot;
}
else
{
if (key == *slot)
return slot;
if ((*ht->ht_compare) (key, *slot) == 0)
return slot;
ht->ht_collisions++;
}
if (!hash_2)
hash_2 = (*ht->ht_hash_2) (key) | 1;
hash_1 += hash_2;
}
}
void *
hash_find_item (struct hash_table *ht, const void *key)
{
void **slot = hash_find_slot (ht, key);
return ((HASH_VACANT (*slot)) ? 0 : *slot);
}
void *
hash_insert (struct hash_table *ht, const void *item)
{
void **slot = hash_find_slot (ht, item);
const void *old_item = *slot;
hash_insert_at (ht, item, slot);
return (void *)((HASH_VACANT (old_item)) ? 0 : old_item);
}
void *
hash_insert_at (struct hash_table *ht, const void *item, const void *slot)
{
const void *old_item = *(void **) slot;
if (HASH_VACANT (old_item))
{
ht->ht_fill++;
if (old_item == 0)
ht->ht_empty_slots--;
old_item = item;
}
*(void const **) slot = item;
if (ht->ht_empty_slots < ht->ht_size - ht->ht_capacity)
{
hash_rehash (ht);
return (void *) hash_find_slot (ht, item);
}
else
return (void *) slot;
}
void *
hash_delete (struct hash_table *ht, const void *item)
{
void **slot = hash_find_slot (ht, item);
return hash_delete_at (ht, slot);
}
void *
hash_delete_at (struct hash_table *ht, const void *slot)
{
void *item = *(void **) slot;
if (!HASH_VACANT (item))
{
*(void const **) slot = hash_deleted_item;
ht->ht_fill--;
return item;
}
else
return 0;
}
void
hash_free_items (struct hash_table *ht)
{
void **vec = ht->ht_vec;
void **end = &vec[ht->ht_size];
for (; vec < end; vec++)
{
void *item = *vec;
if (!HASH_VACANT (item))
free (item);
*vec = 0;
}
ht->ht_fill = 0;
ht->ht_empty_slots = ht->ht_size;
}
void
hash_delete_items (struct hash_table *ht)
{
void **vec = ht->ht_vec;
void **end = &vec[ht->ht_size];
for (; vec < end; vec++)
*vec = 0;
ht->ht_fill = 0;
ht->ht_collisions = 0;
ht->ht_lookups = 0;
ht->ht_rehashes = 0;
ht->ht_empty_slots = ht->ht_size;
}
void
hash_free (struct hash_table *ht, int free_items)
{
if (free_items)
hash_free_items (ht);
else
{
ht->ht_fill = 0;
ht->ht_empty_slots = ht->ht_size;
}
free (ht->ht_vec);
ht->ht_vec = 0;
ht->ht_capacity = 0;
}
void
hash_map (struct hash_table *ht, hash_map_func_t map)
{
void **slot;
void **end = &ht->ht_vec[ht->ht_size];
for (slot = ht->ht_vec; slot < end; slot++)
{
if (!HASH_VACANT (*slot))
(*map) (*slot);
}
}
void
hash_map_arg (struct hash_table *ht, hash_map_arg_func_t map, void *arg)
{
void **slot;
void **end = &ht->ht_vec[ht->ht_size];
for (slot = ht->ht_vec; slot < end; slot++)
{
if (!HASH_VACANT (*slot))
(*map) (*slot, arg);
}
}
/* Double the size of the hash table in the event of overflow... */
static void
hash_rehash (struct hash_table *ht)
{
unsigned long old_ht_size = ht->ht_size;
void **old_vec = ht->ht_vec;
void **ovp;
if (ht->ht_fill >= ht->ht_capacity)
{
ht->ht_size *= 2;
ht->ht_capacity = ht->ht_size - (ht->ht_size >> 4);
}
ht->ht_rehashes++;
ht->ht_vec = (void **) CALLOC (struct token *, ht->ht_size);
for (ovp = old_vec; ovp < &old_vec[old_ht_size]; ovp++)
{
if (! HASH_VACANT (*ovp))
{
void **slot = hash_find_slot (ht, *ovp);
*slot = *ovp;
}
}
ht->ht_empty_slots = ht->ht_size - ht->ht_fill;
free (old_vec);
}
void
hash_print_stats (struct hash_table *ht, FILE *out_FILE)
{
fprintf (out_FILE, _("Load=%lu/%lu=%.0f%%, "), ht->ht_fill, ht->ht_size,
100.0 * (double) ht->ht_fill / (double) ht->ht_size);
fprintf (out_FILE, _("Rehash=%u, "), ht->ht_rehashes);
fprintf (out_FILE, _("Collisions=%lu/%lu=%.0f%%"), ht->ht_collisions, ht->ht_lookups,
(ht->ht_lookups
? (100.0 * (double) ht->ht_collisions / (double) ht->ht_lookups)
: 0));
}
/* Dump all items into a NULL-terminated vector. Use the
user-supplied vector, or malloc one. */
void **
hash_dump (struct hash_table *ht, void **vector_0, qsort_cmp_t compare)
{
void **vector;
void **slot;
void **end = &ht->ht_vec[ht->ht_size];
if (vector_0 == 0)
vector_0 = MALLOC (void *, ht->ht_fill + 1);
vector = vector_0;
for (slot = ht->ht_vec; slot < end; slot++)
if (!HASH_VACANT (*slot))
*vector++ = *slot;
*vector = 0;
if (compare)
qsort (vector_0, ht->ht_fill, sizeof (void *), compare);
return vector_0;
}
/* Round a given number up to the nearest power of 2. */
static unsigned long
round_up_2 (unsigned long n)
{
if (UNLIKELY(!n)) return 1;
return 2ul << _bsrl(n);
}
#define rol32(v, n) \
((v) << (n) | ((v) >> (32 - (n))))
/* jhash_mix -- mix 3 32-bit values reversibly. */
#define jhash_mix(a, b, c) \
{ \
a -= c; a ^= rol32(c, 4); c += b; \
b -= a; b ^= rol32(a, 6); a += c; \
c -= b; c ^= rol32(b, 8); b += a; \
a -= c; a ^= rol32(c, 16); c += b; \
b -= a; b ^= rol32(a, 19); a += c; \
c -= b; c ^= rol32(b, 4); b += a; \
}
/* jhash_final - final mixing of 3 32-bit values (a,b,c) into c */
#define jhash_final(a, b, c) \
{ \
c ^= b; c -= rol32(b, 14); \
a ^= c; a -= rol32(c, 11); \
b ^= a; b -= rol32(a, 25); \
c ^= b; c -= rol32(b, 16); \
a ^= c; a -= rol32(c, 4); \
b ^= a; b -= rol32(a, 14); \
c ^= b; c -= rol32(b, 24); \
}
/* An arbitrary initial parameter */
#define JHASH_INITVAL 0xdeadbeef
#define sum_get_unaligned_32(r, p) \
do { \
unsigned int val; \
memcpy(&val, (p), 4); \
r += val; \
} while(0);
unsigned int
jhash(unsigned const char *k, int length)
{
unsigned int a, b, c;
/* Set up the internal state */
a = b = c = JHASH_INITVAL + length;
/* All but the last block: affect some 32 bits of (a,b,c) */
while (length > 12) {
sum_get_unaligned_32(a, k);
sum_get_unaligned_32(b, k + 4);
sum_get_unaligned_32(c, k + 8);
jhash_mix(a, b, c);
length -= 12;
k += 12;
}
if (!length)
return c;
if (length > 8)
{
sum_get_unaligned_32(a, k);
length -= 4;
k += 4;
}
if (length > 4)
{
sum_get_unaligned_32(b, k);
length -= 4;
k += 4;
}
if (length == 4)
c += (unsigned)k[3]<<24;
if (length >= 3)
c += (unsigned)k[2]<<16;
if (length >= 2)
c += (unsigned)k[1]<<8;
c += k[0];
jhash_final(a, b, c);
return c;
}
#define UINTSZ sizeof (unsigned int)
/* First detect the presence of zeroes. If there is none, we can
sum the 4 bytes directly. Otherwise, the ifs are ordered as in the
big endian case, from the first byte in memory to the last. */
#define sum_up_to_nul(r, p, plen, flag) \
do { \
unsigned int val = 0; \
size_t pn = (plen); \
if (pn >= UINTSZ) \
memcpy(&val, (p), UINTSZ); \
else \
memcpy(&val, (p), pn); \
flag = ((val - 0x01010101) & ~val) & 0x80808080; \
if (!flag) \
r += val; \
else if (val & 0xFF) \
{ \
if ((val & 0xFF00) == 0) \
r += val & 0xFF; \
else if ((val & 0xFF0000) == 0) \
r += val & 0xFFFF; \
else \
r += val; \
} \
} while (0)
unsigned int
jhash_string(unsigned const char *k)
{
unsigned int a, b, c;
unsigned int have_nul = 0;
unsigned const char *start = k;
size_t klen = strlen ((const char*)k);
/* Set up the internal state */
a = b = c = JHASH_INITVAL;
for (; klen > 12; k += 12, klen -= 12)
{
a += READ32LE (k + 0);
b += READ32LE (k + 4);
c += READ32LE (k + 8);
jhash_mix (a, b, c);
}
/* All but the last block: affect some 32 bits of (a,b,c) */
for (;;) {
sum_up_to_nul(a, k, klen, have_nul);
if (have_nul)
break;
k += UINTSZ;
DCHECK (klen >= UINTSZ);
klen -= UINTSZ;
sum_up_to_nul(b, k, klen, have_nul);
if (have_nul)
break;
k += UINTSZ;
DCHECK (klen >= UINTSZ);
klen -= UINTSZ;
sum_up_to_nul(c, k, klen, have_nul);
if (have_nul)
break;
k += UINTSZ;
DCHECK (klen >= UINTSZ);
klen -= UINTSZ;
jhash_mix(a, b, c);
}
jhash_final(a, b, c);
return c + (unsigned) (k - start);
}
| 12,971 | 483 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/COPYING | GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
| 35,147 | 675 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/getopt.c | /* Getopt for GNU.
NOTE: getopt is now part of the C library, so if you don't know what
"Keep this file name-space clean" means, talk to [email protected]
before changing it!
Copyright (C) 1987-2020 Free Software Foundation, Inc.
NOTE: The canonical source of this file is maintained with the GNU C Library.
Bugs can be reported to [email protected].
GNU Make 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.
GNU Make 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/>. */
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
/* clang-format off */
/* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
Ditto for AIX 3.2 and <stdlib.h>. */
#ifndef _NO_PROTO
# define _NO_PROTO
#endif
#ifdef HAVE_CONFIG_H
#include "third_party/make/config.h"
#endif
#pragma GCC diagnostic ignored "-Wredundant-decls"
/* Comment out all this code if we are using the GNU C Library, and are not
actually compiling the library itself. This code is part of the GNU C
Library, but also included in many other GNU distributions. Compiling
and linking in this code is a waste when using the GNU C library
(especially if it is a shared library). Rather than having every GNU
program understand `configure --with-gnu-libc' and omit the object files,
it is simpler to just do this in the source for each such file. */
#define GETOPT_INTERFACE_VERSION 2
#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
# define ELIDE_CODE
# endif
#endif
#ifndef ELIDE_CODE
/* This is for other GNU distributions with internationalized messages.
When compiling libc, the _ macro is predefined. */
#include "third_party/make/gettext.h"
#define _(msgid) gettext (msgid)
/* This version of `getopt' appears to the caller like standard Unix 'getopt'
but it behaves differently for the user, since it allows the user
to intersperse the options with the other arguments.
As `getopt' works, it permutes the elements of ARGV so that,
when it is done, all the options precede everything else. Thus
all application programs are extended to handle flexible argument order.
Setting the environment variable POSIXLY_CORRECT disables permutation.
Then the behavior is completely standard.
GNU application programs can use a third alternative mode in which
they can distinguish the relative order of options and other arguments. */
#include "third_party/make/getopt.h"
/* For communication from `getopt' to the caller.
When `getopt' finds an option that takes an argument,
the argument value is returned here.
Also, when `ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
char *optarg = NULL;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
and for communication between successive calls to `getopt'.
On entry to `getopt', zero means this is the first call; initialize.
When `getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
Otherwise, `optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
/* 1003.2 says this must be 1 before any call. */
int optind = 1;
/* Formerly, initialization of getopt depended on optind==0, which
causes problems with re-calling getopt as programs generally don't
know that. */
int __getopt_initialized = 0;
/* The next char to be scanned in the option-element
in which the last option character we returned was found.
This allows us to pick up the scan where we left off.
If this is zero, or a null string, it means resume the scan
by advancing to the next ARGV-element. */
static char *nextchar;
/* Callers store zero here to inhibit the error message
for unrecognized options. */
int opterr = 1;
/* Set to an option character which was unrecognized.
This must be initialized on some systems to avoid linking in the
system's own getopt implementation. */
int optopt = '?';
/* Describe how to deal with options that follow non-option ARGV-elements.
If the caller did not specify anything,
the default is REQUIRE_ORDER if the environment variable
POSIXLY_CORRECT is defined, PERMUTE otherwise.
REQUIRE_ORDER means don't recognize them as options;
stop option processing when the first non-option is seen.
This is what Unix does.
This mode of operation is selected by either setting the environment
variable POSIXLY_CORRECT, or using `+' as the first character
of the list of option characters.
PERMUTE is the default. We permute the contents of ARGV as we scan,
so that eventually all the non-options are at the end. This allows options
to be given in any order, even with programs that were not written to
expect this.
RETURN_IN_ORDER is an option available to programs that were written
to expect options and other ARGV-elements in any order and that care about
the ordering of the two. We describe each non-option ARGV-element
as if it were the argument of an option with character code 1.
Using `-' as the first character of the list of option characters
selects this mode of operation.
The special argument `--' forces an end of option-scanning regardless
of the value of `ordering'. In the case of RETURN_IN_ORDER, only
`--' can cause `getopt' to return -1 with `optind' != ARGC. */
static enum
{
REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
} ordering;
/* Value of POSIXLY_CORRECT environment variable. */
static char *posixly_correct;
#ifdef __GNU_LIBRARY__
/* We want to avoid inclusion of string.h with non-GNU libraries
because there are many ways it can cause trouble.
On some systems, it contains special magic macros that don't work
in GCC. */
# define my_index strchr
#else
/* Avoid depending on library functions or files
whose names are inconsistent. */
#ifndef getenv
extern char *getenv ();
#endif
static char *
my_index (const char *str, int chr)
{
while (*str)
{
if (*str == chr)
return (char *) str;
str++;
}
return 0;
}
/* If using GCC, we can safely declare strlen this way.
If not using GCC, it is ok not to declare it. */
#ifdef __GNUC__
/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
That was relevant to code that was here before. */
# if (!defined __STDC__ || !__STDC__) && !defined strlen
/* gcc with -traditional declares the built-in strlen to return int,
and has done so at least since version 2.4.5. -- rms. */
extern int strlen (const char *);
# endif /* not __STDC__ */
#endif /* __GNUC__ */
#endif /* not __GNU_LIBRARY__ */
/* Handle permutation of arguments. */
/* Describe the part of ARGV that contains non-options that have
been skipped. `first_nonopt' is the index in ARGV of the first of them;
`last_nonopt' is the index after the last of them. */
static int first_nonopt;
static int last_nonopt;
#ifdef _LIBC
/* Bash 2.0 gives us an environment variable containing flags
indicating ARGV elements that should not be considered arguments. */
/* Defined in getopt_init.c */
extern char *__getopt_nonoption_flags;
static int nonoption_flags_max_len;
static int nonoption_flags_len;
static int original_argc;
static char *const *original_argv;
/* Make sure the environment variable bash 2.0 puts in the environment
is valid for the getopt call we must make sure that the ARGV passed
to getopt is that one passed to the process. */
static void __attribute__ ((unused))
store_args_and_env (int argc, char *const *argv)
{
/* XXX This is no good solution. We should rather copy the args so
that we can compare them later. But we must not use malloc(3). */
original_argc = argc;
original_argv = argv;
}
# ifdef text_set_element
text_set_element (__libc_subinit, store_args_and_env);
# endif /* text_set_element */
# define SWAP_FLAGS(ch1, ch2) \
if (nonoption_flags_len > 0) \
{ \
char __tmp = __getopt_nonoption_flags[ch1]; \
__getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
__getopt_nonoption_flags[ch2] = __tmp; \
}
#else /* !_LIBC */
# define SWAP_FLAGS(ch1, ch2)
#endif /* _LIBC */
/* Exchange two adjacent subsequences of ARGV.
One subsequence is elements [first_nonopt,last_nonopt)
which contains all the non-options that have been skipped so far.
The other is elements [last_nonopt,optind), which contains all
the options processed since those non-options were skipped.
`first_nonopt' and `last_nonopt' are relocated so that they describe
the new indices of the non-options in ARGV after they are moved. */
#if defined __STDC__ && __STDC__
static void exchange (char **);
#endif
static void
exchange (char **argv)
{
int bottom = first_nonopt;
int middle = last_nonopt;
int top = optind;
char *tem;
/* Exchange the shorter segment with the far end of the longer segment.
That puts the shorter segment into the right place.
It leaves the longer segment in the right place overall,
but it consists of two parts that need to be swapped next. */
#ifdef _LIBC
/* First make sure the handling of the `__getopt_nonoption_flags'
string can work normally. Our top argument must be in the range
of the string. */
if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
{
/* We must extend the array. The user plays games with us and
presents new arguments. */
char *new_str = malloc (top + 1);
if (new_str == NULL)
nonoption_flags_len = nonoption_flags_max_len = 0;
else
{
memset (__mempcpy (new_str, __getopt_nonoption_flags,
nonoption_flags_max_len),
'\0', top + 1 - nonoption_flags_max_len);
nonoption_flags_max_len = top + 1;
__getopt_nonoption_flags = new_str;
}
}
#endif
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
{
/* Bottom segment is the short one. */
int len = middle - bottom;
register int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
}
else
{
/* Top segment is the short one. */
int len = top - middle;
register int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
SWAP_FLAGS (bottom + i, middle + i);
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
first_nonopt += (optind - last_nonopt);
last_nonopt = optind;
}
/* Initialize the internal data when the first call is made. */
#if defined __STDC__ && __STDC__
static const char *_getopt_initialize (int, char *const *, const char *);
#endif
static const char *
_getopt_initialize (int argc, char *const *argv, const char *optstring)
{
/* Start processing options with ARGV-element 1 (since ARGV-element 0
is the program name); the sequence of previously skipped
non-option ARGV-elements is empty. */
first_nonopt = last_nonopt = optind;
nextchar = NULL;
posixly_correct = getenv ("POSIXLY_CORRECT");
/* Determine how to handle the ordering of options and nonoptions. */
if (optstring[0] == '-')
{
ordering = RETURN_IN_ORDER;
++optstring;
}
else if (optstring[0] == '+')
{
ordering = REQUIRE_ORDER;
++optstring;
}
else if (posixly_correct != NULL)
ordering = REQUIRE_ORDER;
else
ordering = PERMUTE;
#ifdef _LIBC
if (posixly_correct == NULL
&& argc == original_argc && argv == original_argv)
{
if (nonoption_flags_max_len == 0)
{
if (__getopt_nonoption_flags == NULL
|| __getopt_nonoption_flags[0] == '\0')
nonoption_flags_max_len = -1;
else
{
const char *orig_str = __getopt_nonoption_flags;
int len = nonoption_flags_max_len = strlen (orig_str);
if (nonoption_flags_max_len < argc)
nonoption_flags_max_len = argc;
__getopt_nonoption_flags =
(char *) malloc (nonoption_flags_max_len);
if (__getopt_nonoption_flags == NULL)
nonoption_flags_max_len = -1;
else
memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
'\0', nonoption_flags_max_len - len);
}
}
nonoption_flags_len = nonoption_flags_max_len;
}
else
nonoption_flags_len = 0;
#endif
return optstring;
}
/* Scan elements of ARGV (whose length is ARGC) for option characters
given in OPTSTRING.
If an element of ARGV starts with '-', and is not exactly "-" or "--",
then it is an option element. The characters of this element
(aside from the initial '-') are option characters. If `getopt'
is called repeatedly, it returns successively each of the option characters
from each of the option elements.
If `getopt' finds another option character, it returns that character,
updating `optind' and `nextchar' so that the next call to `getopt' can
resume the scan with the following option character or ARGV-element.
If there are no more option characters, `getopt' returns -1.
Then `optind' is the index in ARGV of the first ARGV-element
that is not an option. (The ARGV-elements have been permuted
so that those that are not options now come last.)
OPTSTRING is a string containing the legitimate option characters.
If an option character is seen that is not listed in OPTSTRING,
return '?' after printing an error message. If you set `opterr' to
zero, the error message is suppressed but we still return '?'.
If a char in OPTSTRING is followed by a colon, that means it wants an arg,
so the following text in the same ARGV-element, or the text of the following
ARGV-element, is returned in `optarg'. Two colons mean an option that
wants an optional arg; if there is text in the current ARGV-element,
it is returned in `optarg', otherwise `optarg' is set to zero.
If OPTSTRING starts with `-' or `+', it requests different methods of
handling the non-option ARGV-elements.
See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
Long-named options begin with `--' instead of `-'.
Their names may be abbreviated as long as the abbreviation is unique
or is an exact match for some defined option. If they have an
argument, it follows the option name in the same ARGV-element, separated
from the option name by a `=', or else the in next ARGV-element.
When `getopt' finds a long-named option, it returns 0 if that option's
`flag' field is nonzero, the value of the option's `val' field
if the `flag' field is zero.
The elements of ARGV aren't really const, because we permute them.
But we pretend they're const in the prototype to be compatible
with other systems.
LONGOPTS is a vector of `struct option' terminated by an
element containing a name which is zero.
LONGIND returns the index in LONGOPT of the long-named option found.
It is only valid when a long-named option has been found by the most
recent call.
If LONG_ONLY is nonzero, '-' as well as '--' can introduce
long-named options. */
int
_getopt_internal (int argc, char *const *argv, const char *optstring,
const struct option *longopts, int *longind, int long_only)
{
optarg = NULL;
if (optind == 0 || !__getopt_initialized)
{
if (optind == 0)
optind = 1; /* Don't scan ARGV[0], the program name. */
optstring = _getopt_initialize (argc, argv, optstring);
__getopt_initialized = 1;
}
/* Test whether ARGV[optind] points to a non-option argument.
Either it does not have option syntax, or there is an environment flag
from the shell indicating it is not an option. The later information
is only used when the used in the GNU libc. */
#ifdef _LIBC
# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
|| (optind < nonoption_flags_len \
&& __getopt_nonoption_flags[optind] == '1'))
#else
# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
#endif
if (nextchar == NULL || *nextchar == '\0')
{
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
moved back by the user (who may also have changed the arguments). */
if (last_nonopt > optind)
last_nonopt = optind;
if (first_nonopt > optind)
first_nonopt = optind;
if (ordering == PERMUTE)
{
/* If we have just processed some options following some non-options,
exchange them so that the options come first. */
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange ((char **) argv);
else if (last_nonopt != optind)
first_nonopt = optind;
/* Skip any additional non-options
and extend the range of non-options previously skipped. */
while (optind < argc && NONOPTION_P)
optind++;
last_nonopt = optind;
}
/* The special ARGV-element `--' means premature end of options.
Skip it like a null option,
then exchange with previous non-options as if it were an option,
then skip everything else like a non-option. */
if (optind != argc && !strcmp (argv[optind], "--"))
{
optind++;
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange ((char **) argv);
else if (first_nonopt == last_nonopt)
first_nonopt = optind;
last_nonopt = argc;
optind = argc;
}
/* If we have done all the ARGV-elements, stop the scan
and back over any non-options that we skipped and permuted. */
if (optind == argc)
{
/* Set the next-arg-index to point at the non-options
that we previously skipped, so the caller will digest them. */
if (first_nonopt != last_nonopt)
optind = first_nonopt;
return -1;
}
/* If we have come to a non-option and did not permute it,
either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P)
{
if (ordering == REQUIRE_ORDER)
return -1;
optarg = argv[optind++];
return 1;
}
/* We have found another option-ARGV-element.
Skip the initial punctuation. */
nextchar = (argv[optind] + 1
+ (longopts != NULL && argv[optind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
/* Check whether the ARGV-element is a long option.
If long_only and the ARGV-element has the form "-f", where f is
a valid short option, don't consider it an abbreviated form of
a long option that starts with f. Otherwise there would be no
way to give the -f short option.
On the other hand, if there's a long option "fubar" and
the ARGV-element is "-fu", do consider that an abbreviation of
the long option, just like "--fu", and not "-f" with arg "u".
This distinction seems to be the most useful approach. */
if (longopts != NULL
&& (argv[optind][1] == '-'
|| (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar)
== (unsigned int) strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (opterr)
fprintf (stderr, _("%s: option '%s' is ambiguous\n"),
argv[0], argv[optind]);
nextchar += strlen (nextchar);
optind++;
optopt = 0;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
optind++;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (opterr)
if (argv[optind - 1][1] == '-')
/* --option */
fprintf (stderr,
_("%s: option '--%s' doesn't allow an argument\n"),
argv[0], pfound->name);
else
/* +option or -option */
fprintf (stderr,
_("%s: option '%c%s' doesn't allow an argument\n"),
argv[0], argv[optind - 1][0], pfound->name);
nextchar += strlen (nextchar);
optopt = pfound->val;
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (opterr)
fprintf (stderr,
_("%s: option '%s' requires an argument\n"),
argv[0], argv[optind - 1]);
nextchar += strlen (nextchar);
optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/* Can't find it as a long option. If this is not getopt_long_only,
or the option starts with '--' or is not a valid short
option, then it's an error.
Otherwise interpret it as a short option. */
if (!long_only || argv[optind][1] == '-'
|| my_index (optstring, *nextchar) == NULL)
{
if (opterr)
{
if (argv[optind][1] == '-')
/* --option */
fprintf (stderr, _("%s: unrecognized option '--%s'\n"),
argv[0], nextchar);
else
/* +option or -option */
fprintf (stderr, _("%s: unrecognized option '%c%s'\n"),
argv[0], argv[optind][0], nextchar);
}
nextchar = (char *) "";
optind++;
optopt = 0;
return '?';
}
}
/* Look at and handle the next short option-character. */
{
char c = *nextchar++;
char *temp = my_index (optstring, c);
/* Increment `optind' when we start to process its last character. */
if (*nextchar == '\0')
++optind;
if (temp == NULL || c == ':')
{
if (opterr)
{
if (posixly_correct)
/* 1003.2 specifies the format of this message. */
fprintf (stderr, _("%s: illegal option -- %c\n"),
argv[0], c);
else
fprintf (stderr, _("%s: invalid option -- %c\n"),
argv[0], c);
}
optopt = c;
return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';')
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = 0;
int option_index;
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (opterr)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr, _("%s: option requires an argument -- %c\n"),
argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
return c;
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
/* optarg is now the argument, see if it's in the
table of longopts. */
for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar) == strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (opterr)
fprintf (stderr, _("%s: option '-W %s' is ambiguous\n"),
argv[0], argv[optind]);
nextchar += strlen (nextchar);
optind++;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (opterr)
fprintf (stderr, _("\
%s: option '-W %s' doesn't allow an argument\n"),
argv[0], pfound->name);
nextchar += strlen (nextchar);
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (opterr)
fprintf (stderr,
_("%s: option '%s' requires an argument\n"),
argv[0], argv[optind - 1]);
nextchar += strlen (nextchar);
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
nextchar = NULL;
return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':')
{
if (temp[2] == ':')
{
/* This is an option that accepts an argument optionally. */
if (*nextchar != '\0')
{
optarg = nextchar;
optind++;
}
else
optarg = NULL;
nextchar = NULL;
}
else
{
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (opterr)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr,
_("%s: option requires an argument -- %c\n"),
argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
nextchar = NULL;
}
}
return c;
}
}
int
getopt (int argc, char *const *argv, const char *optstring)
{
return _getopt_internal (argc, argv, optstring,
(const struct option *) 0,
(int *) 0,
0);
}
#endif /* Not ELIDE_CODE. */
#ifdef TEST
/* Compile with -DTEST to make an executable for use in testing
the above definition of `getopt'. */
int
main (int argc, char **argv)
{
int c;
int digit_optind = 0;
while (1)
{
int this_option_optind = optind ? optind : 1;
c = getopt (argc, argv, "abc:d:0123456789");
if (c == -1)
break;
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf ("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf ("option %c\n", c);
break;
case 'a':
printf ("option a\n");
break;
case 'b':
printf ("option b\n");
break;
case 'c':
printf ("option c with value '%s'\n", optarg);
break;
case '?':
break;
default:
printf ("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
printf ("\n");
}
exit (0);
}
#endif /* TEST */
| 29,143 | 997 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/config.h | /* src/config.h. Generated from config.h.in by configure. */
/* src/config.h.in. Generated from configure.ac by autoheader. */
#include "libc/calls/calls.h"
#define LANDLOCKMAKE_VERSION "1.5"
/* Define to the number of bits in type 'ptrdiff_t'. */
#define BITSIZEOF_PTRDIFF_T 64
/* Define to the number of bits in type 'sig_atomic_t'. */
#define BITSIZEOF_SIG_ATOMIC_T 32
/* Define to the number of bits in type 'size_t'. */
#define BITSIZEOF_SIZE_T 64
/* Define to the number of bits in type 'wchar_t'. */
#define BITSIZEOF_WCHAR_T 32
/* Define to the number of bits in type 'wint_t'. */
#define BITSIZEOF_WINT_T 32
/* Define to 1 if the `closedir' function returns void instead of `int'. */
/* #undef CLOSEDIR_VOID */
/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
systems. This function is required for `alloca.c' support on those systems.
*/
/* #undef CRAY_STACKSEG_END */
/* Define to 1 if using `alloca.c'. */
/* #undef C_ALLOCA */
/* Define to 1 for DGUX with <sys/dg_sys_info.h>. */
/* #undef DGUX */
/* Define to 1 if // is a file system root distinct from /. */
/* #undef DOUBLE_SLASH_IS_DISTINCT_ROOT */
/* Define to 1 if translation of program messages to the user's native
language is requested. */
/* #undef ENABLE_NLS */
/* Define this to 1 if F_DUPFD behavior does not match POSIX */
/* #undef FCNTL_DUPFD_BUGGY */
/* Use high resolution file timestamps if nonzero. */
#define FILE_TIMESTAMP_HI_RES 1
/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
whether the gnulib module fscanf shall be considered present. */
#define GNULIB_FSCANF 1
/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
whether the gnulib module msvc-nothrow shall be considered present. */
#define GNULIB_MSVC_NOTHROW 1
/* Define to 1 if printf and friends should be labeled with attribute
"__gnu_printf__" instead of "__printf__" */
/* #undef GNULIB_PRINTF_ATTRIBUTE_FLAVOR_GNU */
/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
whether the gnulib module scanf shall be considered present. */
#define GNULIB_SCANF 1
/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
whether the gnulib module strerror shall be considered present. */
#define GNULIB_STRERROR 1
/* Define to 1 when the gnulib module access should be tested. */
#define GNULIB_TEST_ACCESS 1
/* Define to 1 when the gnulib module close should be tested. */
#define GNULIB_TEST_CLOSE 1
/* Define to 1 when the gnulib module dup2 should be tested. */
#define GNULIB_TEST_DUP2 1
/* Define to 1 when the gnulib module fcntl should be tested. */
#define GNULIB_TEST_FCNTL 1
/* Define to 1 when the gnulib module getdtablesize should be tested. */
#define GNULIB_TEST_GETDTABLESIZE 1
/* Define to 1 when the gnulib module getloadavg should be tested. */
#define GNULIB_TEST_GETLOADAVG 1
/* Define to 1 when the gnulib module malloc-posix should be tested. */
#define GNULIB_TEST_MALLOC_POSIX 1
/* Define to 1 when the gnulib module stpcpy should be tested. */
#define GNULIB_TEST_STPCPY 1
/* Define to 1 when the gnulib module strerror should be tested. */
#define GNULIB_TEST_STRERROR 1
/* Define to 1 if you have 'alloca' after including <alloca.h>, a header that
may be supplied by this distribution. */
#define HAVE_ALLOCA 1
/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
*/
#define HAVE_ALLOCA_H 1
/* Define to 1 if you have the `atexit' function. */
#define HAVE_ATEXIT 1
/* Use case insensitive file names */
/* #undef HAVE_CASE_INSENSITIVE_FS */
/* Define to 1 if you have the Mac OS X function CFLocaleCopyCurrent in the
CoreFoundation framework. */
/* #undef HAVE_CFLOCALECOPYCURRENT */
/* Define to 1 if you have the Mac OS X function CFPreferencesCopyAppValue in
the CoreFoundation framework. */
/* #undef HAVE_CFPREFERENCESCOPYAPPVALUE */
/* Define if the GNU dcgettext() function is already present or preinstalled.
*/
/* #undef HAVE_DCGETTEXT */
/* Define to 1 if you have the declaration of `bsd_signal', and to 0 if you
don't. */
#define HAVE_DECL_BSD_SIGNAL 0
/* Define to 1 if you have the declaration of `dlerror', and to 0 if you
don't. */
#define HAVE_DECL_DLERROR 1
/* Define to 1 if you have the declaration of `dlopen', and to 0 if you don't.
*/
#define HAVE_DECL_DLOPEN 1
/* Define to 1 if you have the declaration of `dlsym', and to 0 if you don't.
*/
#define HAVE_DECL_DLSYM 1
/* Define to 1 if you have the declaration of `getdtablesize', and to 0 if you
don't. */
#define HAVE_DECL_GETDTABLESIZE 1
/* Define to 1 if you have the declaration of `program_invocation_name', and
to 0 if you don't. */
#define HAVE_DECL_PROGRAM_INVOCATION_NAME 1
/* Define to 1 if you have the declaration of `program_invocation_short_name',
and to 0 if you don't. */
#define HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME 1
/* Define to 1 if you have the declaration of `strerror_r', and to 0 if you
don't. */
#define HAVE_DECL_STRERROR_R 1
/* Define to 1 if you have the declaration of `sys_siglist', and to 0 if you
don't. */
#define HAVE_DECL_SYS_SIGLIST 0
/* Define to 1 if you have the declaration of `_sys_siglist', and to 0 if you
don't. */
#define HAVE_DECL__SYS_SIGLIST 0
/* Define to 1 if you have the declaration of `__argv', and to 0 if you don't.
*/
#define HAVE_DECL___ARGV 1
/* Define to 1 if you have the declaration of `__sys_siglist', and to 0 if you
don't. */
#define HAVE_DECL___SYS_SIGLIST 0
/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
*/
#define HAVE_DIRENT_H 1
/* Use platform specific coding */
/* #undef HAVE_DOS_PATHS */
/* Define to 1 if you have the `dup' function. */
#define HAVE_DUP 1
/* Define to 1 if you have the `dup2' function. */
#define HAVE_DUP2 1
/* Define to 1 if you have the `fcntl' function. */
#define HAVE_FCNTL 1
/* Define to 1 if you have the <fcntl.h> header file. */
#define HAVE_FCNTL_H 1
/* Define to 1 if you have the `fdopen' function. */
#define HAVE_FDOPEN 1
/* Define to 1 if you have the `fork' function. */
#define HAVE_FORK 1
/* Define to 1 if you have the `getcwd' function. */
#define HAVE_GETCWD 1
/* Define to 1 if you have the `getdtablesize' function. */
#define HAVE_GETDTABLESIZE 1
/* Define to 1 if you have the `getexecname' function. */
/* #undef HAVE_GETEXECNAME */
/* Define to 1 if you have the `getgroups' function. */
#define HAVE_GETGROUPS 1
/* Define to 1 if you have the `gethostbyname' function. */
/* #undef HAVE_GETHOSTBYNAME */
/* Define to 1 if you have the `gethostname' function. */
/* #undef HAVE_GETHOSTNAME */
/* Define to 1 if you have the `getprogname' function. */
/* #undef HAVE_GETPROGNAME */
/* Define to 1 if you have the `getrlimit' function. */
#define HAVE_GETRLIMIT 1
/* Define if the GNU gettext() function is already present or preinstalled. */
/* #undef HAVE_GETTEXT */
/* Define to 1 if you have a standard gettimeofday function */
#define HAVE_GETTIMEOFDAY 1
/* Embed GNU Guile support */
/* #undef HAVE_GUILE */
/* Define if you have the iconv() function and it works. */
/* #undef HAVE_ICONV */
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the `isatty' function. */
#define HAVE_ISATTY 1
/* Define to 1 if you have the `dgc' library (-ldgc). */
/* #undef HAVE_LIBDGC */
/* Define to 1 if you have the `kstat' library (-lkstat). */
/* #undef HAVE_LIBKSTAT */
/* Define to 1 if you have the `perfstat' library (-lperfstat). */
/* #undef HAVE_LIBPERFSTAT */
/* Define to 1 if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1
/* Define to 1 if you have the <locale.h> header file. */
#define HAVE_LOCALE_H 1
/* Define to 1 if the system has the type 'long long int'. */
#define HAVE_LONG_LONG_INT 1
/* Define to 1 if you have the `lstat' function. */
#define HAVE_LSTAT 1
/* Define to 1 if you have the <mach/mach.h> header file. */
/* #undef HAVE_MACH_MACH_H */
/* Define if the 'malloc' function is POSIX compliant. */
#define HAVE_MALLOC_POSIX 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `memrchr' function. */
#define HAVE_MEMRCHR 1
/* Define to 1 if you have the `mkstemp' function. */
#define HAVE_MKSTEMP 1
/* Define to 1 if you have the `mktemp' function. */
#define HAVE_MKTEMP 1
/* Define to 1 on MSVC platforms that have the "invalid parameter handler"
concept. */
/* #undef HAVE_MSVC_INVALID_PARAMETER_HANDLER */
/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
/* #undef HAVE_NDIR_H */
/* Define to 1 if you have the <nlist.h> header file. */
/* #undef HAVE_NLIST_H */
/* Define to 1 if you have the `pipe' function. */
#define HAVE_PIPE 1
/* Define to 1 if you have the `posix_spawn' function. */
#define HAVE_POSIX_SPAWN 1
/* Define to 1 if you have the `posix_spawnattr_setsigmask' function. */
#define HAVE_POSIX_SPAWNATTR_SETSIGMASK 1
/* Define to 1 if you have the `pselect' function. */
#define HAVE_PSELECT 1
/* Define to 1 if you have the `pstat_getdynamic' function. */
/* #undef HAVE_PSTAT_GETDYNAMIC */
/* Define to 1 if you have the `readlink' function. */
#define HAVE_READLINK 1
/* Define to 1 if you have the `realpath' function. */
#define HAVE_REALPATH 1
/* Define to 1 if <signal.h> defines the SA_RESTART constant. */
#define HAVE_SA_RESTART 1
/* Define to 1 if you have the `setdtablesize' function. */
/* #undef HAVE_SETDTABLESIZE */
/* Define to 1 if you have the `setegid' function. */
#define HAVE_SETEGID 1
/* Define to 1 if you have the `seteuid' function. */
#define HAVE_SETEUID 1
/* Define to 1 if you have the `setlinebuf' function. */
#define HAVE_SETLINEBUF 1
/* Define to 1 if you have the `setregid' function. */
#define HAVE_SETREGID 1
/* Define to 1 if you have the `setreuid' function. */
#define HAVE_SETREUID 1
/* Define to 1 if you have the `setrlimit' function. */
#define HAVE_SETRLIMIT 1
/* Define to 1 if you have the `setvbuf' function. */
#define HAVE_SETVBUF 1
/* Define to 1 if you have the `sigaction' function. */
#define HAVE_SIGACTION 1
/* Define to 1 if 'sig_atomic_t' is a signed integer type. */
#define HAVE_SIGNED_SIG_ATOMIC_T 1
/* Define to 1 if 'wchar_t' is a signed integer type. */
#define HAVE_SIGNED_WCHAR_T 1
/* Define to 1 if 'wint_t' is a signed integer type. */
/* #undef HAVE_SIGNED_WINT_T */
/* Define to 1 if you have the <spawn.h> header file. */
#define HAVE_SPAWN_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the `stpcpy' function. */
#define HAVE_STPCPY 1
/* Define to 1 if you have the `strcasecmp' function. */
#define HAVE_STRCASECMP 1
/* Define to 1 if you have the `strcmpi' function. */
/* #undef HAVE_STRCMPI */
/* Define to 1 if you have the `strcoll' function and it is properly defined.
*/
#define HAVE_STRCOLL 1
/* Define to 1 if you have the `strdup' function. */
#define HAVE_STRDUP 1
/* Define to 1 if you have the `strerror_r' function. */
#define HAVE_STRERROR_R 1
/* Define to 1 if you have the `stricmp' function. */
/* #undef HAVE_STRICMP */
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strncasecmp' function. */
#define HAVE_STRNCASECMP 1
/* Define to 1 if you have the `strncmpi' function. */
/* #undef HAVE_STRNCMPI */
/* Define to 1 if you have the `strndup' function. */
#define HAVE_STRNDUP 1
/* Define to 1 if you have the `strnicmp' function. */
/* #undef HAVE_STRNICMP */
/* Define to 1 if you have the `strsignal' function. */
#define HAVE_STRSIGNAL 1
/* Define to 1 if `d_type' is a member of `struct dirent'. */
#define HAVE_STRUCT_DIRENT_D_TYPE 1
/* Define to 1 if `n_un.n_name' is a member of `struct nlist'. */
/* #undef HAVE_STRUCT_NLIST_N_UN_N_NAME */
/* Define to 1 if you have the `symlink' function. */
#define HAVE_SYMLINK 1
/* Define to 1 if you have the <sys/bitypes.h> header file. */
/* #undef HAVE_SYS_BITYPES_H */
/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
*/
/* #undef HAVE_SYS_DIR_H */
/* Define to 1 if you have the <sys/file.h> header file. */
#define HAVE_SYS_FILE_H 1
/* Define to 1 if you have the <sys/inttypes.h> header file. */
/* #undef HAVE_SYS_INTTYPES_H */
/* Define to 1 if you have the <sys/loadavg.h> header file. */
/* #undef HAVE_SYS_LOADAVG_H */
/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
*/
/* #undef HAVE_SYS_NDIR_H */
/* Define to 1 if you have the <sys/param.h> header file. */
#define HAVE_SYS_PARAM_H 1
/* Define to 1 if you have the <sys/resource.h> header file. */
#define HAVE_SYS_RESOURCE_H 1
/* Define to 1 if you have the <sys/select.h> header file. */
#define HAVE_SYS_SELECT_H 1
/* Define to 1 if you have the <sys/socket.h> header file. */
#define HAVE_SYS_SOCKET_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/timeb.h> header file. */
/* #undef HAVE_SYS_TIMEB_H */
/* Define to 1 if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/wait.h> header file. */
#define HAVE_SYS_WAIT_H 1
/* Define to 1 if you have the `ttyname' function. */
#define HAVE_TTYNAME 1
/* Define to 1 if the system has the type `uintmax_t'. */
#define HAVE_UINTMAX_T 1
/* Define to 1 if you have the `umask' function. */
#define HAVE_UMASK 1
/* Define to 1 if you have the 'union wait' type in <sys/wait.h>. */
/* #undef HAVE_UNION_WAIT */
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if the system has the type 'unsigned long long int'. */
#define HAVE_UNSIGNED_LONG_LONG_INT 1
/* Define if you have a global __progname variable */
/* #undef HAVE_VAR___PROGNAME */
/* Define to 1 if you have the `wait3' function. */
#define HAVE_WAIT3 1
/* Define to 1 if you have the `waitpid' function. */
#define HAVE_WAITPID 1
/* Define to 1 if you have the <wchar.h> header file. */
#define HAVE_WCHAR_H 1
/* Define if you have the 'wchar_t' type. */
#define HAVE_WCHAR_T 1
/* Define to 1 if you have the <winsock2.h> header file. */
/* #undef HAVE_WINSOCK2_H */
/* Define if you have the 'wint_t' type. */
#define HAVE_WINT_T 1
/* Define to 1 if `fork' works. */
#define HAVE_WORKING_FORK 1
/* Define to 1 if O_NOATIME works. */
#define HAVE_WORKING_O_NOATIME 0
/* Define to 1 if O_NOFOLLOW works. */
#define HAVE_WORKING_O_NOFOLLOW 0
/* Define to 1 if the system has the type `_Bool'. */
#define HAVE__BOOL 1
/* Define to 1 if you have the `_set_invalid_parameter_handler' function. */
/* #undef HAVE__SET_INVALID_PARAMETER_HANDLER */
/* Build host information. */
#define MAKE_HOST "x86_64-cosmopolitan"
/* Define to 1 to enable job server support in GNU make. */
#define MAKE_JOBSERVER 1
/* Define to 1 to enable symbolic link timestamp checking. */
#define MAKE_SYMLINKS 1
/* Define to 1 if the nlist n_name member is a pointer */
/* #undef N_NAME_POINTER */
/* Name of package */
#define PACKAGE "make"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "[email protected]"
/* Define to the full name of this package. */
#define PACKAGE_NAME "GNU make"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "GNU make 4.3"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "make"
/* Define to the home page for this package. */
#define PACKAGE_URL "http://www.gnu.org/software/make/"
/* Define to the version of this package. */
#define PACKAGE_VERSION "4.3"
/* Define to the character that separates directories in PATH. */
#define PATH_SEPARATOR_CHAR ':'
/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type
'ptrdiff_t'. */
#define PTRDIFF_T_SUFFIX l
/* Define to 1 if strerror(0) does not return a message implying success. */
/* #undef REPLACE_STRERROR_0 */
/* Define as the return type of signal handlers (`int' or `void'). */
#define RETSIGTYPE void
/* Define to the name of the SCCS 'get' command. */
#define SCCS_GET "get"
/* Define to 1 if the SCCS 'get' command understands the '-G<file>' option. */
/* #undef SCCS_GET_MINUS_G */
/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type
'sig_atomic_t'. */
#define SIG_ATOMIC_T_SUFFIX
/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type
'size_t'. */
#define SIZE_T_SUFFIX ul
/* If using the C implementation of alloca, define if you know the
direction of stack growth for your system; otherwise it will be
automatically deduced at runtime.
STACK_DIRECTION > 0 => grows toward higher addresses
STACK_DIRECTION < 0 => grows toward lower addresses
STACK_DIRECTION = 0 => direction of growth unknown */
/* #undef STACK_DIRECTION */
/* Define to 1 if the `S_IS*' macros in <sys/stat.h> do not work properly. */
/* #undef STAT_MACROS_BROKEN */
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define to 1 if strerror_r returns char *. */
/* #undef STRERROR_R_CHAR_P */
/* Define if struct stat contains a nanoseconds field */
#define ST_MTIM_NSEC st_mtim.tv_nsec
/* Define to 1 on System V Release 4. */
/* #undef SVR4 */
/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
#define TIME_WITH_SYS_TIME 1
/* Define to 1 for Encore UMAX. */
/* #undef UMAX */
/* Define to 1 for Encore UMAX 4.3 that has <inq_status/cpustats.h> instead of
<sys/cpustats.h>. */
/* #undef UMAX4_3 */
/* Enable extensions on AIX 3, Interix. */
#ifndef _ALL_SOURCE
#define _ALL_SOURCE 1
#endif
/* Enable general extensions on macOS. */
#ifndef _DARWIN_C_SOURCE
#define _DARWIN_C_SOURCE 1
#endif
/* Enable GNU extensions on systems that have them. */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
/* Enable NetBSD extensions on NetBSD. */
#ifndef _NETBSD_SOURCE
#define _NETBSD_SOURCE 1
#endif
/* Enable OpenBSD extensions on NetBSD. */
#ifndef _OPENBSD_SOURCE
#define _OPENBSD_SOURCE 1
#endif
/* Enable threading extensions on Solaris. */
#ifndef _POSIX_PTHREAD_SEMANTICS
#define _POSIX_PTHREAD_SEMANTICS 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-5:2014. */
#ifndef __STDC_WANT_IEC_60559_ATTRIBS_EXT__
#define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-1:2014. */
#ifndef __STDC_WANT_IEC_60559_BFP_EXT__
#define __STDC_WANT_IEC_60559_BFP_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-2:2015. */
#ifndef __STDC_WANT_IEC_60559_DFP_EXT__
#define __STDC_WANT_IEC_60559_DFP_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-4:2015. */
#ifndef __STDC_WANT_IEC_60559_FUNCS_EXT__
#define __STDC_WANT_IEC_60559_FUNCS_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-3:2015. */
#ifndef __STDC_WANT_IEC_60559_TYPES_EXT__
#define __STDC_WANT_IEC_60559_TYPES_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TR 24731-2:2010. */
#ifndef __STDC_WANT_LIB_EXT2__
#define __STDC_WANT_LIB_EXT2__ 1
#endif
/* Enable extensions specified by ISO/IEC 24747:2009. */
#ifndef __STDC_WANT_MATH_SPEC_FUNCS__
#define __STDC_WANT_MATH_SPEC_FUNCS__ 1
#endif
/* Enable extensions on HP NonStop. */
#ifndef _TANDEM_SOURCE
#define _TANDEM_SOURCE 1
#endif
/* Enable X/Open extensions if necessary. HP-UX 11.11 defines
mbstate_t only if _XOPEN_SOURCE is defined to 500, regardless of
whether compiling with -Ae or -D_HPUX_SOURCE=1. */
#ifndef _XOPEN_SOURCE
/* # undef _XOPEN_SOURCE */
#endif
/* Enable X/Open compliant socket functions that do not require linking
with -lxnet on HP-UX 11.11. */
#ifndef _HPUX_ALT_XOPEN_SOCKET_API
#define _HPUX_ALT_XOPEN_SOCKET_API 1
#endif
/* Enable general extensions on Solaris. */
#ifndef __EXTENSIONS__
#define __EXTENSIONS__ 1
#endif
/* Version number of package */
#define VERSION "4.3"
/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type
'wchar_t'. */
#define WCHAR_T_SUFFIX
/* Use platform specific coding */
/* #undef WINDOWS32 */
/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type
'wint_t'. */
#define WINT_T_SUFFIX u
/* Define if using the dmalloc debugging malloc package */
/* #undef WITH_DMALLOC */
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
#if defined __BIG_ENDIAN__
#define WORDS_BIGENDIAN 1
#endif
#else
#ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
#endif
#endif
/* Enable large inode numbers on Mac OS X 10.5. */
#ifndef _DARWIN_USE_64_BIT_INODE
#define _DARWIN_USE_64_BIT_INODE 1
#endif
/* Number of bits in a file offset, on hosts where this is settable. */
/* #undef _FILE_OFFSET_BITS */
/* Define for large files, on AIX-style hosts. */
/* #undef _LARGE_FILES */
/* Define to 1 if on MINIX. */
/* #undef _MINIX */
/* Define to 1 to make NetBSD features available. MINIX 3 needs this. */
#define _NETBSD_SOURCE 1
/* The _Noreturn keyword of C11. */
#ifndef _Noreturn
#if (defined __cplusplus && \
((201103 <= __cplusplus && !(__GNUC__ == 4 && __GNUC_MINOR__ == 7)) || \
(defined _MSC_VER && 1900 <= _MSC_VER)) && \
0)
/* [[noreturn]] is not practically usable, because with it the syntax
extern _Noreturn void func (...);
would not be valid; such a declaration would only be valid with 'extern'
and '_Noreturn' swapped, or without the 'extern' keyword. However, some
AIX system header files and several gnulib header files use precisely
this syntax with 'extern'. */
#define _Noreturn [[noreturn]]
#elif ((!defined __cplusplus || defined __clang__) && \
(201112 <= (defined __STDC_VERSION__ ? __STDC_VERSION__ : 0) || \
4 < __GNUC__ + (7 <= __GNUC_MINOR__)))
/* _Noreturn works as-is. */
#elif 2 < __GNUC__ + (8 <= __GNUC_MINOR__) || 0x5110 <= __SUNPRO_C
#define _Noreturn __attribute__((__noreturn__))
#elif 1200 <= (defined _MSC_VER ? _MSC_VER : 0)
#define _Noreturn __declspec(noreturn)
#else
#define _Noreturn
#endif
#endif
/* Define to 2 if the system does not provide POSIX.1 features except with
this defined. */
/* #undef _POSIX_1_SOURCE */
/* Define to 1 if you need to in order for 'stat' and other things to work. */
/* #undef _POSIX_SOURCE */
/* For standard stat data types on VMS. */
#define _USE_STD_STAT 1
/* Define to 1 if the system <stdint.h> predates C++11. */
/* #undef __STDC_CONSTANT_MACROS */
/* Define to 1 if the system <stdint.h> predates C++11. */
/* #undef __STDC_LIMIT_MACROS */
/* The _GL_ASYNC_SAFE marker should be attached to functions that are
signal handlers (for signals other than SIGABRT, SIGPIPE) or can be
invoked from such signal handlers. Such functions have some restrictions:
* All functions that it calls should be marked _GL_ASYNC_SAFE as well,
or should be listed as async-signal-safe in POSIX
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04>
section 2.4.3. Note that malloc(), sprintf(), and fwrite(), in
particular, are NOT async-signal-safe.
* All memory locations (variables and struct fields) that these functions
access must be marked 'volatile'. This holds for both read and write
accesses. Otherwise the compiler might optimize away stores to and
reads from such locations that occur in the program, depending on its
data flow analysis. For example, when the program contains a loop
that is intended to inspect a variable set from within a signal handler
while (!signal_occurred)
;
the compiler is allowed to transform this into an endless loop if the
variable 'signal_occurred' is not declared 'volatile'.
Additionally, recall that:
* A signal handler should not modify errno (except if it is a handler
for a fatal signal and ends by raising the same signal again, thus
provoking the termination of the process). If it invokes a function
that may clobber errno, it needs to save and restore the value of
errno. */
#define _GL_ASYNC_SAFE
/* Define to empty if `const' does not conform to ANSI C. */
/* #undef const */
/* Define as 'access' if you don't have the eaccess() function. */
#define eaccess access
/* Please see the Gnulib manual for how to use these macros.
Suppress extern inline with HP-UX cc, as it appears to be broken; see
<https://lists.gnu.org/r/bug-texinfo/2013-02/msg00030.html>.
Suppress extern inline with Sun C in standards-conformance mode, as it
mishandles inline functions that call each other. E.g., for 'inline void f
(void) { } inline void g (void) { f (); }', c99 incorrectly complains
'reference to static identifier "f" in extern inline function'.
This bug was observed with Sun C 5.12 SunOS_i386 2011/11/16.
Suppress extern inline (with or without __attribute__ ((__gnu_inline__)))
on configurations that mistakenly use 'static inline' to implement
functions or macros in standard C headers like <ctype.h>. For example,
if isdigit is mistakenly implemented via a static inline function,
a program containing an extern inline function that calls isdigit
may not work since the C standard prohibits extern inline functions
from calling static functions (ISO C 99 section 6.7.4.(3).
This bug is known to occur on:
OS X 10.8 and earlier; see:
https://lists.gnu.org/r/bug-gnulib/2012-12/msg00023.html
DragonFly; see
http://muscles.dragonflybsd.org/bulk/clang-master-potential/20141111_102002/logs/ah-tty-0.3.12.log
FreeBSD; see:
https://lists.gnu.org/r/bug-gnulib/2014-07/msg00104.html
OS X 10.9 has a macro __header_inline indicating the bug is fixed for C and
for clang but remains for g++; see <https://trac.macports.org/ticket/41033>.
Assume DragonFly and FreeBSD will be similar.
GCC 4.3 and above with -std=c99 or -std=gnu99 implements ISO C99
inline semantics, unless -fgnu89-inline is used. It defines a macro
__GNUC_STDC_INLINE__ to indicate this situation or a macro
__GNUC_GNU_INLINE__ to indicate the opposite situation.
GCC 4.2 with -std=c99 or -std=gnu99 implements the GNU C inline
semantics but warns, unless -fgnu89-inline is used:
warning: C99 inline functions are not supported; using GNU89
warning: to disable this warning use -fgnu89-inline or the gnu_inline
function attribute It defines a macro __GNUC_GNU_INLINE__ to indicate this
situation.
*/
#if (((defined __APPLE__ && defined __MACH__) || defined __DragonFly__ || \
defined __FreeBSD__) && \
(defined __header_inline \
? (defined __cplusplus && defined __GNUC_STDC_INLINE__ && \
!defined __clang__) \
: ((!defined _DONT_USE_CTYPE_INLINE_ && \
(defined __GNUC__ || defined __cplusplus)) || \
(defined _FORTIFY_SOURCE && 0 < _FORTIFY_SOURCE && \
defined __GNUC__ && !defined __cplusplus))))
#define _GL_EXTERN_INLINE_STDHEADER_BUG
#endif
#if ((__GNUC__ ? defined __GNUC_STDC_INLINE__ && __GNUC_STDC_INLINE__ \
: (199901L <= __STDC_VERSION__ && !defined __HP_cc && \
!defined __PGI && !(defined __SUNPRO_C && __STDC__))) && \
!defined _GL_EXTERN_INLINE_STDHEADER_BUG)
#define _GL_INLINE inline
#define _GL_EXTERN_INLINE extern inline
#define _GL_EXTERN_INLINE_IN_USE
#elif (2 < __GNUC__ + (7 <= __GNUC_MINOR__) && !defined __STRICT_ANSI__ && \
!defined _GL_EXTERN_INLINE_STDHEADER_BUG)
#if defined __GNUC_GNU_INLINE__ && __GNUC_GNU_INLINE__
/* __gnu_inline__ suppresses a GCC 4.2 diagnostic. */
#define _GL_INLINE extern inline __attribute__((__gnu_inline__))
#else
#define _GL_INLINE extern inline
#endif
#define _GL_EXTERN_INLINE extern
#define _GL_EXTERN_INLINE_IN_USE
#else
#define _GL_INLINE static _GL_UNUSED
#define _GL_EXTERN_INLINE static _GL_UNUSED
#endif
/* In GCC 4.6 (inclusive) to 5.1 (exclusive),
suppress bogus "no previous prototype for 'FOO'"
and "no previous declaration for 'FOO'" diagnostics,
when FOO is an inline function in the header; see
<https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54113> and
<https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63877>. */
#if __GNUC__ == 4 && 6 <= __GNUC_MINOR__
#if defined __GNUC_STDC_INLINE__ && __GNUC_STDC_INLINE__
#define _GL_INLINE_HEADER_CONST_PRAGMA
#else
#define _GL_INLINE_HEADER_CONST_PRAGMA \
_Pragma("GCC diagnostic ignored \"-Wsuggest-attribute=const\"")
#endif
#define _GL_INLINE_HEADER_BEGIN \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wmissing-prototypes\"") \
_Pragma("GCC diagnostic ignored \"-Wmissing-declarations\"") \
_GL_INLINE_HEADER_CONST_PRAGMA
#define _GL_INLINE_HEADER_END _Pragma("GCC diagnostic pop")
#else
#define _GL_INLINE_HEADER_BEGIN
#define _GL_INLINE_HEADER_END
#endif
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef gid_t */
/* Work around a bug in Apple GCC 4.0.1 build 5465: In C99 mode, it supports
the ISO C 99 semantics of 'extern inline' (unlike the GNU C semantics of
earlier versions), but does not display it by setting __GNUC_STDC_INLINE__.
__APPLE__ && __MACH__ test for Mac OS X.
__APPLE_CC__ tests for the Apple compiler and its version.
__STDC_VERSION__ tests for the C99 mode. */
#if defined __APPLE__ && defined __MACH__ && __APPLE_CC__ >= 5465 && \
!defined __cplusplus && __STDC_VERSION__ >= 199901L && \
!defined __GNUC_STDC_INLINE__
#define __GNUC_STDC_INLINE__ 1
#endif
/* Define to `int' if <sys/types.h> does not define. */
/* #undef mode_t */
/* Define to `long int' if <sys/types.h> does not define. */
/* #undef off_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef pid_t */
/* Define to the equivalent of the C99 'restrict' keyword, or to
nothing if this is not supported. Do not define if restrict is
supported directly. */
#define restrict __restrict
/* Work around a bug in older versions of Sun C++, which did not
#define __restrict__ or support _Restrict or __restrict__
even though the corresponding Sun C compiler ended up with
"#define restrict _Restrict" or "#define restrict __restrict__"
in the previous line. This workaround can be removed once
we assume Oracle Developer Studio 12.5 (2016) or later. */
#if defined __SUNPRO_CC && !defined __RESTRICT && !defined __restrict__
#define _Restrict
#define __restrict__
#endif
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef ssize_t */
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef uid_t */
/* Define to the widest unsigned integer type if <stdint.h> and <inttypes.h>
do not define. */
/* #undef uintmax_t */
/* Define as a marker that can be attached to declarations that might not
be used. This helps to reduce warnings, such as from
GCC -Wunused-parameter. */
#if __GNUC__ >= 3 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7)
#define _GL_UNUSED __attribute__((__unused__))
#else
#define _GL_UNUSED
#endif
/* The name _UNUSED_PARAMETER_ is an earlier spelling, although the name
is a misnomer outside of parameter lists. */
#define _UNUSED_PARAMETER_ _GL_UNUSED
/* gcc supports the "unused" attribute on possibly unused labels, and
g++ has since version 4.5. Note to support C++ as well as C,
_GL_UNUSED_LABEL should be used with a trailing ; */
#if !defined __cplusplus || __GNUC__ > 4 || \
(__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
#define _GL_UNUSED_LABEL _GL_UNUSED
#else
#define _GL_UNUSED_LABEL
#endif
/* The __pure__ attribute was added in gcc 2.96. */
#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
#define _GL_ATTRIBUTE_PURE __attribute__((__pure__))
#else
#define _GL_ATTRIBUTE_PURE /* empty */
#endif
/* The __const__ attribute was added in gcc 2.95. */
#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)
#define _GL_ATTRIBUTE_CONST __attribute__((__const__))
#else
#define _GL_ATTRIBUTE_CONST /* empty */
#endif
/* The __malloc__ attribute was added in gcc 3. */
#if 3 <= __GNUC__
#define _GL_ATTRIBUTE_MALLOC __attribute__((__malloc__))
#else
#define _GL_ATTRIBUTE_MALLOC /* empty */
#endif
| 33,175 | 988 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/arscan.c | /* Library function for scanning an archive file.
Copyright (C) 1987-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "libc/sysv/consts/o.h"
#include "third_party/make/makeint.inc"
/* clang-format off */
#ifdef TEST
/* Hack, the real error() routine eventually pulls in die from main.c */
#define error(a, b, c, d)
#endif
/* On the sun386i and in System V rel 3, ar.h defines two different archive
formats depending upon whether you have defined PORTAR (normal) or PORT5AR
(System V Release 1). There is no default, one or the other must be defined
to have a nonzero value. */
#if (!defined (PORTAR) || PORTAR == 0) && (!defined (PORT5AR) || PORT5AR == 0)
#undef PORTAR
#ifdef M_XENIX
/* According to Jim Sievert <[email protected]>, for SCO XENIX defining
PORTAR to 1 gets the wrong archive format, and defining it to 0 gets the
right one. */
#define PORTAR 0
#else
#define PORTAR 1
#endif
#endif
/* On AIX, define these symbols to be sure to get both archive formats.
AIX 4.3 introduced the "big" archive format to support 64-bit object
files, so on AIX 4.3 systems we need to support both the "normal" and
"big" archive formats. An archive's format is indicated in the
"fl_magic" field of the "FL_HDR" structure. For a normal archive,
this field will be the string defined by the AIAMAG symbol. For a
"big" archive, it will be the string defined by the AIAMAGBIG symbol
(at least on AIX it works this way).
Note: we'll define these symbols regardless of which AIX version
we're compiling on, but this is okay since we'll use the new symbols
only if they're present. */
#ifdef _AIX
# define __AR_SMALL__
# define __AR_BIG__
#endif
#ifndef WINDOWS32
# if 0 && !defined (__ANDROID__) && !defined (__BEOS__)
# else
/* These platforms don't have <ar.h> but have archives in the same format
* as many other Unices. This was taken from GNU binutils for BeOS.
*/
# define ARMAG "!<arch>\n" /* String that begins an archive file. */
# define SARMAG 8 /* Size of that string. */
# define ARFMAG "`\n" /* String in ar_fmag at end of each header. */
struct ar_hdr
{
char ar_name[16]; /* Member file name, sometimes / terminated. */
char ar_date[12]; /* File date, decimal seconds since Epoch. */
char ar_uid[6], ar_gid[6]; /* User and group IDs, in ASCII decimal. */
char ar_mode[8]; /* File mode, in ASCII octal. */
char ar_size[10]; /* File size, in ASCII decimal. */
char ar_fmag[2]; /* Always contains ARFMAG. */
};
# endif
# define TOCHAR(_m) (_m)
#else
/* These should allow us to read Windows (VC++) libraries (according to Frank
* Libbrecht <[email protected]>)
*/
# define ARMAG IMAGE_ARCHIVE_START
# define SARMAG IMAGE_ARCHIVE_START_SIZE
# define ar_hdr _IMAGE_ARCHIVE_MEMBER_HEADER
# define ar_name Name
# define ar_mode Mode
# define ar_size Size
# define ar_date Date
# define ar_uid UserID
# define ar_gid GroupID
/* In Windows the member names have type BYTE so we must cast them. */
# define TOCHAR(_m) ((char *)(_m))
#endif
/* Cray's <ar.h> apparently defines this. */
#ifndef AR_HDR_SIZE
# define AR_HDR_SIZE (sizeof (struct ar_hdr))
#endif
#include "third_party/make/output.h"
/* Takes three arguments ARCHIVE, FUNCTION and ARG.
Open the archive named ARCHIVE, find its members one by one,
and for each one call FUNCTION with the following arguments:
archive file descriptor for reading the data,
member name,
member name might be truncated flag,
member header position in file,
member data position in file,
member data size,
member date,
member uid,
member gid,
member protection mode,
ARG.
The descriptor is poised to read the data of the member
when FUNCTION is called. It does not matter how much
data FUNCTION reads.
If FUNCTION returns nonzero, we immediately return
what FUNCTION returned.
Returns -1 if archive does not exist,
Returns -2 if archive has invalid format.
Returns 0 if have scanned successfully. */
long int
ar_scan (const char *archive, ar_member_func_t function, const void *arg)
{
#ifdef AIAMAG
FL_HDR fl_header;
# ifdef AIAMAGBIG
int big_archive = 0;
FL_HDR_BIG fl_header_big;
# endif
#endif
char *namemap = 0;
int namemap_size = 0;
int desc = open (archive, O_RDONLY, 0);
if (desc < 0)
return -1;
#ifdef SARMAG
{
char buf[SARMAG];
int nread;
nread = readbuf (desc, buf, SARMAG);
if (nread != SARMAG || memcmp (buf, ARMAG, SARMAG))
goto invalid;
}
#else
#ifdef AIAMAG
{
int nread;
nread = readbuf (desc, &fl_header, FL_HSZ);
if (nread != FL_HSZ)
goto invalid;
#ifdef AIAMAGBIG
/* If this is a "big" archive, then set the flag and
re-read the header into the "big" structure. */
if (!memcmp (fl_header.fl_magic, AIAMAGBIG, SAIAMAG))
{
off_t o;
big_archive = 1;
/* seek back to beginning of archive */
EINTRLOOP (o, lseek (desc, 0, 0));
if (o < 0)
goto invalid;
/* re-read the header into the "big" structure */
nread = readbuf (desc, &fl_header_big, FL_HSZ_BIG);
if (nread != FL_HSZ_BIG)
goto invalid;
}
else
#endif
/* Check to make sure this is a "normal" archive. */
if (memcmp (fl_header.fl_magic, AIAMAG, SAIAMAG))
goto invalid;
}
#else
{
#ifndef M_XENIX
int buf;
#else
unsigned short int buf;
#endif
int nread;
nread = readbuf (desc, &buf, sizeof (buf));
if (nread != sizeof (buf) || buf != ARMAG)
goto invalid;
}
#endif
#endif
/* Now find the members one by one. */
{
#ifdef SARMAG
long int member_offset = SARMAG;
#else
#ifdef AIAMAG
long int member_offset;
long int last_member_offset;
#ifdef AIAMAGBIG
if ( big_archive )
{
sscanf (fl_header_big.fl_fstmoff, "%20ld", &member_offset);
sscanf (fl_header_big.fl_lstmoff, "%20ld", &last_member_offset);
}
else
#endif
{
sscanf (fl_header.fl_fstmoff, "%12ld", &member_offset);
sscanf (fl_header.fl_lstmoff, "%12ld", &last_member_offset);
}
if (member_offset == 0)
{
/* Empty archive. */
close (desc);
return 0;
}
#else
#ifndef M_XENIX
long int member_offset = sizeof (int);
#else /* Xenix. */
long int member_offset = sizeof (unsigned short int);
#endif /* Not Xenix. */
#endif
#endif
while (1)
{
int nread;
struct ar_hdr member_header;
#ifdef AIAMAGBIG
struct ar_hdr_big member_header_big;
#endif
#ifdef AIAMAG
# define ARNAME_MAX 255
char name[ARNAME_MAX + 1];
int name_len;
long int dateval;
int uidval, gidval;
long int data_offset;
#else
# define ARNAME_MAX (int)sizeof(member_header.ar_name)
char namebuf[ARNAME_MAX + 1];
char *name;
int is_namemap; /* Nonzero if this entry maps long names. */
int long_name = 0;
#endif
long int eltsize;
unsigned int eltmode;
long int fnval;
off_t o;
EINTRLOOP (o, lseek (desc, member_offset, 0));
if (o < 0)
goto invalid;
#ifdef AIAMAG
#define AR_MEMHDR_SZ(x) (sizeof(x) - sizeof (x._ar_name))
#ifdef AIAMAGBIG
if (big_archive)
{
nread = readbuf (desc, &member_header_big,
AR_MEMHDR_SZ(member_header_big));
if (nread != AR_MEMHDR_SZ(member_header_big))
goto invalid;
sscanf (member_header_big.ar_namlen, "%4d", &name_len);
if (name_len < 1 || name_len > ARNAME_MAX)
goto invalid;
nread = readbuf (desc, name, name_len);
if (nread != name_len)
goto invalid;
name[name_len] = '\0';
sscanf (member_header_big.ar_date, "%12ld", &dateval);
sscanf (member_header_big.ar_uid, "%12d", &uidval);
sscanf (member_header_big.ar_gid, "%12d", &gidval);
sscanf (member_header_big.ar_mode, "%12o", &eltmode);
sscanf (member_header_big.ar_size, "%20ld", &eltsize);
data_offset = (member_offset + AR_MEMHDR_SZ(member_header_big)
+ name_len + 2);
}
else
#endif
{
nread = readbuf (desc, &member_header,
AR_MEMHDR_SZ(member_header));
if (nread != AR_MEMHDR_SZ(member_header))
goto invalid;
sscanf (member_header.ar_namlen, "%4d", &name_len);
if (name_len < 1 || name_len > ARNAME_MAX)
goto invalid;
nread = readbuf (desc, name, name_len);
if (nread != name_len)
goto invalid;
name[name_len] = '\0';
sscanf (member_header.ar_date, "%12ld", &dateval);
sscanf (member_header.ar_uid, "%12d", &uidval);
sscanf (member_header.ar_gid, "%12d", &gidval);
sscanf (member_header.ar_mode, "%12o", &eltmode);
sscanf (member_header.ar_size, "%12ld", &eltsize);
data_offset = (member_offset + AR_MEMHDR_SZ(member_header)
+ name_len + 2);
}
data_offset += data_offset % 2;
fnval =
(*function) (desc, name, 0,
member_offset, data_offset, eltsize,
dateval, uidval, gidval,
eltmode, arg);
#else /* Not AIAMAG. */
nread = readbuf (desc, &member_header, AR_HDR_SIZE);
if (nread == 0)
/* No data left means end of file; that is OK. */
break;
if (nread != AR_HDR_SIZE
#if defined(ARFMAG) || defined(ARFZMAG)
|| (
# ifdef ARFMAG
memcmp (member_header.ar_fmag, ARFMAG, 2)
# else
1
# endif
&&
# ifdef ARFZMAG
memcmp (member_header.ar_fmag, ARFZMAG, 2)
# else
1
# endif
)
#endif
)
goto invalid;
name = namebuf;
memcpy (name, member_header.ar_name, sizeof member_header.ar_name);
{
char *p = name + sizeof member_header.ar_name;
do
*p = '\0';
while (p > name && *--p == ' ');
#ifndef AIAMAG
/* If the member name is "//" or "ARFILENAMES/" this may be
a list of file name mappings. The maximum file name
length supported by the standard archive format is 14
characters. This member will actually always be the
first or second entry in the archive, but we don't check
that. */
is_namemap = (!strcmp (name, "//")
|| !strcmp (name, "ARFILENAMES/"));
#endif /* Not AIAMAG. */
/* On some systems, there is a slash after each member name. */
if (*p == '/')
*p = '\0';
#ifndef AIAMAG
/* If the member name starts with a space or a slash, this
is an index into the file name mappings (used by GNU ar).
Otherwise if the member name looks like #1/NUMBER the
real member name appears in the element data (used by
4.4BSD). */
if (! is_namemap
&& (name[0] == ' ' || name[0] == '/')
&& namemap != 0)
{
int name_off = atoi (name + 1);
int name_len;
if (name_off < 0 || name_off >= namemap_size)
goto invalid;
name = namemap + name_off;
name_len = strlen (name);
if (name_len < 1)
goto invalid;
long_name = 1;
}
else if (name[0] == '#'
&& name[1] == '1'
&& name[2] == '/')
{
int name_len = atoi (name + 3);
if (name_len < 1)
goto invalid;
name = alloca (name_len + 1);
nread = readbuf (desc, name, name_len);
if (nread != name_len)
goto invalid;
name[name_len] = '\0';
long_name = 1;
}
#endif /* Not AIAMAG. */
}
#ifndef M_XENIX
sscanf (TOCHAR (member_header.ar_mode), "%8o", &eltmode);
eltsize = atol (TOCHAR (member_header.ar_size));
#else /* Xenix. */
eltmode = (unsigned short int) member_header.ar_mode;
eltsize = member_header.ar_size;
#endif /* Not Xenix. */
fnval =
(*function) (desc, name, ! long_name, member_offset,
member_offset + AR_HDR_SIZE, eltsize,
#ifndef M_XENIX
atol (TOCHAR (member_header.ar_date)),
atoi (TOCHAR (member_header.ar_uid)),
atoi (TOCHAR (member_header.ar_gid)),
#else /* Xenix. */
member_header.ar_date,
member_header.ar_uid,
member_header.ar_gid,
#endif /* Not Xenix. */
eltmode, arg);
#endif /* AIAMAG. */
if (fnval)
{
(void) close (desc);
return fnval;
}
#ifdef AIAMAG
if (member_offset == last_member_offset)
/* End of the chain. */
break;
#ifdef AIAMAGBIG
if (big_archive)
sscanf (member_header_big.ar_nxtmem, "%20ld", &member_offset);
else
#endif
sscanf (member_header.ar_nxtmem, "%12ld", &member_offset);
if (lseek (desc, member_offset, 0) != member_offset)
goto invalid;
#else
/* If this member maps archive names, we must read it in. The
name map will always precede any members whose names must
be mapped. */
if (is_namemap)
{
char *clear;
char *limit;
if (eltsize > INT_MAX)
goto invalid;
namemap = alloca (eltsize + 1);
nread = readbuf (desc, namemap, eltsize);
if (nread != eltsize)
goto invalid;
namemap_size = eltsize;
/* The names are separated by newlines. Some formats have
a trailing slash. Null terminate the strings for
convenience. */
limit = namemap + eltsize;
for (clear = namemap; clear < limit; clear++)
{
if (*clear == '\n')
{
*clear = '\0';
if (clear[-1] == '/')
clear[-1] = '\0';
}
}
*limit = '\0';
is_namemap = 0;
}
member_offset += AR_HDR_SIZE + eltsize;
if (member_offset % 2 != 0)
member_offset++;
#endif
}
}
close (desc);
return 0;
invalid:
close (desc);
return -2;
}
/* Return nonzero iff NAME matches MEM.
If TRUNCATED is nonzero, MEM may be truncated to
sizeof (struct ar_hdr.ar_name) - 1. */
int
ar_name_equal (const char *name, const char *mem, int truncated)
{
const char *p;
p = strrchr (name, '/');
if (p != 0)
name = p + 1;
#ifndef VMS
if (truncated)
{
#ifdef AIAMAG
/* TRUNCATED should never be set on this system. */
abort ();
#else
struct ar_hdr hdr;
#if !defined (__hpux) && !defined (cray)
return strneq (name, mem, sizeof (hdr.ar_name) - 1);
#else
return strneq (name, mem, sizeof (hdr.ar_name) - 2);
#endif /* !__hpux && !cray */
#endif /* !AIAMAG */
}
return !strcmp (name, mem);
#else
/* VMS members do not have suffixes, but the filenames usually
have.
Do we need to strip VMS disk/directory format paths?
Most VMS compilers etc. by default are case insensitive
but produce uppercase external names, incl. module names.
However the VMS librarian (ar) and the linker by default
are case sensitive: they take what they get, usually
uppercase names. So for the non-default settings of the
compilers etc. there is a need to have a case sensitive
mode. */
{
int len;
len = strlen(mem);
int match;
char *dot;
if ((dot=strrchr(name,'.')))
match = (len == dot - name) && !strncasecmp(name, mem, len);
else
match = !strcasecmp (name, mem);
return match;
}
#endif /* !VMS */
}
#ifndef VMS
/* ARGSUSED */
static long int
ar_member_pos (int desc UNUSED, const char *mem, int truncated,
long int hdrpos, long int datapos UNUSED, long int size UNUSED,
long int date UNUSED, int uid UNUSED, int gid UNUSED,
unsigned int mode UNUSED, const void *name)
{
if (!ar_name_equal (name, mem, truncated))
return 0;
return hdrpos;
}
/* Set date of member MEMNAME in archive ARNAME to current time.
Returns 0 if successful,
-1 if file ARNAME does not exist,
-2 if not a valid archive,
-3 if other random system call error (including file read-only),
1 if valid but member MEMNAME does not exist. */
int
ar_member_touch (const char *arname, const char *memname)
{
long int pos = ar_scan (arname, ar_member_pos, memname);
int fd;
struct ar_hdr ar_hdr;
off_t o;
int r;
unsigned int ui;
struct stat statbuf;
if (pos < 0)
return (int) pos;
if (!pos)
return 1;
EINTRLOOP (fd, open (arname, O_RDWR, 0666));
if (fd < 0)
return -3;
/* Read in this member's header */
EINTRLOOP (o, lseek (fd, pos, 0));
if (o < 0)
goto lose;
r = readbuf (fd, &ar_hdr, AR_HDR_SIZE);
if (r != AR_HDR_SIZE)
goto lose;
/* The file's mtime is the time we we want. */
EINTRLOOP (r, fstat (fd, &statbuf));
if (r < 0)
goto lose;
/* Advance member's time to that time */
#if defined(ARFMAG) || defined(ARFZMAG) || defined(AIAMAG) || defined(WINDOWS32)
for (ui = 0; ui < sizeof ar_hdr.ar_date; ui++)
ar_hdr.ar_date[ui] = ' ';
sprintf (TOCHAR (ar_hdr.ar_date), "%lu", (long unsigned) statbuf.st_mtime);
ar_hdr.ar_date[strlen ((char *) ar_hdr.ar_date)] = ' ';
#else
ar_hdr.ar_date = statbuf.st_mtime;
#endif
/* Write back this member's header */
EINTRLOOP (o, lseek (fd, pos, 0));
if (o < 0)
goto lose;
r = writebuf (fd, &ar_hdr, AR_HDR_SIZE);
if (r != AR_HDR_SIZE)
goto lose;
close (fd);
return 0;
lose:
r = errno;
close (fd);
errno = r;
return -3;
}
#endif
#ifdef TEST
long int
describe_member (int desc, const char *name, int truncated,
long int hdrpos, long int datapos, long int size,
long int date, int uid, int gid, unsigned int mode,
const void *arg)
{
extern char *ctime ();
printf (_("Member '%s'%s: %ld bytes at %ld (%ld).\n"),
name, truncated ? _(" (name might be truncated)") : "",
size, hdrpos, datapos);
printf (_(" Date %s"), ctime (&date));
printf (_(" uid = %d, gid = %d, mode = 0%o.\n"), uid, gid, mode);
return 0;
}
int
main (int argc, char **argv)
{
ar_scan (argv[1], describe_member, NULL);
return 0;
}
#endif /* TEST. */
| 19,891 | 684 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/error.h | /* clang-format off */
/* Declaration for error-reporting function
Copyright (C) 1995-1997, 2003, 2006, 2008-2020 Free Software Foundation,
Inc.
This file is part of the GNU C Library.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
#ifndef _ERROR_H
#define _ERROR_H 1
/* The __attribute__ feature is available in gcc versions 2.5 and later.
The __-protected variants of the attributes 'format' and 'printf' are
accepted by gcc versions 2.6.4 (effectively 2.7) and later.
We enable _GL_ATTRIBUTE_FORMAT only if these are supported too, because
gnulib and libintl do '#define printf __printf__' when they override
the 'printf' function. */
#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7)
# define _GL_ATTRIBUTE_FORMAT(spec) __attribute__ ((__format__ spec))
#else
# define _GL_ATTRIBUTE_FORMAT(spec) /* empty */
#endif
/* On mingw, the flavor of printf depends on whether the extensions module
* is in use; the check for <stdio.h> determines the witness macro. */
#ifndef _GL_ATTRIBUTE_SPEC_PRINTF
# if GNULIB_PRINTF_ATTRIBUTE_FLAVOR_GNU
# define _GL_ATTRIBUTE_SPEC_PRINTF __gnu_printf__
# else
# define _GL_ATTRIBUTE_SPEC_PRINTF __printf__
# endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* Print a message with 'fprintf (stderr, FORMAT, ...)';
if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
If STATUS is nonzero, terminate the program with 'exit (STATUS)'. */
extern void error (int __status, int __errnum, const char *__format, ...)
_GL_ATTRIBUTE_FORMAT ((_GL_ATTRIBUTE_SPEC_PRINTF, 3, 4));
extern void error_at_line (int __status, int __errnum, const char *__fname,
unsigned int __lineno, const char *__format, ...)
_GL_ATTRIBUTE_FORMAT ((_GL_ATTRIBUTE_SPEC_PRINTF, 5, 6));
/* If NULL, error will flush stdout, then print on stderr the program
name, a colon and a space. Otherwise, error will call this
function without parameters instead. */
extern void (*error_print_progname) (void);
/* This variable is incremented each time 'error' is called. */
extern unsigned int error_message_count;
/* Sometimes we want to have at most one error per line. This
variable controls whether this mode is selected or not. */
extern int error_one_per_line;
#ifdef __cplusplus
}
#endif
#endif /* error.h */
| 2,930 | 77 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/unistd.c | /* clang-format off */
#include "third_party/make/config.h"
#define _GL_UNISTD_INLINE _GL_EXTERN_INLINE
#include "third_party/make/unistd.h"
typedef int dummy;
| 160 | 6 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/intprops.h | /* clang-format off */
/* intprops.h -- properties of integer types
Copyright (C) 2001-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
#ifndef _GL_INTPROPS_H
#define _GL_INTPROPS_H
/* Return a value with the common real type of E and V and the value of V.
Do not evaluate E. */
#define _GL_INT_CONVERT(e, v) ((1 ? 0 : (e)) + (v))
/* Act like _GL_INT_CONVERT (E, -V) but work around a bug in IRIX 6.5 cc; see
<https://lists.gnu.org/r/bug-gnulib/2011-05/msg00406.html>. */
#define _GL_INT_NEGATE_CONVERT(e, v) ((1 ? 0 : (e)) - (v))
/* The extra casts in the following macros work around compiler bugs,
e.g., in Cray C 5.0.3.0. */
/* True if the arithmetic type T is an integer type. bool counts as
an integer. */
#define TYPE_IS_INTEGER(t) ((t) 1.5 == 1)
/* True if the real type T is signed. */
#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
/* Return 1 if the real expression E, after promotion, has a
signed or floating type. Do not evaluate E. */
#define EXPR_SIGNED(e) (_GL_INT_NEGATE_CONVERT (e, 1) < 0)
/* Minimum and maximum values for integer types and expressions. */
/* The width in bits of the integer type or expression T.
Do not evaluate T.
Padding bits are not supported; this is checked at compile-time below. */
#define TYPE_WIDTH(t) (sizeof (t) * CHAR_BIT)
/* The maximum and minimum values for the integer type T. */
#define TYPE_MINIMUM(t) ((t) ~ TYPE_MAXIMUM (t))
#define TYPE_MAXIMUM(t) \
((t) (! TYPE_SIGNED (t) \
? (t) -1 \
: ((((t) 1 << (TYPE_WIDTH (t) - 2)) - 1) * 2 + 1)))
/* The maximum and minimum values for the type of the expression E,
after integer promotion. E is not evaluated. */
#define _GL_INT_MINIMUM(e) \
(EXPR_SIGNED (e) \
? ~ _GL_SIGNED_INT_MAXIMUM (e) \
: _GL_INT_CONVERT (e, 0))
#define _GL_INT_MAXIMUM(e) \
(EXPR_SIGNED (e) \
? _GL_SIGNED_INT_MAXIMUM (e) \
: _GL_INT_NEGATE_CONVERT (e, 1))
#define _GL_SIGNED_INT_MAXIMUM(e) \
(((_GL_INT_CONVERT (e, 1) << (TYPE_WIDTH ((e) + 0) - 2)) - 1) * 2 + 1)
/* Work around OpenVMS incompatibility with C99. */
#if !defined LLONG_MAX && defined __INT64_MAX
# define LLONG_MAX __INT64_MAX
# define LLONG_MIN __INT64_MIN
#endif
/* This include file assumes that signed types are two's complement without
padding bits; the above macros have undefined behavior otherwise.
If this is a problem for you, please let us know how to fix it for your host.
This assumption is tested by the intprops-tests module. */
/* Does the __typeof__ keyword work? This could be done by
'configure', but for now it's easier to do it by hand. */
#if (2 <= __GNUC__ \
|| (1210 <= __IBMC__ && defined __IBM__TYPEOF__) \
|| (0x5110 <= __SUNPRO_C && !__STDC__))
# define _GL_HAVE___TYPEOF__ 1
#else
# define _GL_HAVE___TYPEOF__ 0
#endif
/* Return 1 if the integer type or expression T might be signed. Return 0
if it is definitely unsigned. This macro does not evaluate its argument,
and expands to an integer constant expression. */
#if _GL_HAVE___TYPEOF__
# define _GL_SIGNED_TYPE_OR_EXPR(t) TYPE_SIGNED (__typeof__ (t))
#else
# define _GL_SIGNED_TYPE_OR_EXPR(t) 1
#endif
/* Bound on length of the string representing an unsigned integer
value representable in B bits. log10 (2.0) < 146/485. The
smallest value of B where this bound is not tight is 2621. */
#define INT_BITS_STRLEN_BOUND(b) (((b) * 146 + 484) / 485)
/* Bound on length of the string representing an integer type or expression T.
Subtract 1 for the sign bit if T is signed, and then add 1 more for
a minus sign if needed.
Because _GL_SIGNED_TYPE_OR_EXPR sometimes returns 1 when its argument is
unsigned, this macro may overestimate the true bound by one byte when
applied to unsigned types of size 2, 4, 16, ... bytes. */
#define INT_STRLEN_BOUND(t) \
(INT_BITS_STRLEN_BOUND (TYPE_WIDTH (t) - _GL_SIGNED_TYPE_OR_EXPR (t)) \
+ _GL_SIGNED_TYPE_OR_EXPR (t))
/* Bound on buffer size needed to represent an integer type or expression T,
including the terminating null. */
#define INT_BUFSIZE_BOUND(t) (INT_STRLEN_BOUND (t) + 1)
/* Range overflow checks.
The INT_<op>_RANGE_OVERFLOW macros return 1 if the corresponding C
operators might not yield numerically correct answers due to
arithmetic overflow. They do not rely on undefined or
implementation-defined behavior. Their implementations are simple
and straightforward, but they are a bit harder to use than the
INT_<op>_OVERFLOW macros described below.
Example usage:
long int i = ...;
long int j = ...;
if (INT_MULTIPLY_RANGE_OVERFLOW (i, j, LONG_MIN, LONG_MAX))
printf ("multiply would overflow");
else
printf ("product is %ld", i * j);
Restrictions on *_RANGE_OVERFLOW macros:
These macros do not check for all possible numerical problems or
undefined or unspecified behavior: they do not check for division
by zero, for bad shift counts, or for shifting negative numbers.
These macros may evaluate their arguments zero or multiple times,
so the arguments should not have side effects. The arithmetic
arguments (including the MIN and MAX arguments) must be of the same
integer type after the usual arithmetic conversions, and the type
must have minimum value MIN and maximum MAX. Unsigned types should
use a zero MIN of the proper type.
These macros are tuned for constant MIN and MAX. For commutative
operations such as A + B, they are also tuned for constant B. */
/* Return 1 if A + B would overflow in [MIN,MAX] arithmetic.
See above for restrictions. */
#define INT_ADD_RANGE_OVERFLOW(a, b, min, max) \
((b) < 0 \
? (a) < (min) - (b) \
: (max) - (b) < (a))
/* Return 1 if A - B would overflow in [MIN,MAX] arithmetic.
See above for restrictions. */
#define INT_SUBTRACT_RANGE_OVERFLOW(a, b, min, max) \
((b) < 0 \
? (max) + (b) < (a) \
: (a) < (min) + (b))
/* Return 1 if - A would overflow in [MIN,MAX] arithmetic.
See above for restrictions. */
#define INT_NEGATE_RANGE_OVERFLOW(a, min, max) \
((min) < 0 \
? (a) < - (max) \
: 0 < (a))
/* Return 1 if A * B would overflow in [MIN,MAX] arithmetic.
See above for restrictions. Avoid && and || as they tickle
bugs in Sun C 5.11 2010/08/13 and other compilers; see
<https://lists.gnu.org/r/bug-gnulib/2011-05/msg00401.html>. */
#define INT_MULTIPLY_RANGE_OVERFLOW(a, b, min, max) \
((b) < 0 \
? ((a) < 0 \
? (a) < (max) / (b) \
: (b) == -1 \
? 0 \
: (min) / (b) < (a)) \
: (b) == 0 \
? 0 \
: ((a) < 0 \
? (a) < (min) / (b) \
: (max) / (b) < (a)))
/* Return 1 if A / B would overflow in [MIN,MAX] arithmetic.
See above for restrictions. Do not check for division by zero. */
#define INT_DIVIDE_RANGE_OVERFLOW(a, b, min, max) \
((min) < 0 && (b) == -1 && (a) < - (max))
/* Return 1 if A % B would overflow in [MIN,MAX] arithmetic.
See above for restrictions. Do not check for division by zero.
Mathematically, % should never overflow, but on x86-like hosts
INT_MIN % -1 traps, and the C standard permits this, so treat this
as an overflow too. */
#define INT_REMAINDER_RANGE_OVERFLOW(a, b, min, max) \
INT_DIVIDE_RANGE_OVERFLOW (a, b, min, max)
/* Return 1 if A << B would overflow in [MIN,MAX] arithmetic.
See above for restrictions. Here, MIN and MAX are for A only, and B need
not be of the same type as the other arguments. The C standard says that
behavior is undefined for shifts unless 0 <= B < wordwidth, and that when
A is negative then A << B has undefined behavior and A >> B has
implementation-defined behavior, but do not check these other
restrictions. */
#define INT_LEFT_SHIFT_RANGE_OVERFLOW(a, b, min, max) \
((a) < 0 \
? (a) < (min) >> (b) \
: (max) >> (b) < (a))
/* True if __builtin_add_overflow (A, B, P) and __builtin_sub_overflow
(A, B, P) work when P is non-null. */
#if 5 <= __GNUC__ && !defined __ICC
# define _GL_HAS_BUILTIN_ADD_OVERFLOW 1
#elif defined __has_builtin
# define _GL_HAS_BUILTIN_ADD_OVERFLOW __has_builtin (__builtin_add_overflow)
#else
# define _GL_HAS_BUILTIN_ADD_OVERFLOW 0
#endif
/* True if __builtin_mul_overflow (A, B, P) works when P is non-null. */
#ifdef __clang__
/* Work around Clang bug <https://bugs.llvm.org/show_bug.cgi?id=16404>. */
# define _GL_HAS_BUILTIN_MUL_OVERFLOW 0
#else
# define _GL_HAS_BUILTIN_MUL_OVERFLOW _GL_HAS_BUILTIN_ADD_OVERFLOW
#endif
/* True if __builtin_add_overflow_p (A, B, C) works, and similarly for
__builtin_mul_overflow_p and __builtin_mul_overflow_p. */
#define _GL_HAS_BUILTIN_OVERFLOW_P (7 <= __GNUC__)
/* The _GL*_OVERFLOW macros have the same restrictions as the
*_RANGE_OVERFLOW macros, except that they do not assume that operands
(e.g., A and B) have the same type as MIN and MAX. Instead, they assume
that the result (e.g., A + B) has that type. */
#if _GL_HAS_BUILTIN_OVERFLOW_P
# define _GL_ADD_OVERFLOW(a, b, min, max) \
__builtin_add_overflow_p (a, b, (__typeof__ ((a) + (b))) 0)
# define _GL_SUBTRACT_OVERFLOW(a, b, min, max) \
__builtin_sub_overflow_p (a, b, (__typeof__ ((a) - (b))) 0)
# define _GL_MULTIPLY_OVERFLOW(a, b, min, max) \
__builtin_mul_overflow_p (a, b, (__typeof__ ((a) * (b))) 0)
#else
# define _GL_ADD_OVERFLOW(a, b, min, max) \
((min) < 0 ? INT_ADD_RANGE_OVERFLOW (a, b, min, max) \
: (a) < 0 ? (b) <= (a) + (b) \
: (b) < 0 ? (a) <= (a) + (b) \
: (a) + (b) < (b))
# define _GL_SUBTRACT_OVERFLOW(a, b, min, max) \
((min) < 0 ? INT_SUBTRACT_RANGE_OVERFLOW (a, b, min, max) \
: (a) < 0 ? 1 \
: (b) < 0 ? (a) - (b) <= (a) \
: (a) < (b))
# define _GL_MULTIPLY_OVERFLOW(a, b, min, max) \
(((min) == 0 && (((a) < 0 && 0 < (b)) || ((b) < 0 && 0 < (a)))) \
|| INT_MULTIPLY_RANGE_OVERFLOW (a, b, min, max))
#endif
#define _GL_DIVIDE_OVERFLOW(a, b, min, max) \
((min) < 0 ? (b) == _GL_INT_NEGATE_CONVERT (min, 1) && (a) < - (max) \
: (a) < 0 ? (b) <= (a) + (b) - 1 \
: (b) < 0 && (a) + (b) <= (a))
#define _GL_REMAINDER_OVERFLOW(a, b, min, max) \
((min) < 0 ? (b) == _GL_INT_NEGATE_CONVERT (min, 1) && (a) < - (max) \
: (a) < 0 ? (a) % (b) != ((max) - (b) + 1) % (b) \
: (b) < 0 && ! _GL_UNSIGNED_NEG_MULTIPLE (a, b, max))
/* Return a nonzero value if A is a mathematical multiple of B, where
A is unsigned, B is negative, and MAX is the maximum value of A's
type. A's type must be the same as (A % B)'s type. Normally (A %
-B == 0) suffices, but things get tricky if -B would overflow. */
#define _GL_UNSIGNED_NEG_MULTIPLE(a, b, max) \
(((b) < -_GL_SIGNED_INT_MAXIMUM (b) \
? (_GL_SIGNED_INT_MAXIMUM (b) == (max) \
? (a) \
: (a) % (_GL_INT_CONVERT (a, _GL_SIGNED_INT_MAXIMUM (b)) + 1)) \
: (a) % - (b)) \
== 0)
/* Check for integer overflow, and report low order bits of answer.
The INT_<op>_OVERFLOW macros return 1 if the corresponding C operators
might not yield numerically correct answers due to arithmetic overflow.
The INT_<op>_WRAPV macros compute the low-order bits of the sum,
difference, and product of two C integers, and return 1 if these
low-order bits are not numerically correct.
These macros work correctly on all known practical hosts, and do not rely
on undefined behavior due to signed arithmetic overflow.
Example usage, assuming A and B are long int:
if (INT_MULTIPLY_OVERFLOW (a, b))
printf ("result would overflow\n");
else
printf ("result is %ld (no overflow)\n", a * b);
Example usage with WRAPV flavor:
long int result;
bool overflow = INT_MULTIPLY_WRAPV (a, b, &result);
printf ("result is %ld (%s)\n", result,
overflow ? "after overflow" : "no overflow");
Restrictions on these macros:
These macros do not check for all possible numerical problems or
undefined or unspecified behavior: they do not check for division
by zero, for bad shift counts, or for shifting negative numbers.
These macros may evaluate their arguments zero or multiple times, so the
arguments should not have side effects.
The WRAPV macros are not constant expressions. They support only
+, binary -, and *. Because the WRAPV macros convert the result,
they report overflow in different circumstances than the OVERFLOW
macros do.
These macros are tuned for their last input argument being a constant.
Return 1 if the integer expressions A * B, A - B, -A, A * B, A / B,
A % B, and A << B would overflow, respectively. */
#define INT_ADD_OVERFLOW(a, b) \
_GL_BINARY_OP_OVERFLOW (a, b, _GL_ADD_OVERFLOW)
#define INT_SUBTRACT_OVERFLOW(a, b) \
_GL_BINARY_OP_OVERFLOW (a, b, _GL_SUBTRACT_OVERFLOW)
#if _GL_HAS_BUILTIN_OVERFLOW_P
# define INT_NEGATE_OVERFLOW(a) INT_SUBTRACT_OVERFLOW (0, a)
#else
# define INT_NEGATE_OVERFLOW(a) \
INT_NEGATE_RANGE_OVERFLOW (a, _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a))
#endif
#define INT_MULTIPLY_OVERFLOW(a, b) \
_GL_BINARY_OP_OVERFLOW (a, b, _GL_MULTIPLY_OVERFLOW)
#define INT_DIVIDE_OVERFLOW(a, b) \
_GL_BINARY_OP_OVERFLOW (a, b, _GL_DIVIDE_OVERFLOW)
#define INT_REMAINDER_OVERFLOW(a, b) \
_GL_BINARY_OP_OVERFLOW (a, b, _GL_REMAINDER_OVERFLOW)
#define INT_LEFT_SHIFT_OVERFLOW(a, b) \
INT_LEFT_SHIFT_RANGE_OVERFLOW (a, b, \
_GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a))
/* Return 1 if the expression A <op> B would overflow,
where OP_RESULT_OVERFLOW (A, B, MIN, MAX) does the actual test,
assuming MIN and MAX are the minimum and maximum for the result type.
Arguments should be free of side effects. */
#define _GL_BINARY_OP_OVERFLOW(a, b, op_result_overflow) \
op_result_overflow (a, b, \
_GL_INT_MINIMUM (_GL_INT_CONVERT (a, b)), \
_GL_INT_MAXIMUM (_GL_INT_CONVERT (a, b)))
/* Store the low-order bits of A + B, A - B, A * B, respectively, into *R.
Return 1 if the result overflows. See above for restrictions. */
#if _GL_HAS_BUILTIN_ADD_OVERFLOW
# define INT_ADD_WRAPV(a, b, r) __builtin_add_overflow (a, b, r)
# define INT_SUBTRACT_WRAPV(a, b, r) __builtin_sub_overflow (a, b, r)
#else
# define INT_ADD_WRAPV(a, b, r) \
_GL_INT_OP_WRAPV (a, b, r, +, _GL_INT_ADD_RANGE_OVERFLOW)
# define INT_SUBTRACT_WRAPV(a, b, r) \
_GL_INT_OP_WRAPV (a, b, r, -, _GL_INT_SUBTRACT_RANGE_OVERFLOW)
#endif
#if _GL_HAS_BUILTIN_MUL_OVERFLOW
# if (9 < __GNUC__ + (3 <= __GNUC_MINOR__) \
|| (__GNUC__ == 8 && 4 <= __GNUC_MINOR__))
# define INT_MULTIPLY_WRAPV(a, b, r) __builtin_mul_overflow (a, b, r)
# else
/* Work around GCC bug 91450. */
# define INT_MULTIPLY_WRAPV(a, b, r) \
((!_GL_SIGNED_TYPE_OR_EXPR (*(r)) && EXPR_SIGNED (a) && EXPR_SIGNED (b) \
&& _GL_INT_MULTIPLY_RANGE_OVERFLOW (a, b, 0, (__typeof__ (*(r))) -1)) \
? ((void) __builtin_mul_overflow (a, b, r), 1) \
: __builtin_mul_overflow (a, b, r))
# endif
#else
# define INT_MULTIPLY_WRAPV(a, b, r) \
_GL_INT_OP_WRAPV (a, b, r, *, _GL_INT_MULTIPLY_RANGE_OVERFLOW)
#endif
/* Nonzero if this compiler has GCC bug 68193 or Clang bug 25390. See:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68193
https://llvm.org/bugs/show_bug.cgi?id=25390
For now, assume all versions of GCC-like compilers generate bogus
warnings for _Generic. This matters only for compilers that
lack relevant builtins. */
#if __GNUC__
# define _GL__GENERIC_BOGUS 1
#else
# define _GL__GENERIC_BOGUS 0
#endif
/* Store the low-order bits of A <op> B into *R, where OP specifies
the operation and OVERFLOW the overflow predicate. Return 1 if the
result overflows. See above for restrictions. */
#if 201112 <= __STDC_VERSION__ && !_GL__GENERIC_BOGUS
# define _GL_INT_OP_WRAPV(a, b, r, op, overflow) \
(_Generic \
(*(r), \
signed char: \
_GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
signed char, SCHAR_MIN, SCHAR_MAX), \
unsigned char: \
_GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
unsigned char, 0, UCHAR_MAX), \
short int: \
_GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
short int, SHRT_MIN, SHRT_MAX), \
unsigned short int: \
_GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
unsigned short int, 0, USHRT_MAX), \
int: \
_GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
int, INT_MIN, INT_MAX), \
unsigned int: \
_GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
unsigned int, 0, UINT_MAX), \
long int: \
_GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
long int, LONG_MIN, LONG_MAX), \
unsigned long int: \
_GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
unsigned long int, 0, ULONG_MAX), \
long long int: \
_GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
long long int, LLONG_MIN, LLONG_MAX), \
unsigned long long int: \
_GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
unsigned long long int, 0, ULLONG_MAX)))
#else
/* Store the low-order bits of A <op> B into *R, where OP specifies
the operation and OVERFLOW the overflow predicate. If *R is
signed, its type is ST with bounds SMIN..SMAX; otherwise its type
is UT with bounds U..UMAX. ST and UT are narrower than int.
Return 1 if the result overflows. See above for restrictions. */
# if _GL_HAVE___TYPEOF__
# define _GL_INT_OP_WRAPV_SMALLISH(a,b,r,op,overflow,st,smin,smax,ut,umax) \
(TYPE_SIGNED (__typeof__ (*(r))) \
? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, st, smin, smax) \
: _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, ut, 0, umax))
# else
# define _GL_INT_OP_WRAPV_SMALLISH(a,b,r,op,overflow,st,smin,smax,ut,umax) \
(overflow (a, b, smin, smax) \
? (overflow (a, b, 0, umax) \
? (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a,b,op,unsigned,st), 1) \
: (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a,b,op,unsigned,st)) < 0) \
: (overflow (a, b, 0, umax) \
? (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a,b,op,unsigned,st)) >= 0 \
: (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a,b,op,unsigned,st), 0)))
# endif
# define _GL_INT_OP_WRAPV(a, b, r, op, overflow) \
(sizeof *(r) == sizeof (signed char) \
? _GL_INT_OP_WRAPV_SMALLISH (a, b, r, op, overflow, \
signed char, SCHAR_MIN, SCHAR_MAX, \
unsigned char, UCHAR_MAX) \
: sizeof *(r) == sizeof (short int) \
? _GL_INT_OP_WRAPV_SMALLISH (a, b, r, op, overflow, \
short int, SHRT_MIN, SHRT_MAX, \
unsigned short int, USHRT_MAX) \
: sizeof *(r) == sizeof (int) \
? (EXPR_SIGNED (*(r)) \
? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
int, INT_MIN, INT_MAX) \
: _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
unsigned int, 0, UINT_MAX)) \
: _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow))
# ifdef LLONG_MAX
# define _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow) \
(sizeof *(r) == sizeof (long int) \
? (EXPR_SIGNED (*(r)) \
? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
long int, LONG_MIN, LONG_MAX) \
: _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
unsigned long int, 0, ULONG_MAX)) \
: (EXPR_SIGNED (*(r)) \
? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
long long int, LLONG_MIN, LLONG_MAX) \
: _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
unsigned long long int, 0, ULLONG_MAX)))
# else
# define _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow) \
(EXPR_SIGNED (*(r)) \
? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
long int, LONG_MIN, LONG_MAX) \
: _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
unsigned long int, 0, ULONG_MAX))
# endif
#endif
/* Store the low-order bits of A <op> B into *R, where the operation
is given by OP. Use the unsigned type UT for calculation to avoid
overflow problems. *R's type is T, with extrema TMIN and TMAX.
T must be a signed integer type. Return 1 if the result overflows. */
#define _GL_INT_OP_CALC(a, b, r, op, overflow, ut, t, tmin, tmax) \
(overflow (a, b, tmin, tmax) \
? (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t), 1) \
: (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t), 0))
/* Return the low-order bits of A <op> B, where the operation is given
by OP. Use the unsigned type UT for calculation to avoid undefined
behavior on signed integer overflow, and convert the result to type T.
UT is at least as wide as T and is no narrower than unsigned int,
T is two's complement, and there is no padding or trap representations.
Assume that converting UT to T yields the low-order bits, as is
done in all known two's-complement C compilers. E.g., see:
https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html
According to the C standard, converting UT to T yields an
implementation-defined result or signal for values outside T's
range. However, code that works around this theoretical problem
runs afoul of a compiler bug in Oracle Studio 12.3 x86. See:
https://lists.gnu.org/r/bug-gnulib/2017-04/msg00049.html
As the compiler bug is real, don't try to work around the
theoretical problem. */
#define _GL_INT_OP_WRAPV_VIA_UNSIGNED(a, b, op, ut, t) \
((t) ((ut) (a) op (ut) (b)))
/* Return true if the numeric values A + B, A - B, A * B fall outside
the range TMIN..TMAX. Arguments should be integer expressions
without side effects. TMIN should be signed and nonpositive.
TMAX should be positive, and should be signed unless TMIN is zero. */
#define _GL_INT_ADD_RANGE_OVERFLOW(a, b, tmin, tmax) \
((b) < 0 \
? (((tmin) \
? ((EXPR_SIGNED (_GL_INT_CONVERT (a, (tmin) - (b))) || (b) < (tmin)) \
&& (a) < (tmin) - (b)) \
: (a) <= -1 - (b)) \
|| ((EXPR_SIGNED (a) ? 0 <= (a) : (tmax) < (a)) && (tmax) < (a) + (b))) \
: (a) < 0 \
? (((tmin) \
? ((EXPR_SIGNED (_GL_INT_CONVERT (b, (tmin) - (a))) || (a) < (tmin)) \
&& (b) < (tmin) - (a)) \
: (b) <= -1 - (a)) \
|| ((EXPR_SIGNED (_GL_INT_CONVERT (a, b)) || (tmax) < (b)) \
&& (tmax) < (a) + (b))) \
: (tmax) < (b) || (tmax) - (b) < (a))
#define _GL_INT_SUBTRACT_RANGE_OVERFLOW(a, b, tmin, tmax) \
(((a) < 0) == ((b) < 0) \
? ((a) < (b) \
? !(tmin) || -1 - (tmin) < (b) - (a) - 1 \
: (tmax) < (a) - (b)) \
: (a) < 0 \
? ((!EXPR_SIGNED (_GL_INT_CONVERT ((a) - (tmin), b)) && (a) - (tmin) < 0) \
|| (a) - (tmin) < (b)) \
: ((! (EXPR_SIGNED (_GL_INT_CONVERT (tmax, b)) \
&& EXPR_SIGNED (_GL_INT_CONVERT ((tmax) + (b), a))) \
&& (tmax) <= -1 - (b)) \
|| (tmax) + (b) < (a)))
#define _GL_INT_MULTIPLY_RANGE_OVERFLOW(a, b, tmin, tmax) \
((b) < 0 \
? ((a) < 0 \
? (EXPR_SIGNED (_GL_INT_CONVERT (tmax, b)) \
? (a) < (tmax) / (b) \
: ((INT_NEGATE_OVERFLOW (b) \
? _GL_INT_CONVERT (b, tmax) >> (TYPE_WIDTH (b) - 1) \
: (tmax) / -(b)) \
<= -1 - (a))) \
: INT_NEGATE_OVERFLOW (_GL_INT_CONVERT (b, tmin)) && (b) == -1 \
? (EXPR_SIGNED (a) \
? 0 < (a) + (tmin) \
: 0 < (a) && -1 - (tmin) < (a) - 1) \
: (tmin) / (b) < (a)) \
: (b) == 0 \
? 0 \
: ((a) < 0 \
? (INT_NEGATE_OVERFLOW (_GL_INT_CONVERT (a, tmin)) && (a) == -1 \
? (EXPR_SIGNED (b) ? 0 < (b) + (tmin) : -1 - (tmin) < (b) - 1) \
: (tmin) / (a) < (b)) \
: (tmax) / (b) < (a)))
#endif /* _GL_INTPROPS_H */
| 26,739 | 585 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/dosname.h | /* clang-format off */
/* File names on MS-DOS/Windows systems.
Copyright (C) 2000-2001, 2004-2006, 2009-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>.
From Paul Eggert and Jim Meyering. */
#ifndef _DOSNAME_H
#define _DOSNAME_H
#if (defined _WIN32 || defined __CYGWIN__ \
|| defined __EMX__ || defined __MSDOS__ || defined __DJGPP__)
/* This internal macro assumes ASCII, but all hosts that support drive
letters use ASCII. */
# define _IS_DRIVE_LETTER(C) (((unsigned int) (C) | ('a' - 'A')) - 'a' \
<= 'z' - 'a')
# define FILE_SYSTEM_PREFIX_LEN(Filename) \
(_IS_DRIVE_LETTER ((Filename)[0]) && (Filename)[1] == ':' ? 2 : 0)
# ifndef __CYGWIN__
# define FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE 1
# endif
# define ISSLASH(C) ((C) == '/' || (C) == '\\')
#else
# define FILE_SYSTEM_PREFIX_LEN(Filename) 0
# define ISSLASH(C) ((C) == '/')
#endif
#ifndef FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
# define FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE 0
#endif
#if FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
# define IS_ABSOLUTE_FILE_NAME(F) ISSLASH ((F)[FILE_SYSTEM_PREFIX_LEN (F)])
# else
# define IS_ABSOLUTE_FILE_NAME(F) \
(ISSLASH ((F)[0]) || FILE_SYSTEM_PREFIX_LEN (F) != 0)
#endif
#define IS_RELATIVE_FILE_NAME(F) (! IS_ABSOLUTE_FILE_NAME (F))
#endif /* DOSNAME_H_ */
| 2,003 | 54 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/fd-hook.c | /* clang-format off */
/* clang-format off */
/* Hook for making file descriptor functions close(), ioctl() extensible.
Copyright (C) 2009-2020 Free Software Foundation, Inc.
Written by Bruno Haible <[email protected]>, 2009.
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 <https://www.gnu.org/licenses/>. */
#include "third_party/make/config.h"
/* Specification. */
#include "third_party/make/fd-hook.h"
/* Currently, this entire code is only needed for the handling of sockets
on native Windows platforms. */
#if WINDOWS_SOCKETS
/* The first and last link in the doubly linked list.
Initially the list is empty. */
static struct fd_hook anchor = { &anchor, &anchor, NULL, NULL };
int
execute_close_hooks (const struct fd_hook *remaining_list, gl_close_fn primary,
int fd)
{
if (remaining_list == &anchor)
/* End of list reached. */
return primary (fd);
else
return remaining_list->private_close_fn (remaining_list->private_next,
primary, fd);
}
int
execute_all_close_hooks (gl_close_fn primary, int fd)
{
return execute_close_hooks (anchor.private_next, primary, fd);
}
int
execute_ioctl_hooks (const struct fd_hook *remaining_list, gl_ioctl_fn primary,
int fd, int request, void *arg)
{
if (remaining_list == &anchor)
/* End of list reached. */
return primary (fd, request, arg);
else
return remaining_list->private_ioctl_fn (remaining_list->private_next,
primary, fd, request, arg);
}
int
execute_all_ioctl_hooks (gl_ioctl_fn primary,
int fd, int request, void *arg)
{
return execute_ioctl_hooks (anchor.private_next, primary, fd, request, arg);
}
void
register_fd_hook (close_hook_fn close_hook, ioctl_hook_fn ioctl_hook, struct fd_hook *link)
{
if (close_hook == NULL)
close_hook = execute_close_hooks;
if (ioctl_hook == NULL)
ioctl_hook = execute_ioctl_hooks;
if (link->private_next == NULL && link->private_prev == NULL)
{
/* Add the link to the doubly linked list. */
link->private_next = anchor.private_next;
link->private_prev = &anchor;
link->private_close_fn = close_hook;
link->private_ioctl_fn = ioctl_hook;
anchor.private_next->private_prev = link;
anchor.private_next = link;
}
else
{
/* The link is already in use. */
if (link->private_close_fn != close_hook
|| link->private_ioctl_fn != ioctl_hook)
abort ();
}
}
void
unregister_fd_hook (struct fd_hook *link)
{
struct fd_hook *next = link->private_next;
struct fd_hook *prev = link->private_prev;
if (next != NULL && prev != NULL)
{
/* The link is in use. Remove it from the doubly linked list. */
prev->private_next = next;
next->private_prev = prev;
/* Clear the link, to mark it unused. */
link->private_next = NULL;
link->private_prev = NULL;
link->private_close_fn = NULL;
link->private_ioctl_fn = NULL;
}
}
#endif
| 3,647 | 117 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/fcntl.h | /* clang-format off */
/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* Like <fcntl.h>, but with non-working flags defined to 0.
Copyright (C) 2006-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* written by Paul Eggert */
#if __GNUC__ >= 3
#pragma GCC system_header
#endif
#if defined __need_system_fcntl_h
/* Special invocation convention. */
/* Needed before <sys/stat.h>.
May also define off_t to a 64-bit type on native Windows. */
/* Native Windows platforms declare open(), creat() in <io.h>. */
#if (0 || 0 || defined GNULIB_POSIXCHECK) && \
(defined _WIN32 && !defined __CYGWIN__)
#endif
#else
/* Normal invocation convention. */
#ifndef _GL_FCNTL_H
/* Needed before <sys/stat.h>.
May also define off_t to a 64-bit type on native Windows. */
/* On some systems other than glibc, <sys/stat.h> is a prerequisite of
<fcntl.h>. On glibc systems, we would like to avoid namespace pollution.
But on glibc systems, <fcntl.h> includes <sys/stat.h> inside an
extern "C" { ... } block, which leads to errors in C++ mode with the
overridden <sys/stat.h> from gnulib. These errors are known to be gone
with g++ version >= 4.3. */
#if !(defined __GLIBC__ || defined __UCLIBC__) || \
(defined __cplusplus && defined GNULIB_NAMESPACE && \
(defined __ICC || \
!(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))))
#endif
/* The include_next requires a split double-inclusion guard. */
/* Native Windows platforms declare open(), creat() in <io.h>. */
#if (0 || 0 || defined GNULIB_POSIXCHECK) && \
(defined _WIN32 && !defined __CYGWIN__)
#endif
#ifndef _GL_FCNTL_H
#define _GL_FCNTL_H
/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
/* C++ compatible function declaration macros.
Copyright (C) 2010-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#ifndef _GL_CXXDEFS_H
#define _GL_CXXDEFS_H
/* Begin/end the GNULIB_NAMESPACE namespace. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
#define _GL_BEGIN_NAMESPACE namespace GNULIB_NAMESPACE {
#define _GL_END_NAMESPACE }
#else
#define _GL_BEGIN_NAMESPACE
#define _GL_END_NAMESPACE
#endif
/* The three most frequent use cases of these macros are:
* For providing a substitute for a function that is missing on some
platforms, but is declared and works fine on the platforms on which
it exists:
#if @GNULIB_FOO@
# if !@HAVE_FOO@
_GL_FUNCDECL_SYS (foo, ...);
# endif
_GL_CXXALIAS_SYS (foo, ...);
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
* For providing a replacement for a function that exists on all platforms,
but is broken/insufficient and needs to be replaced on some platforms:
#if @GNULIB_FOO@
# if @REPLACE_FOO@
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef foo
# define foo rpl_foo
# endif
_GL_FUNCDECL_RPL (foo, ...);
_GL_CXXALIAS_RPL (foo, ...);
# else
_GL_CXXALIAS_SYS (foo, ...);
# endif
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
* For providing a replacement for a function that exists on some platforms
but is broken/insufficient and needs to be replaced on some of them and
is additionally either missing or undeclared on some other platforms:
#if @GNULIB_FOO@
# if @REPLACE_FOO@
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef foo
# define foo rpl_foo
# endif
_GL_FUNCDECL_RPL (foo, ...);
_GL_CXXALIAS_RPL (foo, ...);
# else
# if !@HAVE_FOO@ or if !@HAVE_DECL_FOO@
_GL_FUNCDECL_SYS (foo, ...);
# endif
_GL_CXXALIAS_SYS (foo, ...);
# endif
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
*/
/* _GL_EXTERN_C declaration;
performs the declaration with C linkage. */
#if defined __cplusplus
#define _GL_EXTERN_C extern "C"
#else
#define _GL_EXTERN_C extern
#endif
/* _GL_FUNCDECL_RPL (func, rettype, parameters_and_attributes);
declares a replacement function, named rpl_func, with the given prototype,
consisting of return type, parameters, and attributes.
Example:
_GL_FUNCDECL_RPL (open, int, (const char *filename, int flags, ...)
_GL_ARG_NONNULL ((1)));
*/
#define _GL_FUNCDECL_RPL(func, rettype, parameters_and_attributes) \
_GL_FUNCDECL_RPL_1(rpl_##func, rettype, parameters_and_attributes)
#define _GL_FUNCDECL_RPL_1(rpl_func, rettype, parameters_and_attributes) \
_GL_EXTERN_C rettype rpl_func parameters_and_attributes
/* _GL_FUNCDECL_SYS (func, rettype, parameters_and_attributes);
declares the system function, named func, with the given prototype,
consisting of return type, parameters, and attributes.
Example:
_GL_FUNCDECL_SYS (open, int, (const char *filename, int flags, ...)
_GL_ARG_NONNULL ((1)));
*/
#define _GL_FUNCDECL_SYS(func, rettype, parameters_and_attributes) \
_GL_EXTERN_C rettype func parameters_and_attributes
/* _GL_CXXALIAS_RPL (func, rettype, parameters);
declares a C++ alias called GNULIB_NAMESPACE::func
that redirects to rpl_func, if GNULIB_NAMESPACE is defined.
Example:
_GL_CXXALIAS_RPL (open, int, (const char *filename, int flags, ...));
Wrapping rpl_func in an object with an inline conversion operator
avoids a reference to rpl_func unless GNULIB_NAMESPACE::func is
actually used in the program. */
#define _GL_CXXALIAS_RPL(func, rettype, parameters) \
_GL_CXXALIAS_RPL_1(func, rpl_##func, rettype, parameters)
#if defined __cplusplus && defined GNULIB_NAMESPACE
#define _GL_CXXALIAS_RPL_1(func, rpl_func, rettype, parameters) \
namespace GNULIB_NAMESPACE { \
static const struct _gl_##func##_wrapper { \
typedef rettype(*type) parameters; \
\
inline operator type() const { \
return ::rpl_func; \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
#define _GL_CXXALIAS_RPL_1(func, rpl_func, rettype, parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_RPL_CAST_1 (func, rpl_func, rettype, parameters);
is like _GL_CXXALIAS_RPL_1 (func, rpl_func, rettype, parameters);
except that the C function rpl_func may have a slightly different
declaration. A cast is used to silence the "invalid conversion" error
that would otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
#define _GL_CXXALIAS_RPL_CAST_1(func, rpl_func, rettype, parameters) \
namespace GNULIB_NAMESPACE { \
static const struct _gl_##func##_wrapper { \
typedef rettype(*type) parameters; \
\
inline operator type() const { \
return reinterpret_cast<type>(::rpl_func); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
#define _GL_CXXALIAS_RPL_CAST_1(func, rpl_func, rettype, parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS (func, rettype, parameters);
declares a C++ alias called GNULIB_NAMESPACE::func
that redirects to the system provided function func, if GNULIB_NAMESPACE
is defined.
Example:
_GL_CXXALIAS_SYS (open, int, (const char *filename, int flags, ...));
Wrapping func in an object with an inline conversion operator
avoids a reference to func unless GNULIB_NAMESPACE::func is
actually used in the program. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
#define _GL_CXXALIAS_SYS(func, rettype, parameters) \
namespace GNULIB_NAMESPACE { \
static const struct _gl_##func##_wrapper { \
typedef rettype(*type) parameters; \
\
inline operator type() const { \
return ::func; \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
#define _GL_CXXALIAS_SYS(func, rettype, parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS_CAST (func, rettype, parameters);
is like _GL_CXXALIAS_SYS (func, rettype, parameters);
except that the C function func may have a slightly different declaration.
A cast is used to silence the "invalid conversion" error that would
otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
#define _GL_CXXALIAS_SYS_CAST(func, rettype, parameters) \
namespace GNULIB_NAMESPACE { \
static const struct _gl_##func##_wrapper { \
typedef rettype(*type) parameters; \
\
inline operator type() const { \
return reinterpret_cast<type>(::func); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
#define _GL_CXXALIAS_SYS_CAST(func, rettype, parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS_CAST2 (func, rettype, parameters, rettype2, parameters2);
is like _GL_CXXALIAS_SYS (func, rettype, parameters);
except that the C function is picked among a set of overloaded functions,
namely the one with rettype2 and parameters2. Two consecutive casts
are used to silence the "cannot find a match" and "invalid conversion"
errors that would otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
/* The outer cast must be a reinterpret_cast.
The inner cast: When the function is defined as a set of overloaded
functions, it works as a static_cast<>, choosing the designated variant.
When the function is defined as a single variant, it works as a
reinterpret_cast<>. The parenthesized cast syntax works both ways. */
#define _GL_CXXALIAS_SYS_CAST2(func, rettype, parameters, rettype2, \
parameters2) \
namespace GNULIB_NAMESPACE { \
static const struct _gl_##func##_wrapper { \
typedef rettype(*type) parameters; \
\
inline operator type() const { \
return reinterpret_cast<type>((rettype2(*) parameters2)(::func)); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
#define _GL_CXXALIAS_SYS_CAST2(func, rettype, parameters, rettype2, \
parameters2) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIASWARN (func);
causes a warning to be emitted when ::func is used but not when
GNULIB_NAMESPACE::func is used. func must be defined without overloaded
variants. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
#define _GL_CXXALIASWARN(func) _GL_CXXALIASWARN_1(func, GNULIB_NAMESPACE)
#define _GL_CXXALIASWARN_1(func, namespace) _GL_CXXALIASWARN_2(func, namespace)
/* To work around GCC bug <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=43881>,
we enable the warning only when not optimizing. */
#if !__OPTIMIZE__
#define _GL_CXXALIASWARN_2(func, namespace) \
_GL_WARN_ON_USE(func, \
"The symbol ::" #func " refers to the system function. " \
"Use " #namespace "::" #func " instead.")
#elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
#define _GL_CXXALIASWARN_2(func, namespace) extern __typeof__(func) func
#else
#define _GL_CXXALIASWARN_2(func, namespace) _GL_EXTERN_C int _gl_cxxalias_dummy
#endif
#else
#define _GL_CXXALIASWARN(func) _GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIASWARN1 (func, rettype, parameters_and_attributes);
causes a warning to be emitted when the given overloaded variant of ::func
is used but not when GNULIB_NAMESPACE::func is used. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
#define _GL_CXXALIASWARN1(func, rettype, parameters_and_attributes) \
_GL_CXXALIASWARN1_1(func, rettype, parameters_and_attributes, \
GNULIB_NAMESPACE)
#define _GL_CXXALIASWARN1_1(func, rettype, parameters_and_attributes, \
namespace) \
_GL_CXXALIASWARN1_2(func, rettype, parameters_and_attributes, namespace)
/* To work around GCC bug <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=43881>,
we enable the warning only when not optimizing. */
#if !__OPTIMIZE__
#define _GL_CXXALIASWARN1_2(func, rettype, parameters_and_attributes, \
namespace) \
_GL_WARN_ON_USE_CXX(func, rettype, parameters_and_attributes, \
"The symbol ::" #func " refers to the system function. " \
"Use " #namespace "::" #func " instead.")
#elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
#define _GL_CXXALIASWARN1_2(func, rettype, parameters_and_attributes, \
namespace) \
extern __typeof__(func) func
#else
#define _GL_CXXALIASWARN1_2(func, rettype, parameters_and_attributes, \
namespace) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
#else
#define _GL_CXXALIASWARN1(func, rettype, parameters_and_attributes) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
#endif /* _GL_CXXDEFS_H */
/* The definition of _GL_ARG_NONNULL is copied here. */
/* A C macro for declaring that specific arguments must not be NULL.
Copyright (C) 2009-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* _GL_ARG_NONNULL((n,...,m)) tells the compiler and static analyzer tools
that the values passed as arguments n, ..., m must be non-NULL pointers.
n = 1 stands for the first argument, n = 2 for the second argument etc. */
#ifndef _GL_ARG_NONNULL
#if (__GNUC__ == 3 && __GNUC_MINOR__ >= 3) || __GNUC__ > 3
#define _GL_ARG_NONNULL(params) __attribute__((__nonnull__ params))
#else
#define _GL_ARG_NONNULL(params)
#endif
#endif
/* The definition of _GL_WARN_ON_USE is copied here. */
/* A C macro for emitting warnings if a function is used.
Copyright (C) 2010-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* _GL_WARN_ON_USE (function, "literal string") issues a declaration
for FUNCTION which will then trigger a compiler warning containing
the text of "literal string" anywhere that function is called, if
supported by the compiler. If the compiler does not support this
feature, the macro expands to an unused extern declaration.
_GL_WARN_ON_USE_ATTRIBUTE ("literal string") expands to the
attribute used in _GL_WARN_ON_USE. If the compiler does not support
this feature, it expands to empty.
These macros are useful for marking a function as a potential
portability trap, with the intent that "literal string" include
instructions on the replacement function that should be used
instead.
_GL_WARN_ON_USE is for functions with 'extern' linkage.
_GL_WARN_ON_USE_ATTRIBUTE is for functions with 'static' or 'inline'
linkage.
However, one of the reasons that a function is a portability trap is
if it has the wrong signature. Declaring FUNCTION with a different
signature in C is a compilation error, so this macro must use the
same type as any existing declaration so that programs that avoid
the problematic FUNCTION do not fail to compile merely because they
included a header that poisoned the function. But this implies that
_GL_WARN_ON_USE is only safe to use if FUNCTION is known to already
have a declaration. Use of this macro implies that there must not
be any other macro hiding the declaration of FUNCTION; but
undefining FUNCTION first is part of the poisoning process anyway
(although for symbols that are provided only via a macro, the result
is a compilation error rather than a warning containing
"literal string"). Also note that in C++, it is only safe to use if
FUNCTION has no overloads.
For an example, it is possible to poison 'getline' by:
[getline]) in configure.ac, which potentially defines
HAVE_RAW_DECL_GETLINE
- adding this code to a header that wraps the system <stdio.h>:
#undef getline
#if HAVE_RAW_DECL_GETLINE
_GL_WARN_ON_USE (getline, "getline is required by POSIX 2008, but"
"not universally present; use the gnulib module getline");
#endif
It is not possible to directly poison global variables. But it is
possible to write a wrapper accessor function, and poison that
(less common usage, like &environ, will cause a compilation error
rather than issue the nice warning, but the end result of informing
the developer about their portability problem is still achieved):
#if HAVE_RAW_DECL_ENVIRON
static char ***
rpl_environ (void) { return &environ; }
_GL_WARN_ON_USE (rpl_environ, "environ is not always properly declared");
# undef environ
# define environ (*rpl_environ ())
#endif
or better (avoiding contradictory use of 'static' and 'extern'):
#if HAVE_RAW_DECL_ENVIRON
static char ***
_GL_WARN_ON_USE_ATTRIBUTE ("environ is not always properly declared")
rpl_environ (void) { return &environ; }
# undef environ
# define environ (*rpl_environ ())
#endif
*/
#ifndef _GL_WARN_ON_USE
#if 4 < __GNUC__ || (__GNUC__ == 4 && 3 <= __GNUC_MINOR__)
/* A compiler attribute is available in gcc versions 4.3.0 and later. */
#define _GL_WARN_ON_USE(function, message) \
extern __typeof__(function) function __attribute__((__warning__(message)))
#define _GL_WARN_ON_USE_ATTRIBUTE(message) __attribute__((__warning__(message)))
#elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
/* Verify the existence of the function. */
#define _GL_WARN_ON_USE(function, message) extern __typeof__(function) function
#define _GL_WARN_ON_USE_ATTRIBUTE(message)
#else /* Unsupported. */
#define _GL_WARN_ON_USE(function, message) _GL_WARN_EXTERN_C int _gl_warn_on_use
#define _GL_WARN_ON_USE_ATTRIBUTE(message)
#endif
#endif
/* _GL_WARN_ON_USE_CXX (function, rettype, parameters_and_attributes, "string")
is like _GL_WARN_ON_USE (function, "string"), except that the function is
declared with the given prototype, consisting of return type, parameters,
and attributes.
This variant is useful for overloaded functions in C++. _GL_WARN_ON_USE does
not work in this case. */
#ifndef _GL_WARN_ON_USE_CXX
#if 4 < __GNUC__ || (__GNUC__ == 4 && 3 <= __GNUC_MINOR__)
#define _GL_WARN_ON_USE_CXX(function, rettype, parameters_and_attributes, msg) \
extern rettype function parameters_and_attributes \
__attribute__((__warning__(msg)))
#elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
/* Verify the existence of the function. */
#define _GL_WARN_ON_USE_CXX(function, rettype, parameters_and_attributes, msg) \
extern rettype function parameters_and_attributes
#else /* Unsupported. */
#define _GL_WARN_ON_USE_CXX(function, rettype, parameters_and_attributes, msg) \
_GL_WARN_EXTERN_C int _gl_warn_on_use
#endif
#endif
/* _GL_WARN_EXTERN_C declaration;
performs the declaration with C linkage. */
#ifndef _GL_WARN_EXTERN_C
#if defined __cplusplus
#define _GL_WARN_EXTERN_C extern "C"
#else
#define _GL_WARN_EXTERN_C extern
#endif
#endif
/* Declare overridden functions. */
#if 0
#if 0
#if !(defined __cplusplus && defined GNULIB_NAMESPACE)
#undef creat
#define creat rpl_creat
#endif
_GL_FUNCDECL_RPL (creat, int, (const char *filename, mode_t mode)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (creat, int, (const char *filename, mode_t mode));
#else
_GL_CXXALIAS_SYS (creat, int, (const char *filename, mode_t mode));
#endif
_GL_CXXALIASWARN (creat);
#elif defined GNULIB_POSIXCHECK
#undef creat
/* Assume creat is always declared. */
_GL_WARN_ON_USE(creat, "creat is not always POSIX compliant - "
"use gnulib module creat for portability");
#endif
#if 1
#if 1
#if !(defined __cplusplus && defined GNULIB_NAMESPACE)
#undef fcntl
#define fcntl rpl_fcntl
#endif
_GL_FUNCDECL_RPL(fcntl, int, (int fd, int action, ...));
_GL_CXXALIAS_RPL(fcntl, int, (int fd, int action, ...));
#else
#if !1
_GL_FUNCDECL_SYS(fcntl, int, (int fd, int action, ...));
#endif
_GL_CXXALIAS_SYS(fcntl, int, (int fd, int action, ...));
#endif
_GL_CXXALIASWARN(fcntl);
#elif defined GNULIB_POSIXCHECK
#undef fcntl
#if HAVE_RAW_DECL_FCNTL
_GL_WARN_ON_USE(fcntl, "fcntl is not always POSIX compliant - "
"use gnulib module fcntl for portability");
#endif
#endif
#if 0
#if 0
#if !(defined __cplusplus && defined GNULIB_NAMESPACE)
#undef open
#define open rpl_open
#endif
_GL_FUNCDECL_RPL (open, int, (const char *filename, int flags, ...)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (open, int, (const char *filename, int flags, ...));
#else
_GL_CXXALIAS_SYS (open, int, (const char *filename, int flags, ...));
#endif
/* On HP-UX 11, in C++ mode, open() is defined as an inline function with a
default argument. _GL_CXXALIASWARN does not work in this case. */
#if !defined __hpux
_GL_CXXALIASWARN (open);
#endif
#elif defined GNULIB_POSIXCHECK
#undef open
/* Assume open is always declared. */
_GL_WARN_ON_USE(open, "open is not always POSIX compliant - "
"use gnulib module open for portability");
#endif
#if 0
#if 0
#if !(defined __cplusplus && defined GNULIB_NAMESPACE)
#undef openat
#define openat rpl_openat
#endif
_GL_FUNCDECL_RPL (openat, int,
(int fd, char const *file, int flags, /* mode_t mode */ ...)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (openat, int,
(int fd, char const *file, int flags, /* mode_t mode */ ...));
#else
#if !1
_GL_FUNCDECL_SYS (openat, int,
(int fd, char const *file, int flags, /* mode_t mode */ ...)
_GL_ARG_NONNULL ((2)));
#endif
_GL_CXXALIAS_SYS (openat, int,
(int fd, char const *file, int flags, /* mode_t mode */ ...));
#endif
_GL_CXXALIASWARN (openat);
#elif defined GNULIB_POSIXCHECK
#undef openat
#if HAVE_RAW_DECL_OPENAT
_GL_WARN_ON_USE(openat, "openat is not portable - "
"use gnulib module openat for portability");
#endif
#endif
/* Fix up the FD_* macros, only known to be missing on mingw. */
#ifndef FD_CLOEXEC
#define FD_CLOEXEC 1
#endif
/* Fix up the supported F_* macros. Intentionally leave other F_*
macros undefined. Only known to be missing on mingw. */
#ifndef F_DUPFD_CLOEXEC
#define F_DUPFD_CLOEXEC 0x40000000
/* Witness variable: 1 if gnulib defined F_DUPFD_CLOEXEC, 0 otherwise. */
#define GNULIB_defined_F_DUPFD_CLOEXEC 1
#else
#define GNULIB_defined_F_DUPFD_CLOEXEC 0
#endif
#ifndef F_DUPFD
#define F_DUPFD 1
#endif
#ifndef F_GETFD
#define F_GETFD 2
#endif
/* Fix up the O_* macros. */
#if !defined O_DIRECT && defined O_DIRECTIO
/* Tru64 spells it 'O_DIRECTIO'. */
#define O_DIRECT O_DIRECTIO
#endif
#if !defined O_CLOEXEC && defined O_NOINHERIT
/* Mingw spells it 'O_NOINHERIT'. */
#define O_CLOEXEC O_NOINHERIT
#endif
#ifndef O_CLOEXEC
#define O_CLOEXEC 0x40000000 /* Try to not collide with system O_* flags. */
#define GNULIB_defined_O_CLOEXEC 1
#else
#define GNULIB_defined_O_CLOEXEC 0
#endif
#ifndef O_DIRECT
#define O_DIRECT 0
#endif
#ifndef O_DIRECTORY
#define O_DIRECTORY 0
#endif
#ifndef O_DSYNC
#define O_DSYNC 0
#endif
#ifndef O_EXEC
#define O_EXEC O_RDONLY /* This is often close enough in older systems. */
#endif
#ifndef O_IGNORE_CTTY
#define O_IGNORE_CTTY 0
#endif
#ifndef O_NDELAY
#define O_NDELAY 0
#endif
#ifndef O_NOATIME
#define O_NOATIME 0
#endif
#ifndef O_NONBLOCK
#define O_NONBLOCK O_NDELAY
#endif
/* If the gnulib module 'nonblocking' is in use, guarantee a working non-zero
value of O_NONBLOCK. Otherwise, O_NONBLOCK is defined (above) to O_NDELAY
or to 0 as fallback. */
#if 0
#if O_NONBLOCK
#define GNULIB_defined_O_NONBLOCK 0
#else
#define GNULIB_defined_O_NONBLOCK 1
#undef O_NONBLOCK
#define O_NONBLOCK 0x40000000
#endif
#endif
#ifndef O_NOCTTY
#define O_NOCTTY 0
#endif
#ifndef O_NOFOLLOW
#define O_NOFOLLOW 0
#endif
#ifndef O_NOLINK
#define O_NOLINK 0
#endif
#ifndef O_NOLINKS
#define O_NOLINKS 0
#endif
#ifndef O_NOTRANS
#define O_NOTRANS 0
#endif
#ifndef O_RSYNC
#define O_RSYNC 0
#endif
#ifndef O_SEARCH
#define O_SEARCH O_RDONLY /* This is often close enough in older systems. */
#endif
#ifndef O_SYNC
#define O_SYNC 0
#endif
#ifndef O_TTY_INIT
#define O_TTY_INIT 0
#endif
#if ~O_ACCMODE & (O_RDONLY | O_WRONLY | O_RDWR | O_EXEC | O_SEARCH)
#undef O_ACCMODE
#define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR | O_EXEC | O_SEARCH)
#endif
/* For systems that distinguish between text and binary I/O.
O_BINARY is usually declared in fcntl.h */
#if !defined O_BINARY && defined _O_BINARY
/* For MSC-compatible compilers. */
#define O_BINARY _O_BINARY
#define O_TEXT _O_TEXT
#endif
#if defined __BEOS__ || defined __HAIKU__
/* BeOS 5 and Haiku have O_BINARY and O_TEXT, but they have no effect. */
#undef O_BINARY
#undef O_TEXT
#endif
#ifndef O_BINARY
#define O_BINARY 0
#define O_TEXT 0
#endif
/* Fix up the AT_* macros. */
/* Work around a bug in Solaris 9 and 10: AT_FDCWD is positive. Its
value exceeds INT_MAX, so its use as an int doesn't conform to the
C standard, and GCC and Sun C complain in some cases. If the bug
is present, undef AT_FDCWD here, so it can be redefined below. */
#if 0 < AT_FDCWD && AT_FDCWD == 0xffd19553
#undef AT_FDCWD
#endif
/* Use the same bit pattern as Solaris 9, but with the proper
signedness. The bit pattern is important, in case this actually is
Solaris with the above workaround. */
#ifndef AT_FDCWD
#define AT_FDCWD (-3041965)
#endif
/* Use the same values as Solaris 9. This shouldn't matter, but
there's no real reason to differ. */
#ifndef AT_SYMLINK_NOFOLLOW
#define AT_SYMLINK_NOFOLLOW 4096
#endif
#ifndef AT_REMOVEDIR
#define AT_REMOVEDIR 1
#endif
/* Solaris 9 lacks these two, so just pick unique values. */
#ifndef AT_SYMLINK_FOLLOW
#define AT_SYMLINK_FOLLOW 2
#endif
#ifndef AT_EACCESS
#define AT_EACCESS 4
#endif
#endif /* _GL_FCNTL_H */
#endif /* _GL_FCNTL_H */
#endif
| 30,278 | 812 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/stdio.h | /* clang-format off */
/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* A GNU-like <stdio.h>.
Copyright (C) 2004, 2007-2020 Free Software Foundation, 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; either version 3, 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/>. */
#if __GNUC__ >= 3
#pragma GCC system_header
#endif
#if defined __need_FILE || defined __need___FILE || defined _GL_ALREADY_INCLUDING_STDIO_H
/* Special invocation convention:
- Inside glibc header files.
- On OSF/1 5.1 we have a sequence of nested includes
<stdio.h> -> <getopt.h> -> <ctype.h> -> <sys/localedef.h> ->
<sys/lc_core.h> -> <nl_types.h> -> <mesg.h> -> <stdio.h>.
In this situation, the functions are not yet declared, therefore we cannot
provide the C++ aliases. */
#else
/* Normal invocation convention. */
#ifndef _GL_STDIO_H
#define _GL_ALREADY_INCLUDING_STDIO_H
/* The include_next requires a split double-inclusion guard. */
#undef _GL_ALREADY_INCLUDING_STDIO_H
#ifndef _GL_STDIO_H
#define _GL_STDIO_H
/* Get va_list. Needed on many systems, including glibc 2.8. */
/* Get off_t and ssize_t. Needed on many systems, including glibc 2.8
and eglibc 2.11.2.
May also define off_t to a 64-bit type on native Windows. */
/* The __attribute__ feature is available in gcc versions 2.5 and later.
The __-protected variants of the attributes 'format' and 'printf' are
accepted by gcc versions 2.6.4 (effectively 2.7) and later.
We enable _GL_ATTRIBUTE_FORMAT only if these are supported too, because
gnulib and libintl do '#define printf __printf__' when they override
the 'printf' function. */
#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7)
# define _GL_ATTRIBUTE_FORMAT(spec) __attribute__ ((__format__ spec))
#else
# define _GL_ATTRIBUTE_FORMAT(spec) /* empty */
#endif
/* _GL_ATTRIBUTE_FORMAT_PRINTF
indicates to GCC that the function takes a format string and arguments,
where the format string directives are the ones standardized by ISO C99
and POSIX. */
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)
# define _GL_ATTRIBUTE_FORMAT_PRINTF(formatstring_parameter, first_argument) \
_GL_ATTRIBUTE_FORMAT ((__gnu_printf__, formatstring_parameter, first_argument))
#else
# define _GL_ATTRIBUTE_FORMAT_PRINTF(formatstring_parameter, first_argument) \
_GL_ATTRIBUTE_FORMAT ((__printf__, formatstring_parameter, first_argument))
#endif
/* _GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM is like _GL_ATTRIBUTE_FORMAT_PRINTF,
except that it indicates to GCC that the supported format string directives
are the ones of the system printf(), rather than the ones standardized by
ISO C99 and POSIX. */
#if GNULIB_PRINTF_ATTRIBUTE_FLAVOR_GNU
# define _GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM(formatstring_parameter, first_argument) \
_GL_ATTRIBUTE_FORMAT_PRINTF (formatstring_parameter, first_argument)
#else
# define _GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM(formatstring_parameter, first_argument) \
_GL_ATTRIBUTE_FORMAT ((__printf__, formatstring_parameter, first_argument))
#endif
/* _GL_ATTRIBUTE_FORMAT_SCANF
indicates to GCC that the function takes a format string and arguments,
where the format string directives are the ones standardized by ISO C99
and POSIX. */
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)
# define _GL_ATTRIBUTE_FORMAT_SCANF(formatstring_parameter, first_argument) \
_GL_ATTRIBUTE_FORMAT ((__gnu_scanf__, formatstring_parameter, first_argument))
#else
# define _GL_ATTRIBUTE_FORMAT_SCANF(formatstring_parameter, first_argument) \
_GL_ATTRIBUTE_FORMAT ((__scanf__, formatstring_parameter, first_argument))
#endif
/* _GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM is like _GL_ATTRIBUTE_FORMAT_SCANF,
except that it indicates to GCC that the supported format string directives
are the ones of the system scanf(), rather than the ones standardized by
ISO C99 and POSIX. */
#define _GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM(formatstring_parameter, first_argument) \
_GL_ATTRIBUTE_FORMAT ((__scanf__, formatstring_parameter, first_argument))
/* Solaris 10 and NetBSD 7.0 declare renameat in <unistd.h>, not in <stdio.h>. */
/* But in any case avoid namespace pollution on glibc systems. */
#if (0 || defined GNULIB_POSIXCHECK) && (defined __sun || defined __NetBSD__) \
&& ! defined __GLIBC__
#endif
/* Android 4.3 declares renameat in <sys/stat.h>, not in <stdio.h>. */
/* But in any case avoid namespace pollution on glibc systems. */
#if (0 || defined GNULIB_POSIXCHECK) && defined __ANDROID__ \
&& ! defined __GLIBC__
#endif
/* MSVC declares 'perror' in <stdlib.h>, not in <stdio.h>. We must include
it before we #define perror rpl_perror. */
/* But in any case avoid namespace pollution on glibc systems. */
#if (0 || defined GNULIB_POSIXCHECK) \
&& (defined _WIN32 && ! defined __CYGWIN__) \
&& ! defined __GLIBC__
#endif
/* MSVC declares 'remove' in <io.h>, not in <stdio.h>. We must include
it before we #define remove rpl_remove. */
/* MSVC declares 'rename' in <io.h>, not in <stdio.h>. We must include
it before we #define rename rpl_rename. */
/* But in any case avoid namespace pollution on glibc systems. */
#if (0 || 0 || defined GNULIB_POSIXCHECK) \
&& (defined _WIN32 && ! defined __CYGWIN__) \
&& ! defined __GLIBC__
#endif
/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
/* C++ compatible function declaration macros.
Copyright (C) 2010-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#ifndef _GL_CXXDEFS_H
#define _GL_CXXDEFS_H
/* Begin/end the GNULIB_NAMESPACE namespace. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_BEGIN_NAMESPACE namespace GNULIB_NAMESPACE {
# define _GL_END_NAMESPACE }
#else
# define _GL_BEGIN_NAMESPACE
# define _GL_END_NAMESPACE
#endif
/* The three most frequent use cases of these macros are:
* For providing a substitute for a function that is missing on some
platforms, but is declared and works fine on the platforms on which
it exists:
#if @GNULIB_FOO@
# if !@HAVE_FOO@
_GL_FUNCDECL_SYS (foo, ...);
# endif
_GL_CXXALIAS_SYS (foo, ...);
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
* For providing a replacement for a function that exists on all platforms,
but is broken/insufficient and needs to be replaced on some platforms:
#if @GNULIB_FOO@
# if @REPLACE_FOO@
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef foo
# define foo rpl_foo
# endif
_GL_FUNCDECL_RPL (foo, ...);
_GL_CXXALIAS_RPL (foo, ...);
# else
_GL_CXXALIAS_SYS (foo, ...);
# endif
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
* For providing a replacement for a function that exists on some platforms
but is broken/insufficient and needs to be replaced on some of them and
is additionally either missing or undeclared on some other platforms:
#if @GNULIB_FOO@
# if @REPLACE_FOO@
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef foo
# define foo rpl_foo
# endif
_GL_FUNCDECL_RPL (foo, ...);
_GL_CXXALIAS_RPL (foo, ...);
# else
# if !@HAVE_FOO@ or if !@HAVE_DECL_FOO@
_GL_FUNCDECL_SYS (foo, ...);
# endif
_GL_CXXALIAS_SYS (foo, ...);
# endif
_GL_CXXALIASWARN (foo);
#elif defined GNULIB_POSIXCHECK
...
#endif
*/
/* _GL_EXTERN_C declaration;
performs the declaration with C linkage. */
#if defined __cplusplus
# define _GL_EXTERN_C extern "C"
#else
# define _GL_EXTERN_C extern
#endif
/* _GL_FUNCDECL_RPL (func, rettype, parameters_and_attributes);
declares a replacement function, named rpl_func, with the given prototype,
consisting of return type, parameters, and attributes.
Example:
_GL_FUNCDECL_RPL (open, int, (const char *filename, int flags, ...)
_GL_ARG_NONNULL ((1)));
*/
#define _GL_FUNCDECL_RPL(func,rettype,parameters_and_attributes) \
_GL_FUNCDECL_RPL_1 (rpl_##func, rettype, parameters_and_attributes)
#define _GL_FUNCDECL_RPL_1(rpl_func,rettype,parameters_and_attributes) \
_GL_EXTERN_C rettype rpl_func parameters_and_attributes
/* _GL_FUNCDECL_SYS (func, rettype, parameters_and_attributes);
declares the system function, named func, with the given prototype,
consisting of return type, parameters, and attributes.
Example:
_GL_FUNCDECL_SYS (open, int, (const char *filename, int flags, ...)
_GL_ARG_NONNULL ((1)));
*/
#define _GL_FUNCDECL_SYS(func,rettype,parameters_and_attributes) \
_GL_EXTERN_C rettype func parameters_and_attributes
/* _GL_CXXALIAS_RPL (func, rettype, parameters);
declares a C++ alias called GNULIB_NAMESPACE::func
that redirects to rpl_func, if GNULIB_NAMESPACE is defined.
Example:
_GL_CXXALIAS_RPL (open, int, (const char *filename, int flags, ...));
Wrapping rpl_func in an object with an inline conversion operator
avoids a reference to rpl_func unless GNULIB_NAMESPACE::func is
actually used in the program. */
#define _GL_CXXALIAS_RPL(func,rettype,parameters) \
_GL_CXXALIAS_RPL_1 (func, rpl_##func, rettype, parameters)
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_RPL_1(func,rpl_func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return ::rpl_func; \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_RPL_1(func,rpl_func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_RPL_CAST_1 (func, rpl_func, rettype, parameters);
is like _GL_CXXALIAS_RPL_1 (func, rpl_func, rettype, parameters);
except that the C function rpl_func may have a slightly different
declaration. A cast is used to silence the "invalid conversion" error
that would otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_RPL_CAST_1(func,rpl_func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return reinterpret_cast<type>(::rpl_func); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_RPL_CAST_1(func,rpl_func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS (func, rettype, parameters);
declares a C++ alias called GNULIB_NAMESPACE::func
that redirects to the system provided function func, if GNULIB_NAMESPACE
is defined.
Example:
_GL_CXXALIAS_SYS (open, int, (const char *filename, int flags, ...));
Wrapping func in an object with an inline conversion operator
avoids a reference to func unless GNULIB_NAMESPACE::func is
actually used in the program. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_SYS(func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return ::func; \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_SYS(func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS_CAST (func, rettype, parameters);
is like _GL_CXXALIAS_SYS (func, rettype, parameters);
except that the C function func may have a slightly different declaration.
A cast is used to silence the "invalid conversion" error that would
otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIAS_SYS_CAST(func,rettype,parameters) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return reinterpret_cast<type>(::func); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_SYS_CAST(func,rettype,parameters) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIAS_SYS_CAST2 (func, rettype, parameters, rettype2, parameters2);
is like _GL_CXXALIAS_SYS (func, rettype, parameters);
except that the C function is picked among a set of overloaded functions,
namely the one with rettype2 and parameters2. Two consecutive casts
are used to silence the "cannot find a match" and "invalid conversion"
errors that would otherwise occur. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
/* The outer cast must be a reinterpret_cast.
The inner cast: When the function is defined as a set of overloaded
functions, it works as a static_cast<>, choosing the designated variant.
When the function is defined as a single variant, it works as a
reinterpret_cast<>. The parenthesized cast syntax works both ways. */
# define _GL_CXXALIAS_SYS_CAST2(func,rettype,parameters,rettype2,parameters2) \
namespace GNULIB_NAMESPACE \
{ \
static const struct _gl_ ## func ## _wrapper \
{ \
typedef rettype (*type) parameters; \
\
inline operator type () const \
{ \
return reinterpret_cast<type>((rettype2 (*) parameters2)(::func)); \
} \
} func = {}; \
} \
_GL_EXTERN_C int _gl_cxxalias_dummy
#else
# define _GL_CXXALIAS_SYS_CAST2(func,rettype,parameters,rettype2,parameters2) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIASWARN (func);
causes a warning to be emitted when ::func is used but not when
GNULIB_NAMESPACE::func is used. func must be defined without overloaded
variants. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIASWARN(func) \
_GL_CXXALIASWARN_1 (func, GNULIB_NAMESPACE)
# define _GL_CXXALIASWARN_1(func,namespace) \
_GL_CXXALIASWARN_2 (func, namespace)
/* To work around GCC bug <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=43881>,
we enable the warning only when not optimizing. */
# if !__OPTIMIZE__
# define _GL_CXXALIASWARN_2(func,namespace) \
_GL_WARN_ON_USE (func, \
"The symbol ::" #func " refers to the system function. " \
"Use " #namespace "::" #func " instead.")
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
# define _GL_CXXALIASWARN_2(func,namespace) \
extern __typeof__ (func) func
# else
# define _GL_CXXALIASWARN_2(func,namespace) \
_GL_EXTERN_C int _gl_cxxalias_dummy
# endif
#else
# define _GL_CXXALIASWARN(func) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
/* _GL_CXXALIASWARN1 (func, rettype, parameters_and_attributes);
causes a warning to be emitted when the given overloaded variant of ::func
is used but not when GNULIB_NAMESPACE::func is used. */
#if defined __cplusplus && defined GNULIB_NAMESPACE
# define _GL_CXXALIASWARN1(func,rettype,parameters_and_attributes) \
_GL_CXXALIASWARN1_1 (func, rettype, parameters_and_attributes, \
GNULIB_NAMESPACE)
# define _GL_CXXALIASWARN1_1(func,rettype,parameters_and_attributes,namespace) \
_GL_CXXALIASWARN1_2 (func, rettype, parameters_and_attributes, namespace)
/* To work around GCC bug <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=43881>,
we enable the warning only when not optimizing. */
# if !__OPTIMIZE__
# define _GL_CXXALIASWARN1_2(func,rettype,parameters_and_attributes,namespace) \
_GL_WARN_ON_USE_CXX (func, rettype, parameters_and_attributes, \
"The symbol ::" #func " refers to the system function. " \
"Use " #namespace "::" #func " instead.")
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
# define _GL_CXXALIASWARN1_2(func,rettype,parameters_and_attributes,namespace) \
extern __typeof__ (func) func
# else
# define _GL_CXXALIASWARN1_2(func,rettype,parameters_and_attributes,namespace) \
_GL_EXTERN_C int _gl_cxxalias_dummy
# endif
#else
# define _GL_CXXALIASWARN1(func,rettype,parameters_and_attributes) \
_GL_EXTERN_C int _gl_cxxalias_dummy
#endif
#endif /* _GL_CXXDEFS_H */
/* The definition of _GL_ARG_NONNULL is copied here. */
/* A C macro for declaring that specific arguments must not be NULL.
Copyright (C) 2009-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* _GL_ARG_NONNULL((n,...,m)) tells the compiler and static analyzer tools
that the values passed as arguments n, ..., m must be non-NULL pointers.
n = 1 stands for the first argument, n = 2 for the second argument etc. */
#ifndef _GL_ARG_NONNULL
# if (__GNUC__ == 3 && __GNUC_MINOR__ >= 3) || __GNUC__ > 3
# define _GL_ARG_NONNULL(params) __attribute__ ((__nonnull__ params))
# else
# define _GL_ARG_NONNULL(params)
# endif
#endif
/* The definition of _GL_WARN_ON_USE is copied here. */
/* A C macro for emitting warnings if a function is used.
Copyright (C) 2010-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
/* _GL_WARN_ON_USE (function, "literal string") issues a declaration
for FUNCTION which will then trigger a compiler warning containing
the text of "literal string" anywhere that function is called, if
supported by the compiler. If the compiler does not support this
feature, the macro expands to an unused extern declaration.
_GL_WARN_ON_USE_ATTRIBUTE ("literal string") expands to the
attribute used in _GL_WARN_ON_USE. If the compiler does not support
this feature, it expands to empty.
These macros are useful for marking a function as a potential
portability trap, with the intent that "literal string" include
instructions on the replacement function that should be used
instead.
_GL_WARN_ON_USE is for functions with 'extern' linkage.
_GL_WARN_ON_USE_ATTRIBUTE is for functions with 'static' or 'inline'
linkage.
However, one of the reasons that a function is a portability trap is
if it has the wrong signature. Declaring FUNCTION with a different
signature in C is a compilation error, so this macro must use the
same type as any existing declaration so that programs that avoid
the problematic FUNCTION do not fail to compile merely because they
included a header that poisoned the function. But this implies that
_GL_WARN_ON_USE is only safe to use if FUNCTION is known to already
have a declaration. Use of this macro implies that there must not
be any other macro hiding the declaration of FUNCTION; but
undefining FUNCTION first is part of the poisoning process anyway
(although for symbols that are provided only via a macro, the result
is a compilation error rather than a warning containing
"literal string"). Also note that in C++, it is only safe to use if
FUNCTION has no overloads.
For an example, it is possible to poison 'getline' by:
[getline]) in configure.ac, which potentially defines
HAVE_RAW_DECL_GETLINE
- adding this code to a header that wraps the system <stdio.h>:
#undef getline
#if HAVE_RAW_DECL_GETLINE
_GL_WARN_ON_USE (getline, "getline is required by POSIX 2008, but"
"not universally present; use the gnulib module getline");
#endif
It is not possible to directly poison global variables. But it is
possible to write a wrapper accessor function, and poison that
(less common usage, like &environ, will cause a compilation error
rather than issue the nice warning, but the end result of informing
the developer about their portability problem is still achieved):
#if HAVE_RAW_DECL_ENVIRON
static char ***
rpl_environ (void) { return &environ; }
_GL_WARN_ON_USE (rpl_environ, "environ is not always properly declared");
# undef environ
# define environ (*rpl_environ ())
#endif
or better (avoiding contradictory use of 'static' and 'extern'):
#if HAVE_RAW_DECL_ENVIRON
static char ***
_GL_WARN_ON_USE_ATTRIBUTE ("environ is not always properly declared")
rpl_environ (void) { return &environ; }
# undef environ
# define environ (*rpl_environ ())
#endif
*/
#ifndef _GL_WARN_ON_USE
# if 4 < __GNUC__ || (__GNUC__ == 4 && 3 <= __GNUC_MINOR__)
/* A compiler attribute is available in gcc versions 4.3.0 and later. */
# define _GL_WARN_ON_USE(function, message) \
extern __typeof__ (function) function __attribute__ ((__warning__ (message)))
# define _GL_WARN_ON_USE_ATTRIBUTE(message) \
__attribute__ ((__warning__ (message)))
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
/* Verify the existence of the function. */
# define _GL_WARN_ON_USE(function, message) \
extern __typeof__ (function) function
# define _GL_WARN_ON_USE_ATTRIBUTE(message)
# else /* Unsupported. */
# define _GL_WARN_ON_USE(function, message) \
_GL_WARN_EXTERN_C int _gl_warn_on_use
# define _GL_WARN_ON_USE_ATTRIBUTE(message)
# endif
#endif
/* _GL_WARN_ON_USE_CXX (function, rettype, parameters_and_attributes, "string")
is like _GL_WARN_ON_USE (function, "string"), except that the function is
declared with the given prototype, consisting of return type, parameters,
and attributes.
This variant is useful for overloaded functions in C++. _GL_WARN_ON_USE does
not work in this case. */
#ifndef _GL_WARN_ON_USE_CXX
# if 4 < __GNUC__ || (__GNUC__ == 4 && 3 <= __GNUC_MINOR__)
# define _GL_WARN_ON_USE_CXX(function,rettype,parameters_and_attributes,msg) \
extern rettype function parameters_and_attributes \
__attribute__ ((__warning__ (msg)))
# elif __GNUC__ >= 3 && GNULIB_STRICT_CHECKING
/* Verify the existence of the function. */
# define _GL_WARN_ON_USE_CXX(function,rettype,parameters_and_attributes,msg) \
extern rettype function parameters_and_attributes
# else /* Unsupported. */
# define _GL_WARN_ON_USE_CXX(function,rettype,parameters_and_attributes,msg) \
_GL_WARN_EXTERN_C int _gl_warn_on_use
# endif
#endif
/* _GL_WARN_EXTERN_C declaration;
performs the declaration with C linkage. */
#ifndef _GL_WARN_EXTERN_C
# if defined __cplusplus
# define _GL_WARN_EXTERN_C extern "C"
# else
# define _GL_WARN_EXTERN_C extern
# endif
#endif
/* Macros for stringification. */
#define _GL_STDIO_STRINGIZE(token) #token
#define _GL_STDIO_MACROEXPAND_AND_STRINGIZE(token) _GL_STDIO_STRINGIZE(token)
/* When also using extern inline, suppress the use of static inline in
standard headers of problematic Apple configurations, as Libc at
least through Libc-825.26 (2013-04-09) mishandles it; see, e.g.,
<https://lists.gnu.org/r/bug-gnulib/2012-12/msg00023.html>.
Perhaps Apple will fix this some day. */
#if (defined _GL_EXTERN_INLINE_IN_USE && defined __APPLE__ \
&& defined __GNUC__ && defined __STDC__)
# undef putc_unlocked
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define dprintf rpl_dprintf
# endif
_GL_FUNCDECL_RPL (dprintf, int, (int fd, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (dprintf, int, (int fd, const char *format, ...));
# else
# if !1
_GL_FUNCDECL_SYS (dprintf, int, (int fd, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
_GL_ARG_NONNULL ((2)));
# endif
_GL_CXXALIAS_SYS (dprintf, int, (int fd, const char *format, ...));
# endif
_GL_CXXALIASWARN (dprintf);
#elif defined GNULIB_POSIXCHECK
# undef dprintf
# if HAVE_RAW_DECL_DPRINTF
_GL_WARN_ON_USE (dprintf, "dprintf is unportable - "
"use gnulib module dprintf for portability");
# endif
#endif
#if 0
/* Close STREAM and its underlying file descriptor. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define fclose rpl_fclose
# endif
_GL_FUNCDECL_RPL (fclose, int, (FILE *stream) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (fclose, int, (FILE *stream));
# else
_GL_CXXALIAS_SYS (fclose, int, (FILE *stream));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fclose);
# endif
#elif defined GNULIB_POSIXCHECK
# undef fclose
/* Assume fclose is always declared. */
_GL_WARN_ON_USE (fclose, "fclose is not always POSIX compliant - "
"use gnulib module fclose for portable POSIX compliance");
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fdopen
# define fdopen rpl_fdopen
# endif
_GL_FUNCDECL_RPL (fdopen, FILE *, (int fd, const char *mode)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (fdopen, FILE *, (int fd, const char *mode));
# else
_GL_CXXALIAS_SYS (fdopen, FILE *, (int fd, const char *mode));
# endif
_GL_CXXALIASWARN (fdopen);
#elif defined GNULIB_POSIXCHECK
# undef fdopen
/* Assume fdopen is always declared. */
_GL_WARN_ON_USE (fdopen, "fdopen on native Windows platforms is not POSIX compliant - "
"use gnulib module fdopen for portability");
#endif
#if 0
/* Flush all pending data on STREAM according to POSIX rules. Both
output and seekable input streams are supported.
Note! LOSS OF DATA can occur if fflush is applied on an input stream
that is _not_seekable_ or on an update stream that is _not_seekable_
and in which the most recent operation was input. Seekability can
be tested with lseek(fileno(fp),0,SEEK_CUR). */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define fflush rpl_fflush
# endif
_GL_FUNCDECL_RPL (fflush, int, (FILE *gl_stream));
_GL_CXXALIAS_RPL (fflush, int, (FILE *gl_stream));
# else
_GL_CXXALIAS_SYS (fflush, int, (FILE *gl_stream));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fflush);
# endif
#elif defined GNULIB_POSIXCHECK
# undef fflush
/* Assume fflush is always declared. */
_GL_WARN_ON_USE (fflush, "fflush is not always POSIX compliant - "
"use gnulib module fflush for portable POSIX compliance");
#endif
#if 1
# if 0 && 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fgetc
# define fgetc rpl_fgetc
# endif
_GL_FUNCDECL_RPL (fgetc, int, (FILE *stream) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (fgetc, int, (FILE *stream));
# else
_GL_CXXALIAS_SYS (fgetc, int, (FILE *stream));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fgetc);
# endif
#endif
#if 1
# if 0 && 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fgets
# define fgets rpl_fgets
# endif
_GL_FUNCDECL_RPL (fgets, char *, (char *s, int n, FILE *stream)
_GL_ARG_NONNULL ((1, 3)));
_GL_CXXALIAS_RPL (fgets, char *, (char *s, int n, FILE *stream));
# else
_GL_CXXALIAS_SYS (fgets, char *, (char *s, int n, FILE *stream));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fgets);
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fopen
# define fopen rpl_fopen
# endif
_GL_FUNCDECL_RPL (fopen, FILE *, (const char *filename, const char *mode)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (fopen, FILE *, (const char *filename, const char *mode));
# else
_GL_CXXALIAS_SYS (fopen, FILE *, (const char *filename, const char *mode));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fopen);
# endif
#elif defined GNULIB_POSIXCHECK
# undef fopen
/* Assume fopen is always declared. */
_GL_WARN_ON_USE (fopen, "fopen on native Windows platforms is not POSIX compliant - "
"use gnulib module fopen for portability");
#endif
#if 0 || 1
# if (0 && 0) \
|| (1 && 0 && (0 || 0))
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define fprintf rpl_fprintf
# endif
# define GNULIB_overrides_fprintf 1
# if 0 || 0
_GL_FUNCDECL_RPL (fprintf, int, (FILE *fp, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
_GL_ARG_NONNULL ((1, 2)));
# else
_GL_FUNCDECL_RPL (fprintf, int, (FILE *fp, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM (2, 3)
_GL_ARG_NONNULL ((1, 2)));
# endif
_GL_CXXALIAS_RPL (fprintf, int, (FILE *fp, const char *format, ...));
# else
_GL_CXXALIAS_SYS (fprintf, int, (FILE *fp, const char *format, ...));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fprintf);
# endif
#endif
#if !0 && defined GNULIB_POSIXCHECK
# if !GNULIB_overrides_fprintf
# undef fprintf
# endif
/* Assume fprintf is always declared. */
_GL_WARN_ON_USE (fprintf, "fprintf is not always POSIX compliant - "
"use gnulib module fprintf-posix for portable "
"POSIX compliance");
#endif
#if 0
/* Discard all pending buffered I/O data on STREAM.
STREAM must not be wide-character oriented.
When discarding pending output, the file position is set back to where it
was before the write calls. When discarding pending input, the file
position is advanced to match the end of the previously read input.
Return 0 if successful. Upon error, return -1 and set errno. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define fpurge rpl_fpurge
# endif
_GL_FUNCDECL_RPL (fpurge, int, (FILE *gl_stream) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (fpurge, int, (FILE *gl_stream));
# else
# if !1
_GL_FUNCDECL_SYS (fpurge, int, (FILE *gl_stream) _GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (fpurge, int, (FILE *gl_stream));
# endif
_GL_CXXALIASWARN (fpurge);
#elif defined GNULIB_POSIXCHECK
# undef fpurge
# if HAVE_RAW_DECL_FPURGE
_GL_WARN_ON_USE (fpurge, "fpurge is not always present - "
"use gnulib module fpurge for portability");
# endif
#endif
#if 1
# if 0 && (0 || 0)
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fputc
# define fputc rpl_fputc
# endif
_GL_FUNCDECL_RPL (fputc, int, (int c, FILE *stream) _GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (fputc, int, (int c, FILE *stream));
# else
_GL_CXXALIAS_SYS (fputc, int, (int c, FILE *stream));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fputc);
# endif
#endif
#if 1
# if 0 && (0 || 0)
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fputs
# define fputs rpl_fputs
# endif
_GL_FUNCDECL_RPL (fputs, int, (const char *string, FILE *stream)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (fputs, int, (const char *string, FILE *stream));
# else
_GL_CXXALIAS_SYS (fputs, int, (const char *string, FILE *stream));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fputs);
# endif
#endif
#if 1
# if 0 && 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fread
# define fread rpl_fread
# endif
_GL_FUNCDECL_RPL (fread, size_t, (void *ptr, size_t s, size_t n, FILE *stream)
_GL_ARG_NONNULL ((4)));
_GL_CXXALIAS_RPL (fread, size_t, (void *ptr, size_t s, size_t n, FILE *stream));
# else
_GL_CXXALIAS_SYS (fread, size_t, (void *ptr, size_t s, size_t n, FILE *stream));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fread);
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef freopen
# define freopen rpl_freopen
# endif
_GL_FUNCDECL_RPL (freopen, FILE *,
(const char *filename, const char *mode, FILE *stream)
_GL_ARG_NONNULL ((2, 3)));
_GL_CXXALIAS_RPL (freopen, FILE *,
(const char *filename, const char *mode, FILE *stream));
# else
_GL_CXXALIAS_SYS (freopen, FILE *,
(const char *filename, const char *mode, FILE *stream));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (freopen);
# endif
#elif defined GNULIB_POSIXCHECK
# undef freopen
/* Assume freopen is always declared. */
_GL_WARN_ON_USE (freopen,
"freopen on native Windows platforms is not POSIX compliant - "
"use gnulib module freopen for portability");
#endif
#if 1
# if 0 && 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fscanf
# define fscanf rpl_fscanf
# endif
_GL_FUNCDECL_RPL (fscanf, int, (FILE *stream, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM (2, 3)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (fscanf, int, (FILE *stream, const char *format, ...));
# else
_GL_CXXALIAS_SYS (fscanf, int, (FILE *stream, const char *format, ...));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fscanf);
# endif
#endif
/* Set up the following warnings, based on which modules are in use.
GNU Coding Standards discourage the use of fseek, since it imposes
an arbitrary limitation on some 32-bit hosts. Remember that the
fseek module depends on the fseeko module, so we only have three
cases to consider:
1. The developer is not using either module. Issue a warning under
GNULIB_POSIXCHECK for both functions, to remind them that both
functions have bugs on some systems. _GL_NO_LARGE_FILES has no
impact on this warning.
2. The developer is using both modules. They may be unaware of the
arbitrary limitations of fseek, so issue a warning under
GNULIB_POSIXCHECK. On the other hand, they may be using both
modules intentionally, so the developer can define
_GL_NO_LARGE_FILES in the compilation units where the use of fseek
is safe, to silence the warning.
3. The developer is using the fseeko module, but not fseek. Gnulib
guarantees that fseek will still work around platform bugs in that
case, but we presume that the developer is aware of the pitfalls of
fseek and was trying to avoid it, so issue a warning even when
GNULIB_POSIXCHECK is undefined. Again, _GL_NO_LARGE_FILES can be
defined to silence the warning in particular compilation units.
In C++ compilations with GNULIB_NAMESPACE, in order to avoid that
fseek gets defined as a macro, it is recommended that the developer
uses the fseek module, even if he is not calling the fseek function.
Most gnulib clients that perform stream operations should fall into
category 3. */
#if 0
# if defined GNULIB_POSIXCHECK && !defined _GL_NO_LARGE_FILES
# define _GL_FSEEK_WARN /* Category 2, above. */
# undef fseek
# endif
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fseek
# define fseek rpl_fseek
# endif
_GL_FUNCDECL_RPL (fseek, int, (FILE *fp, long offset, int whence)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (fseek, int, (FILE *fp, long offset, int whence));
# else
_GL_CXXALIAS_SYS (fseek, int, (FILE *fp, long offset, int whence));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fseek);
# endif
#endif
#if 0
# if !0 && !defined _GL_NO_LARGE_FILES
# define _GL_FSEEK_WARN /* Category 3, above. */
# undef fseek
# endif
# if 0
/* Provide an fseeko function that is aware of a preceding fflush(), and which
detects pipes. */
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fseeko
# define fseeko rpl_fseeko
# endif
_GL_FUNCDECL_RPL (fseeko, int, (FILE *fp, off_t offset, int whence)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (fseeko, int, (FILE *fp, off_t offset, int whence));
# else
# if ! 1
_GL_FUNCDECL_SYS (fseeko, int, (FILE *fp, off_t offset, int whence)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (fseeko, int, (FILE *fp, off_t offset, int whence));
# endif
_GL_CXXALIASWARN (fseeko);
#elif defined GNULIB_POSIXCHECK
# define _GL_FSEEK_WARN /* Category 1, above. */
# undef fseek
# undef fseeko
# if HAVE_RAW_DECL_FSEEKO
_GL_WARN_ON_USE (fseeko, "fseeko is unportable - "
"use gnulib module fseeko for portability");
# endif
#endif
#ifdef _GL_FSEEK_WARN
# undef _GL_FSEEK_WARN
/* Here, either fseek is undefined (but C89 guarantees that it is
declared), or it is defined as rpl_fseek (declared above). */
_GL_WARN_ON_USE (fseek, "fseek cannot handle files larger than 4 GB "
"on 32-bit platforms - "
"use fseeko function for handling of large files");
#endif
/* ftell, ftello. See the comments on fseek/fseeko. */
#if 0
# if defined GNULIB_POSIXCHECK && !defined _GL_NO_LARGE_FILES
# define _GL_FTELL_WARN /* Category 2, above. */
# undef ftell
# endif
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef ftell
# define ftell rpl_ftell
# endif
_GL_FUNCDECL_RPL (ftell, long, (FILE *fp) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (ftell, long, (FILE *fp));
# else
_GL_CXXALIAS_SYS (ftell, long, (FILE *fp));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (ftell);
# endif
#endif
#if 0
# if !0 && !defined _GL_NO_LARGE_FILES
# define _GL_FTELL_WARN /* Category 3, above. */
# undef ftell
# endif
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef ftello
# define ftello rpl_ftello
# endif
_GL_FUNCDECL_RPL (ftello, off_t, (FILE *fp) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (ftello, off_t, (FILE *fp));
# else
# if ! 1
_GL_FUNCDECL_SYS (ftello, off_t, (FILE *fp) _GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (ftello, off_t, (FILE *fp));
# endif
_GL_CXXALIASWARN (ftello);
#elif defined GNULIB_POSIXCHECK
# define _GL_FTELL_WARN /* Category 1, above. */
# undef ftell
# undef ftello
# if HAVE_RAW_DECL_FTELLO
_GL_WARN_ON_USE (ftello, "ftello is unportable - "
"use gnulib module ftello for portability");
# endif
#endif
#ifdef _GL_FTELL_WARN
# undef _GL_FTELL_WARN
/* Here, either ftell is undefined (but C89 guarantees that it is
declared), or it is defined as rpl_ftell (declared above). */
_GL_WARN_ON_USE (ftell, "ftell cannot handle files larger than 4 GB "
"on 32-bit platforms - "
"use ftello function for handling of large files");
#endif
#if 1
# if 0 && (0 || 0)
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef fwrite
# define fwrite rpl_fwrite
# endif
_GL_FUNCDECL_RPL (fwrite, size_t,
(const void *ptr, size_t s, size_t n, FILE *stream)
_GL_ARG_NONNULL ((1, 4)));
_GL_CXXALIAS_RPL (fwrite, size_t,
(const void *ptr, size_t s, size_t n, FILE *stream));
# else
_GL_CXXALIAS_SYS (fwrite, size_t,
(const void *ptr, size_t s, size_t n, FILE *stream));
/* Work around bug 11959 when fortifying glibc 2.4 through 2.15
<https://sourceware.org/bugzilla/show_bug.cgi?id=11959>,
which sometimes causes an unwanted diagnostic for fwrite calls.
This affects only function declaration attributes under certain
versions of gcc and clang, and is not needed for C++. */
# if (0 < __USE_FORTIFY_LEVEL \
&& __GLIBC__ == 2 && 4 <= __GLIBC_MINOR__ && __GLIBC_MINOR__ <= 15 \
&& 3 < __GNUC__ + (4 <= __GNUC_MINOR__) \
&& !defined __cplusplus)
# undef fwrite
# undef fwrite_unlocked
extern size_t __REDIRECT (rpl_fwrite,
(const void *__restrict, size_t, size_t,
FILE *__restrict),
fwrite);
extern size_t __REDIRECT (rpl_fwrite_unlocked,
(const void *__restrict, size_t, size_t,
FILE *__restrict),
fwrite_unlocked);
# define fwrite rpl_fwrite
# define fwrite_unlocked rpl_fwrite_unlocked
# endif
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (fwrite);
# endif
#endif
#if 1
# if 0 && 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef getc
# define getc rpl_fgetc
# endif
_GL_FUNCDECL_RPL (fgetc, int, (FILE *stream) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL_1 (getc, rpl_fgetc, int, (FILE *stream));
# else
_GL_CXXALIAS_SYS (getc, int, (FILE *stream));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (getc);
# endif
#endif
#if 1
# if 0 && 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef getchar
# define getchar rpl_getchar
# endif
_GL_FUNCDECL_RPL (getchar, int, (void));
_GL_CXXALIAS_RPL (getchar, int, (void));
# else
_GL_CXXALIAS_SYS (getchar, int, (void));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (getchar);
# endif
#endif
#if 0
/* Read input, up to (and including) the next occurrence of DELIMITER, from
STREAM, store it in *LINEPTR (and NUL-terminate it).
*LINEPTR is a pointer returned from malloc (or NULL), pointing to *LINESIZE
bytes of space. It is realloc'd as necessary.
Return the number of bytes read and stored at *LINEPTR (not including the
NUL terminator), or -1 on error or EOF. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef getdelim
# define getdelim rpl_getdelim
# endif
_GL_FUNCDECL_RPL (getdelim, ssize_t,
(char **lineptr, size_t *linesize, int delimiter,
FILE *stream)
_GL_ARG_NONNULL ((1, 2, 4)));
_GL_CXXALIAS_RPL (getdelim, ssize_t,
(char **lineptr, size_t *linesize, int delimiter,
FILE *stream));
# else
# if !1
_GL_FUNCDECL_SYS (getdelim, ssize_t,
(char **lineptr, size_t *linesize, int delimiter,
FILE *stream)
_GL_ARG_NONNULL ((1, 2, 4)));
# endif
_GL_CXXALIAS_SYS (getdelim, ssize_t,
(char **lineptr, size_t *linesize, int delimiter,
FILE *stream));
# endif
_GL_CXXALIASWARN (getdelim);
#elif defined GNULIB_POSIXCHECK
# undef getdelim
# if HAVE_RAW_DECL_GETDELIM
_GL_WARN_ON_USE (getdelim, "getdelim is unportable - "
"use gnulib module getdelim for portability");
# endif
#endif
#if 0
/* Read a line, up to (and including) the next newline, from STREAM, store it
in *LINEPTR (and NUL-terminate it).
*LINEPTR is a pointer returned from malloc (or NULL), pointing to *LINESIZE
bytes of space. It is realloc'd as necessary.
Return the number of bytes read and stored at *LINEPTR (not including the
NUL terminator), or -1 on error or EOF. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef getline
# define getline rpl_getline
# endif
_GL_FUNCDECL_RPL (getline, ssize_t,
(char **lineptr, size_t *linesize, FILE *stream)
_GL_ARG_NONNULL ((1, 2, 3)));
_GL_CXXALIAS_RPL (getline, ssize_t,
(char **lineptr, size_t *linesize, FILE *stream));
# else
# if !1
_GL_FUNCDECL_SYS (getline, ssize_t,
(char **lineptr, size_t *linesize, FILE *stream)
_GL_ARG_NONNULL ((1, 2, 3)));
# endif
_GL_CXXALIAS_SYS (getline, ssize_t,
(char **lineptr, size_t *linesize, FILE *stream));
# endif
# if 1
_GL_CXXALIASWARN (getline);
# endif
#elif defined GNULIB_POSIXCHECK
# undef getline
# if HAVE_RAW_DECL_GETLINE
_GL_WARN_ON_USE (getline, "getline is unportable - "
"use gnulib module getline for portability");
# endif
#endif
/* It is very rare that the developer ever has full control of stdin,
so any use of gets warrants an unconditional warning; besides, C11
removed it. */
#undef gets
#if HAVE_RAW_DECL_GETS && !defined __cplusplus
_GL_WARN_ON_USE (gets, "gets is a security hole - use fgets instead");
#endif
#if 0 || 0
struct obstack;
/* Grow an obstack with formatted output. Return the number of
bytes added to OBS. No trailing nul byte is added, and the
object should be closed with obstack_finish before use. Upon
memory allocation error, call obstack_alloc_failed_handler. Upon
other error, return -1. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define obstack_printf rpl_obstack_printf
# endif
_GL_FUNCDECL_RPL (obstack_printf, int,
(struct obstack *obs, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (obstack_printf, int,
(struct obstack *obs, const char *format, ...));
# else
# if !1
_GL_FUNCDECL_SYS (obstack_printf, int,
(struct obstack *obs, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
_GL_ARG_NONNULL ((1, 2)));
# endif
_GL_CXXALIAS_SYS (obstack_printf, int,
(struct obstack *obs, const char *format, ...));
# endif
_GL_CXXALIASWARN (obstack_printf);
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define obstack_vprintf rpl_obstack_vprintf
# endif
_GL_FUNCDECL_RPL (obstack_vprintf, int,
(struct obstack *obs, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (obstack_vprintf, int,
(struct obstack *obs, const char *format, va_list args));
# else
# if !1
_GL_FUNCDECL_SYS (obstack_vprintf, int,
(struct obstack *obs, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
_GL_ARG_NONNULL ((1, 2)));
# endif
_GL_CXXALIAS_SYS (obstack_vprintf, int,
(struct obstack *obs, const char *format, va_list args));
# endif
_GL_CXXALIASWARN (obstack_vprintf);
#endif
#if 0
# if !1
_GL_FUNCDECL_SYS (pclose, int, (FILE *stream) _GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_SYS (pclose, int, (FILE *stream));
_GL_CXXALIASWARN (pclose);
#elif defined GNULIB_POSIXCHECK
# undef pclose
# if HAVE_RAW_DECL_PCLOSE
_GL_WARN_ON_USE (pclose, "pclose is unportable - "
"use gnulib module pclose for more portability");
# endif
#endif
#if 0
/* Print a message to standard error, describing the value of ERRNO,
(if STRING is not NULL and not empty) prefixed with STRING and ": ",
and terminated with a newline. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define perror rpl_perror
# endif
_GL_FUNCDECL_RPL (perror, void, (const char *string));
_GL_CXXALIAS_RPL (perror, void, (const char *string));
# else
_GL_CXXALIAS_SYS (perror, void, (const char *string));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (perror);
# endif
#elif defined GNULIB_POSIXCHECK
# undef perror
/* Assume perror is always declared. */
_GL_WARN_ON_USE (perror, "perror is not always POSIX compliant - "
"use gnulib module perror for portability");
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef popen
# define popen rpl_popen
# endif
_GL_FUNCDECL_RPL (popen, FILE *, (const char *cmd, const char *mode)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (popen, FILE *, (const char *cmd, const char *mode));
# else
# if !1
_GL_FUNCDECL_SYS (popen, FILE *, (const char *cmd, const char *mode)
_GL_ARG_NONNULL ((1, 2)));
# endif
_GL_CXXALIAS_SYS (popen, FILE *, (const char *cmd, const char *mode));
# endif
_GL_CXXALIASWARN (popen);
#elif defined GNULIB_POSIXCHECK
# undef popen
# if HAVE_RAW_DECL_POPEN
_GL_WARN_ON_USE (popen, "popen is buggy on some platforms - "
"use gnulib module popen or pipe for more portability");
# endif
#endif
#if 0 || 1
# if (0 && 0) \
|| (1 && 0 && (0 || 0))
# if defined __GNUC__
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
/* Don't break __attribute__((format(printf,M,N))). */
# define printf __printf__
# endif
# if 0 || 0
_GL_FUNCDECL_RPL_1 (__printf__, int,
(const char *format, ...)
__asm__ (
_GL_STDIO_MACROEXPAND_AND_STRINGIZE(rpl_printf))
_GL_ATTRIBUTE_FORMAT_PRINTF (1, 2)
_GL_ARG_NONNULL ((1)));
# else
_GL_FUNCDECL_RPL_1 (__printf__, int,
(const char *format, ...)
__asm__ (
_GL_STDIO_MACROEXPAND_AND_STRINGIZE(rpl_printf))
_GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM (1, 2)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_RPL_1 (printf, __printf__, int, (const char *format, ...));
# else
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define printf rpl_printf
# endif
_GL_FUNCDECL_RPL (printf, int,
(const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF (1, 2)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (printf, int, (const char *format, ...));
# endif
# define GNULIB_overrides_printf 1
# else
_GL_CXXALIAS_SYS (printf, int, (const char *format, ...));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (printf);
# endif
#endif
#if !0 && defined GNULIB_POSIXCHECK
# if !GNULIB_overrides_printf
# undef printf
# endif
/* Assume printf is always declared. */
_GL_WARN_ON_USE (printf, "printf is not always POSIX compliant - "
"use gnulib module printf-posix for portable "
"POSIX compliance");
#endif
#if 1
# if 0 && (0 || 0)
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef putc
# define putc rpl_fputc
# endif
_GL_FUNCDECL_RPL (fputc, int, (int c, FILE *stream) _GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL_1 (putc, rpl_fputc, int, (int c, FILE *stream));
# else
_GL_CXXALIAS_SYS (putc, int, (int c, FILE *stream));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (putc);
# endif
#endif
#if 1
# if 0 && (0 || 0)
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef putchar
# define putchar rpl_putchar
# endif
_GL_FUNCDECL_RPL (putchar, int, (int c));
_GL_CXXALIAS_RPL (putchar, int, (int c));
# else
_GL_CXXALIAS_SYS (putchar, int, (int c));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (putchar);
# endif
#endif
#if 1
# if 0 && (0 || 0)
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef puts
# define puts rpl_puts
# endif
_GL_FUNCDECL_RPL (puts, int, (const char *string) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (puts, int, (const char *string));
# else
_GL_CXXALIAS_SYS (puts, int, (const char *string));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (puts);
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef remove
# define remove rpl_remove
# endif
_GL_FUNCDECL_RPL (remove, int, (const char *name) _GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (remove, int, (const char *name));
# else
_GL_CXXALIAS_SYS (remove, int, (const char *name));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (remove);
# endif
#elif defined GNULIB_POSIXCHECK
# undef remove
/* Assume remove is always declared. */
_GL_WARN_ON_USE (remove, "remove cannot handle directories on some platforms - "
"use gnulib module remove for more portability");
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef rename
# define rename rpl_rename
# endif
_GL_FUNCDECL_RPL (rename, int,
(const char *old_filename, const char *new_filename)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (rename, int,
(const char *old_filename, const char *new_filename));
# else
_GL_CXXALIAS_SYS (rename, int,
(const char *old_filename, const char *new_filename));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (rename);
# endif
#elif defined GNULIB_POSIXCHECK
# undef rename
/* Assume rename is always declared. */
_GL_WARN_ON_USE (rename, "rename is buggy on some platforms - "
"use gnulib module rename for more portability");
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef renameat
# define renameat rpl_renameat
# endif
_GL_FUNCDECL_RPL (renameat, int,
(int fd1, char const *file1, int fd2, char const *file2)
_GL_ARG_NONNULL ((2, 4)));
_GL_CXXALIAS_RPL (renameat, int,
(int fd1, char const *file1, int fd2, char const *file2));
# else
# if !1
_GL_FUNCDECL_SYS (renameat, int,
(int fd1, char const *file1, int fd2, char const *file2)
_GL_ARG_NONNULL ((2, 4)));
# endif
_GL_CXXALIAS_SYS (renameat, int,
(int fd1, char const *file1, int fd2, char const *file2));
# endif
_GL_CXXALIASWARN (renameat);
#elif defined GNULIB_POSIXCHECK
# undef renameat
# if HAVE_RAW_DECL_RENAMEAT
_GL_WARN_ON_USE (renameat, "renameat is not portable - "
"use gnulib module renameat for portability");
# endif
#endif
#if 1
# if 0 && 0
# if defined __GNUC__
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef scanf
/* Don't break __attribute__((format(scanf,M,N))). */
# define scanf __scanf__
# endif
_GL_FUNCDECL_RPL_1 (__scanf__, int,
(const char *format, ...)
__asm__ (
_GL_STDIO_MACROEXPAND_AND_STRINGIZE(rpl_scanf))
_GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM (1, 2)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL_1 (scanf, __scanf__, int, (const char *format, ...));
# else
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef scanf
# define scanf rpl_scanf
# endif
_GL_FUNCDECL_RPL (scanf, int, (const char *format, ...)
_GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM (1, 2)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (scanf, int, (const char *format, ...));
# endif
# else
_GL_CXXALIAS_SYS (scanf, int, (const char *format, ...));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (scanf);
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define snprintf rpl_snprintf
# endif
_GL_FUNCDECL_RPL (snprintf, int,
(char *str, size_t size, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF (3, 4)
_GL_ARG_NONNULL ((3)));
_GL_CXXALIAS_RPL (snprintf, int,
(char *str, size_t size, const char *format, ...));
# else
# if !1
_GL_FUNCDECL_SYS (snprintf, int,
(char *str, size_t size, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF (3, 4)
_GL_ARG_NONNULL ((3)));
# endif
_GL_CXXALIAS_SYS (snprintf, int,
(char *str, size_t size, const char *format, ...));
# endif
_GL_CXXALIASWARN (snprintf);
#elif defined GNULIB_POSIXCHECK
# undef snprintf
# if HAVE_RAW_DECL_SNPRINTF
_GL_WARN_ON_USE (snprintf, "snprintf is unportable - "
"use gnulib module snprintf for portability");
# endif
#endif
/* Some people would argue that all sprintf uses should be warned about
(for example, OpenBSD issues a link warning for it),
since it can cause security holes due to buffer overruns.
However, we believe that sprintf can be used safely, and is more
efficient than snprintf in those safe cases; and as proof of our
belief, we use sprintf in several gnulib modules. So this header
intentionally avoids adding a warning to sprintf except when
GNULIB_POSIXCHECK is defined. */
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define sprintf rpl_sprintf
# endif
_GL_FUNCDECL_RPL (sprintf, int, (char *str, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (sprintf, int, (char *str, const char *format, ...));
# else
_GL_CXXALIAS_SYS (sprintf, int, (char *str, const char *format, ...));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (sprintf);
# endif
#elif defined GNULIB_POSIXCHECK
# undef sprintf
/* Assume sprintf is always declared. */
_GL_WARN_ON_USE (sprintf, "sprintf is not always POSIX compliant - "
"use gnulib module sprintf-posix for portable "
"POSIX compliance");
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define tmpfile rpl_tmpfile
# endif
_GL_FUNCDECL_RPL (tmpfile, FILE *, (void));
_GL_CXXALIAS_RPL (tmpfile, FILE *, (void));
# else
_GL_CXXALIAS_SYS (tmpfile, FILE *, (void));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (tmpfile);
# endif
#elif defined GNULIB_POSIXCHECK
# undef tmpfile
# if HAVE_RAW_DECL_TMPFILE
_GL_WARN_ON_USE (tmpfile, "tmpfile is not usable on mingw - "
"use gnulib module tmpfile for portability");
# endif
#endif
#if 0
/* Write formatted output to a string dynamically allocated with malloc().
If the memory allocation succeeds, store the address of the string in
*RESULT and return the number of resulting bytes, excluding the trailing
NUL. Upon memory allocation error, or some other error, return -1. */
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define asprintf rpl_asprintf
# endif
_GL_FUNCDECL_RPL (asprintf, int,
(char **result, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (asprintf, int,
(char **result, const char *format, ...));
# else
# if !1
_GL_FUNCDECL_SYS (asprintf, int,
(char **result, const char *format, ...)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
_GL_ARG_NONNULL ((1, 2)));
# endif
_GL_CXXALIAS_SYS (asprintf, int,
(char **result, const char *format, ...));
# endif
_GL_CXXALIASWARN (asprintf);
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define vasprintf rpl_vasprintf
# endif
_GL_FUNCDECL_RPL (vasprintf, int,
(char **result, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (vasprintf, int,
(char **result, const char *format, va_list args));
# else
# if !1
_GL_FUNCDECL_SYS (vasprintf, int,
(char **result, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
_GL_ARG_NONNULL ((1, 2)));
# endif
_GL_CXXALIAS_SYS (vasprintf, int,
(char **result, const char *format, va_list args));
# endif
_GL_CXXALIASWARN (vasprintf);
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define vdprintf rpl_vdprintf
# endif
_GL_FUNCDECL_RPL (vdprintf, int, (int fd, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
_GL_ARG_NONNULL ((2)));
_GL_CXXALIAS_RPL (vdprintf, int, (int fd, const char *format, va_list args));
# else
# if !1
_GL_FUNCDECL_SYS (vdprintf, int, (int fd, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
_GL_ARG_NONNULL ((2)));
# endif
/* Need to cast, because on Solaris, the third parameter will likely be
__va_list args. */
_GL_CXXALIAS_SYS_CAST (vdprintf, int,
(int fd, const char *format, va_list args));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (vdprintf);
# endif
#elif defined GNULIB_POSIXCHECK
# undef vdprintf
# if HAVE_RAW_DECL_VDPRINTF
_GL_WARN_ON_USE (vdprintf, "vdprintf is unportable - "
"use gnulib module vdprintf for portability");
# endif
#endif
#if 0 || 1
# if (0 && 0) \
|| (1 && 0 && (0 || 0))
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define vfprintf rpl_vfprintf
# endif
# define GNULIB_overrides_vfprintf 1
# if 0
_GL_FUNCDECL_RPL (vfprintf, int, (FILE *fp, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
_GL_ARG_NONNULL ((1, 2)));
# else
_GL_FUNCDECL_RPL (vfprintf, int, (FILE *fp, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM (2, 0)
_GL_ARG_NONNULL ((1, 2)));
# endif
_GL_CXXALIAS_RPL (vfprintf, int, (FILE *fp, const char *format, va_list args));
# else
/* Need to cast, because on Solaris, the third parameter is
__va_list args
and GCC's fixincludes did not change this to __gnuc_va_list. */
_GL_CXXALIAS_SYS_CAST (vfprintf, int,
(FILE *fp, const char *format, va_list args));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (vfprintf);
# endif
#endif
#if !0 && defined GNULIB_POSIXCHECK
# if !GNULIB_overrides_vfprintf
# undef vfprintf
# endif
/* Assume vfprintf is always declared. */
_GL_WARN_ON_USE (vfprintf, "vfprintf is not always POSIX compliant - "
"use gnulib module vfprintf-posix for portable "
"POSIX compliance");
#endif
#if 0
# if 0 && 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef vfscanf
# define vfscanf rpl_vfscanf
# endif
_GL_FUNCDECL_RPL (vfscanf, int,
(FILE *stream, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM (2, 0)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (vfscanf, int,
(FILE *stream, const char *format, va_list args));
# else
_GL_CXXALIAS_SYS (vfscanf, int,
(FILE *stream, const char *format, va_list args));
# endif
_GL_CXXALIASWARN (vfscanf);
#endif
#if 0 || 1
# if (0 && 0) \
|| (1 && 0 && (0 || 0))
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define vprintf rpl_vprintf
# endif
# define GNULIB_overrides_vprintf 1
# if 0 || 0
_GL_FUNCDECL_RPL (vprintf, int, (const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF (1, 0)
_GL_ARG_NONNULL ((1)));
# else
_GL_FUNCDECL_RPL (vprintf, int, (const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM (1, 0)
_GL_ARG_NONNULL ((1)));
# endif
_GL_CXXALIAS_RPL (vprintf, int, (const char *format, va_list args));
# else
/* Need to cast, because on Solaris, the second parameter is
__va_list args
and GCC's fixincludes did not change this to __gnuc_va_list. */
_GL_CXXALIAS_SYS_CAST (vprintf, int, (const char *format, va_list args));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (vprintf);
# endif
#endif
#if !0 && defined GNULIB_POSIXCHECK
# if !GNULIB_overrides_vprintf
# undef vprintf
# endif
/* Assume vprintf is always declared. */
_GL_WARN_ON_USE (vprintf, "vprintf is not always POSIX compliant - "
"use gnulib module vprintf-posix for portable "
"POSIX compliance");
#endif
#if 0
# if 0 && 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# undef vscanf
# define vscanf rpl_vscanf
# endif
_GL_FUNCDECL_RPL (vscanf, int, (const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM (1, 0)
_GL_ARG_NONNULL ((1)));
_GL_CXXALIAS_RPL (vscanf, int, (const char *format, va_list args));
# else
_GL_CXXALIAS_SYS (vscanf, int, (const char *format, va_list args));
# endif
_GL_CXXALIASWARN (vscanf);
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define vsnprintf rpl_vsnprintf
# endif
_GL_FUNCDECL_RPL (vsnprintf, int,
(char *str, size_t size, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF (3, 0)
_GL_ARG_NONNULL ((3)));
_GL_CXXALIAS_RPL (vsnprintf, int,
(char *str, size_t size, const char *format, va_list args));
# else
# if !1
_GL_FUNCDECL_SYS (vsnprintf, int,
(char *str, size_t size, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF (3, 0)
_GL_ARG_NONNULL ((3)));
# endif
_GL_CXXALIAS_SYS (vsnprintf, int,
(char *str, size_t size, const char *format, va_list args));
# endif
_GL_CXXALIASWARN (vsnprintf);
#elif defined GNULIB_POSIXCHECK
# undef vsnprintf
# if HAVE_RAW_DECL_VSNPRINTF
_GL_WARN_ON_USE (vsnprintf, "vsnprintf is unportable - "
"use gnulib module vsnprintf for portability");
# endif
#endif
#if 0
# if 0
# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
# define vsprintf rpl_vsprintf
# endif
_GL_FUNCDECL_RPL (vsprintf, int,
(char *str, const char *format, va_list args)
_GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
_GL_ARG_NONNULL ((1, 2)));
_GL_CXXALIAS_RPL (vsprintf, int,
(char *str, const char *format, va_list args));
# else
/* Need to cast, because on Solaris, the third parameter is
__va_list args
and GCC's fixincludes did not change this to __gnuc_va_list. */
_GL_CXXALIAS_SYS_CAST (vsprintf, int,
(char *str, const char *format, va_list args));
# endif
# if __GLIBC__ >= 2
_GL_CXXALIASWARN (vsprintf);
# endif
#elif defined GNULIB_POSIXCHECK
# undef vsprintf
/* Assume vsprintf is always declared. */
_GL_WARN_ON_USE (vsprintf, "vsprintf is not always POSIX compliant - "
"use gnulib module vsprintf-posix for portable "
"POSIX compliance");
#endif
#endif /* _GL_STDIO_H */
#endif /* _GL_STDIO_H */
#endif
| 70,479 | 1,908 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/exitfail.h | /* clang-format off */
/* Failure exit status
Copyright (C) 2002, 2009-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
extern int volatile exit_failure;
| 794 | 20 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/dirname.h | /* Take file names apart into directory and base names.
Copyright (C) 1998, 2001, 2003-2006, 2009-2020 Free Software Foundation,
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; 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 <https://www.gnu.org/licenses/>. */
/* clang-format off */
#ifndef DIRNAME_H_
# define DIRNAME_H_ 1
#include "third_party/make/dosname.h"
# ifndef DIRECTORY_SEPARATOR
# define DIRECTORY_SEPARATOR '/'
# endif
# ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
# define DOUBLE_SLASH_IS_DISTINCT_ROOT 0
# endif
#ifdef __cplusplus
extern "C" {
#endif
# if GNULIB_DIRNAME
char *base_name (char const *file) _GL_ATTRIBUTE_MALLOC;
char *dir_name (char const *file);
# endif
char *mdir_name (char const *file);
size_t base_len (char const *file) _GL_ATTRIBUTE_PURE;
size_t dir_len (char const *file) _GL_ATTRIBUTE_PURE;
char *last_component (char const *file) _GL_ATTRIBUTE_PURE;
bool strip_trailing_slashes (char *file);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* not DIRNAME_H_ */
| 1,553 | 54 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/basename-lgpl.c | /* clang-format off */
/* basename.c -- return the last element in a file name
Copyright (C) 1990, 1998-2001, 2003-2006, 2009-2020 Free Software
Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#include "third_party/make/config.h"
/**/
#include "libc/str/str.h"
#include "third_party/make/dirname.h"
/* clang-format off */
/* Return the address of the last file name component of NAME. If
NAME has no relative file name components because it is a file
system root, return the empty string. */
char *
last_component (char const *name)
{
char const *base = name + FILE_SYSTEM_PREFIX_LEN (name);
char const *p;
bool saw_slash = false;
while (ISSLASH (*base))
base++;
for (p = base; *p; p++)
{
if (ISSLASH (*p))
saw_slash = true;
else if (saw_slash)
{
base = p;
saw_slash = false;
}
}
return (char *) base;
}
/* Return the length of the basename NAME. Typically NAME is the
value returned by base_name or last_component. Act like strlen
(NAME), except omit all trailing slashes. */
size_t
base_len (char const *name)
{
size_t len;
size_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
for (len = strlen (name); 1 < len && ISSLASH (name[len - 1]); len--)
continue;
if (DOUBLE_SLASH_IS_DISTINCT_ROOT && len == 1
&& ISSLASH (name[0]) && ISSLASH (name[1]) && ! name[2])
return 2;
if (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE && prefix_len
&& len == prefix_len && ISSLASH (name[prefix_len]))
return prefix_len + 1;
return len;
}
| 2,187 | 77 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/load.c | /* clang-format off */
/* Loading dynamic objects for GNU Make.
Copyright (C) 2012-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
int
load_file (const floc *flocp, const char **ldname UNUSED, int noerror)
{
if (! noerror)
O (fatal, flocp,
_("The 'load' operation is not supported on this platform."));
return 0;
}
void
unload_file (const char *name UNUSED)
{
O (fatal, NILF, "INTERNAL: Cannot unload when load is not supported!");
}
| 1,123 | 35 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/getprogname.h | /* clang-format off */
/* Program name management.
Copyright (C) 2016-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#ifndef _GL_GETPROGNAME_H
#define _GL_GETPROGNAME_H
#ifdef __cplusplus
extern "C" {
#endif
/* Return the base name of the executing program.
On native Windows this will usually end in ".exe" or ".EXE". */
#ifndef HAVE_GETPROGNAME
extern char const *getprogname(void)
#ifdef HAVE_DECL_PROGRAM_INVOCATION_NAME
_GL_ATTRIBUTE_PURE
#endif
;
#endif
#ifdef __cplusplus
}
#endif
#endif
| 1,151 | 40 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/guile.c | /* clang-format off */
/* GNU Guile interface for GNU Make.
Copyright (C) 2011-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
int
guile_gmake_setup (const floc *flocp UNUSED)
{
return 1;
}
| 862 | 25 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/xalloc.h | /* clang-format off */
/* xalloc.h -- malloc with out-of-memory checking
Copyright (C) 1990-2000, 2003-2004, 2006-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#ifndef XALLOC_H_
#define XALLOC_H_
#include "libc/limits.h"
#include "third_party/make/xalloc-oversized.h"
#ifndef _GL_INLINE_HEADER_BEGIN
#error "Please include config.h first."
#endif
_GL_INLINE_HEADER_BEGIN
#ifndef XALLOC_INLINE
# define XALLOC_INLINE _GL_INLINE
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if ! defined __clang__ && \
(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
# define _GL_ATTRIBUTE_ALLOC_SIZE(args) __attribute__ ((__alloc_size__ args))
#else
# define _GL_ATTRIBUTE_ALLOC_SIZE(args)
#endif
/* This function is always triggered when memory is exhausted.
It must be defined by the application, either explicitly
or by using gnulib's xalloc-die module. This is the
function to call when one wants the program to die because of a
memory allocation failure. */
extern _Noreturn void xalloc_die (void);
void *xmalloc (size_t s)
_GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1));
void *xzalloc (size_t s)
_GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1));
void *xcalloc (size_t n, size_t s)
_GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1, 2));
void *xrealloc (void *p, size_t s)
_GL_ATTRIBUTE_ALLOC_SIZE ((2));
void *x2realloc (void *p, size_t *pn);
void *xmemdup (void const *p, size_t s)
_GL_ATTRIBUTE_ALLOC_SIZE ((2));
char *xstrdup (char const *str)
_GL_ATTRIBUTE_MALLOC;
/* In the following macros, T must be an elementary or structure/union or
typedef'ed type, or a pointer to such a type. To apply one of the
following macros to a function pointer or array type, you need to typedef
it first and use the typedef name. */
/* Allocate an object of type T dynamically, with error checking. */
/* extern t *XMALLOC (typename t); */
#define XMALLOC(t) ((t *) xmalloc (sizeof (t)))
/* Allocate memory for N elements of type T, with error checking. */
/* extern t *XNMALLOC (size_t n, typename t); */
#define XNMALLOC(n, t) \
((t *) (sizeof (t) == 1 ? xmalloc (n) : xnmalloc (n, sizeof (t))))
/* Allocate an object of type T dynamically, with error checking,
and zero it. */
/* extern t *XZALLOC (typename t); */
#define XZALLOC(t) ((t *) xzalloc (sizeof (t)))
/* Allocate memory for N elements of type T, with error checking,
and zero it. */
/* extern t *XCALLOC (size_t n, typename t); */
#define XCALLOC(n, t) \
((t *) (sizeof (t) == 1 ? xzalloc (n) : xcalloc (n, sizeof (t))))
/* Allocate an array of N objects, each with S bytes of memory,
dynamically, with error checking. S must be nonzero. */
XALLOC_INLINE void *xnmalloc (size_t n, size_t s)
_GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1, 2));
XALLOC_INLINE void *
xnmalloc (size_t n, size_t s)
{
if (xalloc_oversized (n, s))
xalloc_die ();
return xmalloc (n * s);
}
/* Change the size of an allocated block of memory P to an array of N
objects each of S bytes, with error checking. S must be nonzero. */
XALLOC_INLINE void *xnrealloc (void *p, size_t n, size_t s)
_GL_ATTRIBUTE_ALLOC_SIZE ((2, 3));
XALLOC_INLINE void *
xnrealloc (void *p, size_t n, size_t s)
{
if (xalloc_oversized (n, s))
xalloc_die ();
return xrealloc (p, n * s);
}
/* If P is null, allocate a block of at least *PN such objects;
otherwise, reallocate P so that it contains more than *PN objects
each of S bytes. S must be nonzero. Set *PN to the new number of
objects, and return the pointer to the new block. *PN is never set
to zero, and the returned pointer is never null.
Repeated reallocations are guaranteed to make progress, either by
allocating an initial block with a nonzero size, or by allocating a
larger block.
In the following implementation, nonzero sizes are increased by a
factor of approximately 1.5 so that repeated reallocations have
O(N) overall cost rather than O(N**2) cost, but the
specification for this function does not guarantee that rate.
Here is an example of use:
int *p = NULL;
size_t used = 0;
size_t allocated = 0;
void
append_int (int value)
{
if (used == allocated)
p = x2nrealloc (p, &allocated, sizeof *p);
p[used++] = value;
}
This causes x2nrealloc to allocate a block of some nonzero size the
first time it is called.
To have finer-grained control over the initial size, set *PN to a
nonzero value before calling this function with P == NULL. For
example:
int *p = NULL;
size_t used = 0;
size_t allocated = 0;
size_t allocated1 = 1000;
void
append_int (int value)
{
if (used == allocated)
{
p = x2nrealloc (p, &allocated1, sizeof *p);
allocated = allocated1;
}
p[used++] = value;
}
*/
XALLOC_INLINE void *
x2nrealloc (void *p, size_t *pn, size_t s)
{
size_t n = *pn;
if (! p)
{
if (! n)
{
/* The approximate size to use for initial small allocation
requests, when the invoking code specifies an old size of
zero. This is the largest "small" request for the GNU C
library malloc. */
enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
n = DEFAULT_MXFAST / s;
n += !n;
}
if (xalloc_oversized (n, s))
xalloc_die ();
}
else
{
/* Set N = floor (1.5 * N) + 1 so that progress is made even if N == 0.
Check for overflow, so that N * S stays in both ptrdiff_t and
size_t range. The check may be slightly conservative, but an
exact check isn't worth the trouble. */
if ((PTRDIFF_MAX < SIZE_MAX ? PTRDIFF_MAX : SIZE_MAX) / 3 * 2 / s
<= n)
xalloc_die ();
n += n / 2 + 1;
}
*pn = n;
return xrealloc (p, n * s);
}
/* Return a pointer to a new buffer of N bytes. This is like xmalloc,
except it returns char *. */
XALLOC_INLINE char *xcharalloc (size_t n)
_GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1));
XALLOC_INLINE char *
xcharalloc (size_t n)
{
return XNMALLOC (n, char);
}
#ifdef __cplusplus
}
/* C++ does not allow conversions from void * to other pointer types
without a cast. Use templates to work around the problem when
possible. */
template <typename T> inline T *
xrealloc (T *p, size_t s)
{
return (T *) xrealloc ((void *) p, s);
}
template <typename T> inline T *
xnrealloc (T *p, size_t n, size_t s)
{
return (T *) xnrealloc ((void *) p, n, s);
}
template <typename T> inline T *
x2realloc (T *p, size_t *pn)
{
return (T *) x2realloc ((void *) p, pn);
}
template <typename T> inline T *
x2nrealloc (T *p, size_t *pn, size_t s)
{
return (T *) x2nrealloc ((void *) p, pn, s);
}
template <typename T> inline T *
xmemdup (T const *p, size_t s)
{
return (T *) xmemdup ((void const *) p, s);
}
#endif
_GL_INLINE_HEADER_END
#endif /* !XALLOC_H_ */
| 7,748 | 263 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/xalloc-oversized.h | /* clang-format off */
/* xalloc-oversized.h -- memory allocation size checking
Copyright (C) 1990-2000, 2003-2004, 2006-2020 Free Software Foundation, 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; 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 <https://www.gnu.org/licenses/>. */
#ifndef XALLOC_OVERSIZED_H_
#define XALLOC_OVERSIZED_H_
/* True if N * S would overflow in a size_t calculation,
or would generate a value larger than PTRDIFF_MAX.
This expands to a constant expression if N and S are both constants.
By gnulib convention, SIZE_MAX represents overflow in size
calculations, so the conservative size_t-based dividend to use here
is SIZE_MAX - 1. */
#define __xalloc_oversized(n, s) \
((size_t) (PTRDIFF_MAX < SIZE_MAX ? PTRDIFF_MAX : SIZE_MAX - 1) / (s) < (n))
#if PTRDIFF_MAX < SIZE_MAX
typedef ptrdiff_t __xalloc_count_type;
#else
typedef size_t __xalloc_count_type;
#endif
/* Return 1 if an array of N objects, each of size S, cannot exist
reliably due to size or ptrdiff_t arithmetic overflow. S must be
positive and N must be nonnegative. This is a macro, not a
function, so that it works correctly even when SIZE_MAX < N. */
#if 7 <= __GNUC__
# define xalloc_oversized(n, s) \
__builtin_mul_overflow_p (n, s, (__xalloc_count_type) 1)
#elif 5 <= __GNUC__ && !defined __ICC && !__STRICT_ANSI__
# define xalloc_oversized(n, s) \
(__builtin_constant_p (n) && __builtin_constant_p (s) \
? __xalloc_oversized (n, s) \
: ({ __xalloc_count_type __xalloc_count; \
__builtin_mul_overflow (n, s, &__xalloc_count); }))
/* Other compilers use integer division; this may be slower but is
more portable. */
#else
# define xalloc_oversized(n, s) __xalloc_oversized (n, s)
#endif
#endif /* !XALLOC_OVERSIZED_H_ */
| 2,308 | 60 | jart/cosmopolitan | false |
cosmopolitan/third_party/make/variable.c | /* clang-format off */
/* Internals of variables for GNU Make.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This file is part of GNU Make.
GNU Make 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.
GNU Make 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/>. */
#include "third_party/make/makeint.inc"
#include "third_party/make/filedef.h"
#include "third_party/make/dep.h"
#include "third_party/make/job.h"
#include "third_party/make/commands.h"
#include "third_party/make/variable.h"
#include "third_party/make/rule.h"
#include "third_party/make/hash.h"
/* Incremented every time we add or remove a global variable. */
static unsigned long variable_changenum;
/* Chain of all pattern-specific variables. */
static struct pattern_var *pattern_vars;
/* Pointer to the last struct in the pack of a specific size, from 1 to 255.*/
static struct pattern_var *last_pattern_vars[256];
/* Create a new pattern-specific variable struct. The new variable is
inserted into the PATTERN_VARS list in the shortest patterns first
order to support the shortest stem matching (the variables are
matched in the reverse order so the ones with the longest pattern
will be considered first). Variables with the same pattern length
are inserted in the definition order. */
struct pattern_var *
create_pattern_var (const char *target, const char *suffix)
{
size_t len = strlen (target);
struct pattern_var *p = xcalloc (sizeof (struct pattern_var));
if (pattern_vars != 0)
{
if (len < 256 && last_pattern_vars[len] != 0)
{
p->next = last_pattern_vars[len]->next;
last_pattern_vars[len]->next = p;
}
else
{
/* Find the position where we can insert this variable. */
struct pattern_var **v;
for (v = &pattern_vars; ; v = &(*v)->next)
{
/* Insert at the end of the pack so that patterns with the
same length appear in the order they were defined .*/
if (*v == 0 || (*v)->len > len)
{
p->next = *v;
*v = p;
break;
}
}
}
}
else
{
pattern_vars = p;
p->next = 0;
}
p->target = target;
p->len = len;
p->suffix = suffix + 1;
if (len < 256)
last_pattern_vars[len] = p;
return p;
}
/* Look up a target in the pattern-specific variable list. */
static struct pattern_var *
lookup_pattern_var (struct pattern_var *start, const char *target)
{
struct pattern_var *p;
size_t targlen = strlen (target);
for (p = start ? start->next : pattern_vars; p != 0; p = p->next)
{
const char *stem;
size_t stemlen;
if (p->len > targlen)
/* It can't possibly match. */
continue;
/* From the lengths of the filename and the pattern parts,
find the stem: the part of the filename that matches the %. */
stem = target + (p->suffix - p->target - 1);
stemlen = targlen - p->len + 1;
/* Compare the text in the pattern before the stem, if any. */
if (stem > target && !strneq (p->target, target, stem - target))
continue;
/* Compare the text in the pattern after the stem, if any.
We could test simply using streq, but this way we compare the
first two characters immediately. This saves time in the very
common case where the first character matches because it is a
period. */
if (*p->suffix == stem[stemlen]
&& (*p->suffix == '\0' || streq (&p->suffix[1], &stem[stemlen+1])))
break;
}
return p;
}
/* Hash table of all global variable definitions. */
static unsigned long
variable_hash_1 (const void *keyv)
{
struct variable const *key = (struct variable const *) keyv;
return_STRING_N_HASH_1 (key->name, key->length);
}
static unsigned long
variable_hash_2 (const void *keyv)
{
struct variable const *key = (struct variable const *) keyv;
return_STRING_N_HASH_2 (key->name, key->length);
}
static int
variable_hash_cmp (const void *xv, const void *yv)
{
struct variable const *x = (struct variable const *) xv;
struct variable const *y = (struct variable const *) yv;
int result = x->length - y->length;
if (result)
return result;
return_STRING_N_COMPARE (x->name, y->name, x->length);
}
#ifndef VARIABLE_BUCKETS
#define VARIABLE_BUCKETS 523
#endif
#ifndef PERFILE_VARIABLE_BUCKETS
#define PERFILE_VARIABLE_BUCKETS 23
#endif
#ifndef SMALL_SCOPE_VARIABLE_BUCKETS
#define SMALL_SCOPE_VARIABLE_BUCKETS 13
#endif
static struct variable_set global_variable_set;
static struct variable_set_list global_setlist
= { 0, &global_variable_set, 0 };
struct variable_set_list *current_variable_set_list = &global_setlist;
/* Implement variables. */
void
init_hash_global_variable_set (void)
{
hash_init (&global_variable_set.table, VARIABLE_BUCKETS,
variable_hash_1, variable_hash_2, variable_hash_cmp);
}
/* Define variable named NAME with value VALUE in SET. VALUE is copied.
LENGTH is the length of NAME, which does not need to be null-terminated.
ORIGIN specifies the origin of the variable (makefile, command line
or environment).
If RECURSIVE is nonzero a flag is set in the variable saying
that it should be recursively re-expanded. */
struct variable *
define_variable_in_set (const char *name, size_t length,
const char *value, enum variable_origin origin,
int recursive, struct variable_set *set,
const floc *flocp)
{
struct variable *v;
struct variable **var_slot;
struct variable var_key;
if (set == NULL)
set = &global_variable_set;
var_key.name = (char *) name;
var_key.length = (unsigned int) length;
var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
v = *var_slot;
if (env_overrides && origin == o_env)
origin = o_env_override;
if (! HASH_VACANT (v))
{
if (env_overrides && v->origin == o_env)
/* V came from in the environment. Since it was defined
before the switches were parsed, it wasn't affected by -e. */
v->origin = o_env_override;
/* A variable of this name is already defined.
If the old definition is from a stronger source
than this one, don't redefine it. */
if ((int) origin >= (int) v->origin)
{
free (v->value);
v->value = xstrdup (value);
if (flocp != 0)
v->fileinfo = *flocp;
else
v->fileinfo.filenm = 0;
v->origin = origin;
v->recursive = recursive;
}
return v;
}
/* Create a new variable definition and add it to the hash table. */
v = xcalloc (sizeof (struct variable));
v->name = xstrndup (name, length);
v->length = (unsigned int) length;
hash_insert_at (&set->table, v, var_slot);
if (set == &global_variable_set)
++variable_changenum;
v->value = xstrdup (value);
if (flocp != 0)
v->fileinfo = *flocp;
v->origin = origin;
v->recursive = recursive;
v->export = v_default;
v->exportable = 1;
if (*name != '_' && (*name < 'A' || *name > 'Z')
&& (*name < 'a' || *name > 'z'))
v->exportable = 0;
else
{
for (++name; *name != '\0'; ++name)
if (*name != '_' && (*name < 'a' || *name > 'z')
&& (*name < 'A' || *name > 'Z') && !ISDIGIT(*name))
break;
if (*name != '\0')
v->exportable = 0;
}
return v;
}
/* Undefine variable named NAME in SET. LENGTH is the length of NAME, which
does not need to be null-terminated. ORIGIN specifies the origin of the
variable (makefile, command line or environment). */
static void
free_variable_name_and_value (const void *item)
{
struct variable *v = (struct variable *) item;
free (v->name);
free (v->value);
}
void
free_variable_set (struct variable_set_list *list)
{
hash_map (&list->set->table, free_variable_name_and_value);
hash_free (&list->set->table, 1);
free (list->set);
free (list);
}
void
undefine_variable_in_set (const char *name, size_t length,
enum variable_origin origin,
struct variable_set *set)
{
struct variable *v;
struct variable **var_slot;
struct variable var_key;
if (set == NULL)
set = &global_variable_set;
var_key.name = (char *) name;
var_key.length = (unsigned int) length;
var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
if (env_overrides && origin == o_env)
origin = o_env_override;
v = *var_slot;
if (! HASH_VACANT (v))
{
if (env_overrides && v->origin == o_env)
/* V came from in the environment. Since it was defined
before the switches were parsed, it wasn't affected by -e. */
v->origin = o_env_override;
/* Undefine only if this undefinition is from an equal or stronger
source than the variable definition. */
if ((int) origin >= (int) v->origin)
{
hash_delete_at (&set->table, var_slot);
free_variable_name_and_value (v);
free (v);
if (set == &global_variable_set)
++variable_changenum;
}
}
}
/* If the variable passed in is "special", handle its special nature.
Currently there are two such variables, both used for introspection:
.VARIABLES expands to a list of all the variables defined in this instance
of make.
.TARGETS expands to a list of all the targets defined in this
instance of make.
Returns the variable reference passed in. */
#define EXPANSION_INCREMENT(_l) ((((_l) / 500) + 1) * 500)
static struct variable *
lookup_special_var (struct variable *var)
{
static unsigned long last_changenum = 0;
/* This one actually turns out to be very hard, due to the way the parser
records targets. The way it works is that target information is collected
internally until make knows the target is completely specified. It unitl
it sees that some new construct (a new target or variable) is defined that
it knows the previous one is done. In short, this means that if you do
this:
all:
TARGS := $(.TARGETS)
then $(TARGS) won't contain "all", because it's not until after the
variable is created that the previous target is completed.
Changing this would be a major pain. I think a less complex way to do it
would be to pre-define the target files as soon as the first line is
parsed, then come back and do the rest of the definition as now. That
would allow $(.TARGETS) to be correct without a major change to the way
the parser works.
if (streq (var->name, ".TARGETS"))
var->value = build_target_list (var->value);
else
*/
if (variable_changenum != last_changenum && streq (var->name, ".VARIABLES"))
{
size_t max = EXPANSION_INCREMENT (strlen (var->value));
size_t len;
char *p;
struct variable **vp = (struct variable **) global_variable_set.table.ht_vec;
struct variable **end = &vp[global_variable_set.table.ht_size];
/* Make sure we have at least MAX bytes in the allocated buffer. */
var->value = xrealloc (var->value, max);
/* Walk through the hash of variables, constructing a list of names. */
p = var->value;
len = 0;
for (; vp < end; ++vp)
if (!HASH_VACANT (*vp))
{
struct variable *v = *vp;
int l = v->length;
len += l + 1;
if (len > max)
{
size_t off = p - var->value;
max += EXPANSION_INCREMENT (l + 1);
var->value = xrealloc (var->value, max);
p = &var->value[off];
}
memcpy (p, v->name, l);
p += l;
*(p++) = ' ';
}
*(p-1) = '\0';
/* Remember the current variable change number. */
last_changenum = variable_changenum;
}
return var;
}
/* Lookup a variable whose name is a string starting at NAME
and with LENGTH chars. NAME need not be null-terminated.
Returns address of the 'struct variable' containing all info
on the variable, or nil if no such variable is defined. */
struct variable *
lookup_variable (const char *name, size_t length)
{
const struct variable_set_list *setlist;
struct variable var_key;
int is_parent = 0;
var_key.name = (char *) name;
var_key.length = (unsigned int) length;
for (setlist = current_variable_set_list;
setlist != 0; setlist = setlist->next)
{
const struct variable_set *set = setlist->set;
struct variable *v;
v = (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
if (v && (!is_parent || !v->private_var))
return v->special ? lookup_special_var (v) : v;
is_parent |= setlist->next_is_parent;
}
return 0;
}
/* Lookup a variable whose name is a string starting at NAME
and with LENGTH chars in set SET. NAME need not be null-terminated.
Returns address of the 'struct variable' containing all info
on the variable, or nil if no such variable is defined. */
struct variable *
lookup_variable_in_set (const char *name, size_t length,
const struct variable_set *set)
{
struct variable var_key;
var_key.name = (char *) name;
var_key.length = (unsigned int) length;
return (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
}
/* Initialize FILE's variable set list. If FILE already has a variable set
list, the topmost variable set is left intact, but the the rest of the
chain is replaced with FILE->parent's setlist. If FILE is a double-colon
rule, then we will use the "root" double-colon target's variable set as the
parent of FILE's variable set.
If we're READING a makefile, don't do the pattern variable search now,
since the pattern variable might not have been defined yet. */
void
initialize_file_variables (struct file *file, int reading)
{
struct variable_set_list *l = file->variables;
if (l == 0)
{
l = (struct variable_set_list *)
xmalloc (sizeof (struct variable_set_list));
l->set = xmalloc (sizeof (struct variable_set));
hash_init (&l->set->table, PERFILE_VARIABLE_BUCKETS,
variable_hash_1, variable_hash_2, variable_hash_cmp);
file->variables = l;
}
/* If this is a double-colon, then our "parent" is the "root" target for
this double-colon rule. Since that rule has the same name, parent,
etc. we can just use its variables as the "next" for ours. */
if (file->double_colon && file->double_colon != file)
{
initialize_file_variables (file->double_colon, reading);
l->next = file->double_colon->variables;
l->next_is_parent = 0;
return;
}
if (file->parent == 0)
l->next = &global_setlist;
else
{
initialize_file_variables (file->parent, reading);
l->next = file->parent->variables;
}
l->next_is_parent = 1;
/* If we're not reading makefiles and we haven't looked yet, see if
we can find pattern variables for this target. */
if (!reading && !file->pat_searched)
{
struct pattern_var *p;
p = lookup_pattern_var (0, file->name);
if (p != 0)
{
struct variable_set_list *global = current_variable_set_list;
/* We found at least one. Set up a new variable set to accumulate
all the pattern variables that match this target. */
file->pat_variables = create_new_variable_set ();
current_variable_set_list = file->pat_variables;
do
{
/* We found one, so insert it into the set. */
struct variable *v;
if (p->variable.flavor == f_simple)
{
v = define_variable_loc (
p->variable.name, strlen (p->variable.name),
p->variable.value, p->variable.origin,
0, &p->variable.fileinfo);
v->flavor = f_simple;
}
else
{
v = do_variable_definition (
&p->variable.fileinfo, p->variable.name,
p->variable.value, p->variable.origin,
p->variable.flavor, 1);
}
/* Also mark it as a per-target and copy export status. */
v->per_target = p->variable.per_target;
v->export = p->variable.export;
v->private_var = p->variable.private_var;
}
while ((p = lookup_pattern_var (p, file->name)) != 0);
current_variable_set_list = global;
}
file->pat_searched = 1;
}
/* If we have a pattern variable match, set it up. */
if (file->pat_variables != 0)
{
file->pat_variables->next = l->next;
file->pat_variables->next_is_parent = l->next_is_parent;
l->next = file->pat_variables;
l->next_is_parent = 0;
}
}
/* Pop the top set off the current variable set list,
and free all its storage. */
struct variable_set_list *
create_new_variable_set (void)
{
struct variable_set_list *setlist;
struct variable_set *set;
set = xmalloc (sizeof (struct variable_set));
hash_init (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
variable_hash_1, variable_hash_2, variable_hash_cmp);
setlist = (struct variable_set_list *)
xmalloc (sizeof (struct variable_set_list));
setlist->set = set;
setlist->next = current_variable_set_list;
setlist->next_is_parent = 0;
return setlist;
}
/* Create a new variable set and push it on the current setlist.
If we're pushing a global scope (that is, the current scope is the global
scope) then we need to "push" it the other way: file variable sets point
directly to the global_setlist so we need to replace that with the new one.
*/
struct variable_set_list *
push_new_variable_scope (void)
{
current_variable_set_list = create_new_variable_set ();
if (current_variable_set_list->next == &global_setlist)
{
/* It was the global, so instead of new -> &global we want to replace
&global with the new one and have &global -> new, with current still
pointing to &global */
struct variable_set *set = current_variable_set_list->set;
current_variable_set_list->set = global_setlist.set;
global_setlist.set = set;
current_variable_set_list->next = global_setlist.next;
global_setlist.next = current_variable_set_list;
current_variable_set_list = &global_setlist;
}
return (current_variable_set_list);
}
void
pop_variable_scope (void)
{
struct variable_set_list *setlist;
struct variable_set *set;
/* Can't call this if there's no scope to pop! */
assert (current_variable_set_list->next != NULL);
if (current_variable_set_list != &global_setlist)
{
/* We're not pointing to the global setlist, so pop this one. */
setlist = current_variable_set_list;
set = setlist->set;
current_variable_set_list = setlist->next;
}
else
{
/* This set is the one in the global_setlist, but there is another global
set beyond that. We want to copy that set to global_setlist, then
delete what used to be in global_setlist. */
setlist = global_setlist.next;
set = global_setlist.set;
global_setlist.set = setlist->set;
global_setlist.next = setlist->next;
global_setlist.next_is_parent = setlist->next_is_parent;
}
/* Free the one we no longer need. */
free (setlist);
hash_map (&set->table, free_variable_name_and_value);
hash_free (&set->table, 1);
free (set);
}
/* Merge FROM_SET into TO_SET, freeing unused storage in FROM_SET. */
static void
merge_variable_sets (struct variable_set *to_set,
struct variable_set *from_set)
{
struct variable **from_var_slot = (struct variable **) from_set->table.ht_vec;
struct variable **from_var_end = from_var_slot + from_set->table.ht_size;
int inc = to_set == &global_variable_set ? 1 : 0;
for ( ; from_var_slot < from_var_end; from_var_slot++)
if (! HASH_VACANT (*from_var_slot))
{
struct variable *from_var = *from_var_slot;
struct variable **to_var_slot
= (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
if (HASH_VACANT (*to_var_slot))
{
hash_insert_at (&to_set->table, from_var, to_var_slot);
variable_changenum += inc;
}
else
{
/* GKM FIXME: delete in from_set->table */
free (from_var->value);
free (from_var);
}
}
}
/* Merge SETLIST1 into SETLIST0, freeing unused storage in SETLIST1. */
void
merge_variable_set_lists (struct variable_set_list **setlist0,
struct variable_set_list *setlist1)
{
struct variable_set_list *to = *setlist0;
struct variable_set_list *last0 = 0;
/* If there's nothing to merge, stop now. */
if (!setlist1 || setlist1 == &global_setlist)
return;
if (to)
{
/* These loops rely on the fact that all setlists terminate with the
global setlist (before NULL). If not, arguably we SHOULD die. */
/* Make sure that setlist1 is not already a subset of setlist0. */
while (to != &global_setlist)
{
if (to == setlist1)
return;
to = to->next;
}
to = *setlist0;
while (setlist1 != &global_setlist && to != &global_setlist)
{
struct variable_set_list *from = setlist1;
setlist1 = setlist1->next;
merge_variable_sets (to->set, from->set);
last0 = to;
to = to->next;
}
}
if (setlist1 != &global_setlist)
{
if (last0 == 0)
*setlist0 = setlist1;
else
last0->next = setlist1;
}
}
/* Define the automatic variables, and record the addresses
of their structures so we can change their values quickly. */
void
define_automatic_variables (void)
{
struct variable *v;
char buf[200];
sprintf (buf, "%u", makelevel);
define_variable_cname (MAKELEVEL_NAME, buf, o_env, 0);
sprintf (buf, "%s%s%s",
version_string,
(remote_description == 0 || remote_description[0] == '\0')
? "" : "-",
(remote_description == 0 || remote_description[0] == '\0')
? "" : remote_description);
define_variable_cname ("LANDLOCKMAKE_VERSION",
LANDLOCKMAKE_VERSION, o_default, 0);
define_variable_cname ("MAKE_VERSION", buf, o_default, 0);
define_variable_cname ("MAKE_HOST", make_host, o_default, 0);
/* This won't override any definition, but it will provide one if there
isn't one there. */
v = define_variable_cname ("SHELL", default_shell, o_default, 0);
/* Don't let SHELL come from the environment. */
if (*v->value == '\0' || v->origin == o_env || v->origin == o_env_override)
{
free (v->value);
v->origin = o_file;
v->value = xstrdup (default_shell);
}
/* Make sure MAKEFILES gets exported if it is set. */
v = define_variable_cname ("MAKEFILES", "", o_default, 0);
v->export = v_ifset;
/* Define the magic D and F variables in terms of
the automatic variables they are variations of. */
define_variable_cname ("@D", "$(patsubst %/,%,$(dir $@))", o_automatic, 1);
define_variable_cname ("%D", "$(patsubst %/,%,$(dir $%))", o_automatic, 1);
define_variable_cname ("*D", "$(patsubst %/,%,$(dir $*))", o_automatic, 1);
define_variable_cname ("<D", "$(patsubst %/,%,$(dir $<))", o_automatic, 1);
define_variable_cname ("?D", "$(patsubst %/,%,$(dir $?))", o_automatic, 1);
define_variable_cname ("^D", "$(patsubst %/,%,$(dir $^))", o_automatic, 1);
define_variable_cname ("+D", "$(patsubst %/,%,$(dir $+))", o_automatic, 1);
define_variable_cname ("@F", "$(notdir $@)", o_automatic, 1);
define_variable_cname ("%F", "$(notdir $%)", o_automatic, 1);
define_variable_cname ("*F", "$(notdir $*)", o_automatic, 1);
define_variable_cname ("<F", "$(notdir $<)", o_automatic, 1);
define_variable_cname ("?F", "$(notdir $?)", o_automatic, 1);
define_variable_cname ("^F", "$(notdir $^)", o_automatic, 1);
define_variable_cname ("+F", "$(notdir $+)", o_automatic, 1);
}
int export_all_variables;
/* Create a new environment for FILE's commands.
If FILE is nil, this is for the 'shell' function.
The child's MAKELEVEL variable is incremented. */
char **
target_environment (struct file *file)
{
struct variable_set_list *set_list;
struct variable_set_list *s;
struct hash_table table;
struct variable **v_slot;
struct variable **v_end;
struct variable makelevel_key;
char **result_0;
char **result;
if (file == 0)
set_list = current_variable_set_list;
else
set_list = file->variables;
hash_init (&table, VARIABLE_BUCKETS,
variable_hash_1, variable_hash_2, variable_hash_cmp);
/* Run through all the variable sets in the list,
accumulating variables in TABLE. */
for (s = set_list; s != 0; s = s->next)
{
struct variable_set *set = s->set;
v_slot = (struct variable **) set->table.ht_vec;
v_end = v_slot + set->table.ht_size;
for ( ; v_slot < v_end; v_slot++)
if (! HASH_VACANT (*v_slot))
{
struct variable **new_slot;
struct variable *v = *v_slot;
/* If this is a per-target variable and it hasn't been touched
already then look up the global version and take its export
value. */
if (v->per_target && v->export == v_default)
{
struct variable *gv;
gv = lookup_variable_in_set (v->name, strlen (v->name),
&global_variable_set);
if (gv)
v->export = gv->export;
}
switch (v->export)
{
case v_default:
if (v->origin == o_default || v->origin == o_automatic)
/* Only export default variables by explicit request. */
continue;
/* The variable doesn't have a name that can be exported. */
if (! v->exportable)
continue;
if (! export_all_variables
&& v->origin != o_command
&& v->origin != o_env && v->origin != o_env_override)
continue;
break;
case v_export:
break;
case v_noexport:
{
/* If this is the SHELL variable and it's not exported,
then add the value from our original environment, if
the original environment defined a value for SHELL. */
if (streq (v->name, "SHELL") && shell_var.value)
{
v = &shell_var;
break;
}
continue;
}
case v_ifset:
if (v->origin == o_default)
continue;
break;
}
new_slot = (struct variable **) hash_find_slot (&table, v);
if (HASH_VACANT (*new_slot))
hash_insert_at (&table, v, new_slot);
}
}
makelevel_key.name = (char *)MAKELEVEL_NAME;
makelevel_key.length = MAKELEVEL_LENGTH;
hash_delete (&table, &makelevel_key);
result = result_0 = xmalloc ((table.ht_fill + 2) * sizeof (char *));
v_slot = (struct variable **) table.ht_vec;
v_end = v_slot + table.ht_size;
for ( ; v_slot < v_end; v_slot++)
if (! HASH_VACANT (*v_slot))
{
struct variable *v = *v_slot;
/* If V is recursively expanded and didn't come from the environment,
expand its value. If it came from the environment, it should
go back into the environment unchanged. */
if (v->recursive
&& v->origin != o_env && v->origin != o_env_override)
{
char *value = recursively_expand_for_file (v, file);
*result++ = xstrdup (concat (3, v->name, "=", value));
free (value);
}
else
{
*result++ = xstrdup (concat (3, v->name, "=", v->value));
}
}
*result = xmalloc (100);
sprintf (*result, "%s=%u", MAKELEVEL_NAME, makelevel + 1);
*++result = 0;
hash_free (&table, 0);
return result_0;
}
static struct variable *
set_special_var (struct variable *var)
{
if (streq (var->name, RECIPEPREFIX_NAME))
{
/* The user is resetting the command introduction prefix. This has to
happen immediately, so that subsequent rules are interpreted
properly. */
cmd_prefix = var->value[0]=='\0' ? RECIPEPREFIX_DEFAULT : var->value[0];
}
return var;
}
/* Given a string, shell-execute it and return a malloc'ed string of the
* result. This removes only ONE newline (if any) at the end, for maximum
* compatibility with the *BSD makes. If it fails, returns NULL. */
static char *
shell_result (const char *p)
{
char *buf;
size_t len;
char *args[2];
char *result;
install_variable_buffer (&buf, &len);
args[0] = (char *) p;
args[1] = NULL;
variable_buffer_output (func_shell_base (variable_buffer, args, 0), "\0", 1);
result = strdup (variable_buffer);
restore_variable_buffer (buf, len);
return result;
}
/* Given a variable, a value, and a flavor, define the variable.
See the try_variable_definition() function for details on the parameters. */
struct variable *
do_variable_definition (const floc *flocp, const char *varname,
const char *value, enum variable_origin origin,
enum variable_flavor flavor, int target_var)
{
const char *p;
char *alloc_value = NULL;
struct variable *v;
int append = 0;
int conditional = 0;
/* Calculate the variable's new value in VALUE. */
switch (flavor)
{
default:
case f_bogus:
/* Should not be possible. */
abort ();
case f_simple:
/* A simple variable definition "var := value". Expand the value.
We have to allocate memory since otherwise it'll clobber the
variable buffer, and we may still need that if we're looking at a
target-specific variable. */
p = alloc_value = allocated_variable_expand (value);
break;
case f_shell:
{
/* A shell definition "var != value". Expand value, pass it to
the shell, and store the result in recursively-expanded var. */
char *q = allocated_variable_expand (value);
p = alloc_value = shell_result (q);
free (q);
flavor = f_recursive;
break;
}
case f_conditional:
/* A conditional variable definition "var ?= value".
The value is set IFF the variable is not defined yet. */
v = lookup_variable (varname, strlen (varname));
if (v)
goto done;
conditional = 1;
flavor = f_recursive;
/* FALLTHROUGH */
case f_recursive:
/* A recursive variable definition "var = value".
The value is used verbatim. */
p = value;
break;
case f_append:
case f_append_value:
{
/* If we have += but we're in a target variable context, we want to
append only with other variables in the context of this target. */
if (target_var)
{
append = 1;
v = lookup_variable_in_set (varname, strlen (varname),
current_variable_set_list->set);
/* Don't append from the global set if a previous non-appending
target-specific variable definition exists. */
if (v && !v->append)
append = 0;
}
else
v = lookup_variable (varname, strlen (varname));
if (v == 0)
{
/* There was no old value.
This becomes a normal recursive definition. */
p = value;
flavor = f_recursive;
}
else
{
/* Paste the old and new values together in VALUE. */
size_t oldlen, vallen;
const char *val;
char *tp = NULL;
val = value;
if (v->recursive)
/* The previous definition of the variable was recursive.
The new value is the unexpanded old and new values. */
flavor = f_recursive;
else if (flavor != f_append_value)
/* The previous definition of the variable was simple.
The new value comes from the old value, which was expanded
when it was set; and from the expanded new value. Allocate
memory for the expansion as we may still need the rest of the
buffer if we're looking at a target-specific variable. */
val = tp = allocated_variable_expand (val);
/* If the new value is empty, nothing to do. */
vallen = strlen (val);
if (!vallen)
{
alloc_value = tp;
goto done;
}
oldlen = strlen (v->value);
p = alloc_value = xmalloc (oldlen + 1 + vallen + 1);
if (oldlen)
{
memcpy (alloc_value, v->value, oldlen);
alloc_value[oldlen] = ' ';
++oldlen;
}
memcpy (&alloc_value[oldlen], val, vallen + 1);
free (tp);
}
break;
}
}
/* If we are defining variables inside an $(eval ...), we might have a
different variable context pushed, not the global context (maybe we're
inside a $(call ...) or something. Since this function is only ever
invoked in places where we want to define globally visible variables,
make sure we define this variable in the global set. */
v = define_variable_in_set (varname, strlen (varname), p,
origin, flavor == f_recursive,
(target_var
? current_variable_set_list->set : NULL),
flocp);
v->append = append;
v->conditional = conditional;
done:
free (alloc_value);
return v->special ? set_special_var (v) : v;
}
/* Parse P (a null-terminated string) as a variable definition.
If it is not a variable definition, return NULL and the contents of *VAR
are undefined, except NAME is set to the first non-space character or NIL.
If it is a variable definition, return a pointer to the char after the
assignment token and set the following fields (only) of *VAR:
name : name of the variable (ALWAYS SET) (NOT NUL-TERMINATED!)
length : length of the variable name
value : value of the variable (nul-terminated)
flavor : flavor of the variable
Other values in *VAR are unchanged.
*/
char *
parse_variable_definition (const char *p, struct variable *var)
{
int wspace = 0;
const char *e = NULL;
NEXT_TOKEN (p);
var->name = (char *)p;
var->length = 0;
while (1)
{
int c = *p++;
/* If we find a comment or EOS, it's not a variable definition. */
if (STOP_SET (c, MAP_COMMENT|MAP_NUL))
return NULL;
if (c == '$')
{
/* This begins a variable expansion reference. Make sure we don't
treat chars inside the reference as assignment tokens. */
char closeparen;
unsigned int count;
c = *p++;
if (c == '(')
closeparen = ')';
else if (c == '{')
closeparen = '}';
else if (c == '\0')
return NULL;
else
/* '$$' or '$X'. Either way, nothing special to do here. */
continue;
/* P now points past the opening paren or brace.
Count parens or braces until it is matched. */
for (count = 1; *p != '\0'; ++p)
{
if (*p == closeparen && --count == 0)
{
++p;
break;
}
if (*p == c)
++count;
}
continue;
}
/* If we find whitespace skip it, and remember we found it. */
if (ISBLANK (c))
{
wspace = 1;
e = p - 1;
NEXT_TOKEN (p);
c = *p;
if (c == '\0')
return NULL;
++p;
}
if (c == '=')
{
var->flavor = f_recursive;
if (! e)
e = p - 1;
break;
}
/* Match assignment variants (:=, +=, ?=, !=) */
if (*p == '=')
{
switch (c)
{
case ':':
var->flavor = f_simple;
break;
case '+':
var->flavor = f_append;
break;
case '?':
var->flavor = f_conditional;
break;
case '!':
var->flavor = f_shell;
break;
default:
/* If we skipped whitespace, non-assignments means no var. */
if (wspace)
return NULL;
/* Might be assignment, or might be $= or #=. Check. */
continue;
}
if (! e)
e = p - 1;
++p;
break;
}
/* Check for POSIX ::= syntax */
if (c == ':')
{
/* A colon other than :=/::= is not a variable defn. */
if (*p != ':' || p[1] != '=')
return NULL;
/* POSIX allows ::= to be the same as GNU make's := */
var->flavor = f_simple;
if (! e)
e = p - 1;
p += 2;
break;
}
/* If we skipped whitespace, non-assignments means no var. */
if (wspace)
return NULL;
}
var->length = (unsigned int) (e - var->name);
var->value = next_token (p);
return (char *)p;
}
/* Try to interpret LINE (a null-terminated string) as a variable definition.
If LINE was recognized as a variable definition, a pointer to its 'struct
variable' is returned. If LINE is not a variable definition, NULL is
returned. */
struct variable *
assign_variable_definition (struct variable *v, const char *line)
{
char *name;
if (!parse_variable_definition (line, v))
return NULL;
/* Expand the name, so "$(foo)bar = baz" works. */
name = alloca (v->length + 1);
memcpy (name, v->name, v->length);
name[v->length] = '\0';
v->name = allocated_variable_expand (name);
if (v->name[0] == '\0')
O (fatal, &v->fileinfo, _("empty variable name"));
return v;
}
/* Try to interpret LINE (a null-terminated string) as a variable definition.
ORIGIN may be o_file, o_override, o_env, o_env_override,
or o_command specifying that the variable definition comes
from a makefile, an override directive, the environment with
or without the -e switch, or the command line.
See the comments for assign_variable_definition().
If LINE was recognized as a variable definition, a pointer to its 'struct
variable' is returned. If LINE is not a variable definition, NULL is
returned. */
struct variable *
try_variable_definition (const floc *flocp, const char *line,
enum variable_origin origin, int target_var)
{
struct variable v;
struct variable *vp;
if (flocp != 0)
v.fileinfo = *flocp;
else
v.fileinfo.filenm = 0;
if (!assign_variable_definition (&v, line))
return 0;
vp = do_variable_definition (flocp, v.name, v.value,
origin, v.flavor, target_var);
free (v.name);
return vp;
}
/* Print information for variable V, prefixing it with PREFIX. */
static void
print_variable (const void *item, void *arg)
{
const struct variable *v = item;
const char *prefix = arg;
const char *origin;
switch (v->origin)
{
case o_automatic:
origin = _("automatic");
break;
case o_default:
origin = _("default");
break;
case o_env:
origin = _("environment");
break;
case o_file:
origin = _("makefile");
break;
case o_env_override:
origin = _("environment under -e");
break;
case o_command:
origin = _("command line");
break;
case o_override:
origin = _("'override' directive");
break;
case o_invalid:
default:
abort ();
}
fputs ("# ", stdout);
fputs (origin, stdout);
if (v->private_var)
fputs (" private", stdout);
if (v->fileinfo.filenm)
printf (_(" (from '%s', line %lu)"),
v->fileinfo.filenm, v->fileinfo.lineno + v->fileinfo.offset);
putchar ('\n');
fputs (prefix, stdout);
/* Is this a 'define'? */
if (v->recursive && strchr (v->value, '\n') != 0)
printf ("define %s\n%s\nendef\n", v->name, v->value);
else
{
char *p;
printf ("%s %s= ", v->name, v->recursive ? v->append ? "+" : "" : ":");
/* Check if the value is just whitespace. */
p = next_token (v->value);
if (p != v->value && *p == '\0')
/* All whitespace. */
printf ("$(subst ,,%s)", v->value);
else if (v->recursive)
fputs (v->value, stdout);
else
/* Double up dollar signs. */
for (p = v->value; *p != '\0'; ++p)
{
if (*p == '$')
putchar ('$');
putchar (*p);
}
putchar ('\n');
}
}
static void
print_auto_variable (const void *item, void *arg)
{
const struct variable *v = item;
if (v->origin == o_automatic)
print_variable (item, arg);
}
static void
print_noauto_variable (const void *item, void *arg)
{
const struct variable *v = item;
if (v->origin != o_automatic)
print_variable (item, arg);
}
/* Print all the variables in SET. PREFIX is printed before
the actual variable definitions (everything else is comments). */
static void
print_variable_set (struct variable_set *set, const char *prefix, int pauto)
{
hash_map_arg (&set->table, (pauto ? print_auto_variable : print_variable),
(void *)prefix);
fputs (_("# variable set hash-table stats:\n"), stdout);
fputs ("# ", stdout);
hash_print_stats (&set->table, stdout);
putc ('\n', stdout);
}
/* Print the data base of variables. */
void
print_variable_data_base (void)
{
puts (_("\n# Variables\n"));
print_variable_set (&global_variable_set, "", 0);
puts (_("\n# Pattern-specific Variable Values"));
{
struct pattern_var *p;
unsigned int rules = 0;
for (p = pattern_vars; p != 0; p = p->next)
{
++rules;
printf ("\n%s :\n", p->target);
print_variable (&p->variable, (void *)"# ");
}
if (rules == 0)
puts (_("\n# No pattern-specific variable values."));
else
printf (_("\n# %u pattern-specific variable values"), rules);
}
}
/* Print all the local variables of FILE. */
void
print_file_variables (const struct file *file)
{
if (file->variables != 0)
print_variable_set (file->variables->set, "# ", 1);
}
void
print_target_variables (const struct file *file)
{
if (file->variables != 0)
{
size_t l = strlen (file->name);
char *t = alloca (l + 3);
strcpy (t, file->name);
t[l] = ':';
t[l+1] = ' ';
t[l+2] = '\0';
hash_map_arg (&file->variables->set->table, print_noauto_variable, t);
}
}
| 44,604 | 1,479 | jart/cosmopolitan | false |
cosmopolitan/third_party/stb/README.txt | /*
* stb_image - v2.23 - public domain image loader - http://nothings.org/stb
* no warranty implied; use at your own risk
*
* [heavily modified by justine tunney]
*
* JPEG baseline & progressive (12 bpc/arithmetic not supported, same
* as stock IJG lib) PNG 1/2/4/8/16-bit-per-channel
* GIF (*comp always reports as 4-channel)
* HDR (radiance rgbE format)
* PNM (PPM and PGM binary only)
*
* Animated GIF still needs a proper API, but here's one way to do it:
* http://gist.github.com/urraka/685d9a6340b26b830d49
*
* - decode from memory or through FILE (define STBI_NO_STDIO to remove code)
* - decode from arbitrary I/O callbacks
*
* ============================ Contributors =========================
*
* Image formats Extensions, features
* Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info)
* Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info)
* Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG)
* Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks)
* Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG)
* Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip)
* Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD)
* github:urraka (animated gif) Junggon Kim (PNM comments)
* Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA)
* socks-the-fox (16-bit PNG)
* Jeremy Sawicki (ImageNet JPGs)
* Mikhail Morozov (1-bit BMP)
* Optimizations & bugfixes Anael Seghezzi (is-16-bit query)
* Fabian "ryg" Giesen
* Arseny Kapoulkine
* John-Mark Allen
* Carmelo J Fdez-Aguera
*
* Bug & warning fixes
* Marc LeBlanc David Woo Guillaume George Martins Mozeiko
* Christpher Lloyd Jerry Jansson Joseph Thomson Phil Jordan
* Dave Moore Roy Eltham Hayaki Saito Nathan Reed
* Won Chun Luke Graham Johan Duparc Nick Verigakis
* the Horde3D community Thomas Ruf Ronny Chevalier github:rlyeh
* Janez Zemva John Bartholomew Michal Cichon github:romigrou
* Jonathan Blow Ken Hamada Tero Hanninen github:svdijk
* Laurent Gomila Cort Stratton Sergio Gonzalez github:snagar
* Aruelien Pocheville Thibault Reuille Cass Everitt github:Zelex
* Ryamond Barbiero Paul Du Bois Engin Manap github:grim210
* Aldo Culquicondor Philipp Wiesemann Dale Weiler github:sammyhw
* Oriol Ferrer Mesia Josh Tobin Matthew Gregan github:phprus
* Julian Raschke Gregory Mullen Baldur Karlsson
* github:poppolopoppo Christian Floisand Kevin Schmidt JR Smith
* github:darealshinji Blazej Dariusz Roszkowski github:Michaelangel007
*/
/*
* DOCUMENTATION
*
* Limitations:
* - no 12-bit-per-channel JPEG
* - no JPEGs with arithmetic coding
* - GIF always returns *comp=4
*
* Basic usage (see HDR discussion below for HDR usage):
* int x,y,n;
* unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
* // ... process data if not NULL ...
* // ... x = width, y = height, n = # 8-bit components per pixel ...
* // ... replace '0' with '1'..'4' to force that many components per pixel
* // ... but 'n' will always be the number that it would have been if you
* said 0 stbi_image_free(data)
*
* Standard parameters:
* int *x -- outputs image width in pixels
* int *y -- outputs image height in pixels
* int *channels_in_file -- outputs # of image components in image file
* int desired_channels -- if non-zero, # of image components requested in
* result
*
* The return value from an image loader is an 'unsigned char *' which points
* to the pixel data, or NULL on an allocation failure or if the image is
* corrupt or invalid. The pixel data consists of *y scanlines of *x pixels,
* with each pixel consisting of N interleaved 8-bit components; the first
* pixel pointed to is top-left-most in the image. There is no padding between
* image scanlines or between pixels, regardless of format. The number of
* components N is 'desired_channels' if desired_channels is non-zero, or
* *channels_in_file otherwise. If desired_channels is non-zero,
* *channels_in_file has the number of components that _would_ have been
* output otherwise. E.g. if you set desired_channels to 4, you will always
* get RGBA output, but you can check *channels_in_file to see if it's trivially
* opaque because e.g. there were only 3 channels in the source image.
*
* An output image with N components has the following components interleaved
* in this order in each pixel:
*
* N=#comp components
* 1 grey
* 2 grey, alpha
* 3 red, green, blue
* 4 red, green, blue, alpha
*
* If image loading fails for any reason, the return value will be NULL,
* and *x, *y, *channels_in_file will be unchanged. The function
* stbi_failure_reason() can be queried for an extremely brief, end-user
* unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS
* to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get
* slightly more user-friendly ones.
*
* Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
*
* ===========================================================================
*
* I/O callbacks
*
* I/O callbacks allow you to read from arbitrary sources, like packaged
* files or some other source. Data read from callbacks are processed
* through a small internal buffer (currently 128 bytes) to try to reduce
* overhead.
*
* The three functions you must define are "read" (reads some bytes of data),
* "skip" (skips some bytes of data), "eof" (reports if the stream is at the
* end).
*
* ===========================================================================
*
* HDR image support (disable by defining STBI_NO_HDR)
*
* stb_image supports loading HDR images in general, and currently the Radiance
* .HDR file format specifically. You can still load any file through the
* existing interface; if you attempt to load an HDR file, it will be
* automatically remapped to LDR, assuming gamma 2.2 and an arbitrary scale
* factor defaulting to 1; both of these constants can be reconfigured through
* this interface:
*
* stbi_hdr_to_ldr_gamma(2.2f);
* stbi_hdr_to_ldr_scale(1.0f);
*
* (note, do not use _inverse_ constants; stbi_image will invert them
* appropriately).
*
* Additionally, there is a new, parallel interface for loading files as
* (linear) floats to preserve the full dynamic range:
*
* float *data = stbi_loadf(filename, &x, &y, &n, 0);
*
* If you load LDR images through this interface, those images will
* be promoted to floating point values, run through the inverse of
* constants corresponding to the above:
*
* stbi_ldr_to_hdr_scale(1.0f);
* stbi_ldr_to_hdr_gamma(2.2f);
*
* Finally, given a filename (or an open file or memory block--see header
* file for details) containing image data, you can query for the "most
* appropriate" interface to use (that is, whether the image is HDR or
* not), using:
*
* stbi_is_hdr(char *filename);
*
* ===========================================================================
*
* iPhone PNG support:
*
* By default we convert iphone-formatted PNGs back to RGB, even though
* they are internally encoded differently. You can disable this conversion
* by calling stbi_convert_iphone_png_to_rgb(0), in which case
* you will always just get the native iphone "format" through (which
* is BGR stored in RGB).
*
* Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
* pixel to remove any premultiplied alpha *only* if the image file explicitly
* says there's premultiplied data (currently only happens in iPhone images,
* and only if iPhone convert-to-rgb processing is on).
*
* ===========================================================================
*
* ADDITIONAL CONFIGURATION
*
* - You can suppress implementation of any of the decoders to reduce
* your code footprint by #defining one or more of the following
* symbols before creating the implementation.
*
* STBI_NO_JPEG
* STBI_NO_PNG
* STBI_NO_GIF
* STBI_NO_HDR
* STBI_NO_PNM (.ppm and .pgm)
*
* - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still
* want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB
*
*/
/* stb_image_resize - v0.96 - public domain image resizing
* by Jorge L Rodriguez (@VinoBS) - 2014
* http://github.com/nothings/stb
*
* Written with emphasis on usability, portability, and efficiency. (No
* SIMD or threads, so it be easily outperformed by libs that use those.)
* Only scaling and translation is supported, no rotations or shears.
* Easy API downsamples w/Mitchell filter, upsamples w/cubic interpolation.
*
* QUICKSTART
* stbir_resize_uint8( input_pixels , in_w , in_h , 0,
* output_pixels, out_w, out_h, 0, num_channels)
* stbir_resize_float(...)
* stbir_resize_uint8_srgb( input_pixels , in_w , in_h , 0,
* output_pixels, out_w, out_h, 0,
* num_channels , alpha_chan , 0)
* stbir_resize_uint8_srgb_edgemode(
* input_pixels , in_w , in_h , 0,
* output_pixels, out_w, out_h, 0,
* num_channels , alpha_chan , 0, STBIR_EDGE_CLAMP)
* // WRAP/REFLECT/ZERO
*/
/*
* DOCUMENTATION
*
* SRGB & FLOATING POINT REPRESENTATION
* The sRGB functions presume IEEE floating point. If you do not have
* IEEE floating point, define STBIR_NON_IEEE_FLOAT. This will use
* a slower implementation.
*
* MEMORY ALLOCATION
* The resize functions here perform a single memory allocation using
* malloc. To control the memory allocation, before the #include that
* triggers the implementation, do:
*
* #define STBIR_MALLOC(size,context) ...
* #define STBIR_FREE(ptr,context) ...
*
* Each resize function makes exactly one call to malloc/free, so to use
* temp memory, store the temp memory in the context and return that.
*
* ASSERT
* Define STBIR_ASSERT(boolval) to override assert() and not use assert.h
*
* OPTIMIZATION
* Define STBIR_SATURATE_INT to compute clamp values in-range using
* integer operations instead of float operations. This may be faster
* on some platforms.
*
* DEFAULT FILTERS
* For functions which don't provide explicit control over what filters
* to use, you can change the compile-time defaults with
*
* #define STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_something
* #define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_something
*
* See stbir_filter in the header-file section for the list of filters.
*
* NEW FILTERS
* A number of 1D filter kernels are used. For a list of
* supported filters see the stbir_filter enum. To add a new filter,
* write a filter function and add it to stbir__filter_info_table.
*
* PROGRESS
* For interactive use with slow resize operations, you can install
* a progress-report callback:
*
* #define STBIR_PROGRESS_REPORT(val) some_func(val)
*
* The parameter val is a float which goes from 0 to 1 as progress
* is made.
*
* For example:
*
* static void my_progress_report(float progress);
* #define STBIR_PROGRESS_REPORT(val) my_progress_report(val)
*
* #define STB_IMAGE_RESIZE_IMPLEMENTATION
*
* static void my_progress_report(float progress)
* {
* printf("Progress: %f%%\n", progress*100);
* }
*
* MAX CHANNELS
* If your image has more than 64 channels, define STBIR_MAX_CHANNELS
* to the max you'll have.
*
* ALPHA CHANNEL
* Most of the resizing functions provide the ability to control how
* the alpha channel of an image is processed. The important things
* to know about this:
*
* 1. The best mathematically-behaved version of alpha to use is
* called "premultiplied alpha", in which the other color channels
* have had the alpha value multiplied in. If you use premultiplied
* alpha, linear filtering (such as image resampling done by this
* library, or performed in texture units on GPUs) does the "right
* thing". While premultiplied alpha is standard in the movie CGI
* industry, it is still uncommon in the videogame/real-time world.
*
* If you linearly filter non-premultiplied alpha, strange effects
* occur. (For example, the 50/50 average of 99% transparent bright green
* and 1% transparent black produces 50% transparent dark green when
* non-premultiplied, whereas premultiplied it produces 50%
* transparent near-black. The former introduces green energy
* that doesn't exist in the source image.)
*
* 2. Artists should not edit premultiplied-alpha images; artists
* want non-premultiplied alpha images. Thus, art tools generally output
* non-premultiplied alpha images.
*
* 3. You will get best results in most cases by converting images
* to premultiplied alpha before processing them mathematically.
*
* 4. If you pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED, the
* resizer does not do anything special for the alpha channel;
* it is resampled identically to other channels. This produces
* the correct results for premultiplied-alpha images, but produces
* less-than-ideal results for non-premultiplied-alpha images.
*
* 5. If you do not pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED,
* then the resizer weights the contribution of input pixels
* based on their alpha values, or, equivalently, it multiplies
* the alpha value into the color channels, resamples, then divides
* by the resultant alpha value. Input pixels which have alpha=0 do
* not contribute at all to output pixels unless _all_ of the input
* pixels affecting that output pixel have alpha=0, in which case
* the result for that pixel is the same as it would be without
* STBIR_FLAG_ALPHA_PREMULTIPLIED. However, this is only true for
* input images in integer formats. For input images in float format,
* input pixels with alpha=0 have no effect, and output pixels
* which have alpha=0 will be 0 in all channels. (For float images,
* you can manually achieve the same result by adding a tiny epsilon
* value to the alpha channel of every image, and then subtracting
* or clamping it at the end.)
*
* 6. You can suppress the behavior described in #5 and make
* all-0-alpha pixels have 0 in all channels by #defining
* STBIR_NO_ALPHA_EPSILON.
*
* 7. You can separately control whether the alpha channel is
* interpreted as linear or affected by the colorspace. By default
* it is linear; you almost never want to apply the colorspace.
* (For example, graphics hardware does not apply sRGB conversion
* to the alpha channel.)
*
* CONTRIBUTORS
* Jorge L Rodriguez: Implementation
* Sean Barrett: API design, optimizations
* Aras Pranckevicius: bugfix
* Nathan Reed: warning fixes
*
* REVISIONS
* 0.96 (2019-03-04) fixed warnings
* 0.95 (2017-07-23) fixed warnings
* 0.94 (2017-03-18) fixed warnings
* 0.93 (2017-03-03) fixed bug with certain combinations of heights
* 0.92 (2017-01-02) fix integer overflow on large (>2GB) images
* 0.91 (2016-04-02) fix warnings; fix handling of subpixel regions
* 0.90 (2014-09-17) first released version
*
* LICENSE
* See end of file for license information.
*
* TODO
* Don't decode all of the image data when only processing a partial tile
* Don't use full-width decode buffers when only processing a partial tile
* When processing wide images, break processing into tiles so data fits in
* L1 cache Installable filters? Resize that respects alpha test coverage
* (Reference code: FloatImage::alphaTestCoverage and
* FloatImage::scaleAlphaToCoverage:
* https://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvimage/FloatImage.cpp
* )
*/
| 17,019 | 372 | jart/cosmopolitan | false |
cosmopolitan/third_party/stb/stb_truetype.h | #ifndef COSMOPOLITAN_THIRD_PARTY_STB_STB_TRUETYPE_H_
#define COSMOPOLITAN_THIRD_PARTY_STB_STB_TRUETYPE_H_
#include "libc/runtime/runtime.h"
#include "third_party/stb/stb_rect_pack.h"
#define STBTT_vmove 1
#define STBTT_vline 2
#define STBTT_vcurve 3
#define STBTT_vcubic 4
#define STBTT_MACSTYLE_DONTCARE 0
#define STBTT_MACSTYLE_BOLD 1
#define STBTT_MACSTYLE_ITALIC 2
#define STBTT_MACSTYLE_UNDERSCORE 4
#define STBTT_MACSTYLE_NONE 8
#define STBTT_PLATFORM_ID_UNICODE 0
#define STBTT_PLATFORM_ID_MAC 1
#define STBTT_PLATFORM_ID_ISO 2
#define STBTT_PLATFORM_ID_MICROSOFT 3
#define STBTT_UNICODE_EID_UNICODE_1_0 0
#define STBTT_UNICODE_EID_UNICODE_1_1 1
#define STBTT_UNICODE_EID_ISO_10646 2
#define STBTT_UNICODE_EID_UNICODE_2_0_BMP 3
#define STBTT_UNICODE_EID_UNICODE_2_0_FULL 4
#define STBTT_MS_EID_SYMBOL 0
#define STBTT_MS_EID_UNICODE_BMP 1
#define STBTT_MS_EID_SHIFTJIS 2
#define STBTT_MS_EID_UNICODE_FULL 10
#define STBTT_MAC_EID_ROMAN 0
#define STBTT_MAC_EID_ARABIC 4
#define STBTT_MAC_EID_JAPANESE 1
#define STBTT_MAC_EID_HEBREW 5
#define STBTT_MAC_EID_CHINESE_TRAD 2
#define STBTT_MAC_EID_GREEK 6
#define STBTT_MAC_EID_KOREAN 3
#define STBTT_MAC_EID_RUSSIAN 7
#define STBTT_MS_LANG_ENGLISH 0x0409
#define STBTT_MS_LANG_ITALIAN 0x0410
#define STBTT_MS_LANG_CHINESE 0x0804
#define STBTT_MS_LANG_JAPANESE 0x0411
#define STBTT_MS_LANG_DUTCH 0x0413
#define STBTT_MS_LANG_KOREAN 0x0412
#define STBTT_MS_LANG_FRENCH 0x040c
#define STBTT_MS_LANG_RUSSIAN 0x0419
#define STBTT_MS_LANG_GERMAN 0x0407
#define STBTT_MS_LANG_SPANISH 0x0409
#define STBTT_MS_LANG_HEBREW 0x040d
#define STBTT_MS_LANG_SWEDISH 0x041D
#define STBTT_MAC_LANG_ENGLISH 0
#define STBTT_MAC_LANG_JAPANESE 11
#define STBTT_MAC_LANG_ARABIC 12
#define STBTT_MAC_LANG_KOREAN 23
#define STBTT_MAC_LANG_DUTCH 4
#define STBTT_MAC_LANG_RUSSIAN 32
#define STBTT_MAC_LANG_FRENCH 1
#define STBTT_MAC_LANG_SPANISH 6
#define STBTT_MAC_LANG_GERMAN 2
#define STBTT_MAC_LANG_SWEDISH 5
#define STBTT_MAC_LANG_HEBREW 10
#define STBTT_MAC_LANG_CHINESE_SIMPLIFIED 33
#define STBTT_MAC_LANG_ITALIAN 3
#define STBTT_MAC_LANG_CHINESE_TRAD 19
#define STBTT_POINT_SIZE(x) (-(x))
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
typedef int16_t stbtt_vertex_type;
typedef struct stbtt_fontinfo stbtt_fontinfo;
typedef struct stbtt_pack_context stbtt_pack_context;
typedef struct {
unsigned char *data;
int cursor;
int size;
} stbtt__buf;
typedef struct {
unsigned short x0, y0, x1, y1;
float xoff, yoff, xadvance;
} stbtt_bakedchar;
typedef struct {
float x0, y0, s0, t0;
float x1, y1, s1, t1;
} stbtt_aligned_quad;
typedef struct {
unsigned short x0, y0, x1, y1;
float xoff, yoff, xadvance;
float xoff2, yoff2;
} stbtt_packedchar;
typedef struct {
int w, h, stride;
unsigned char *pixels;
} stbtt__bitmap;
typedef struct {
float font_size;
int first_unicode_codepoint_in_range;
int *array_of_unicode_codepoints;
int num_chars;
stbtt_packedchar *chardata_for_range;
unsigned char h_oversample, v_oversample;
} stbtt_pack_range;
struct stbtt_pack_context {
void *user_allocator_context;
void *pack_info;
int width;
int height;
int stride_in_bytes;
int padding;
int skip_missing;
unsigned int h_oversample, v_oversample;
unsigned char *pixels;
void *nodes;
};
struct stbtt_fontinfo {
void *userdata;
int hmtx, kern, gpos, svg;
int loca, head, glyf, hhea;
unsigned char *data; // pointer to .ttf file
int fontstart; // offset of start of font
int numGlyphs; // needed for range checking
int index_map; // cmap mapping for chosen char encoding
int indexToLocFormat; // format mapping glyph index to glyph
stbtt__buf cff; // cff font data
stbtt__buf charstrings; // charstring index
stbtt__buf gsubrs; // global charstring subroutines index
stbtt__buf subrs; // private charstring subroutines index
stbtt__buf fontdicts; // array of font dicts
stbtt__buf fdselect; // map from glyph to fontdict
};
typedef struct stbtt_kerningentry {
int glyph1; // use stbtt_FindGlyphIndex
int glyph2;
int advance;
} stbtt_kerningentry;
typedef struct {
stbtt_vertex_type x, y, cx, cy, cx1, cy1;
unsigned char type, padding;
} stbtt_vertex;
extern jmp_buf stbtt_jmpbuf;
int stbtt_BakeFontBitmap(const unsigned char *, int, float, unsigned char *,
int, int, int, int, stbtt_bakedchar *);
void stbtt_GetBakedQuad(const stbtt_bakedchar *, int, int, int, float *,
float *, stbtt_aligned_quad *, int);
void stbtt_GetScaledFontVMetrics(const unsigned char *, int, float, float *,
float *, float *);
int stbtt_PackBegin(stbtt_pack_context *, unsigned char *, int, int, int, int,
void *);
void stbtt_PackEnd(stbtt_pack_context *);
int stbtt_PackFontRange(stbtt_pack_context *, const unsigned char *, int, float,
int, int, stbtt_packedchar *);
int stbtt_PackFontRanges(stbtt_pack_context *, const unsigned char *, int,
stbtt_pack_range *, int);
void stbtt_PackSetOversampling(stbtt_pack_context *, unsigned int,
unsigned int);
void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *, int);
void stbtt_GetPackedQuad(const stbtt_packedchar *, int, int, int, float *,
float *, stbtt_aligned_quad *, int);
int stbtt_PackFontRangesGatherRects(stbtt_pack_context *,
const stbtt_fontinfo *, stbtt_pack_range *,
int, stbrp_rect *);
void stbtt_PackFontRangesPackRects(stbtt_pack_context *, stbrp_rect *, int);
int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *,
const stbtt_fontinfo *,
stbtt_pack_range *, int, stbrp_rect *);
int stbtt_GetNumberOfFonts(const unsigned char *);
int stbtt_GetFontOffsetForIndex(const unsigned char *, int);
int stbtt_InitFont(stbtt_fontinfo *, const unsigned char *, int);
int stbtt_FindGlyphIndex(const stbtt_fontinfo *, int);
float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *, float);
float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *, float);
void stbtt_GetFontVMetrics(const stbtt_fontinfo *, int *, int *, int *);
int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *, int *, int *, int *);
void stbtt_GetFontBoundingBox(const stbtt_fontinfo *, int *, int *, int *,
int *);
void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *, int, int *, int *);
int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *, int, int);
int stbtt_GetCodepointBox(const stbtt_fontinfo *, int, int *, int *, int *,
int *);
void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *, int, int *, int *);
int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *, int, int);
int stbtt_GetGlyphBox(const stbtt_fontinfo *, int, int *, int *, int *, int *);
int stbtt_GetKerningTableLength(const stbtt_fontinfo *);
int stbtt_GetKerningTable(const stbtt_fontinfo *, stbtt_kerningentry *, int);
int stbtt_IsGlyphEmpty(const stbtt_fontinfo *, int);
int stbtt_GetCodepointShape(const stbtt_fontinfo *, int, stbtt_vertex **);
int stbtt_GetGlyphShape(const stbtt_fontinfo *, int, stbtt_vertex **);
void stbtt_FreeShape(const stbtt_fontinfo *, stbtt_vertex *);
unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *, int);
int stbtt_GetCodepointSVG(const stbtt_fontinfo *, int, const char **);
int stbtt_GetGlyphSVG(const stbtt_fontinfo *, int, const char **);
void stbtt_FreeBitmap(unsigned char *, void *);
void *stbtt_GetCodepointBitmap(const stbtt_fontinfo *, float, float, int, int *,
int *, int *, int *);
void *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *, float, float,
float, float, int, int *, int *, int *,
int *);
void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *, unsigned char *, int,
int, int, float, float, int);
void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *, unsigned char *,
int, int, int, float, float, float,
float, int);
void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *,
unsigned char *, int, int, int,
float, float, float, float, int,
int, float *, float *, int);
void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *, int, float, float,
int *, int *, int *, int *);
void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *, int, float,
float, float, float, int *, int *,
int *, int *);
unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *, float, float, int,
int *, int *, int *, int *);
unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *, float,
float, float, float, int, int *,
int *, int *, int *);
void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *, unsigned char *, int, int,
int, float, float, int);
void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *, unsigned char *, int,
int, int, float, float, float, float, int);
void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *,
unsigned char *, int, int, int,
float, float, float, float, int,
int, float *, float *, int);
void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *, int, float, float, int *,
int *, int *, int *);
void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *, int, float, float,
float, float, int *, int *, int *, int *);
void stbtt_Rasterize(stbtt__bitmap *, float, stbtt_vertex *, int, float, float,
float, float, int, int, int, void *);
void stbtt_FreeSDF(unsigned char *, void *);
unsigned char *stbtt_GetGlyphSDF(const stbtt_fontinfo *, float, int, int,
unsigned char, float, int *, int *, int *,
int *);
unsigned char *stbtt_GetCodepointSDF(const stbtt_fontinfo *, float, int, int,
unsigned char, float, int *, int *, int *,
int *);
int stbtt_FindMatchingFont(const unsigned char *, const char *, int);
int stbtt_CompareUTF8toUTF16_bigendian(const char *, int, const char *, int);
const char *stbtt_GetFontNameString(const stbtt_fontinfo *, int *, int, int,
int, int);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_THIRD_PARTY_STB_STB_TRUETYPE_H_ */
| 11,459 | 263 | jart/cosmopolitan | false |
cosmopolitan/third_party/stb/stb_image.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/stb/stb_image.h"
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/bits.h"
#include "libc/limits.h"
#include "libc/log/gdb.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/math.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/x86feature.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/x/x.h"
#include "third_party/aarch64/arm_neon.h"
#include "third_party/intel/ammintrin.internal.h"
asm(".ident\t\"\\n\\n\
stb_image (Public Domain)\\n\
Credit: Sean Barrett, et al.\\n\
http://nothings.org/stb\"");
#ifdef __x86_64__
#define STBI_SSE2
#define idct_block_kernel stbi__idct_simd
#elif defined(__aarch64__)
#define STBI_NEON
#define idct_block_kernel stbi__idct_simd
#else
#define idct_block_kernel stbi__idct_block
#endif
#define ROL(w, k) ((w) << (k) | CheckUnsigned(w) >> (sizeof(w) * 8 - (k)))
#ifndef STBI_REALLOC_SIZED
#define STBI_REALLOC_SIZED(p, oldsz, newsz) realloc(p, newsz)
#endif
typedef unsigned char stbi_uc;
typedef unsigned short stbi_us;
// stbi__context structure is our basic context used by all images, so it
// contains all the IO context, plus some basic image information
typedef struct {
uint32_t img_x, img_y;
int img_n, img_out_n;
stbi_io_callbacks io;
void *io_user_data;
int read_from_callbacks;
int buflen;
unsigned char buffer_start[128];
unsigned char *img_buffer, *img_buffer_end;
unsigned char *img_buffer_original, *img_buffer_original_end;
} stbi__context;
static const unsigned char kPngSig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
static void stbi__refill_buffer(stbi__context *s);
// initialize a memory-decode context
static void stbi__start_mem(stbi__context *s, unsigned char const *buffer,
int len) {
s->io.read = NULL;
s->read_from_callbacks = 0;
s->img_buffer = s->img_buffer_original = (unsigned char *)buffer;
s->img_buffer_end = s->img_buffer_original_end =
(unsigned char *)buffer + len;
}
// initialize a callback-based context
static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c,
void *user) {
s->io = *c;
s->io_user_data = user;
s->buflen = sizeof(s->buffer_start);
s->read_from_callbacks = 1;
s->img_buffer_original = s->buffer_start;
stbi__refill_buffer(s);
s->img_buffer_original_end = s->img_buffer_end;
}
static int stbi__stdio_read(void *user, char *data, int size) {
return fread(data, 1, size, user);
}
static void stbi__stdio_skip(void *user, int n) {
fseek(user, n, SEEK_CUR);
}
static int stbi__stdio_eof(void *user) {
return feof(user);
}
static stbi_io_callbacks stbi__stdio_callbacks = {
stbi__stdio_read,
stbi__stdio_skip,
stbi__stdio_eof,
};
static void stbi__start_file(stbi__context *s, FILE *f) {
stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *)f);
}
static void stbi__rewind(stbi__context *s) {
// conceptually rewind SHOULD rewind to the beginning of the stream,
// but we just rewind to the beginning of the initial buffer, because
// we only use it after doing 'test', which only ever looks at at most 92
// bytes
s->img_buffer = s->img_buffer_original;
s->img_buffer_end = s->img_buffer_original_end;
}
enum { STBI_ORDER_RGB, STBI_ORDER_BGR };
typedef struct {
int bits_per_channel;
int num_channels;
} stbi__result_info;
static int stbi__jpeg_test(stbi__context *);
static void *stbi__jpeg_load(stbi__context *, int *, int *, int *, int,
stbi__result_info *);
static int stbi__jpeg_info(stbi__context *, int *, int *, int *);
static int stbi__png_test(stbi__context *);
static void *stbi__png_load(stbi__context *, int *, int *, int *, int,
stbi__result_info *);
static int stbi__png_info(stbi__context *, int *, int *, int *);
static int stbi__png_is16(stbi__context *);
static int stbi__gif_test(stbi__context *);
static void *stbi__gif_load(stbi__context *, int *, int *, int *, int,
stbi__result_info *);
static void *stbi__load_gif_main(stbi__context *, int **, int *, int *, int *,
int *, int);
static int stbi__gif_info(stbi__context *, int *, int *, int *);
static int stbi__pnm_test(stbi__context *);
static void *stbi__pnm_load(stbi__context *, int *, int *, int *, int,
stbi__result_info *);
static int stbi__pnm_info(stbi__context *, int *, int *, int *);
static const char *stbi__g_failure_reason;
static int stbi__vertically_flip_on_load = 0;
const char *stbi_failure_reason(void) {
return stbi__g_failure_reason;
}
static int stbi__err(const char *specific_details,
const char *general_details) {
/* DebugBreak(); */
/* WARNF("%s: %s", general_details, specific_details); */
stbi__g_failure_reason = general_details;
return 0;
}
// stb_image uses ints pervasively, including for offset calculations.
// therefore the largest decoded image size we can support with the
// current code, even on 64-bit targets, is INT_MAX. this is not a
// significant limitation for the intended use case.
//
// we do, however, need to make sure our size calculations don't
// overflow. hence a few helper functions for size calculations that
// multiply integers together, making sure that they're non-negative
// and no overflow occurs.
// return 1 if the sum is valid, 0 on overflow.
// negative terms are considered invalid.
static int stbi__addsizes_valid(int a, int b) {
if (b < 0) return 0;
// now 0 <= b <= INT_MAX, hence also
// 0 <= INT_MAX - b <= INTMAX.
// And "a + b <= INT_MAX" (which might overflow) is the
// same as a <= INT_MAX - b (no overflow)
return a <= INT_MAX - b;
}
// returns 1 if the product is valid, 0 on overflow.
// negative factors are considered invalid.
static int stbi__mul2sizes_valid(int a, int b) {
if (a < 0 || b < 0) return 0;
if (b == 0) return 1; // mul-by-0 is always safe
// portable way to check for no overflows in a*b
return a <= INT_MAX / b;
}
// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow
static int stbi__mad2sizes_valid(int a, int b, int add) {
return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a * b, add);
}
// returns 1 if "a*b*c + add" has no negaive terms/factors and doesn't overflow
static int stbi__mad3sizes_valid(int a, int b, int c, int add) {
return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a * b, c) &&
stbi__addsizes_valid(a * b * c, add);
}
// mallocs with size overflow checking
static void *stbi__malloc_mad2(int a, int b, int add) {
if (!stbi__mad2sizes_valid(a, b, add)) return NULL;
return xmalloc(a * b + add);
}
static void *stbi__malloc_mad3(int a, int b, int c, int add) {
if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL;
return xmalloc(a * b * c + add);
}
#define stbi__errpf(x, y) \
({ \
stbi__err(x, y); \
NULL; \
})
#define stbi__errpuc(x, y) \
({ \
stbi__err(x, y); \
NULL; \
})
void stbi_image_free(void *retval_from_stbi_load) {
free(retval_from_stbi_load);
}
void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) {
stbi__vertically_flip_on_load = flag_true_if_should_flip;
}
static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp,
int req_comp, stbi__result_info *ri, int bpc) {
bzero(ri, sizeof(*ri));
ri->bits_per_channel = 8;
ri->num_channels = 0;
#ifndef STBI_NO_JPEG
if (stbi__jpeg_test(s)) return stbi__jpeg_load(s, x, y, comp, req_comp, ri);
#endif
#ifndef STBI_NO_PNG
if (stbi__png_test(s)) return stbi__png_load(s, x, y, comp, req_comp, ri);
#endif
#ifndef STBI_NO_GIF
if (stbi__gif_test(s)) return stbi__gif_load(s, x, y, comp, req_comp, ri);
#endif
#ifndef STBI_NO_PNM
if (stbi__pnm_test(s)) return stbi__pnm_load(s, x, y, comp, req_comp, ri);
#endif
return stbi__errpuc("unknown image type",
"Image not of any known type, or corrupt");
}
unsigned char *stbi__convert_16_to_8(uint16_t *orig, int w, int h,
int channels) {
int i;
int img_len = w * h * channels;
unsigned char *reduced = xmalloc(img_len);
for (i = 0; i < img_len; ++i) {
// top half of each byte is sufficient
// approx of 16->8 bit scaling
reduced[i] = (orig[i] >> 8) & 0xff;
}
free(orig);
return reduced;
}
uint16_t *stbi__convert_8_to_16(unsigned char *orig, int w, int h,
int channels) {
int i;
int img_len = w * h * channels;
uint16_t *enlarged = xmalloc(img_len * 2);
for (i = 0; i < img_len; ++i) {
// replicate to high and low byte, maps 0->0, 255->0xffff
enlarged[i] = (uint16_t)((orig[i] << 8) + orig[i]);
}
free(orig);
return enlarged;
}
static void stbi__vertical_flip(void *image, int w, int h,
int bytes_per_pixel) {
int row;
size_t bytes_per_row, bytes_left, bytes_copy;
unsigned char *row0, *row1, *bytes, temp[2048];
bytes = image;
bytes_per_row = bytes_per_pixel * w;
for (row = 0; row < (h >> 1); row++) {
row0 = bytes + row * bytes_per_row;
row1 = bytes + (h - row - 1) * bytes_per_row;
// swap row0 with row1
bytes_left = bytes_per_row;
while (bytes_left) {
bytes_copy = bytes_left < sizeof(temp) ? bytes_left : sizeof(temp);
memcpy(temp, row0, bytes_copy);
memcpy(row0, row1, bytes_copy);
memcpy(row1, temp, bytes_copy);
row0 += bytes_copy;
row1 += bytes_copy;
bytes_left -= bytes_copy;
}
}
}
static void stbi__vertical_flip_slices(void *image, int w, int h, int z,
int bytes_per_pixel) {
unsigned char *bytes;
int slice, slice_size;
bytes = image;
slice_size = w * h * bytes_per_pixel;
for (slice = 0; slice < z; ++slice) {
stbi__vertical_flip(bytes, w, h, bytes_per_pixel);
bytes += slice_size;
}
}
static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x,
int *y, int *comp,
int req_comp) {
void *result;
stbi__result_info ri;
result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8);
if (result == NULL) return NULL;
if (ri.bits_per_channel != 8) {
assert(ri.bits_per_channel == 16);
result =
stbi__convert_16_to_8(result, *x, *y, req_comp == 0 ? *comp : req_comp);
ri.bits_per_channel = 8;
}
// @TODO: move stbi__convert_format to here
if (stbi__vertically_flip_on_load) {
int channels = req_comp ? req_comp : *comp;
stbi__vertical_flip(result, *x, *y, channels * sizeof(unsigned char));
}
return (unsigned char *)result;
}
static uint16_t *stbi__load_and_postprocess_16bit(stbi__context *s, int *x,
int *y, int *comp,
int req_comp) {
stbi__result_info ri;
void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16);
if (result == NULL) return NULL;
if (ri.bits_per_channel != 16) {
assert(ri.bits_per_channel == 8);
result = stbi__convert_8_to_16((unsigned char *)result, *x, *y,
req_comp == 0 ? *comp : req_comp);
ri.bits_per_channel = 16;
}
// @TODO: move stbi__convert_format16 to here
// @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to
// keep more precision
if (stbi__vertically_flip_on_load) {
int channels = req_comp ? req_comp : *comp;
stbi__vertical_flip(result, *x, *y, channels * sizeof(uint16_t));
}
return (uint16_t *)result;
}
static FILE *stbi__fopen(char const *filename, char const *mode) {
return fopen(filename, mode);
}
unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp,
int req_comp) {
FILE *f = stbi__fopen(filename, "rb");
unsigned char *result;
if (!f) return stbi__errpuc("can't fopen", "Unable to open file");
result = stbi_load_from_file(f, x, y, comp, req_comp);
fclose(f);
return result;
}
unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp,
int req_comp) {
unsigned char *result;
stbi__context s;
stbi__start_file(&s, f);
result = stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp);
if (result) {
// need to 'unget' all the characters in the IO buffer
fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR);
}
return result;
}
uint16_t *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp,
int req_comp) {
uint16_t *result;
stbi__context s;
stbi__start_file(&s, f);
result = stbi__load_and_postprocess_16bit(&s, x, y, comp, req_comp);
if (result) {
// need to 'unget' all the characters in the IO buffer
fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR);
}
return result;
}
unsigned short *stbi_load_16(char const *filename, int *x, int *y, int *comp,
int req_comp) {
FILE *f = stbi__fopen(filename, "rb");
uint16_t *result;
if (!f) return stbi__errpuc("can't fopen", "Unable to open file");
result = stbi_load_from_file_16(f, x, y, comp, req_comp);
fclose(f);
return result;
}
unsigned short *stbi_load_16_from_memory(unsigned char const *buffer, int len,
int *x, int *y, int *channels_in_file,
int desired_channels) {
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file,
desired_channels);
}
unsigned short *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk,
void *user, int *x, int *y,
int *channels_in_file,
int desired_channels) {
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user);
return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file,
desired_channels);
}
unsigned char *stbi_load_from_memory(unsigned char const *buffer, int len,
int *x, int *y, int *comp, int req_comp) {
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp);
}
unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk,
void *user, int *x, int *y, int *comp,
int req_comp) {
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user);
return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp);
}
unsigned char *stbi_load_gif_from_memory(unsigned char const *buffer, int len,
int **delays, int *x, int *y, int *z,
int *comp, int req_comp) {
unsigned char *result;
stbi__context s;
stbi__start_mem(&s, buffer, len);
result =
(unsigned char *)stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp);
if (stbi__vertically_flip_on_load) {
stbi__vertical_flip_slices(result, *x, *y, *z, *comp);
}
return result;
}
enum { STBI__SCAN_load = 0, STBI__SCAN_type, STBI__SCAN_header };
static void stbi__refill_buffer(stbi__context *s) {
int n = (s->io.read)(s->io_user_data, (char *)s->buffer_start, s->buflen);
if (n == 0) {
// at end of file, treat same as if from memory, but need to handle case
// where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file
s->read_from_callbacks = 0;
s->img_buffer = s->buffer_start;
s->img_buffer_end = s->buffer_start + 1;
*s->img_buffer = 0;
} else {
s->img_buffer = s->buffer_start;
s->img_buffer_end = s->buffer_start + n;
}
}
forceinline unsigned char stbi__get8(stbi__context *s) {
if (s->img_buffer < s->img_buffer_end) return *s->img_buffer++;
if (s->read_from_callbacks) {
stbi__refill_buffer(s);
return *s->img_buffer++;
}
return 0;
}
forceinline int stbi__at_eof(stbi__context *s) {
if (s->io.read) {
if (!(s->io.eof)(s->io_user_data)) return 0;
// if feof() is true, check if buffer = end
// special case: we've only got the special 0 character at the end
if (s->read_from_callbacks == 0) return 1;
}
return s->img_buffer >= s->img_buffer_end;
}
static void stbi__skip(stbi__context *s, int n) {
if (n < 0) {
s->img_buffer = s->img_buffer_end;
return;
}
if (s->io.read) {
int blen = (int)(s->img_buffer_end - s->img_buffer);
if (blen < n) {
s->img_buffer = s->img_buffer_end;
(s->io.skip)(s->io_user_data, n - blen);
return;
}
}
s->img_buffer += n;
}
static int stbi__getn(stbi__context *s, unsigned char *buffer, int n) {
if (s->io.read) {
int blen = (int)(s->img_buffer_end - s->img_buffer);
if (blen < n) {
int res, count;
memcpy(buffer, s->img_buffer, blen);
count = (s->io.read)(s->io_user_data, (char *)buffer + blen, n - blen);
res = (count == (n - blen));
s->img_buffer = s->img_buffer_end;
return res;
}
}
if (s->img_buffer + n <= s->img_buffer_end) {
memcpy(buffer, s->img_buffer, n);
s->img_buffer += n;
return 1;
} else {
return 0;
}
}
static int stbi__get16le(stbi__context *s) {
int z = stbi__get8(s);
return z + (stbi__get8(s) << 8);
}
static int stbi__get16be(stbi__context *s) {
int z = stbi__get8(s);
return (z << 8) + stbi__get8(s);
}
static uint32_t stbi__get32be(stbi__context *s) {
uint32_t z = stbi__get16be(s);
return (z << 16) + stbi__get16be(s);
}
#define STBI__BYTECAST(x) \
((unsigned char)((x)&255)) // truncate int to byte without warnings
//////////////////////////////////////////////////////////////////////////////
//
// generic converter from built-in img_n to req_comp
// individual types do this automatically as much as possible (e.g. jpeg
// does all cases internally since it needs to colorspace convert anyway,
// and it never has alpha, so very few cases ). png can automatically
// interleave an alpha=255 channel, but falls back to this for other cases
//
// assume data buffer is malloced, so malloc a new one and free that one
// only failure mode is malloc failing
static unsigned char stbi__compute_y(int r, int g, int b) {
return (unsigned char)(((r * 77) + (g * 150) + (29 * b)) >> 8);
}
static unsigned char *stbi__convert_format(unsigned char *data, int img_n,
int req_comp, unsigned int x,
unsigned int y) {
int i, j;
unsigned char *good, *src, *dest;
if (req_comp == img_n) return data;
assert(req_comp >= 1 && req_comp <= 4);
good = stbi__malloc_mad3(req_comp, x, y, 0);
for (j = 0; j < (int)y; ++j) {
src = data + j * x * img_n;
dest = good + j * x * req_comp;
#define STBI__COMBO(a, b) ((a)*8 + (b))
#define STBI__CASE(a, b) \
case STBI__COMBO(a, b): \
for (i = x - 1; i >= 0; --i, src += a, dest += b)
// convert source image with img_n components to one with req_comp
// components; avoid switch per pixel, so use switch per scanline and
// massive macros
switch (STBI__COMBO(img_n, req_comp)) {
STBI__CASE(1, 2) {
dest[0] = src[0];
dest[1] = 255;
}
break;
STBI__CASE(1, 3) {
dest[0] = dest[1] = dest[2] = src[0];
}
break;
STBI__CASE(1, 4) {
dest[0] = dest[1] = dest[2] = src[0];
dest[3] = 255;
}
break;
STBI__CASE(2, 1) {
dest[0] = src[0];
}
break;
STBI__CASE(2, 3) {
dest[0] = dest[1] = dest[2] = src[0];
}
break;
STBI__CASE(2, 4) {
dest[0] = dest[1] = dest[2] = src[0];
dest[3] = src[1];
}
break;
STBI__CASE(3, 4) {
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
dest[3] = 255;
}
break;
STBI__CASE(3, 1) {
dest[0] = stbi__compute_y(src[0], src[1], src[2]);
}
break;
STBI__CASE(3, 2) {
dest[0] = stbi__compute_y(src[0], src[1], src[2]);
dest[1] = 255;
}
break;
STBI__CASE(4, 1) {
dest[0] = stbi__compute_y(src[0], src[1], src[2]);
}
break;
STBI__CASE(4, 2) {
dest[0] = stbi__compute_y(src[0], src[1], src[2]);
dest[1] = src[3];
}
break;
STBI__CASE(4, 3) {
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
}
break;
default:
assert(0);
}
#undef STBI__CASE
}
free(data);
return good;
}
static uint16_t stbi__compute_y_16(int r, int g, int b) {
return (uint16_t)(((r * 77) + (g * 150) + (29 * b)) >> 8);
}
static uint16_t *stbi__convert_format16(uint16_t *data, int img_n, int req_comp,
unsigned int x, unsigned int y) {
int i, j;
uint16_t *good;
if (req_comp == img_n) return data;
assert(req_comp >= 1 && req_comp <= 4);
good = xmalloc(req_comp * x * y * 2);
for (j = 0; j < (int)y; ++j) {
uint16_t *src = data + j * x * img_n;
uint16_t *dest = good + j * x * req_comp;
#define STBI__COMBO(a, b) ((a)*8 + (b))
#define STBI__CASE(a, b) \
case STBI__COMBO(a, b): \
for (i = x - 1; i >= 0; --i, src += a, dest += b)
// convert source image with img_n components to one with req_comp
// components; avoid switch per pixel, so use switch per scanline and
// massive macros
switch (STBI__COMBO(img_n, req_comp)) {
STBI__CASE(1, 2) {
dest[0] = src[0];
dest[1] = 0xffff;
}
break;
STBI__CASE(1, 3) {
dest[0] = dest[1] = dest[2] = src[0];
}
break;
STBI__CASE(1, 4) {
dest[0] = dest[1] = dest[2] = src[0];
dest[3] = 0xffff;
}
break;
STBI__CASE(2, 1) {
dest[0] = src[0];
}
break;
STBI__CASE(2, 3) {
dest[0] = dest[1] = dest[2] = src[0];
}
break;
STBI__CASE(2, 4) {
dest[0] = dest[1] = dest[2] = src[0];
dest[3] = src[1];
}
break;
STBI__CASE(3, 4) {
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
dest[3] = 0xffff;
}
break;
STBI__CASE(3, 1) {
dest[0] = stbi__compute_y_16(src[0], src[1], src[2]);
}
break;
STBI__CASE(3, 2) {
dest[0] = stbi__compute_y_16(src[0], src[1], src[2]);
dest[1] = 0xffff;
}
break;
STBI__CASE(4, 1) {
dest[0] = stbi__compute_y_16(src[0], src[1], src[2]);
}
break;
STBI__CASE(4, 2) {
dest[0] = stbi__compute_y_16(src[0], src[1], src[2]);
dest[1] = src[3];
}
break;
STBI__CASE(4, 3) {
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
}
break;
default:
assert(0);
}
#undef STBI__CASE
}
free(data);
return good;
}
//////////////////////////////////////////////////////////////////////////////
//
// "baseline" JPEG/JFIF decoder
//
// simple implementation
// - doesn't support delayed output of y-dimension
// - simple interface (only one output format: 8-bit interleaved RGB)
// - doesn't try to recover corrupt jpegs
// - doesn't allow partial loading, loading multiple at once
// - still fast on x86 (copying globals into locals doesn't help x86)
// - allocates lots of intermediate memory (full size of all components)
// - non-interleaved case requires this anyway
// - allows good upsampling (see next)
// high-quality
// - upsampled channels are bilinearly interpolated, even across blocks
// - quality integer IDCT derived from IJG's 'slow'
// performance
// - fast huffman; reasonable integer IDCT
// - some SIMD kernels for common paths on targets with SSE2/NEON
// - uses a lot of intermediate memory, could cache poorly
// huffman decoding acceleration
#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
typedef struct {
unsigned char fast[1 << FAST_BITS];
// weirdly, repacking this into AoS is a 10% speed loss, instead of a win
uint16_t code[256];
unsigned char values[256];
unsigned char size[257];
unsigned int maxcode[18];
int delta[17]; // old 'firstsymbol' - old 'firstcode'
} stbi__huffman;
typedef struct {
stbi__context *s;
stbi__huffman huff_dc[4];
stbi__huffman huff_ac[4];
uint16_t dequant[4][64];
int16_t fast_ac[4][1 << FAST_BITS];
// sizes for components, interleaved MCUs
int img_h_max, img_v_max;
int img_mcu_x, img_mcu_y;
int img_mcu_w, img_mcu_h;
// definition of jpeg image component
struct {
int id;
int h, v;
int tq;
int hd, ha;
int dc_pred;
int x, y, w2, h2;
unsigned char *data;
unsigned char *linebuf;
short *coeff; // progressive only
int coeff_w, coeff_h; // number of 8x8 coefficient blocks
} img_comp[4];
uint32_t code_buffer; // jpeg entropy-coded buffer
int code_bits; // number of valid bits
unsigned char marker; // marker seen while filling entropy buffer
int nomore; // flag if we saw a marker so must stop
int progressive;
int spec_start;
int spec_end;
int succ_high;
int succ_low;
int eob_run;
int jfif;
int app14_color_transform; // Adobe APP14 tag
int rgb;
int scan_n, order[4];
int restart_interval, todo;
// kernels
unsigned char *(*resample_row_hv_2_kernel)(unsigned char *out,
unsigned char *in_near,
unsigned char *in_far, int w,
int hs);
} stbi__jpeg;
static int stbi__build_huffman(stbi__huffman *h, int *count) {
int i, j, k = 0;
unsigned int code;
// build size list for each symbol (from JPEG spec)
for (i = 0; i < 16; ++i)
for (j = 0; j < count[i]; ++j) h->size[k++] = (unsigned char)(i + 1);
h->size[k] = 0;
// compute actual symbols (from jpeg spec)
code = 0;
k = 0;
for (j = 1; j <= 16; ++j) {
// compute delta to add to code to compute symbol id
h->delta[j] = k - code;
if (h->size[k] == j) {
while (h->size[k] == j) h->code[k++] = (uint16_t)(code++);
if (code - 1 >= (1u << j)) {
return stbi__err("bad code lengths", "Corrupt JPEG");
}
}
// compute largest code + 1 for this size, preshifted as needed later
h->maxcode[j] = code << (16 - j);
code <<= 1;
}
h->maxcode[j] = 0xffffffff;
// build non-spec acceleration table; 255 is flag for not-accelerated
memset(h->fast, 255, 1 << FAST_BITS);
for (i = 0; i < k; ++i) {
int s = h->size[i];
if (s <= FAST_BITS) {
int c = h->code[i] << (FAST_BITS - s);
int m = 1 << (FAST_BITS - s);
for (j = 0; j < m; ++j) {
h->fast[c + j] = (unsigned char)i;
}
}
}
return 1;
}
// build a table that decodes both magnitude and value of small ACs in
// one go.
static void stbi__build_fast_ac(int16_t *fast_ac, stbi__huffman *h) {
int i;
for (i = 0; i < (1 << FAST_BITS); ++i) {
unsigned char fast = h->fast[i];
fast_ac[i] = 0;
if (fast < 255) {
int rs = h->values[fast];
int run = (rs >> 4) & 15;
int magbits = rs & 15;
int len = h->size[fast];
if (magbits && len + magbits <= FAST_BITS) {
// magnitude code followed by receive_extend code
int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits);
int m = 1 << (magbits - 1);
if (k < m) k += (~0U << magbits) + 1;
// if the result is small enough, we can fit it in fast_ac table
if (k >= -128 && k <= 127)
fast_ac[i] = (int16_t)((k * 256) + (run * 16) + (len + magbits));
}
}
}
}
static void stbi__grow_buffer_unsafe(stbi__jpeg *j) {
do {
unsigned b = j->nomore ? 0 : stbi__get8(j->s);
if (b == 0xff) {
int c = stbi__get8(j->s);
while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes
if (c != 0) {
j->marker = (unsigned char)c;
j->nomore = 1;
return;
}
}
j->code_buffer |= b << (24 - j->code_bits);
j->code_bits += 8;
} while (j->code_bits <= 24);
}
// (1 << n) - 1
static const uint32_t stbi__bmask[17] = {0, 1, 3, 7, 15, 31,
63, 127, 255, 511, 1023, 2047,
4095, 8191, 16383, 32767, 65535};
// decode a jpeg huffman value from the bitstream
forceinline int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) {
unsigned int temp;
int c, k;
if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
// look at the top FAST_BITS and determine what symbol ID it is,
// if the code is <= FAST_BITS
c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1);
k = h->fast[c];
if (k < 255) {
int s = h->size[k];
if (s > j->code_bits) return -1;
j->code_buffer <<= s;
j->code_bits -= s;
return h->values[k];
}
// naive test is to shift the code_buffer down so k bits are
// valid, then test against maxcode. To speed this up, we've
// preshifted maxcode left so that it has (16-k) 0s at the
// end; in other words, regardless of the number of bits, it
// wants to be compared against something shifted to have 16;
// that way we don't need to shift inside the loop.
temp = j->code_buffer >> 16;
for (k = FAST_BITS + 1;; ++k)
if (temp < h->maxcode[k]) break;
if (k == 17) {
// error! code not found
j->code_bits -= 16;
return -1;
}
if (k > j->code_bits) return -1;
// convert the huffman code to the symbol id
c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];
assert((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) ==
h->code[c]);
// convert the id to a symbol
j->code_bits -= k;
j->code_buffer <<= k;
return h->values[c];
}
// bias[n] = (-1<<n) + 1
static const int stbi__jbias[16] = {0, -1, -3, -7, -15, -31,
-63, -127, -255, -511, -1023, -2047,
-4095, -8191, -16383, -32767};
// combined JPEG 'receive' and JPEG 'extend', since baseline
// always extends everything it receives.
forceinline int stbi__extend_receive(stbi__jpeg *j, int n) {
int sgn;
unsigned int k;
// TODO(jart): what is this
if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
sgn = (int32_t)j->code_buffer >> 31; // sign bit is always in MSB
k = ROL(j->code_buffer, n);
assert(n >= 0 && n < (int)(sizeof(stbi__bmask) / sizeof(*stbi__bmask)));
j->code_buffer = k & ~stbi__bmask[n];
k &= stbi__bmask[n];
j->code_bits -= n;
return k + (stbi__jbias[n] & ~sgn);
}
// get some unsigned bits
forceinline int stbi__jpeg_get_bits(stbi__jpeg *j, int n) {
unsigned int k;
if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
k = ROL(j->code_buffer, n);
j->code_buffer = k & ~stbi__bmask[n];
k &= stbi__bmask[n];
j->code_bits -= n;
return k;
}
forceinline int stbi__jpeg_get_bit(stbi__jpeg *j) {
unsigned int k;
if (j->code_bits < 1) stbi__grow_buffer_unsafe(j);
k = j->code_buffer;
j->code_buffer <<= 1;
--j->code_bits;
return k & 0x80000000;
}
// given a value that's at position X in the zigzag stream,
// where does it appear in the 8x8 matrix coded as row-major?
static const unsigned char stbi__jpeg_dezigzag[64 + 15] = {
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40,
48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61,
54, 47, 55, 62, 63,
// let corrupt input sample past end
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63};
// decode one 64-entry block
static optimizespeed int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64],
stbi__huffman *hdc,
stbi__huffman *hac,
int16_t *fac, int b,
uint16_t *dequant) {
unsigned int zig;
int diff, dc, k, t, c, r, s, rs;
if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
t = stbi__jpeg_huff_decode(j, hdc);
if (t < 0) return stbi__err("bad huffman code", "Corrupt JPEG");
// 0 all the ac values now so we can do it 32-bits at a time
bzero(data, 64 * sizeof(data[0]));
diff = t ? stbi__extend_receive(j, t) : 0;
dc = j->img_comp[b].dc_pred + diff;
j->img_comp[b].dc_pred = dc;
data[0] = (short)(dc * dequant[0]);
// decode AC components, see JPEG spec
k = 1;
do {
if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1);
r = fac[c];
if (r) { // fast-AC path
k += (r >> 4) & 15; // run
s = r & 15; // combined length
j->code_buffer <<= s;
j->code_bits -= s;
// decode into unzigzag'd location
zig = stbi__jpeg_dezigzag[k++];
data[zig] = (short)((r >> 8) * dequant[zig]);
} else {
rs = stbi__jpeg_huff_decode(j, hac);
if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0) {
if (rs != 0xf0) break; // end block
k += 16;
} else {
k += r;
// decode into unzigzag'd location
zig = stbi__jpeg_dezigzag[k++];
data[zig] = (short)(stbi__extend_receive(j, s) * dequant[zig]);
}
}
} while (k < 64);
return 1;
}
static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64],
stbi__huffman *hdc, int b) {
int t;
short s;
int diff, dc;
if (j->spec_end != 0) {
return stbi__err("can't merge dc and ac", "Corrupt JPEG");
}
if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
if (j->succ_high == 0) {
// first scan for DC coefficient, must be first
bzero(data, 64 * sizeof(data[0])); // 0 all the ac values now
t = stbi__jpeg_huff_decode(j, hdc);
diff = t ? stbi__extend_receive(j, t) : 0;
dc = j->img_comp[b].dc_pred + diff;
j->img_comp[b].dc_pred = dc;
s = dc;
s *= 1u << j->succ_low;
data[0] = s; /* (short)(dc << j->succ_low); */
} else {
// refinement scan for DC coefficient
if (stbi__jpeg_get_bit(j)) data[0] += (short)(1 << j->succ_low);
}
return 1;
}
// @OPTIMIZE: store non-zigzagged during the decode passes,
// and only de-zigzag when dequantizing
static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64],
stbi__huffman *hac, int16_t *fac) {
short bit;
unsigned zig;
int k, c, r, s, rs, shift;
if (j->spec_start == 0) {
return stbi__err("can't merge dc and ac", "Corrupt JPEG");
}
if (j->succ_high == 0) {
shift = j->succ_low;
if (j->eob_run) {
--j->eob_run;
return 1;
}
k = j->spec_start;
do {
if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1);
r = fac[c];
if (r) { // fast-AC path
k += (r >> 4) & 15; // run
s = r & 15; // combined length
j->code_buffer <<= s;
j->code_bits -= s;
zig = stbi__jpeg_dezigzag[k++];
data[zig] = (r / 256) * (1u << shift);
} else {
rs = stbi__jpeg_huff_decode(j, hac);
if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0) {
if (r < 15) {
j->eob_run = (1 << r);
if (r) j->eob_run += stbi__jpeg_get_bits(j, r);
--j->eob_run;
break;
}
k += 16;
} else {
k += r;
zig = stbi__jpeg_dezigzag[k++];
data[zig] = stbi__extend_receive(j, s) * (1u << shift);
}
}
} while (k <= j->spec_end);
} else {
// refinement scan for these AC coefficients
bit = (short)(1 << j->succ_low);
if (j->eob_run) {
--j->eob_run;
for (k = j->spec_start; k <= j->spec_end; ++k) {
short *p = &data[stbi__jpeg_dezigzag[k]];
if (*p != 0)
if (stbi__jpeg_get_bit(j))
if ((*p & bit) == 0) {
if (*p > 0)
*p += bit;
else
*p -= bit;
}
}
} else {
k = j->spec_start;
do {
rs = stbi__jpeg_huff_decode(j, hac);
if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0) {
if (r < 15) {
j->eob_run = (1 << r) - 1;
if (r) j->eob_run += stbi__jpeg_get_bits(j, r);
r = 64; // force end of block
} else {
// r=15 s=0 should write 16 0s, so we just do
// a run of 15 0s and then write s (which is 0),
// so we don't have to do anything special here
}
} else {
if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG");
// sign bit
if (stbi__jpeg_get_bit(j)) {
s = bit;
} else {
s = -bit;
}
}
// advance by r
while (k <= j->spec_end) {
short *p = &data[stbi__jpeg_dezigzag[k++]];
if (*p != 0) {
if (stbi__jpeg_get_bit(j))
if ((*p & bit) == 0) {
if (*p > 0)
*p += bit;
else
*p -= bit;
}
} else {
if (r == 0) {
*p = (short)s;
break;
}
--r;
}
}
} while (k <= j->spec_end);
}
}
return 1;
}
// take a -128..127 value and stbi__clamp it and convert to 0..255
forceinline unsigned char stbi__clamp(int x) {
// trick to use a single test to catch both cases
if ((unsigned int)x > 255) {
if (x < 0) return 0;
if (x > 255) return 255;
}
return (unsigned char)x;
}
#define stbi__f2f(x) ((int)(((x)*4096 + 0.5)))
#define stbi__fsh(x) ((x)*4096)
// derived from jidctint -- DCT_ISLOW
#define STBI__IDCT_1D(s0, s1, s2, s3, s4, s5, s6, s7) \
int t0, t1, t2, t3, p1, p2, p3, p4, p5, x0, x1, x2, x3; \
p2 = s2; \
p3 = s6; \
p1 = (p2 + p3) * stbi__f2f(0.5411961f); \
t2 = p1 + p3 * stbi__f2f(-1.847759065f); \
t3 = p1 + p2 * stbi__f2f(0.765366865f); \
p2 = s0; \
p3 = s4; \
t0 = stbi__fsh(p2 + p3); \
t1 = stbi__fsh(p2 - p3); \
x0 = t0 + t3; \
x3 = t0 - t3; \
x1 = t1 + t2; \
x2 = t1 - t2; \
t0 = s7; \
t1 = s5; \
t2 = s3; \
t3 = s1; \
p3 = t0 + t2; \
p4 = t1 + t3; \
p1 = t0 + t3; \
p2 = t1 + t2; \
p5 = (p3 + p4) * stbi__f2f(1.175875602f); \
t0 = t0 * stbi__f2f(0.298631336f); \
t1 = t1 * stbi__f2f(2.053119869f); \
t2 = t2 * stbi__f2f(3.072711026f); \
t3 = t3 * stbi__f2f(1.501321110f); \
p1 = p5 + p1 * stbi__f2f(-0.899976223f); \
p2 = p5 + p2 * stbi__f2f(-2.562915447f); \
p3 = p3 * stbi__f2f(-1.961570560f); \
p4 = p4 * stbi__f2f(-0.390180644f); \
t3 += p1 + p4; \
t2 += p2 + p3; \
t1 += p2 + p4; \
t0 += p1 + p3;
static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) {
int i, val[64], *v = val;
stbi_uc *o;
short *d = data;
// columns
for (i = 0; i < 8; ++i, ++d, ++v) {
// if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
if (d[8] == 0 && d[16] == 0 && d[24] == 0 && d[32] == 0 && d[40] == 0 &&
d[48] == 0 && d[56] == 0) {
// no shortcut 0 seconds
// (1|2|3|4|5|6|7)==0 0 seconds
// all separate -0.047 seconds
// 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
int dcterm = d[0] * 4;
v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
} else {
STBI__IDCT_1D(d[0], d[8], d[16], d[24], d[32], d[40], d[48], d[56])
// constants scaled things up by 1<<12; let's bring them back
// down, but keep 2 extra bits of precision
x0 += 512;
x1 += 512;
x2 += 512;
x3 += 512;
v[0] = (x0 + t3) >> 10;
v[56] = (x0 - t3) >> 10;
v[8] = (x1 + t2) >> 10;
v[48] = (x1 - t2) >> 10;
v[16] = (x2 + t1) >> 10;
v[40] = (x2 - t1) >> 10;
v[24] = (x3 + t0) >> 10;
v[32] = (x3 - t0) >> 10;
}
}
for (i = 0, v = val, o = out; i < 8; ++i, v += 8, o += out_stride) {
// no fast case since the first 1D IDCT spread components out
STBI__IDCT_1D(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7])
// constants scaled things up by 1<<12, plus we had 1<<2 from first
// loop, plus horizontal and vertical each scale by sqrt(8) so together
// we've got an extra 1<<3, so 1<<17 total we need to remove.
// so we want to round that, which means adding 0.5 * 1<<17,
// aka 65536. Also, we'll end up with -128 to 127 that we want
// to encode as 0..255 by adding 128, so we'll add that before the shift
x0 += 65536 + (128 << 17);
x1 += 65536 + (128 << 17);
x2 += 65536 + (128 << 17);
x3 += 65536 + (128 << 17);
// tried computing the shifts into temps, or'ing the temps to see
// if any were out of range, but that was slower
o[0] = stbi__clamp((x0 + t3) >> 17);
o[7] = stbi__clamp((x0 - t3) >> 17);
o[1] = stbi__clamp((x1 + t2) >> 17);
o[6] = stbi__clamp((x1 - t2) >> 17);
o[2] = stbi__clamp((x2 + t1) >> 17);
o[5] = stbi__clamp((x2 - t1) >> 17);
o[3] = stbi__clamp((x3 + t0) >> 17);
o[4] = stbi__clamp((x3 - t0) >> 17);
}
}
#ifdef STBI_SSE2
// sse2 integer IDCT. not the fastest possible implementation but it
// produces bit-identical results to the generic C version so it's
// fully "transparent".
static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) {
// This is constructed to match our regular (generic) integer IDCT exactly.
__m128i row0, row1, row2, row3, row4, row5, row6, row7;
__m128i tmp;
// dot product constant: even elems=x, odd elems=y
#define dct_const(x, y) _mm_setr_epi16((x), (y), (x), (y), (x), (y), (x), (y))
// out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit)
// out(1) = c1[even]*x + c1[odd]*y
#define dct_rot(out0, out1, x, y, c0, c1) \
__m128i c0##lo = _mm_unpacklo_epi16((x), (y)); \
__m128i c0##hi = _mm_unpackhi_epi16((x), (y)); \
__m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \
__m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \
__m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \
__m128i out1##_h = _mm_madd_epi16(c0##hi, c1)
// out = in << 12 (in 16-bit, out 32-bit)
#define dct_widen(out, in) \
__m128i out##_l = \
_mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \
__m128i out##_h = \
_mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4)
// wide add
#define dct_wadd(out, a, b) \
__m128i out##_l = _mm_add_epi32(a##_l, b##_l); \
__m128i out##_h = _mm_add_epi32(a##_h, b##_h)
// wide sub
#define dct_wsub(out, a, b) \
__m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \
__m128i out##_h = _mm_sub_epi32(a##_h, b##_h)
// butterfly a/b, add bias, then shift by "s" and pack
#define dct_bfly32o(out0, out1, a, b, bias, s) \
{ \
__m128i abiased_l = _mm_add_epi32(a##_l, bias); \
__m128i abiased_h = _mm_add_epi32(a##_h, bias); \
dct_wadd(sum, abiased, b); \
dct_wsub(dif, abiased, b); \
out0 = \
_mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \
out1 = \
_mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \
}
// 8-bit interleave step (for transposes)
#define dct_interleave8(a, b) \
tmp = a; \
a = _mm_unpacklo_epi8(a, b); \
b = _mm_unpackhi_epi8(tmp, b)
// 16-bit interleave step (for transposes)
#define dct_interleave16(a, b) \
tmp = a; \
a = _mm_unpacklo_epi16(a, b); \
b = _mm_unpackhi_epi16(tmp, b)
#define dct_pass(bias, shift) \
{ \
/* even part */ \
dct_rot(t2e, t3e, row2, row6, rot0_0, rot0_1); \
__m128i sum04 = _mm_add_epi16(row0, row4); \
__m128i dif04 = _mm_sub_epi16(row0, row4); \
dct_widen(t0e, sum04); \
dct_widen(t1e, dif04); \
dct_wadd(x0, t0e, t3e); \
dct_wsub(x3, t0e, t3e); \
dct_wadd(x1, t1e, t2e); \
dct_wsub(x2, t1e, t2e); \
/* odd part */ \
dct_rot(y0o, y2o, row7, row3, rot2_0, rot2_1); \
dct_rot(y1o, y3o, row5, row1, rot3_0, rot3_1); \
__m128i sum17 = _mm_add_epi16(row1, row7); \
__m128i sum35 = _mm_add_epi16(row3, row5); \
dct_rot(y4o, y5o, sum17, sum35, rot1_0, rot1_1); \
dct_wadd(x4, y0o, y4o); \
dct_wadd(x5, y1o, y5o); \
dct_wadd(x6, y2o, y5o); \
dct_wadd(x7, y3o, y4o); \
dct_bfly32o(row0, row7, x0, x7, bias, shift); \
dct_bfly32o(row1, row6, x1, x6, bias, shift); \
dct_bfly32o(row2, row5, x2, x5, bias, shift); \
dct_bfly32o(row3, row4, x3, x4, bias, shift); \
}
__m128i rot0_0 = dct_const(stbi__f2f(0.5411961f),
stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f));
__m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f(0.765366865f),
stbi__f2f(0.5411961f));
__m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f),
stbi__f2f(1.175875602f));
__m128i rot1_1 =
dct_const(stbi__f2f(1.175875602f),
stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f));
__m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f),
stbi__f2f(-1.961570560f));
__m128i rot2_1 =
dct_const(stbi__f2f(-1.961570560f),
stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f));
__m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f),
stbi__f2f(-0.390180644f));
__m128i rot3_1 =
dct_const(stbi__f2f(-0.390180644f),
stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f));
// rounding biases in column/row passes, see stbi__idct_block for explanation.
__m128i bias_0 = _mm_set1_epi32(512);
__m128i bias_1 = _mm_set1_epi32(65536 + (128 << 17));
// load
row0 = _mm_load_si128((const __m128i *)(data + 0 * 8));
row1 = _mm_load_si128((const __m128i *)(data + 1 * 8));
row2 = _mm_load_si128((const __m128i *)(data + 2 * 8));
row3 = _mm_load_si128((const __m128i *)(data + 3 * 8));
row4 = _mm_load_si128((const __m128i *)(data + 4 * 8));
row5 = _mm_load_si128((const __m128i *)(data + 5 * 8));
row6 = _mm_load_si128((const __m128i *)(data + 6 * 8));
row7 = _mm_load_si128((const __m128i *)(data + 7 * 8));
// column pass
dct_pass(bias_0, 10);
{
// 16bit 8x8 transpose pass 1
dct_interleave16(row0, row4);
dct_interleave16(row1, row5);
dct_interleave16(row2, row6);
dct_interleave16(row3, row7);
// transpose pass 2
dct_interleave16(row0, row2);
dct_interleave16(row1, row3);
dct_interleave16(row4, row6);
dct_interleave16(row5, row7);
// transpose pass 3
dct_interleave16(row0, row1);
dct_interleave16(row2, row3);
dct_interleave16(row4, row5);
dct_interleave16(row6, row7);
}
// row pass
dct_pass(bias_1, 17);
{
// pack
__m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7
__m128i p1 = _mm_packus_epi16(row2, row3);
__m128i p2 = _mm_packus_epi16(row4, row5);
__m128i p3 = _mm_packus_epi16(row6, row7);
// 8bit 8x8 transpose pass 1
dct_interleave8(p0, p2); // a0e0a1e1...
dct_interleave8(p1, p3); // c0g0c1g1...
// transpose pass 2
dct_interleave8(p0, p1); // a0c0e0g0...
dct_interleave8(p2, p3); // b0d0f0h0...
// transpose pass 3
dct_interleave8(p0, p2); // a0b0c0d0...
dct_interleave8(p1, p3); // a4b4c4d4...
// store
_mm_storel_epi64((__m128i *)out, p0);
out += out_stride;
_mm_storel_epi64((__m128i *)out, _mm_shuffle_epi32(p0, 0x4e));
out += out_stride;
_mm_storel_epi64((__m128i *)out, p2);
out += out_stride;
_mm_storel_epi64((__m128i *)out, _mm_shuffle_epi32(p2, 0x4e));
out += out_stride;
_mm_storel_epi64((__m128i *)out, p1);
out += out_stride;
_mm_storel_epi64((__m128i *)out, _mm_shuffle_epi32(p1, 0x4e));
out += out_stride;
_mm_storel_epi64((__m128i *)out, p3);
out += out_stride;
_mm_storel_epi64((__m128i *)out, _mm_shuffle_epi32(p3, 0x4e));
}
#undef dct_const
#undef dct_rot
#undef dct_widen
#undef dct_wadd
#undef dct_wsub
#undef dct_bfly32o
#undef dct_interleave8
#undef dct_interleave16
#undef dct_pass
}
#endif // STBI_SSE2
#ifdef STBI_NEON
// NEON integer IDCT. should produce bit-identical
// results to the generic C version.
static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) {
int16x8_t row0, row1, row2, row3, row4, row5, row6, row7;
int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f));
int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f));
int16x4_t rot0_2 = vdup_n_s16(stbi__f2f(0.765366865f));
int16x4_t rot1_0 = vdup_n_s16(stbi__f2f(1.175875602f));
int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f));
int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f));
int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f));
int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f));
int16x4_t rot3_0 = vdup_n_s16(stbi__f2f(0.298631336f));
int16x4_t rot3_1 = vdup_n_s16(stbi__f2f(2.053119869f));
int16x4_t rot3_2 = vdup_n_s16(stbi__f2f(3.072711026f));
int16x4_t rot3_3 = vdup_n_s16(stbi__f2f(1.501321110f));
#define dct_long_mul(out, inq, coeff) \
int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \
int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff)
#define dct_long_mac(out, acc, inq, coeff) \
int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \
int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff)
#define dct_widen(out, inq) \
int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \
int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12)
// wide add
#define dct_wadd(out, a, b) \
int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \
int32x4_t out##_h = vaddq_s32(a##_h, b##_h)
// wide sub
#define dct_wsub(out, a, b) \
int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \
int32x4_t out##_h = vsubq_s32(a##_h, b##_h)
// butterfly a/b, then shift using "shiftop" by "s" and pack
#define dct_bfly32o(out0, out1, a, b, shiftop, s) \
{ \
dct_wadd(sum, a, b); \
dct_wsub(dif, a, b); \
out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \
out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \
}
#define dct_pass(shiftop, shift) \
{ \
/* even part */ \
int16x8_t sum26 = vaddq_s16(row2, row6); \
dct_long_mul(p1e, sum26, rot0_0); \
dct_long_mac(t2e, p1e, row6, rot0_1); \
dct_long_mac(t3e, p1e, row2, rot0_2); \
int16x8_t sum04 = vaddq_s16(row0, row4); \
int16x8_t dif04 = vsubq_s16(row0, row4); \
dct_widen(t0e, sum04); \
dct_widen(t1e, dif04); \
dct_wadd(x0, t0e, t3e); \
dct_wsub(x3, t0e, t3e); \
dct_wadd(x1, t1e, t2e); \
dct_wsub(x2, t1e, t2e); \
/* odd part */ \
int16x8_t sum15 = vaddq_s16(row1, row5); \
int16x8_t sum17 = vaddq_s16(row1, row7); \
int16x8_t sum35 = vaddq_s16(row3, row5); \
int16x8_t sum37 = vaddq_s16(row3, row7); \
int16x8_t sumodd = vaddq_s16(sum17, sum35); \
dct_long_mul(p5o, sumodd, rot1_0); \
dct_long_mac(p1o, p5o, sum17, rot1_1); \
dct_long_mac(p2o, p5o, sum35, rot1_2); \
dct_long_mul(p3o, sum37, rot2_0); \
dct_long_mul(p4o, sum15, rot2_1); \
dct_wadd(sump13o, p1o, p3o); \
dct_wadd(sump24o, p2o, p4o); \
dct_wadd(sump23o, p2o, p3o); \
dct_wadd(sump14o, p1o, p4o); \
dct_long_mac(x4, sump13o, row7, rot3_0); \
dct_long_mac(x5, sump24o, row5, rot3_1); \
dct_long_mac(x6, sump23o, row3, rot3_2); \
dct_long_mac(x7, sump14o, row1, rot3_3); \
dct_bfly32o(row0, row7, x0, x7, shiftop, shift); \
dct_bfly32o(row1, row6, x1, x6, shiftop, shift); \
dct_bfly32o(row2, row5, x2, x5, shiftop, shift); \
dct_bfly32o(row3, row4, x3, x4, shiftop, shift); \
}
// load
row0 = vld1q_s16(data + 0 * 8);
row1 = vld1q_s16(data + 1 * 8);
row2 = vld1q_s16(data + 2 * 8);
row3 = vld1q_s16(data + 3 * 8);
row4 = vld1q_s16(data + 4 * 8);
row5 = vld1q_s16(data + 5 * 8);
row6 = vld1q_s16(data + 6 * 8);
row7 = vld1q_s16(data + 7 * 8);
// add DC bias
row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0));
// column pass
dct_pass(vrshrn_n_s32, 10);
// 16bit 8x8 transpose
{
// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively.
// whether compilers actually get this is another story, sadly.
#define dct_trn16(x, y) \
{ \
int16x8x2_t t = vtrnq_s16(x, y); \
x = t.val[0]; \
y = t.val[1]; \
}
#define dct_trn32(x, y) \
{ \
int32x4x2_t t = \
vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); \
x = vreinterpretq_s16_s32(t.val[0]); \
y = vreinterpretq_s16_s32(t.val[1]); \
}
#define dct_trn64(x, y) \
{ \
int16x8_t x0 = x; \
int16x8_t y0 = y; \
x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); \
y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); \
}
// pass 1
dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6
dct_trn16(row2, row3);
dct_trn16(row4, row5);
dct_trn16(row6, row7);
// pass 2
dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4
dct_trn32(row1, row3);
dct_trn32(row4, row6);
dct_trn32(row5, row7);
// pass 3
dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0
dct_trn64(row1, row5);
dct_trn64(row2, row6);
dct_trn64(row3, row7);
#undef dct_trn16
#undef dct_trn32
#undef dct_trn64
}
// row pass
// vrshrn_n_s32 only supports shifts up to 16, we need
// 17. so do a non-rounding shift of 16 first then follow
// up with a rounding shift by 1.
dct_pass(vshrn_n_s32, 16);
{
// pack and round
uint8x8_t p0 = vqrshrun_n_s16(row0, 1);
uint8x8_t p1 = vqrshrun_n_s16(row1, 1);
uint8x8_t p2 = vqrshrun_n_s16(row2, 1);
uint8x8_t p3 = vqrshrun_n_s16(row3, 1);
uint8x8_t p4 = vqrshrun_n_s16(row4, 1);
uint8x8_t p5 = vqrshrun_n_s16(row5, 1);
uint8x8_t p6 = vqrshrun_n_s16(row6, 1);
uint8x8_t p7 = vqrshrun_n_s16(row7, 1);
// again, these can translate into one instruction, but often don't.
#define dct_trn8_8(x, y) \
{ \
uint8x8x2_t t = vtrn_u8(x, y); \
x = t.val[0]; \
y = t.val[1]; \
}
#define dct_trn8_16(x, y) \
{ \
uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); \
x = vreinterpret_u8_u16(t.val[0]); \
y = vreinterpret_u8_u16(t.val[1]); \
}
#define dct_trn8_32(x, y) \
{ \
uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); \
x = vreinterpret_u8_u32(t.val[0]); \
y = vreinterpret_u8_u32(t.val[1]); \
}
// sadly can't use interleaved stores here since we only write
// 8 bytes to each scan line!
// 8x8 8-bit transpose pass 1
dct_trn8_8(p0, p1);
dct_trn8_8(p2, p3);
dct_trn8_8(p4, p5);
dct_trn8_8(p6, p7);
// pass 2
dct_trn8_16(p0, p2);
dct_trn8_16(p1, p3);
dct_trn8_16(p4, p6);
dct_trn8_16(p5, p7);
// pass 3
dct_trn8_32(p0, p4);
dct_trn8_32(p1, p5);
dct_trn8_32(p2, p6);
dct_trn8_32(p3, p7);
// store
vst1_u8(out, p0);
out += out_stride;
vst1_u8(out, p1);
out += out_stride;
vst1_u8(out, p2);
out += out_stride;
vst1_u8(out, p3);
out += out_stride;
vst1_u8(out, p4);
out += out_stride;
vst1_u8(out, p5);
out += out_stride;
vst1_u8(out, p6);
out += out_stride;
vst1_u8(out, p7);
#undef dct_trn8_8
#undef dct_trn8_16
#undef dct_trn8_32
}
#undef dct_long_mul
#undef dct_long_mac
#undef dct_widen
#undef dct_wadd
#undef dct_wsub
#undef dct_bfly32o
#undef dct_pass
}
#endif // STBI_NEON
#define STBI__MARKER_none 0xff
// if there's a pending marker from the entropy stream, return that
// otherwise, fetch from the stream and get a marker. if there's no
// marker, return 0xff, which is never a valid marker value
static unsigned char stbi__get_marker(stbi__jpeg *j) {
unsigned char x;
if (j->marker != STBI__MARKER_none) {
x = j->marker;
j->marker = STBI__MARKER_none;
return x;
}
x = stbi__get8(j->s);
if (x != 0xff) return STBI__MARKER_none;
while (x == 0xff) x = stbi__get8(j->s); // consume repeated 0xff fill bytes
return x;
}
// in each scan, we'll have scan_n components, and the order
// of the components is specified by order[]
#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
// after a restart interval, stbi__jpeg_reset the entropy decoder and
// the dc prediction
static void stbi__jpeg_reset(stbi__jpeg *j) {
j->code_bits = 0;
j->code_buffer = 0;
j->nomore = 0;
j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred =
j->img_comp[3].dc_pred = 0;
j->marker = STBI__MARKER_none;
j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
j->eob_run = 0;
// no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
// since we don't even allow 1<<30 pixels
}
static int stbi__parse_entropy_coded_data(stbi__jpeg *z) {
stbi__jpeg_reset(z);
if (!z->progressive) {
if (z->scan_n == 1) {
int i, j;
short data[64] forcealign(16);
int n = z->order[0];
// non-interleaved data, we just need to process one block at a time,
// in trivial scanline order
// number of blocks to do just depends on how many actual "pixels" this
// component has, independent of interleaved MCU blocking and such
int w = (z->img_comp[n].x + 7) >> 3;
int h = (z->img_comp[n].y + 7) >> 3;
for (j = 0; j < h; ++j) {
for (i = 0; i < w; ++i) {
int ha = z->img_comp[n].ha;
if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd,
z->huff_ac + ha, z->fast_ac[ha], n,
z->dequant[z->img_comp[n].tq]))
return 0;
idct_block_kernel(
z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8,
z->img_comp[n].w2, data);
// every data block is an MCU, so countdown the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
// if it's NOT a restart, then just bail, so we get corrupt data
// rather than no data
if (!STBI__RESTART(z->marker)) return 1;
stbi__jpeg_reset(z);
}
}
}
return 1;
} else { // interleaved
int i, j, k, x, y;
short data[64] forcealign(16);
for (j = 0; j < z->img_mcu_y; ++j) {
for (i = 0; i < z->img_mcu_x; ++i) {
// scan an interleaved mcu... process scan_n components in order
for (k = 0; k < z->scan_n; ++k) {
int n = z->order[k];
// scan out an mcu's worth of this component; that's just determined
// by the basic H and V specified for the component
for (y = 0; y < z->img_comp[n].v; ++y) {
for (x = 0; x < z->img_comp[n].h; ++x) {
int x2 = (i * z->img_comp[n].h + x) * 8;
int y2 = (j * z->img_comp[n].v + y) * 8;
int ha = z->img_comp[n].ha;
if (!stbi__jpeg_decode_block(z, data,
z->huff_dc + z->img_comp[n].hd,
z->huff_ac + ha, z->fast_ac[ha], n,
z->dequant[z->img_comp[n].tq]))
return 0;
idct_block_kernel(
z->img_comp[n].data + z->img_comp[n].w2 * y2 + x2,
z->img_comp[n].w2, data);
}
}
}
// after all interleaved components, that's an interleaved MCU,
// so now count down the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
if (!STBI__RESTART(z->marker)) return 1;
stbi__jpeg_reset(z);
}
}
}
return 1;
}
} else {
if (z->scan_n == 1) {
int i, j;
int n = z->order[0];
// non-interleaved data, we just need to process one block at a time,
// in trivial scanline order
// number of blocks to do just depends on how many actual "pixels" this
// component has, independent of interleaved MCU blocking and such
int w = (z->img_comp[n].x + 7) >> 3;
int h = (z->img_comp[n].y + 7) >> 3;
for (j = 0; j < h; ++j) {
for (i = 0; i < w; ++i) {
short *data =
z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
if (z->spec_start == 0) {
if (!stbi__jpeg_decode_block_prog_dc(
z, data, &z->huff_dc[z->img_comp[n].hd], n))
return 0;
} else {
int ha = z->img_comp[n].ha;
if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha],
z->fast_ac[ha]))
return 0;
}
// every data block is an MCU, so countdown the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
if (!STBI__RESTART(z->marker)) return 1;
stbi__jpeg_reset(z);
}
}
}
return 1;
} else { // interleaved
int i, j, k, x, y;
for (j = 0; j < z->img_mcu_y; ++j) {
for (i = 0; i < z->img_mcu_x; ++i) {
// scan an interleaved mcu... process scan_n components in order
for (k = 0; k < z->scan_n; ++k) {
int n = z->order[k];
// scan out an mcu's worth of this component; that's just determined
// by the basic H and V specified for the component
for (y = 0; y < z->img_comp[n].v; ++y) {
for (x = 0; x < z->img_comp[n].h; ++x) {
int x2 = (i * z->img_comp[n].h + x);
int y2 = (j * z->img_comp[n].v + y);
short *data = z->img_comp[n].coeff +
64 * (x2 + y2 * z->img_comp[n].coeff_w);
if (!stbi__jpeg_decode_block_prog_dc(
z, data, &z->huff_dc[z->img_comp[n].hd], n))
return 0;
}
}
}
// after all interleaved components, that's an interleaved MCU,
// so now count down the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
if (!STBI__RESTART(z->marker)) return 1;
stbi__jpeg_reset(z);
}
}
}
return 1;
}
}
}
static void stbi__jpeg_dequantize(short *data, uint16_t *dequant) {
int i;
for (i = 0; i < 64; ++i) data[i] *= dequant[i];
}
static void stbi__jpeg_finish(stbi__jpeg *z) {
if (z->progressive) {
// dequantize and idct the data
int i, j, n;
for (n = 0; n < z->s->img_n; ++n) {
int w = (z->img_comp[n].x + 7) >> 3;
int h = (z->img_comp[n].y + 7) >> 3;
for (j = 0; j < h; ++j) {
for (i = 0; i < w; ++i) {
short *data =
z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]);
idct_block_kernel(
z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8,
z->img_comp[n].w2, data);
}
}
}
}
}
static int stbi__process_marker(stbi__jpeg *z, int m) {
int L;
switch (m) {
case STBI__MARKER_none: // no marker found
return stbi__err("expected marker", "Corrupt JPEG");
case 0xDD: // DRI - specify restart interval
if (stbi__get16be(z->s) != 4)
return stbi__err("bad DRI len", "Corrupt JPEG");
z->restart_interval = stbi__get16be(z->s);
return 1;
case 0xDB: // DQT - define quantization table
L = stbi__get16be(z->s) - 2;
while (L > 0) {
int q = stbi__get8(z->s);
int p = q >> 4, sixteen = (p != 0);
int t = q & 15, i;
if (p != 0 && p != 1) return stbi__err("bad DQT type", "Corrupt JPEG");
if (t > 3) return stbi__err("bad DQT table", "Corrupt JPEG");
for (i = 0; i < 64; ++i)
z->dequant[t][stbi__jpeg_dezigzag[i]] =
(uint16_t)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s));
L -= (sixteen ? 129 : 65);
}
return L == 0;
case 0xC4: // DHT - define huffman table
L = stbi__get16be(z->s) - 2;
while (L > 0) {
unsigned char *v;
int sizes[16], i, n = 0;
int q = stbi__get8(z->s);
int tc = q >> 4;
int th = q & 15;
if (tc > 1 || th > 3)
return stbi__err("bad DHT header", "Corrupt JPEG");
for (i = 0; i < 16; ++i) {
sizes[i] = stbi__get8(z->s);
n += sizes[i];
}
L -= 17;
if (tc == 0) {
if (!stbi__build_huffman(z->huff_dc + th, sizes)) return 0;
v = z->huff_dc[th].values;
} else {
if (!stbi__build_huffman(z->huff_ac + th, sizes)) return 0;
v = z->huff_ac[th].values;
}
for (i = 0; i < n; ++i) v[i] = stbi__get8(z->s);
if (tc != 0) stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th);
L -= n;
}
return L == 0;
}
// check for comment block or APP blocks
if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
L = stbi__get16be(z->s);
if (L < 2) {
if (m == 0xFE)
return stbi__err("bad COM len", "Corrupt JPEG");
else
return stbi__err("bad APP len", "Corrupt JPEG");
}
L -= 2;
if (m == 0xE0 && L >= 5) { // JFIF APP0 segment
static const unsigned char tag[5] = {'J', 'F', 'I', 'F', '\0'};
int ok = 1;
int i;
for (i = 0; i < 5; ++i)
if (stbi__get8(z->s) != tag[i]) ok = 0;
L -= 5;
if (ok) z->jfif = 1;
} else if (m == 0xEE && L >= 12) { // Adobe APP14 segment
static const unsigned char tag[6] = {'A', 'd', 'o', 'b', 'e', '\0'};
int ok = 1;
int i;
for (i = 0; i < 6; ++i)
if (stbi__get8(z->s) != tag[i]) ok = 0;
L -= 6;
if (ok) {
stbi__get8(z->s); // version
stbi__get16be(z->s); // flags0
stbi__get16be(z->s); // flags1
z->app14_color_transform = stbi__get8(z->s); // color transform
L -= 6;
}
}
stbi__skip(z->s, L);
return 1;
}
return stbi__err("unknown marker", "Corrupt JPEG");
}
// after we see SOS
static int stbi__process_scan_header(stbi__jpeg *z) {
int i;
int Ls = stbi__get16be(z->s);
z->scan_n = stbi__get8(z->s);
if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int)z->s->img_n)
return stbi__err("bad SOS component count", "Corrupt JPEG");
if (Ls != 6 + 2 * z->scan_n) return stbi__err("bad SOS len", "Corrupt JPEG");
for (i = 0; i < z->scan_n; ++i) {
int id = stbi__get8(z->s), which;
int q = stbi__get8(z->s);
for (which = 0; which < z->s->img_n; ++which)
if (z->img_comp[which].id == id) break;
if (which == z->s->img_n) return 0; // no match
z->img_comp[which].hd = q >> 4;
if (z->img_comp[which].hd > 3)
return stbi__err("bad DC huff", "Corrupt JPEG");
z->img_comp[which].ha = q & 15;
if (z->img_comp[which].ha > 3)
return stbi__err("bad AC huff", "Corrupt JPEG");
z->order[i] = which;
}
{
int aa;
z->spec_start = stbi__get8(z->s);
z->spec_end = stbi__get8(z->s); // should be 63, but might be 0
aa = stbi__get8(z->s);
z->succ_high = (aa >> 4);
z->succ_low = (aa & 15);
if (z->progressive) {
if (z->spec_start > 63 || z->spec_end > 63 ||
z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13)
return stbi__err("bad SOS", "Corrupt JPEG");
} else {
if (z->spec_start != 0) return stbi__err("bad SOS", "Corrupt JPEG");
if (z->succ_high != 0 || z->succ_low != 0)
return stbi__err("bad SOS", "Corrupt JPEG");
z->spec_end = 63;
}
}
return 1;
}
static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) {
int i;
for (i = 0; i < ncomp; ++i) {
if (z->img_comp[i].data) {
free(z->img_comp[i].data);
z->img_comp[i].data = NULL;
}
if (z->img_comp[i].coeff) {
free(z->img_comp[i].coeff);
z->img_comp[i].coeff = NULL;
}
if (z->img_comp[i].linebuf) {
free(z->img_comp[i].linebuf);
z->img_comp[i].linebuf = NULL;
}
}
return why;
}
static int stbi__process_frame_header(stbi__jpeg *z, int scan) {
stbi__context *s = z->s;
int Lf, p, i, q, h_max = 1, v_max = 1, c;
Lf = stbi__get16be(s);
if (Lf < 11) return stbi__err("bad SOF len", "Corrupt JPEG"); // JPEG
p = stbi__get8(s);
if (p != 8)
return stbi__err("only 8-bit",
"JPEG format not supported: 8-bit only"); // JPEG baseline
s->img_y = stbi__get16be(s);
if (s->img_y == 0)
return stbi__err(
"no header height",
"JPEG format not supported: delayed height"); // Legal, but we don't
// handle it--but neither
// does IJG
s->img_x = stbi__get16be(s);
if (s->img_x == 0)
return stbi__err("0 width", "Corrupt JPEG"); // JPEG requires
c = stbi__get8(s);
if (c != 3 && c != 1 && c != 4)
return stbi__err("bad component count", "Corrupt JPEG");
s->img_n = c;
for (i = 0; i < c; ++i) {
z->img_comp[i].data = NULL;
z->img_comp[i].linebuf = NULL;
}
if (Lf != 8 + 3 * s->img_n) return stbi__err("bad SOF len", "Corrupt JPEG");
z->rgb = 0;
for (i = 0; i < s->img_n; ++i) {
static const unsigned char rgb[3] = {'R', 'G', 'B'};
z->img_comp[i].id = stbi__get8(s);
if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) ++z->rgb;
q = stbi__get8(s);
z->img_comp[i].h = (q >> 4);
if (!z->img_comp[i].h || z->img_comp[i].h > 4)
return stbi__err("bad H", "Corrupt JPEG");
z->img_comp[i].v = q & 15;
if (!z->img_comp[i].v || z->img_comp[i].v > 4)
return stbi__err("bad V", "Corrupt JPEG");
z->img_comp[i].tq = stbi__get8(s);
if (z->img_comp[i].tq > 3) return stbi__err("bad TQ", "Corrupt JPEG");
}
if (scan != STBI__SCAN_load) return 1;
if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0))
return stbi__err("too large", "Image too large to decode");
for (i = 0; i < s->img_n; ++i) {
if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
}
// compute interleaved mcu info
z->img_h_max = h_max;
z->img_v_max = v_max;
z->img_mcu_w = h_max * 8;
z->img_mcu_h = v_max * 8;
// these sizes can't be more than 17 bits
z->img_mcu_x = (s->img_x + z->img_mcu_w - 1) / z->img_mcu_w;
z->img_mcu_y = (s->img_y + z->img_mcu_h - 1) / z->img_mcu_h;
for (i = 0; i < s->img_n; ++i) {
// number of effective pixels (e.g. for non-interleaved MCU)
z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max - 1) / h_max;
z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max - 1) / v_max;
// to simplify generation, we'll allocate enough memory to decode
// the bogus oversized data from using interleaved MCUs and their
// big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
// discard the extra data until colorspace conversion
//
// img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked
// earlier) so these muls can't overflow with 32-bit ints (which we require)
z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
z->img_comp[i].coeff = NULL;
z->img_comp[i].linebuf = NULL;
z->img_comp[i].data =
stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15);
if (z->progressive) {
// w2, h2 are multiples of 8 (see above)
z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8;
z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8;
z->img_comp[i].coeff = stbi__malloc_mad3(
z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15);
}
}
return 1;
}
// use comparisons since in some cases we handle more than one case (e.g. SOF)
#define stbi__DNL(x) ((x) == 0xdc)
#define stbi__SOI(x) ((x) == 0xd8)
#define stbi__EOI(x) ((x) == 0xd9)
#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2)
#define stbi__SOS(x) ((x) == 0xda)
#define stbi__SOF_progressive(x) ((x) == 0xc2)
static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) {
int m;
z->jfif = 0;
z->app14_color_transform = -1; // valid values are 0,1,2
z->marker = STBI__MARKER_none; // initialize cached marker to empty
m = stbi__get_marker(z);
if (!stbi__SOI(m)) return 0;
if (scan == STBI__SCAN_type) return 1;
m = stbi__get_marker(z);
while (!stbi__SOF(m)) {
if (!stbi__process_marker(z, m)) return 0;
m = stbi__get_marker(z);
while (m == STBI__MARKER_none) {
// some files have extra padding after their blocks, so ok, we'll scan
if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG");
m = stbi__get_marker(z);
}
}
z->progressive = stbi__SOF_progressive(m);
if (!stbi__process_frame_header(z, scan)) return 0;
return 1;
}
// decode image to YCbCr format
static int stbi__decode_jpeg_image(stbi__jpeg *j) {
int m;
for (m = 0; m < 4; m++) {
j->img_comp[m].data = NULL;
j->img_comp[m].coeff = NULL;
}
j->restart_interval = 0;
if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0;
m = stbi__get_marker(j);
while (!stbi__EOI(m)) {
if (stbi__SOS(m)) {
if (!stbi__process_scan_header(j)) return 0;
if (!stbi__parse_entropy_coded_data(j)) return 0;
if (j->marker == STBI__MARKER_none) {
// handle 0s at the end of image data from IP Kamera 9060
while (!stbi__at_eof(j->s)) {
int x = stbi__get8(j->s);
if (x == 255) {
j->marker = stbi__get8(j->s);
break;
}
}
// if we reach eof without hitting a marker, stbi__get_marker() below
// will fail and we'll eventually return 0
}
} else if (stbi__DNL(m)) {
int Ld = stbi__get16be(j->s);
uint32_t NL = stbi__get16be(j->s);
if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG");
if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG");
} else {
if (!stbi__process_marker(j, m)) return 0;
}
m = stbi__get_marker(j);
}
if (j->progressive) stbi__jpeg_finish(j);
return 1;
}
// static jfif-centered resampling (across block boundaries)
typedef unsigned char *(*resample_row_func)(unsigned char *out,
unsigned char *in0,
unsigned char *in1, int w, int hs);
#define stbi__div4(x) ((unsigned char)((x) >> 2))
static unsigned char *resample_row_1(unsigned char *out, unsigned char *in_near,
unsigned char *in_far, int w, int hs) {
return in_near;
}
static unsigned char *stbi__resample_row_v_2(unsigned char *out,
unsigned char *in_near,
unsigned char *in_far, int w,
int hs) {
// need to generate two samples vertically for every one in input
int i;
for (i = 0; i < w; ++i) out[i] = stbi__div4(3 * in_near[i] + in_far[i] + 2);
return out;
}
static unsigned char *stbi__resample_row_h_2(unsigned char *out,
unsigned char *in_near,
unsigned char *in_far, int w,
int hs) {
// need to generate two samples horizontally for every one in input
int i;
unsigned char *input = in_near;
if (w == 1) {
// if only one sample, can't do any interpolation
out[0] = out[1] = input[0];
return out;
}
out[0] = input[0];
out[1] = stbi__div4(input[0] * 3 + input[1] + 2);
for (i = 1; i < w - 1; ++i) {
int n = 3 * input[i] + 2;
out[i * 2 + 0] = stbi__div4(n + input[i - 1]);
out[i * 2 + 1] = stbi__div4(n + input[i + 1]);
}
out[i * 2 + 0] = stbi__div4(input[w - 2] * 3 + input[w - 1] + 2);
out[i * 2 + 1] = input[w - 1];
return out;
}
#define stbi__div16(x) ((unsigned char)((x) >> 4))
static unsigned char *stbi__resample_row_hv_2(unsigned char *out,
unsigned char *in_near,
unsigned char *in_far, int w,
int hs) {
// need to generate 2x2 samples for every one in input
int i, t0, t1;
if (w == 1) {
out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2);
return out;
}
t1 = 3 * in_near[0] + in_far[0];
out[0] = stbi__div4(t1 + 2);
for (i = 1; i < w; ++i) {
t0 = t1;
t1 = 3 * in_near[i] + in_far[i];
out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8);
out[i * 2] = stbi__div16(3 * t1 + t0 + 8);
}
out[w * 2 - 1] = stbi__div4(t1 + 2);
return out;
}
#if defined(STBI_SSE2)
static unsigned char *stbi__resample_row_hv_2_simd(unsigned char *out,
unsigned char *in_near,
unsigned char *in_far, int w,
int hs) {
// need to generate 2x2 samples for every one in input
int i = 0, t0, t1;
if (w == 1) {
out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2);
return out;
}
t1 = 3 * in_near[0] + in_far[0];
// process groups of 8 pixels for as long as we can.
// note we can't handle the last pixel in a row in this loop
// because we need to handle the filter boundary conditions.
for (; i < ((w - 1) & ~7); i += 8) {
// load and perform the vertical filtering pass
// this uses 3*x + y = 4*x + (y - x)
__m128i zero = _mm_setzero_si128();
__m128i farb = _mm_loadl_epi64((__m128i *)(in_far + i));
__m128i nearb = _mm_loadl_epi64((__m128i *)(in_near + i));
__m128i farw = _mm_unpacklo_epi8(farb, zero);
__m128i nearw = _mm_unpacklo_epi8(nearb, zero);
__m128i diff = _mm_sub_epi16(farw, nearw);
__m128i nears = _mm_slli_epi16(nearw, 2);
__m128i curr = _mm_add_epi16(nears, diff); // current row
// horizontal filter works the same based on shifted vers of current
// row. "prev" is current row shifted right by 1 pixel; we need to
// insert the previous pixel value (from t1).
// "next" is current row shifted left by 1 pixel, with first pixel
// of next block of 8 pixels added in.
__m128i prv0 = _mm_slli_si128(curr, 2);
__m128i nxt0 = _mm_srli_si128(curr, 2);
__m128i prev = _mm_insert_epi16(prv0, t1, 0);
__m128i next =
_mm_insert_epi16(nxt0, 3 * in_near[i + 8] + in_far[i + 8], 7);
// horizontal filter, polyphase implementation since it's convenient:
// even pixels = 3*cur + prev = cur*4 + (prev - cur)
// odd pixels = 3*cur + next = cur*4 + (next - cur)
// note the shared term.
__m128i bias = _mm_set1_epi16(8);
__m128i curs = _mm_slli_epi16(curr, 2);
__m128i prvd = _mm_sub_epi16(prev, curr);
__m128i nxtd = _mm_sub_epi16(next, curr);
__m128i curb = _mm_add_epi16(curs, bias);
__m128i even = _mm_add_epi16(prvd, curb);
__m128i odd = _mm_add_epi16(nxtd, curb);
// interleave even and odd pixels, then undo scaling.
__m128i int0 = _mm_unpacklo_epi16(even, odd);
__m128i int1 = _mm_unpackhi_epi16(even, odd);
__m128i de0 = _mm_srli_epi16(int0, 4);
__m128i de1 = _mm_srli_epi16(int1, 4);
// pack and write output
__m128i outv = _mm_packus_epi16(de0, de1);
_mm_storeu_si128((__m128i *)(out + i * 2), outv);
// "previous" value for next iter
t1 = 3 * in_near[i + 7] + in_far[i + 7];
}
t0 = t1;
t1 = 3 * in_near[i] + in_far[i];
out[i * 2] = stbi__div16(3 * t1 + t0 + 8);
for (++i; i < w; ++i) {
t0 = t1;
t1 = 3 * in_near[i] + in_far[i];
out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8);
out[i * 2] = stbi__div16(3 * t1 + t0 + 8);
}
out[w * 2 - 1] = stbi__div4(t1 + 2);
return out;
}
#endif
static unsigned char *stbi__resample_row_nearest(unsigned char *out,
unsigned char *in_near,
unsigned char *in_far, int w,
int hs) {
int i, j;
for (i = 0; i < w; ++i) {
for (j = 0; j < hs; ++j) {
out[i * hs + j] = in_near[i];
}
}
return out;
}
// this is a reduced-precision calculation of YCbCr-to-RGB introduced
// to make sure the code produces the same results in both SIMD and scalar
#define stbi__float2fixed(x) (((int)((x)*4096.0f + 0.5f)) << 8)
static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y,
const stbi_uc *pcb, const stbi_uc *pcr,
int count, int step) {
int i;
for (i = 0; i < count; ++i) {
int y_fixed = (y[i] << 20) + (1 << 19); // rounding
int r, g, b;
int cr = pcr[i] - 128;
int cb = pcb[i] - 128;
r = y_fixed + cr * stbi__float2fixed(1.40200f);
g = y_fixed + (cr * -stbi__float2fixed(0.71414f)) +
((cb * -stbi__float2fixed(0.34414f)) & 0xffff0000);
b = y_fixed + cb * stbi__float2fixed(1.77200f);
r >>= 20;
g >>= 20;
b >>= 20;
if ((unsigned)r > 255) {
if (r < 0)
r = 0;
else
r = 255;
}
if ((unsigned)g > 255) {
if (g < 0)
g = 0;
else
g = 255;
}
if ((unsigned)b > 255) {
if (b < 0)
b = 0;
else
b = 255;
}
out[0] = (stbi_uc)r;
out[1] = (stbi_uc)g;
out[2] = (stbi_uc)b;
out[3] = 255;
out += step;
}
}
#if defined(STBI_SSE2) || defined(STBI_NEON)
static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y,
stbi_uc const *pcb, stbi_uc const *pcr,
int count, int step) {
int i = 0;
#ifdef STBI_SSE2
// step == 3 is pretty ugly on the final interleave, and i'm not convinced
// it's useful in practice (you wouldn't use it for textures, for example).
// so just accelerate step == 4 case.
if (step == 4) {
// this is a fairly straightforward implementation and not super-optimized.
__m128i signflip = _mm_set1_epi8(-0x80);
__m128i cr_const0 = _mm_set1_epi16((short)(1.40200f * 4096.0f + 0.5f));
__m128i cr_const1 = _mm_set1_epi16(-(short)(0.71414f * 4096.0f + 0.5f));
__m128i cb_const0 = _mm_set1_epi16(-(short)(0.34414f * 4096.0f + 0.5f));
__m128i cb_const1 = _mm_set1_epi16((short)(1.77200f * 4096.0f + 0.5f));
__m128i y_bias = _mm_set1_epi8((char)(unsigned char)128);
__m128i xw = _mm_set1_epi16(255); // alpha channel
for (; i + 7 < count; i += 8) {
// load
__m128i y_bytes = _mm_loadl_epi64((__m128i *)(y + i));
__m128i cr_bytes = _mm_loadl_epi64((__m128i *)(pcr + i));
__m128i cb_bytes = _mm_loadl_epi64((__m128i *)(pcb + i));
__m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128
__m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128
// unpack to short (and left-shift cr, cb by 8)
__m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes);
__m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased);
__m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased);
// color transform
__m128i yws = _mm_srli_epi16(yw, 4);
__m128i cr0 = _mm_mulhi_epi16(cr_const0, crw);
__m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw);
__m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1);
__m128i cr1 = _mm_mulhi_epi16(crw, cr_const1);
__m128i rws = _mm_add_epi16(cr0, yws);
__m128i gwt = _mm_add_epi16(cb0, yws);
__m128i bws = _mm_add_epi16(yws, cb1);
__m128i gws = _mm_add_epi16(gwt, cr1);
// descale
__m128i rw = _mm_srai_epi16(rws, 4);
__m128i bw = _mm_srai_epi16(bws, 4);
__m128i gw = _mm_srai_epi16(gws, 4);
// back to byte, set up for transpose
__m128i brb = _mm_packus_epi16(rw, bw);
__m128i gxb = _mm_packus_epi16(gw, xw);
// transpose to interleave channels
__m128i t0 = _mm_unpacklo_epi8(brb, gxb);
__m128i t1 = _mm_unpackhi_epi8(brb, gxb);
__m128i o0 = _mm_unpacklo_epi16(t0, t1);
__m128i o1 = _mm_unpackhi_epi16(t0, t1);
// store
_mm_storeu_si128((__m128i *)(out + 0), o0);
_mm_storeu_si128((__m128i *)(out + 16), o1);
out += 32;
}
}
#endif
#ifdef STBI_NEON
// in this version, step=3 support would be easy to add. but is there demand?
if (step == 4) {
// this is a fairly straightforward implementation and not super-optimized.
uint8x8_t signflip = vdup_n_u8(0x80);
int16x8_t cr_const0 = vdupq_n_s16((short)(1.40200f * 4096.0f + 0.5f));
int16x8_t cr_const1 = vdupq_n_s16(-(short)(0.71414f * 4096.0f + 0.5f));
int16x8_t cb_const0 = vdupq_n_s16(-(short)(0.34414f * 4096.0f + 0.5f));
int16x8_t cb_const1 = vdupq_n_s16((short)(1.77200f * 4096.0f + 0.5f));
for (; i + 7 < count; i += 8) {
// load
uint8x8_t y_bytes = vld1_u8(y + i);
uint8x8_t cr_bytes = vld1_u8(pcr + i);
uint8x8_t cb_bytes = vld1_u8(pcb + i);
int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip));
int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip));
// expand to s16
int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4));
int16x8_t crw = vshll_n_s8(cr_biased, 7);
int16x8_t cbw = vshll_n_s8(cb_biased, 7);
// color transform
int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0);
int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0);
int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1);
int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1);
int16x8_t rws = vaddq_s16(yws, cr0);
int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1);
int16x8_t bws = vaddq_s16(yws, cb1);
// undo scaling, round, convert to byte
uint8x8x4_t o;
o.val[0] = vqrshrun_n_s16(rws, 4);
o.val[1] = vqrshrun_n_s16(gws, 4);
o.val[2] = vqrshrun_n_s16(bws, 4);
o.val[3] = vdup_n_u8(255);
// store, interleaving r/g/b/a
vst4_u8(out, o);
out += 8 * 4;
}
}
#endif
for (; i < count; ++i) {
int y_fixed = (y[i] << 20) + (1 << 19); // rounding
int r, g, b;
int cr = pcr[i] - 128;
int cb = pcb[i] - 128;
r = y_fixed + cr * stbi__float2fixed(1.40200f);
g = y_fixed + cr * -stbi__float2fixed(0.71414f) +
((cb * -stbi__float2fixed(0.34414f)) & 0xffff0000);
b = y_fixed + cb * stbi__float2fixed(1.77200f);
r >>= 20;
g >>= 20;
b >>= 20;
if ((unsigned)r > 255) {
if (r < 0)
r = 0;
else
r = 255;
}
if ((unsigned)g > 255) {
if (g < 0)
g = 0;
else
g = 255;
}
if ((unsigned)b > 255) {
if (b < 0)
b = 0;
else
b = 255;
}
out[0] = (stbi_uc)r;
out[1] = (stbi_uc)g;
out[2] = (stbi_uc)b;
out[3] = 255;
out += step;
}
}
#endif
// set up the kernels
static void stbi__setup_jpeg(stbi__jpeg *j) {
j->resample_row_hv_2_kernel = stbi__resample_row_hv_2;
#if 0
if (stbi__sse2_available()) {
j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
}
#endif
}
// clean up the temporary component buffers
static void stbi__cleanup_jpeg(stbi__jpeg *j) {
stbi__free_jpeg_components(j, j->s->img_n, 0);
}
typedef struct {
resample_row_func resample;
unsigned char *line0, *line1;
int hs, vs; // expansion factor in each axis
int w_lores; // horizontal pixels pre-expansion
int ystep; // how far through vertical expansion we are
int ypos; // which pre-expansion row we're on
} stbi__resample;
// fast 0..255 * 0..255 => 0..255 rounded multiplication
static unsigned char stbi__blinn_8x8(unsigned char x, unsigned char y) {
unsigned t;
t = x * y + 128;
return (t + (t >> 8)) >> 8;
}
static unsigned char *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y,
int *comp, int req_comp) {
int n, decode_n, is_rgb;
z->s->img_n = 0; // make stbi__cleanup_jpeg safe
// validate req_comp
if (req_comp < 0 || req_comp > 4) {
return stbi__errpuc("bad req_comp", "Internal error");
}
// load a jpeg image from whichever source, but leave in YCbCr format
if (!stbi__decode_jpeg_image(z)) {
stbi__cleanup_jpeg(z);
return NULL;
}
// determine actual number of components to generate
n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1;
is_rgb = z->s->img_n == 3 &&
(z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif));
if (z->s->img_n == 3 && n < 3 && !is_rgb) {
decode_n = 1;
} else {
decode_n = z->s->img_n;
}
// resample and color-convert
{
int k;
unsigned int i, j;
unsigned char *output;
unsigned char *coutput[4];
stbi__resample res_comp[4];
bzero(coutput, sizeof(coutput));
for (k = 0; k < decode_n; ++k) {
stbi__resample *r = &res_comp[k];
// allocate line buffer big enough for upsampling off the edges
// with upsample factor of 4
z->img_comp[k].linebuf = xmalloc(z->s->img_x + 3);
r->hs = z->img_h_max / z->img_comp[k].h;
r->vs = z->img_v_max / z->img_comp[k].v;
r->ystep = r->vs >> 1;
r->w_lores = (z->s->img_x + r->hs - 1) / r->hs;
r->ypos = 0;
r->line0 = r->line1 = z->img_comp[k].data;
if (r->hs == 1 && r->vs == 1) {
r->resample = resample_row_1;
} else if (r->hs == 1 && r->vs == 2) {
r->resample = stbi__resample_row_v_2;
} else if (r->hs == 2 && r->vs == 1) {
r->resample = stbi__resample_row_h_2;
} else if (r->hs == 2 && r->vs == 2) {
r->resample = z->resample_row_hv_2_kernel;
} else {
r->resample = stbi__resample_row_nearest;
}
}
// can't error after this so, this is safe
output = stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1);
// now go ahead and resample
for (j = 0; j < z->s->img_y; ++j) {
unsigned char *out = output + n * z->s->img_x * j;
for (k = 0; k < decode_n; ++k) {
stbi__resample *r = &res_comp[k];
int y_bot = r->ystep >= (r->vs >> 1);
coutput[k] =
r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0,
y_bot ? r->line0 : r->line1, r->w_lores, r->hs);
if (++r->ystep >= r->vs) {
r->ystep = 0;
r->line0 = r->line1;
if (++r->ypos < z->img_comp[k].y) r->line1 += z->img_comp[k].w2;
}
}
if (n >= 3) {
unsigned char *y = coutput[0];
if (z->s->img_n == 3) {
if (is_rgb) {
for (i = 0; i < z->s->img_x; ++i) {
out[0] = y[i];
out[1] = coutput[1][i];
out[2] = coutput[2][i];
out[3] = 255;
out += n;
}
} else {
stbi__YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x,
n);
}
} else if (z->s->img_n == 4) {
if (z->app14_color_transform == 0) { // CMYK
for (i = 0; i < z->s->img_x; ++i) {
unsigned char m = coutput[3][i];
out[0] = stbi__blinn_8x8(coutput[0][i], m);
out[1] = stbi__blinn_8x8(coutput[1][i], m);
out[2] = stbi__blinn_8x8(coutput[2][i], m);
out[3] = 255;
out += n;
}
} else if (z->app14_color_transform == 2) { // YCCK
stbi__YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x,
n);
for (i = 0; i < z->s->img_x; ++i) {
unsigned char m = coutput[3][i];
out[0] = stbi__blinn_8x8(255 - out[0], m);
out[1] = stbi__blinn_8x8(255 - out[1], m);
out[2] = stbi__blinn_8x8(255 - out[2], m);
out += n;
}
} else { // YCbCr + alpha? Ignore the fourth channel for now
stbi__YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x,
n);
}
} else
for (i = 0; i < z->s->img_x; ++i) {
out[0] = out[1] = out[2] = y[i];
out[3] = 255; // not used if n==3
out += n;
}
} else {
if (is_rgb) {
if (n == 1)
for (i = 0; i < z->s->img_x; ++i)
*out++ =
stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
else {
for (i = 0; i < z->s->img_x; ++i, out += 2) {
out[0] =
stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
out[1] = 255;
}
}
} else if (z->s->img_n == 4 && z->app14_color_transform == 0) {
for (i = 0; i < z->s->img_x; ++i) {
unsigned char m = coutput[3][i];
unsigned char r = stbi__blinn_8x8(coutput[0][i], m);
unsigned char g = stbi__blinn_8x8(coutput[1][i], m);
unsigned char b = stbi__blinn_8x8(coutput[2][i], m);
out[0] = stbi__compute_y(r, g, b);
out[1] = 255;
out += n;
}
} else if (z->s->img_n == 4 && z->app14_color_transform == 2) {
for (i = 0; i < z->s->img_x; ++i) {
out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]);
out[1] = 255;
out += n;
}
} else {
unsigned char *y = coutput[0];
if (n == 1)
for (i = 0; i < z->s->img_x; ++i) out[i] = y[i];
else
for (i = 0; i < z->s->img_x; ++i) {
*out++ = y[i];
*out++ = 255;
}
}
}
}
stbi__cleanup_jpeg(z);
*out_x = z->s->img_x;
*out_y = z->s->img_y;
if (comp)
*comp =
z->s->img_n >= 3 ? 3 : 1; // report original components, not output
return output;
}
}
static dontinline void *stbi__jpeg_load(stbi__context *s, int *x, int *y,
int *comp, int req_comp,
stbi__result_info *ri) {
unsigned char *result;
stbi__jpeg *j = (stbi__jpeg *)malloc(sizeof(stbi__jpeg));
j->s = s;
stbi__setup_jpeg(j);
result = load_jpeg_image(j, x, y, comp, req_comp);
free(j);
return result;
}
static int stbi__jpeg_test(stbi__context *s) {
int r;
stbi__jpeg *j;
j = malloc(sizeof(stbi__jpeg));
j->s = s;
stbi__setup_jpeg(j);
r = stbi__decode_jpeg_header(j, STBI__SCAN_type);
stbi__rewind(s);
free(j);
return r;
}
static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) {
if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) {
stbi__rewind(j->s);
return 0;
}
if (x) *x = j->s->img_x;
if (y) *y = j->s->img_y;
if (comp) *comp = j->s->img_n >= 3 ? 3 : 1;
return 1;
}
static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) {
int result;
stbi__jpeg *j = (stbi__jpeg *)(malloc(sizeof(stbi__jpeg)));
j->s = s;
result = stbi__jpeg_info_raw(j, x, y, comp);
free(j);
return result;
}
// public domain zlib decode v0.2 Sean Barrett 2006-11-18
// simple implementation
// - all input must be provided in an upfront buffer
// - all output is written to a single output buffer (can malloc/realloc)
// performance
// - fast huffman
// fast-way is faster to check than jpeg huffman, but slow way is slower
#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables
#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)
// zlib-style huffman encoding
// (jpegs packs from left, zlib from right, so can't share code)
typedef struct {
uint16_t fast[1 << STBI__ZFAST_BITS];
uint16_t firstcode[16];
int maxcode[17];
uint16_t firstsymbol[16];
unsigned char size[288];
uint16_t value[288];
} stbi__zhuffman;
forceinline int stbi__bit_reverse(int v, int bits) {
assert(bits <= 16);
// to bit reverse n bits, reverse 16 and shift
// e.g. 11 bits, bit reverse and shift away 5
return _bitreverse16(v) >> (16 - bits);
}
static int stbi__zbuild_huffman(stbi__zhuffman *z,
const unsigned char *sizelist, int num) {
int i, k = 0;
int code, next_code[16], sizes[17];
// DEFLATE spec for generating codes
bzero(sizes, sizeof(sizes));
bzero(z->fast, sizeof(z->fast));
for (i = 0; i < num; ++i) ++sizes[sizelist[i]];
sizes[0] = 0;
for (i = 1; i < 16; ++i)
if (sizes[i] > (1 << i)) return stbi__err("bad sizes", "Corrupt PNG");
code = 0;
for (i = 1; i < 16; ++i) {
next_code[i] = code;
z->firstcode[i] = (uint16_t)code;
z->firstsymbol[i] = (uint16_t)k;
code = (code + sizes[i]);
if (sizes[i])
if (code - 1 >= (1 << i))
return stbi__err("bad codelengths", "Corrupt PNG");
z->maxcode[i] = code << (16 - i); // preshift for inner loop
code <<= 1;
k += sizes[i];
}
z->maxcode[16] = 0x10000; // sentinel
for (i = 0; i < num; ++i) {
int s = sizelist[i];
if (s) {
int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
uint16_t fastv = (uint16_t)((s << 9) | i);
z->size[c] = (unsigned char)s;
z->value[c] = (uint16_t)i;
if (s <= STBI__ZFAST_BITS) {
int j = stbi__bit_reverse(next_code[s], s);
while (j < (1 << STBI__ZFAST_BITS)) {
z->fast[j] = fastv;
j += (1 << s);
}
}
++next_code[s];
}
}
return 1;
}
// zlib-from-memory implementation for PNG reading
// because PNG allows splitting the zlib stream arbitrarily,
// and it's annoying structurally to have PNG call ZLIB call PNG,
// we require PNG read all the IDATs and combine them into a single
// memory buffer
typedef struct {
unsigned char *zbuffer, *zbuffer_end;
int num_bits;
uint32_t code_buffer;
char *zout;
char *zout_start;
char *zout_end;
int z_expandable;
stbi__zhuffman z_length, z_distance;
} stbi__zbuf;
forceinline unsigned char stbi__zget8(stbi__zbuf *z) {
if (z->zbuffer >= z->zbuffer_end) return 0;
return *z->zbuffer++;
}
static void stbi__fill_bits(stbi__zbuf *z) {
do {
assert(z->code_buffer < (1u << z->num_bits));
z->code_buffer |= (unsigned int)stbi__zget8(z) << z->num_bits;
z->num_bits += 8;
} while (z->num_bits <= 24);
}
forceinline unsigned int stbi__zreceive(stbi__zbuf *z, int n) {
unsigned int k;
if (z->num_bits < n) stbi__fill_bits(z);
k = z->code_buffer & ((1 << n) - 1);
z->code_buffer >>= n;
z->num_bits -= n;
return k;
}
static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) {
int b, s, k;
// not resolved by fast table, so compute it the slow way
// use jpeg approach, which requires MSbits at top
k = stbi__bit_reverse(a->code_buffer, 16);
for (s = STBI__ZFAST_BITS + 1;; ++s)
if (k < z->maxcode[s]) break;
if (s == 16) return -1; // invalid code!
// code size is s, so:
b = (k >> (16 - s)) - z->firstcode[s] + z->firstsymbol[s];
assert(z->size[b] == s);
a->code_buffer >>= s;
a->num_bits -= s;
return z->value[b];
}
forceinline int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) {
int b, s;
if (a->num_bits < 16) stbi__fill_bits(a);
b = z->fast[a->code_buffer & STBI__ZFAST_MASK];
if (b) {
s = b >> 9;
a->code_buffer >>= s;
a->num_bits -= s;
return b & 511;
}
return stbi__zhuffman_decode_slowpath(a, z);
}
static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) {
char *q;
int cur, limit, old_limit;
z->zout = zout;
if (!z->z_expandable) return stbi__err("output buffer limit", "Corrupt PNG");
cur = (int)(z->zout - z->zout_start);
limit = old_limit = (int)(z->zout_end - z->zout_start);
while (cur + n > limit) limit *= 2;
q = (char *)STBI_REALLOC_SIZED(z->zout_start, old_limit, limit);
if (q == NULL) return stbi__err("outofmem", "Out of memory");
z->zout_start = q;
z->zout = q + cur;
z->zout_end = q + limit;
return 1;
}
static const int stbi__zlength_base[31] = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0,
};
static const int stbi__zlength_extra[31] = {
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0,
};
static const int stbi__zdist_base[32] = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33,
49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0,
};
static const int stbi__zdist_extra[32] = {
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6,
6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
};
static int stbi__parse_huffman_block(stbi__zbuf *a) {
char *zout = a->zout;
for (;;) {
int z = stbi__zhuffman_decode(a, &a->z_length);
if (z < 256) {
if (z < 0) return stbi__err("bad huffman code", "Corrupt PNG");
if (zout >= a->zout_end) {
if (!stbi__zexpand(a, zout, 1)) return 0;
zout = a->zout;
}
*zout++ = (char)z;
} else {
unsigned char *p;
int len, dist;
if (z == 256) {
a->zout = zout;
return 1;
}
z -= 257;
len = stbi__zlength_base[z];
if (stbi__zlength_extra[z])
len += stbi__zreceive(a, stbi__zlength_extra[z]);
z = stbi__zhuffman_decode(a, &a->z_distance);
if (z < 0) return stbi__err("bad huffman code", "Corrupt PNG");
dist = stbi__zdist_base[z];
if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);
if (zout - a->zout_start < dist)
return stbi__err("bad dist", "Corrupt PNG");
if (zout + len > a->zout_end) {
if (!stbi__zexpand(a, zout, len)) return 0;
zout = a->zout;
}
p = (unsigned char *)(zout - dist);
if (dist == 1) { // run of one byte; common in images.
unsigned char v = *p;
if (len) {
do *zout++ = v;
while (--len);
}
} else {
if (len) {
do *zout++ = *p++;
while (--len);
}
}
}
}
}
static int stbi__compute_huffman_codes(stbi__zbuf *a) {
static const unsigned char length_dezigzag[19] = {
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
stbi__zhuffman z_codelength;
unsigned char lencodes[286 + 32 + 137]; // padding for maximum single op
unsigned char codelength_sizes[19];
int i, n;
int hlit = stbi__zreceive(a, 5) + 257;
int hdist = stbi__zreceive(a, 5) + 1;
int hclen = stbi__zreceive(a, 4) + 4;
int ntot = hlit + hdist;
bzero(codelength_sizes, sizeof(codelength_sizes));
for (i = 0; i < hclen; ++i) {
int s = stbi__zreceive(a, 3);
codelength_sizes[length_dezigzag[i]] = (unsigned char)s;
}
if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
n = 0;
while (n < ntot) {
int c = stbi__zhuffman_decode(a, &z_codelength);
if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG");
if (c < 16)
lencodes[n++] = (unsigned char)c;
else {
unsigned char fill = 0;
if (c == 16) {
c = stbi__zreceive(a, 2) + 3;
if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG");
fill = lencodes[n - 1];
} else if (c == 17)
c = stbi__zreceive(a, 3) + 3;
else {
assert(c == 18);
c = stbi__zreceive(a, 7) + 11;
}
if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG");
memset(lencodes + n, fill, c);
n += c;
}
}
if (n != ntot) return stbi__err("bad codelengths", "Corrupt PNG");
if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
if (!stbi__zbuild_huffman(&a->z_distance, lencodes + hlit, hdist)) return 0;
return 1;
}
static int stbi__parse_uncompressed_block(stbi__zbuf *a) {
unsigned char header[4];
int len, nlen, k;
if (a->num_bits & 7) stbi__zreceive(a, a->num_bits & 7); // discard
// drain the bit-packed data into header
k = 0;
while (a->num_bits > 0) {
header[k++] =
(unsigned char)(a->code_buffer & 255); // suppress MSVC run-time check
a->code_buffer >>= 8;
a->num_bits -= 8;
}
assert(a->num_bits == 0);
// now fill header the normal way
while (k < 4) header[k++] = stbi__zget8(a);
len = header[1] * 256 + header[0];
nlen = header[3] * 256 + header[2];
if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt", "Corrupt PNG");
if (a->zbuffer + len > a->zbuffer_end)
return stbi__err("read past buffer", "Corrupt PNG");
if (a->zout + len > a->zout_end)
if (!stbi__zexpand(a, a->zout, len)) return 0;
memcpy(a->zout, a->zbuffer, len);
a->zbuffer += len;
a->zout += len;
return 1;
}
static int stbi__parse_zlib_header(stbi__zbuf *a) {
int cmf = stbi__zget8(a);
int cm = cmf & 15;
/* int cinfo = cmf >> 4; */
int flg = stbi__zget8(a);
if ((cmf * 256 + flg) % 31 != 0)
return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec
if (flg & 32)
return stbi__err("no preset dict",
"Corrupt PNG"); // preset dictionary not allowed in png
if (cm != 8)
return stbi__err("bad compression",
"Corrupt PNG"); // DEFLATE required for png
// window = 1 << (8 + cinfo)... but who cares, we fully buffer output
return 1;
}
static const unsigned char stbi__zdefault_length[288] = {
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8};
static const unsigned char stbi__zdefault_distance[32] = {
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
};
/*
Init algorithm:{
int i; // use <= to match clearly with spec
for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8;
for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9;
for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7;
for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8;
for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5;
}
*/
static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) {
int final, type;
if (parse_header)
if (!stbi__parse_zlib_header(a)) return 0;
a->num_bits = 0;
a->code_buffer = 0;
do {
final = stbi__zreceive(a, 1);
type = stbi__zreceive(a, 2);
if (type == 0) {
if (!stbi__parse_uncompressed_block(a)) return 0;
} else if (type == 3) {
return 0;
} else {
if (type == 1) {
// use fixed code lengths
if (!stbi__zbuild_huffman(&a->z_length, stbi__zdefault_length, 288))
return 0;
if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32))
return 0;
} else {
if (!stbi__compute_huffman_codes(a)) return 0;
}
if (!stbi__parse_huffman_block(a)) return 0;
}
} while (!final);
return 1;
}
static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp,
int parse_header) {
a->zout_start = obuf;
a->zout = obuf;
a->zout_end = obuf + olen;
a->z_expandable = exp;
return stbi__parse_zlib(a, parse_header);
}
char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len,
int initial_size, int *outlen) {
char *res, *p;
stbi__zbuf *a;
a = NULL;
res = NULL;
if ((p = (char *)malloc(initial_size)) &&
(a = (stbi__zbuf *)malloc(sizeof(stbi__zbuf)))) {
a->zbuffer = (unsigned char *)buffer;
a->zbuffer_end = (unsigned char *)buffer + len;
if (stbi__do_zlib(a, p, initial_size, 1, 1)) {
if (outlen) *outlen = (int)(a->zout - a->zout_start);
res = a->zout_start;
a->zout_start = NULL;
}
}
free(a->zout_start);
free(a);
return res;
}
char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) {
return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
}
char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len,
int initial_size,
int *outlen,
int parse_header) {
char *res;
stbi__zbuf *a = malloc(sizeof(stbi__zbuf));
char *p = (char *)malloc(initial_size);
if (!p) return NULL;
a->zbuffer = (unsigned char *)buffer;
a->zbuffer_end = (unsigned char *)buffer + len;
if (stbi__do_zlib(a, p, initial_size, 1, parse_header)) {
if (outlen) *outlen = (int)(a->zout - a->zout_start);
res = a->zout_start;
} else {
free(a->zout_start);
res = NULL;
}
free(a);
return res;
}
int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer,
int ilen) {
stbi__zbuf a;
a.zbuffer = (unsigned char *)ibuffer;
a.zbuffer_end = (unsigned char *)ibuffer + ilen;
if (stbi__do_zlib(&a, obuffer, olen, 0, 1))
return (int)(a.zout - a.zout_start);
else
return -1;
}
char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len,
int *outlen) {
stbi__zbuf a;
char *p = (char *)malloc(16384);
if (p == NULL) return NULL;
a.zbuffer = (unsigned char *)buffer;
a.zbuffer_end = (unsigned char *)buffer + len;
if (stbi__do_zlib(&a, p, 16384, 1, 0)) {
if (outlen) *outlen = (int)(a.zout - a.zout_start);
return a.zout_start;
} else {
free(a.zout_start);
return NULL;
}
}
int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen,
const char *ibuffer, int ilen) {
stbi__zbuf a;
a.zbuffer = (unsigned char *)ibuffer;
a.zbuffer_end = (unsigned char *)ibuffer + ilen;
if (stbi__do_zlib(&a, obuffer, olen, 0, 0))
return (int)(a.zout - a.zout_start);
else
return -1;
}
// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
// simple implementation
// - only 8-bit samples
// - no CRC checking
// - allocates lots of intermediate memory
// - avoids problem of streaming data between subsystems
// - avoids explicit window management
// performance
// - uses stb_zlib, a PD zlib implementation with fast huffman decoding
typedef struct {
uint32_t length;
uint32_t type;
} stbi__pngchunk;
static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) {
stbi__pngchunk c;
c.length = stbi__get32be(s);
c.type = stbi__get32be(s);
return c;
}
static int stbi__check_png_header(stbi__context *s) {
int i;
for (i = 0; i < 8; ++i) {
if (stbi__get8(s) != kPngSig[i]) {
return stbi__err("bad png sig", "Not a PNG");
}
}
return 1;
}
typedef struct {
stbi__context *s;
unsigned char *idata, *expanded, *out;
int depth;
} stbi__png;
enum {
STBI__F_none = 0,
STBI__F_sub = 1,
STBI__F_up = 2,
STBI__F_avg = 3,
STBI__F_paeth = 4,
// synthetic filters used for first scanline to avoid needing a dummy row of
// 0s
STBI__F_avg_first,
STBI__F_paeth_first
};
static int stbi__de_iphone_flag = 0;
static int stbi__unpremultiply_on_load = 0;
static unsigned char first_row_filter[5] = {STBI__F_none, STBI__F_sub,
STBI__F_none, STBI__F_avg_first,
STBI__F_paeth_first};
static int stbi__paeth(int a, int b, int c) {
int p = a + b - c;
int pa = abs(p - a);
int pb = abs(p - b);
int pc = abs(p - c);
if (pa <= pb && pa <= pc) return a;
if (pb <= pc) return b;
return c;
}
static const unsigned char stbi__depth_scale_table[9] = {
0, 0xff, 0x55, 0, 0x11, 0, 0, 0, 0x01};
// create the png data from post-deflated data
static int stbi__create_png_image_raw(stbi__png *a, unsigned char *raw,
uint32_t raw_len, int out_n, uint32_t x,
uint32_t y, int depth, int color) {
int bytes = (depth == 16 ? 2 : 1);
stbi__context *s = a->s;
uint32_t i, j, stride = x * out_n * bytes;
uint32_t img_len, img_width_bytes;
int k;
int img_n = s->img_n; // copy it into a local for later
int output_bytes = out_n * bytes;
int filter_bytes = img_n * bytes;
int width = x;
assert(out_n == s->img_n || out_n == s->img_n + 1);
a->out = stbi__malloc_mad3(x, y, output_bytes,
0); // extra bytes to write off the end into
if (!stbi__mad3sizes_valid(img_n, x, depth, 7))
return stbi__err("too large", "Corrupt PNG");
img_width_bytes = (((img_n * x * depth) + 7) >> 3);
img_len = (img_width_bytes + 1) * y;
// we used to check for exact match between raw_len and img_len on
// non-interlaced PNGs, but issue #276 reported a PNG in the wild that had
// extra data at the end (all zeros), so just check for raw_len < img_len
// always.
if (raw_len < img_len) return stbi__err("not enough pixels", "Corrupt PNG");
for (j = 0; j < y; ++j) {
unsigned char *cur = a->out + stride * j;
unsigned char *prior;
int filter = *raw++;
if (filter > 4) return stbi__err("invalid filter", "Corrupt PNG");
if (depth < 8) {
assert(img_width_bytes <= x);
cur +=
x * out_n - img_width_bytes; // store output to the rightmost img_len
// bytes, so we can decode in place
filter_bytes = 1;
width = img_width_bytes;
}
prior = cur - stride; // bugfix: need to compute this after 'cur +='
// computation above
// if first row, use special filter that doesn't sample previous row
if (j == 0) filter = first_row_filter[filter];
// handle first byte explicitly
for (k = 0; k < filter_bytes; ++k) {
switch (filter) {
case STBI__F_none:
cur[k] = raw[k];
break;
case STBI__F_sub:
cur[k] = raw[k];
break;
case STBI__F_up:
cur[k] = STBI__BYTECAST(raw[k] + prior[k]);
break;
case STBI__F_avg:
cur[k] = STBI__BYTECAST(raw[k] + (prior[k] >> 1));
break;
case STBI__F_paeth:
cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0, prior[k], 0));
break;
case STBI__F_avg_first:
cur[k] = raw[k];
break;
case STBI__F_paeth_first:
cur[k] = raw[k];
break;
}
}
if (depth == 8) {
if (img_n != out_n) cur[img_n] = 255; // first pixel
raw += img_n;
cur += out_n;
prior += out_n;
} else if (depth == 16) {
if (img_n != out_n) {
cur[filter_bytes] = 255; // first pixel top byte
cur[filter_bytes + 1] = 255; // first pixel bottom byte
}
raw += filter_bytes;
cur += output_bytes;
prior += output_bytes;
} else {
raw += 1;
cur += 1;
prior += 1;
}
// this is a little gross, so that we don't switch per-pixel or
// per-component
if (depth < 8 || img_n == out_n) {
int nk = (width - 1) * filter_bytes;
#define STBI__CASE(f) \
case f: \
for (k = 0; k < nk; ++k)
switch (filter) {
// "none" filter turns into a memcpy here; make that explicit.
case STBI__F_none:
memcpy(cur, raw, nk);
break;
STBI__CASE(STBI__F_sub) {
cur[k] = STBI__BYTECAST(raw[k] + cur[k - filter_bytes]);
}
break;
STBI__CASE(STBI__F_up) {
cur[k] = STBI__BYTECAST(raw[k] + prior[k]);
}
break;
STBI__CASE(STBI__F_avg) {
cur[k] = STBI__BYTECAST(raw[k] +
((prior[k] + cur[k - filter_bytes]) >> 1));
}
break;
STBI__CASE(STBI__F_paeth) {
cur[k] = STBI__BYTECAST(raw[k] +
stbi__paeth(cur[k - filter_bytes], prior[k],
prior[k - filter_bytes]));
}
break;
STBI__CASE(STBI__F_avg_first) {
cur[k] = STBI__BYTECAST(raw[k] + (cur[k - filter_bytes] >> 1));
}
break;
STBI__CASE(STBI__F_paeth_first) {
cur[k] = STBI__BYTECAST(raw[k] +
stbi__paeth(cur[k - filter_bytes], 0, 0));
}
break;
}
#undef STBI__CASE
raw += nk;
} else {
assert(img_n + 1 == out_n);
#define STBI__CASE(f) \
case f: \
for (i = x - 1; i >= 1; --i, cur[filter_bytes] = 255, raw += filter_bytes, \
cur += output_bytes, prior += output_bytes) \
for (k = 0; k < filter_bytes; ++k)
switch (filter) {
STBI__CASE(STBI__F_none) {
cur[k] = raw[k];
}
break;
STBI__CASE(STBI__F_sub) {
cur[k] = STBI__BYTECAST(raw[k] + cur[k - output_bytes]);
}
break;
STBI__CASE(STBI__F_up) {
cur[k] = STBI__BYTECAST(raw[k] + prior[k]);
}
break;
STBI__CASE(STBI__F_avg) {
cur[k] = STBI__BYTECAST(raw[k] +
((prior[k] + cur[k - output_bytes]) >> 1));
}
break;
STBI__CASE(STBI__F_paeth) {
cur[k] = STBI__BYTECAST(raw[k] +
stbi__paeth(cur[k - output_bytes], prior[k],
prior[k - output_bytes]));
}
break;
STBI__CASE(STBI__F_avg_first) {
cur[k] = STBI__BYTECAST(raw[k] + (cur[k - output_bytes] >> 1));
}
break;
STBI__CASE(STBI__F_paeth_first) {
cur[k] =
STBI__BYTECAST(raw[k] + stbi__paeth(cur[k - output_bytes], 0, 0));
}
break;
}
#undef STBI__CASE
// the loop above sets the high byte of the pixels' alpha, but for
// 16 bit png files we also need the low byte set. we'll do that here.
if (depth == 16) {
cur = a->out + stride * j; // start at the beginning of the row again
for (i = 0; i < x; ++i, cur += output_bytes) {
cur[filter_bytes + 1] = 255;
}
}
}
}
// we make a separate pass to expand bits to pixels; for performance,
// this could run two scanlines behind the above code, so it won't
// intefere with filtering but will still be in the cache.
if (depth < 8) {
for (j = 0; j < y; ++j) {
unsigned char *cur = a->out + stride * j;
unsigned char *in = a->out + stride * j + x * out_n - img_width_bytes;
// unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common
// 8-bit path optimal at minimal cost for 1/2/4-bit png guarante byte
// alignment, if width is not multiple of 8/4/2 we'll decode dummy
// trailing data that will be skipped in the later loop
unsigned char scale = (color == 0)
? stbi__depth_scale_table[depth]
: 1; // scale grayscale values to 0..255 range
// note that the final byte might overshoot and write more data than
// desired. we can allocate enough data that this never writes out of
// memory, but it could also overwrite the next scanline. can it
// overwrite non-empty data on the next scanline? yes, consider
// 1-pixel-wide scanlines with 1-bit-per-pixel. so we need to explicitly
// clamp the final ones
if (depth == 4) {
for (k = x * img_n; k >= 2; k -= 2, ++in) {
*cur++ = scale * ((*in >> 4));
*cur++ = scale * ((*in) & 0x0f);
}
if (k > 0) *cur++ = scale * ((*in >> 4));
} else if (depth == 2) {
for (k = x * img_n; k >= 4; k -= 4, ++in) {
*cur++ = scale * ((*in >> 6));
*cur++ = scale * ((*in >> 4) & 0x03);
*cur++ = scale * ((*in >> 2) & 0x03);
*cur++ = scale * ((*in) & 0x03);
}
if (k > 0) *cur++ = scale * ((*in >> 6));
if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03);
if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03);
} else if (depth == 1) {
for (k = x * img_n; k >= 8; k -= 8, ++in) {
*cur++ = scale * ((*in >> 7));
*cur++ = scale * ((*in >> 6) & 0x01);
*cur++ = scale * ((*in >> 5) & 0x01);
*cur++ = scale * ((*in >> 4) & 0x01);
*cur++ = scale * ((*in >> 3) & 0x01);
*cur++ = scale * ((*in >> 2) & 0x01);
*cur++ = scale * ((*in >> 1) & 0x01);
*cur++ = scale * ((*in) & 0x01);
}
if (k > 0) *cur++ = scale * ((*in >> 7));
if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01);
if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01);
if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01);
if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01);
if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01);
if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01);
}
if (img_n != out_n) {
int q;
// insert alpha = 255
cur = a->out + stride * j;
if (img_n == 1) {
for (q = x - 1; q >= 0; --q) {
cur[q * 2 + 1] = 255;
cur[q * 2 + 0] = cur[q];
}
} else {
assert(img_n == 3);
for (q = x - 1; q >= 0; --q) {
cur[q * 4 + 3] = 255;
cur[q * 4 + 2] = cur[q * 3 + 2];
cur[q * 4 + 1] = cur[q * 3 + 1];
cur[q * 4 + 0] = cur[q * 3 + 0];
}
}
}
}
} else if (depth == 16) {
// force the image data from big-endian to platform-native.
// this is done in a separate pass due to the decoding relying
// on the data being untouched, but could probably be done
// per-line during decode if care is taken.
unsigned char *cur = a->out;
uint16_t *cur16 = (uint16_t *)cur;
for (i = 0; i < x * y * out_n; ++i, cur16++, cur += 2) {
*cur16 = (cur[0] << 8) | cur[1];
}
}
return 1;
}
static int stbi__create_png_image(stbi__png *a, unsigned char *image_data,
uint32_t image_data_len, int out_n, int depth,
int color, int interlaced) {
int bytes = (depth == 16 ? 2 : 1);
int out_bytes = out_n * bytes;
unsigned char *final;
int p;
if (!interlaced)
return stbi__create_png_image_raw(a, image_data, image_data_len, out_n,
a->s->img_x, a->s->img_y, depth, color);
// de-interlacing
final = stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);
for (p = 0; p < 7; ++p) {
int xorig[] = {0, 4, 0, 2, 0, 1, 0};
int yorig[] = {0, 0, 4, 0, 2, 0, 1};
int xspc[] = {8, 8, 4, 4, 2, 2, 1};
int yspc[] = {8, 8, 8, 4, 4, 2, 2};
int i, j, x, y;
// pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
x = (a->s->img_x - xorig[p] + xspc[p] - 1) / xspc[p];
y = (a->s->img_y - yorig[p] + yspc[p] - 1) / yspc[p];
if (x && y) {
uint32_t img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y;
if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x,
y, depth, color)) {
free(final);
return 0;
}
for (j = 0; j < y; ++j) {
for (i = 0; i < x; ++i) {
int out_y = j * yspc[p] + yorig[p];
int out_x = i * xspc[p] + xorig[p];
memcpy(final + out_y * a->s->img_x * out_bytes + out_x * out_bytes,
a->out + (j * x + i) * out_bytes, out_bytes);
}
}
free(a->out);
image_data += img_len;
image_data_len -= img_len;
}
}
a->out = final;
return 1;
}
static int stbi__compute_transparency(stbi__png *z, unsigned char tc[3],
int out_n) {
stbi__context *s = z->s;
uint32_t i, pixel_count = s->img_x * s->img_y;
unsigned char *p = z->out;
// compute color-based transparency, assuming we've
// already got 255 as the alpha value in the output
assert(out_n == 2 || out_n == 4);
if (out_n == 2) {
for (i = 0; i < pixel_count; ++i) {
p[1] = (p[0] == tc[0] ? 0 : 255);
p += 2;
}
} else {
for (i = 0; i < pixel_count; ++i) {
if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0;
p += 4;
}
}
return 1;
}
static int stbi__compute_transparency16(stbi__png *z, uint16_t tc[3],
int out_n) {
stbi__context *s = z->s;
uint32_t i, pixel_count = s->img_x * s->img_y;
uint16_t *p = (uint16_t *)z->out;
// compute color-based transparency, assuming we've
// already got 65535 as the alpha value in the output
assert(out_n == 2 || out_n == 4);
if (out_n == 2) {
for (i = 0; i < pixel_count; ++i) {
p[1] = (p[0] == tc[0] ? 0 : 65535);
p += 2;
}
} else {
for (i = 0; i < pixel_count; ++i) {
if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0;
p += 4;
}
}
return 1;
}
static int stbi__expand_png_palette(stbi__png *a, unsigned char *palette,
int len, int pal_img_n) {
uint32_t i, pixel_count = a->s->img_x * a->s->img_y;
unsigned char *p, *temp_out, *orig = a->out;
p = stbi__malloc_mad2(pixel_count, pal_img_n, 0);
// between here and free(out) below, exitting would leak
temp_out = p;
if (pal_img_n == 3) {
for (i = 0; i < pixel_count; ++i) {
int n = orig[i] * 4;
p[0] = palette[n];
p[1] = palette[n + 1];
p[2] = palette[n + 2];
p += 3;
}
} else {
for (i = 0; i < pixel_count; ++i) {
int n = orig[i] * 4;
p[0] = palette[n];
p[1] = palette[n + 1];
p[2] = palette[n + 2];
p[3] = palette[n + 3];
p += 4;
}
}
free(a->out);
a->out = temp_out;
return 1;
}
void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) {
stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply;
}
void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) {
stbi__de_iphone_flag = flag_true_if_should_convert;
}
static void stbi__de_iphone(stbi__png *z) {
stbi__context *s = z->s;
uint32_t i, pixel_count = s->img_x * s->img_y;
unsigned char *p = z->out;
if (s->img_out_n == 3) { // convert bgr to rgb
for (i = 0; i < pixel_count; ++i) {
unsigned char t = p[0];
p[0] = p[2];
p[2] = t;
p += 3;
}
} else {
assert(s->img_out_n == 4);
if (stbi__unpremultiply_on_load) {
// convert bgr to rgb and unpremultiply
for (i = 0; i < pixel_count; ++i) {
unsigned char a = p[3];
unsigned char t = p[0];
if (a) {
unsigned char half = a / 2;
p[0] = (p[2] * 255 + half) / a;
p[1] = (p[1] * 255 + half) / a;
p[2] = (t * 255 + half) / a;
} else {
p[0] = p[2];
p[2] = t;
}
p += 4;
}
} else {
// convert bgr to rgb
for (i = 0; i < pixel_count; ++i) {
unsigned char t = p[0];
p[0] = p[2];
p[2] = t;
p += 4;
}
}
}
}
#define STBI__PNG_TYPE(a, b, c, d) \
(((unsigned)(a) << 24) + ((unsigned)(b) << 16) + ((unsigned)(c) << 8) + \
(unsigned)(d))
static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) {
unsigned char palette[1024], pal_img_n = 0;
unsigned char has_trans = 0, tc[3] = {0};
uint16_t tc16[3];
uint32_t ioff = 0, idata_limit = 0, i, pal_len = 0;
int first = 1, k, interlace = 0, color = 0, is_iphone = 0;
stbi__context *s = z->s;
z->expanded = NULL;
z->idata = NULL;
z->out = NULL;
if (!stbi__check_png_header(s)) return 0;
if (scan == STBI__SCAN_type) return 1;
for (;;) {
stbi__pngchunk c = stbi__get_chunk_header(s);
switch (c.type) {
case STBI__PNG_TYPE('C', 'g', 'B', 'I'):
is_iphone = 1;
stbi__skip(s, c.length);
break;
case STBI__PNG_TYPE('I', 'H', 'D', 'R'): {
int comp, filter;
if (!first) return stbi__err("multiple IHDR", "Corrupt PNG");
first = 0;
if (c.length != 13) return stbi__err("bad IHDR len", "Corrupt PNG");
s->img_x = stbi__get32be(s);
if (s->img_x > (1 << 24))
return stbi__err("too large", "Very large image (corrupt?)");
s->img_y = stbi__get32be(s);
if (s->img_y > (1 << 24))
return stbi__err("too large", "Very large image (corrupt?)");
z->depth = stbi__get8(s);
if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 &&
z->depth != 16)
return stbi__err("1/2/4/8/16-bit only",
"PNG not supported: 1/2/4/8/16-bit only");
color = stbi__get8(s);
if (color > 6) return stbi__err("bad ctype", "Corrupt PNG");
if (color == 3 && z->depth == 16)
return stbi__err("bad ctype", "Corrupt PNG");
if (color == 3)
pal_img_n = 3;
else if (color & 1)
return stbi__err("bad ctype", "Corrupt PNG");
comp = stbi__get8(s);
if (comp) return stbi__err("bad comp method", "Corrupt PNG");
filter = stbi__get8(s);
if (filter) return stbi__err("bad filter method", "Corrupt PNG");
interlace = stbi__get8(s);
if (interlace > 1)
return stbi__err("bad interlace method", "Corrupt PNG");
if (!s->img_x || !s->img_y)
return stbi__err("0-pixel image", "Corrupt PNG");
if (!pal_img_n) {
s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
if ((1 << 30) / s->img_x / s->img_n < s->img_y)
return stbi__err("too large", "Image too large to decode");
if (scan == STBI__SCAN_header) return 1;
} else {
// if paletted, then pal_n is our final components, and
// img_n is # components to decompress/filter.
s->img_n = 1;
if ((1 << 30) / s->img_x / 4 < s->img_y)
return stbi__err("too large", "Corrupt PNG");
// if SCAN_header, have to scan to see if we have a tRNS
}
break;
}
case STBI__PNG_TYPE('P', 'L', 'T', 'E'): {
if (first) return stbi__err("first not IHDR", "Corrupt PNG");
if (c.length > 256 * 3) return stbi__err("invalid PLTE", "Corrupt PNG");
pal_len = c.length / 3;
if (pal_len * 3 != c.length)
return stbi__err("invalid PLTE", "Corrupt PNG");
for (i = 0; i < pal_len; ++i) {
palette[i * 4 + 0] = stbi__get8(s);
palette[i * 4 + 1] = stbi__get8(s);
palette[i * 4 + 2] = stbi__get8(s);
palette[i * 4 + 3] = 255;
}
break;
}
case STBI__PNG_TYPE('t', 'R', 'N', 'S'): {
if (first) return stbi__err("first not IHDR", "Corrupt PNG");
if (z->idata) return stbi__err("tRNS after IDAT", "Corrupt PNG");
if (pal_img_n) {
if (scan == STBI__SCAN_header) {
s->img_n = 4;
return 1;
}
if (pal_len == 0) return stbi__err("tRNS before PLTE", "Corrupt PNG");
if (c.length > pal_len)
return stbi__err("bad tRNS len", "Corrupt PNG");
pal_img_n = 4;
for (i = 0; i < c.length; ++i) palette[i * 4 + 3] = stbi__get8(s);
} else {
if (!(s->img_n & 1))
return stbi__err("tRNS with alpha", "Corrupt PNG");
if (c.length != (uint32_t)s->img_n * 2)
return stbi__err("bad tRNS len", "Corrupt PNG");
has_trans = 1;
if (z->depth == 16) {
for (k = 0; k < s->img_n; ++k)
tc16[k] = (uint16_t)stbi__get16be(s); // copy the values as-is
} else {
for (k = 0; k < s->img_n; ++k)
tc[k] = (unsigned char)(stbi__get16be(s) & 255) *
stbi__depth_scale_table[z->depth]; // non 8-bit images
// will be larger
}
}
break;
}
case STBI__PNG_TYPE('I', 'D', 'A', 'T'): {
if (first) return stbi__err("first not IHDR", "Corrupt PNG");
if (pal_img_n && !pal_len) return stbi__err("no PLTE", "Corrupt PNG");
if (scan == STBI__SCAN_header) {
s->img_n = pal_img_n;
return 1;
}
if ((int)(ioff + c.length) < (int)ioff) return 0;
if (ioff + c.length > idata_limit) {
uint32_t idata_limit_old = idata_limit;
unsigned char *p;
if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
while (ioff + c.length > idata_limit) idata_limit *= 2;
(void)idata_limit_old;
p = STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit);
if (p == NULL) return stbi__err("outofmem", "Out of memory");
z->idata = p;
}
if (!stbi__getn(s, z->idata + ioff, c.length))
return stbi__err("outofdata", "Corrupt PNG");
ioff += c.length;
break;
}
case STBI__PNG_TYPE('I', 'E', 'N', 'D'): {
uint32_t raw_len, bpl;
if (first) return stbi__err("first not IHDR", "Corrupt PNG");
if (scan != STBI__SCAN_load) return 1;
if (z->idata == NULL) return stbi__err("no IDAT", "Corrupt PNG");
// initial guess for decoded data size to avoid unnecessary reallocs
bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component
raw_len = bpl * s->img_y * s->img_n /* pixels */ +
s->img_y /* filter mode per row */;
z->expanded =
(unsigned char *)stbi_zlib_decode_malloc_guesssize_headerflag(
(char *)z->idata, ioff, raw_len, (int *)&raw_len, !is_iphone);
if (z->expanded == NULL) return 0; // zlib should set error
free(z->idata);
z->idata = NULL;
if ((req_comp == s->img_n + 1 && req_comp != 3 && !pal_img_n) ||
has_trans) {
s->img_out_n = s->img_n + 1;
} else {
s->img_out_n = s->img_n;
}
if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n,
z->depth, color, interlace))
return 0;
if (has_trans) {
if (z->depth == 16) {
if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0;
} else {
if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;
}
}
if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)
stbi__de_iphone(z);
if (pal_img_n) {
// pal_img_n == 3 or 4
s->img_n = pal_img_n; // record the actual colors we had
s->img_out_n = pal_img_n;
if (req_comp >= 3) s->img_out_n = req_comp;
if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))
return 0;
} else if (has_trans) {
// non-paletted image with tRNS -> source image has (constant) alpha
++s->img_n;
}
free(z->expanded);
z->expanded = NULL;
stbi__get32be(s); /* nothings/stb#835 */
return 1;
}
default:
// if critical, fail
if (first) return stbi__err("first not IHDR", "Corrupt PNG");
if ((c.type & (1 << 29)) == 0) {
#ifndef STBI_NO_FAILURE_STRINGS
// not threadsafe
static char invalid_chunk[] = "XXXX PNG chunk not known";
invalid_chunk[0] = STBI__BYTECAST(c.type >> 24);
invalid_chunk[1] = STBI__BYTECAST(c.type >> 16);
invalid_chunk[2] = STBI__BYTECAST(c.type >> 8);
invalid_chunk[3] = STBI__BYTECAST(c.type >> 0);
#endif
return stbi__err(invalid_chunk,
"PNG not supported: unknown PNG chunk type");
}
stbi__skip(s, c.length);
break;
}
// end of PNG chunk, read and skip CRC
stbi__get32be(s);
}
}
static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp,
stbi__result_info *ri) {
void *result = NULL;
if (req_comp < 0 || req_comp > 4)
return stbi__errpuc("bad req_comp", "Internal error");
if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) {
if (p->depth < 8)
ri->bits_per_channel = 8;
else
ri->bits_per_channel = p->depth;
result = p->out;
p->out = NULL;
if (req_comp && req_comp != p->s->img_out_n) {
if (ri->bits_per_channel == 8)
result = stbi__convert_format((unsigned char *)result, p->s->img_out_n,
req_comp, p->s->img_x, p->s->img_y);
else
result = stbi__convert_format16((uint16_t *)result, p->s->img_out_n,
req_comp, p->s->img_x, p->s->img_y);
p->s->img_out_n = req_comp;
if (result == NULL) return result;
}
*x = p->s->img_x;
*y = p->s->img_y;
if (n) *n = p->s->img_n;
}
free(p->out);
p->out = NULL;
free(p->expanded);
p->expanded = NULL;
free(p->idata);
p->idata = NULL;
return result;
}
static dontinline void *stbi__png_load(stbi__context *s, int *x, int *y,
int *comp, int req_comp,
stbi__result_info *ri) {
stbi__png p;
p.s = s;
return stbi__do_png(&p, x, y, comp, req_comp, ri);
}
static int stbi__png_test(stbi__context *s) {
int r;
r = stbi__check_png_header(s);
stbi__rewind(s);
return r;
}
static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) {
if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) {
stbi__rewind(p->s);
return 0;
}
if (x) *x = p->s->img_x;
if (y) *y = p->s->img_y;
if (comp) *comp = p->s->img_n;
return 1;
}
static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) {
stbi__png p;
p.s = s;
return stbi__png_info_raw(&p, x, y, comp);
}
static int stbi__png_is16(stbi__context *s) {
stbi__png p;
p.s = s;
if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) return 0;
if (p.depth != 16) {
stbi__rewind(p.s);
return 0;
}
return 1;
}
// *****************************************************************************
// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by
// stb
typedef struct {
int16_t prefix;
unsigned char first;
unsigned char suffix;
} stbi__gif_lzw;
typedef struct {
int w, h;
unsigned char *out; // output buffer (always 4 components)
unsigned char
*background; // The current "background" as far as a gif is concerned
unsigned char *history;
int flags, bgindex, ratio, transparent, eflags;
unsigned char pal[256][4];
unsigned char lpal[256][4];
stbi__gif_lzw codes[8192];
unsigned char *color_table;
int parse, step;
int lflags;
int start_x, start_y;
int max_x, max_y;
int cur_x, cur_y;
int line_size;
int delay;
} stbi__gif;
static int stbi__gif_test_raw(stbi__context *s) {
int sz;
if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' ||
stbi__get8(s) != '8')
return 0;
sz = stbi__get8(s);
if (sz != '9' && sz != '7') return 0;
if (stbi__get8(s) != 'a') return 0;
return 1;
}
static int stbi__gif_test(stbi__context *s) {
int r = stbi__gif_test_raw(s);
stbi__rewind(s);
return r;
}
static void stbi__gif_parse_colortable(stbi__context *s,
unsigned char pal[256][4],
int num_entries, int transp) {
int i;
for (i = 0; i < num_entries; ++i) {
pal[i][2] = stbi__get8(s);
pal[i][1] = stbi__get8(s);
pal[i][0] = stbi__get8(s);
pal[i][3] = transp == i ? 0 : 255;
}
}
static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp,
int is_info) {
unsigned char version;
if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' ||
stbi__get8(s) != '8')
return stbi__err("not GIF", "Corrupt GIF");
version = stbi__get8(s);
if (version != '7' && version != '9') {
return stbi__err("not GIF", "Corrupt GIF");
}
if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF");
stbi__g_failure_reason = "";
g->w = stbi__get16le(s);
g->h = stbi__get16le(s);
g->flags = stbi__get8(s);
g->bgindex = stbi__get8(s);
g->ratio = stbi__get8(s);
g->transparent = -1;
if (comp != 0) {
*comp = 4; // can't actually tell whether it's 3 or 4 until we parse the
// comments
}
if (is_info) return 1;
if (g->flags & 0x80) {
stbi__gif_parse_colortable(s, g->pal, 2 << (g->flags & 7), -1);
}
return 1;
}
static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) {
stbi__gif *g = (stbi__gif *)malloc(sizeof(stbi__gif));
if (!stbi__gif_header(s, g, comp, 1)) {
free(g);
stbi__rewind(s);
return 0;
}
if (x) *x = g->w;
if (y) *y = g->h;
free(g);
return 1;
}
static void stbi__out_gif_code(stbi__gif *g, uint16_t code) {
unsigned char *p, *c;
int idx;
// recurse to decode the prefixes, since the linked-list is backwards,
// and working backwards through an interleaved image would be nasty
if (g->codes[code].prefix >= 0) stbi__out_gif_code(g, g->codes[code].prefix);
if (g->cur_y >= g->max_y) return;
idx = g->cur_x + g->cur_y;
p = &g->out[idx];
g->history[idx / 4] = 1;
c = &g->color_table[g->codes[code].suffix * 4];
if (c[3] > 128) { // don't render transparent pixels;
p[0] = c[2];
p[1] = c[1];
p[2] = c[0];
p[3] = c[3];
}
g->cur_x += 4;
if (g->cur_x >= g->max_x) {
g->cur_x = g->start_x;
g->cur_y += g->step;
while (g->cur_y >= g->max_y && g->parse > 0) {
g->step = (1 << g->parse) * g->line_size;
g->cur_y = g->start_y + (g->step >> 1);
--g->parse;
}
}
}
static unsigned char *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) {
unsigned char lzw_cs;
int32_t len, init_code;
uint32_t first;
int32_t codesize, codemask, avail, oldcode, bits, valid_bits, clear;
stbi__gif_lzw *p;
lzw_cs = stbi__get8(s);
if (lzw_cs > 12) return NULL;
clear = 1 << lzw_cs;
first = 1;
codesize = lzw_cs + 1;
codemask = (1 << codesize) - 1;
bits = 0;
valid_bits = 0;
for (init_code = 0; init_code < clear; init_code++) {
g->codes[init_code].prefix = -1;
g->codes[init_code].first = (unsigned char)init_code;
g->codes[init_code].suffix = (unsigned char)init_code;
}
// support no starting clear code
avail = clear + 2;
oldcode = -1;
len = 0;
for (;;) {
if (valid_bits < codesize) {
if (len == 0) {
len = stbi__get8(s); // start new block
if (len == 0) return g->out;
}
--len;
bits |= (int32_t)stbi__get8(s) << valid_bits;
valid_bits += 8;
} else {
int32_t code = bits & codemask;
bits >>= codesize;
valid_bits -= codesize;
// @OPTIMIZE: is there some way we can accelerate the non-clear path?
if (code == clear) { // clear code
codesize = lzw_cs + 1;
codemask = (1 << codesize) - 1;
avail = clear + 2;
oldcode = -1;
first = 0;
} else if (code == clear + 1) { // end of stream code
stbi__skip(s, len);
while ((len = stbi__get8(s)) > 0) stbi__skip(s, len);
return g->out;
} else if (code <= avail) {
if (first) {
return stbi__errpuc("no clear code", "Corrupt GIF");
}
if (oldcode >= 0) {
p = &g->codes[avail++];
if (avail > 8192) {
return stbi__errpuc("too many codes", "Corrupt GIF");
}
p->prefix = (int16_t)oldcode;
p->first = g->codes[oldcode].first;
p->suffix = (code == avail) ? p->first : g->codes[code].first;
} else if (code == avail)
return stbi__errpuc("illegal code in raster", "Corrupt GIF");
stbi__out_gif_code(g, (uint16_t)code);
if ((avail & codemask) == 0 && avail <= 0x0FFF) {
codesize++;
codemask = (1 << codesize) - 1;
}
oldcode = code;
} else {
return stbi__errpuc("illegal code in raster", "Corrupt GIF");
}
}
}
}
// this function is designed to support animated gifs, although stb_image
// doesn't support it two back is the image from two frames ago, used for a
// very specific disposal format
static unsigned char *stbi__gif_load_next(stbi__context *s, stbi__gif *g,
int *comp, int req_comp,
unsigned char *two_back) {
int dispose;
int first_frame;
int pi;
int pcount;
// on first frame, any non-written pixels get the background colour
// (non-transparent)
first_frame = 0;
if (g->out == 0) {
if (!stbi__gif_header(s, g, comp, 0))
return 0; // stbi__g_failure_reason set by stbi__gif_header
if (!stbi__mad3sizes_valid(4, g->w, g->h, 0))
return stbi__errpuc("too large", "GIF image is too large");
pcount = g->w * g->h;
g->out = malloc(4 * pcount);
g->background = malloc(4 * pcount);
g->history = malloc(pcount);
if (!g->out || !g->background || !g->history)
return stbi__errpuc("outofmem", "Out of memory");
// image is treated as "transparent" at the start - ie, nothing overwrites
// the current background; background colour is only used for pixels that
// are not rendered first frame, after that "background" color refers to
// the color that was there the previous frame.
bzero(g->out, 4 * pcount);
bzero(g->background,
4 * pcount); // state of the background (starts transparent)
bzero(g->history,
pcount); // pixels that were affected previous frame
first_frame = 1;
} else {
// second frame - how do we dispoase of the previous one?
dispose = (g->eflags & 0x1C) >> 2;
pcount = g->w * g->h;
if ((dispose == 3) && (two_back == 0)) {
dispose = 2; // if I don't have an image to revert back to, default to
// the old background
}
if (dispose == 3) { // use previous graphic
for (pi = 0; pi < pcount; ++pi) {
if (g->history[pi]) {
memcpy(&g->out[pi * 4], &two_back[pi * 4], 4);
}
}
} else if (dispose == 2) {
// restore what was changed last frame to background before that frame;
for (pi = 0; pi < pcount; ++pi) {
if (g->history[pi]) {
memcpy(&g->out[pi * 4], &g->background[pi * 4], 4);
}
}
} else {
// This is a non-disposal case eithe way, so just
// leave the pixels as is, and they will become the new background
// 1: do not dispose
// 0: not specified.
}
// background is what out is after the undoing of the previou frame;
memcpy(g->background, g->out, 4 * g->w * g->h);
}
// clear my history;
bzero(g->history,
g->w * g->h); // pixels that were affected previous frame
for (;;) {
int tag = stbi__get8(s);
switch (tag) {
case 0x2C: /* Image Descriptor */
{
int32_t x, y, w, h;
unsigned char *o;
x = stbi__get16le(s);
y = stbi__get16le(s);
w = stbi__get16le(s);
h = stbi__get16le(s);
if (((x + w) > (g->w)) || ((y + h) > (g->h)))
return stbi__errpuc("bad Image Descriptor", "Corrupt GIF");
g->line_size = g->w * 4;
g->start_x = x * 4;
g->start_y = y * g->line_size;
g->max_x = g->start_x + w * 4;
g->max_y = g->start_y + h * g->line_size;
g->cur_x = g->start_x;
g->cur_y = g->start_y;
// if the width of the specified rectangle is 0, that means
// we may not see *any* pixels or the image is malformed;
// to make sure this is caught, move the current y down to
// max_y (which is what out_gif_code checks).
if (w == 0) g->cur_y = g->max_y;
g->lflags = stbi__get8(s);
if (g->lflags & 0x40) {
g->step = 8 * g->line_size; // first interlaced spacing
g->parse = 3;
} else {
g->step = g->line_size;
g->parse = 0;
}
if (g->lflags & 0x80) {
stbi__gif_parse_colortable(s, g->lpal, 2 << (g->lflags & 7),
g->eflags & 0x01 ? g->transparent : -1);
g->color_table = (unsigned char *)g->lpal;
} else if (g->flags & 0x80) {
g->color_table = (unsigned char *)g->pal;
} else
return stbi__errpuc("missing color table", "Corrupt GIF");
o = stbi__process_gif_raster(s, g);
if (!o) return NULL;
// if this was the first frame,
pcount = g->w * g->h;
if (first_frame && (g->bgindex > 0)) {
// if first frame, any pixel not drawn to gets the background color
for (pi = 0; pi < pcount; ++pi) {
if (g->history[pi] == 0) {
g->pal[g->bgindex][3] =
255; // just in case it was made transparent, undo that; It
// will be reset next frame if need be;
memcpy(&g->out[pi * 4], &g->pal[g->bgindex], 4);
}
}
}
return o;
}
case 0x21: // Comment Extension.
{
int len;
int ext = stbi__get8(s);
if (ext == 0xF9) { // Graphic Control Extension.
len = stbi__get8(s);
if (len == 4) {
g->eflags = stbi__get8(s);
g->delay =
10 *
stbi__get16le(
s); // delay - 1/100th of a second, saving as 1/1000ths.
// unset old transparent
if (g->transparent >= 0) {
g->pal[g->transparent][3] = 255;
}
if (g->eflags & 0x01) {
g->transparent = stbi__get8(s);
if (g->transparent >= 0) {
g->pal[g->transparent][3] = 0;
}
} else {
// don't need transparent
stbi__skip(s, 1);
g->transparent = -1;
}
} else {
stbi__skip(s, len);
break;
}
}
while ((len = stbi__get8(s)) != 0) {
stbi__skip(s, len);
}
break;
}
case 0x3B: // gif stream termination code
return (
unsigned char *)s; // using '1' causes warning on some compilers
default:
return stbi__errpuc("unknown code", "Corrupt GIF");
}
}
}
static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y,
int *z, int *comp, int req_comp) {
if (stbi__gif_test(s)) {
int layers = 0;
unsigned char *u = 0;
unsigned char *out = 0;
unsigned char *two_back = 0;
stbi__gif *g;
int stride;
g = calloc(1, sizeof(stbi__gif));
if (delays) {
*delays = 0;
}
do {
u = stbi__gif_load_next(s, g, comp, req_comp, two_back);
if (u == (unsigned char *)s) u = 0; // end of animated gif marker
if (u) {
*x = g->w;
*y = g->h;
++layers;
stride = g->w * g->h * 4;
if (out) {
out = (unsigned char *)realloc(out, layers * stride);
if (!out) abort();
if (delays) {
*delays = (int *)realloc(*delays, sizeof(int) * layers);
if (!*delays) abort();
}
} else {
out = malloc(layers * stride);
if (delays) {
*delays = malloc(layers * sizeof(int));
}
}
memcpy(out + ((layers - 1) * stride), u, stride);
if (layers >= 2) {
two_back = out - 2 * stride;
}
if (delays) {
(*delays)[layers - 1U] = g->delay;
}
}
} while (u != 0);
free(g->out);
free(g->history);
free(g->background);
// do the final conversion after loading everything;
if (req_comp && req_comp != 4)
out = stbi__convert_format(out, 4, req_comp, layers * g->w, g->h);
free(g);
*z = layers;
return out;
} else {
return stbi__errpuc("not GIF", "Image was not as a gif type.");
}
}
static dontinline void *stbi__gif_load(stbi__context *s, int *x, int *y,
int *comp, int req_comp,
stbi__result_info *ri) {
unsigned char *u = 0;
stbi__gif *g;
g = calloc(1, sizeof(stbi__gif));
u = stbi__gif_load_next(s, g, comp, req_comp, 0);
if (u == (unsigned char *)s) u = 0; // end of animated gif marker
if (u) {
*x = g->w;
*y = g->h;
// moved conversion to after successful load so that the same
// can be done for multiple frames.
if (req_comp && req_comp != 4)
u = stbi__convert_format(u, 4, req_comp, g->w, g->h);
} else if (g->out) {
// if there was an error and we allocated an image buffer, free it!
free(g->out);
}
// free buffers needed for multiple frame loading;
free(g->history);
free(g->background);
free(g);
return u;
}
static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) {
return stbi__gif_info_raw(s, x, y, comp);
}
// ********************************************************************
// Portable Gray Map and Portable Pixel Map loader
// by Ken Miller
//
// PGM: http://netpbm.sourceforge.net/doc/pgm.html
// PPM: http://netpbm.sourceforge.net/doc/ppm.html
//
// Known limitations:
// Does not support comments in the header section
// Does not support ASCII image data (formats P2 and P3)
// Does not support 16-bit-per-channel
static int stbi__pnm_test(stbi__context *s) {
char p, t;
p = (char)stbi__get8(s);
t = (char)stbi__get8(s);
if (p != 'P' || (t != '5' && t != '6')) {
stbi__rewind(s);
return 0;
}
return 1;
}
static dontinline void *stbi__pnm_load(stbi__context *s, int *x, int *y,
int *comp, int req_comp,
stbi__result_info *ri) {
unsigned char *out;
if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y,
(int *)&s->img_n)) {
return 0;
}
*x = s->img_x;
*y = s->img_y;
if (comp) *comp = s->img_n;
if (!stbi__mad3sizes_valid(s->img_n, s->img_x, s->img_y, 0)) {
return stbi__errpuc("too large", "PNM too large");
}
out = stbi__malloc_mad3(s->img_n, s->img_x, s->img_y, 0);
stbi__getn(s, out, s->img_n * s->img_x * s->img_y);
if (req_comp && req_comp != s->img_n) {
out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);
if (out == NULL) return out; // stbi__convert_format frees input on failure
}
return out;
}
static int stbi__pnm_isspace(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' ||
c == '\r';
}
static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) {
for (;;) {
while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) *c = (char)stbi__get8(s);
if (stbi__at_eof(s) || *c != '#') break;
while (!stbi__at_eof(s) && *c != '\n' && *c != '\r')
*c = (char)stbi__get8(s);
}
}
static int stbi__pnm_isdigit(char c) {
return c >= '0' && c <= '9';
}
static int stbi__pnm_getinteger(stbi__context *s, char *c) {
int value = 0;
while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) {
value = value * 10 + (*c - '0');
*c = (char)stbi__get8(s);
}
return value;
}
static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) {
int maxv, dummy;
char c, p, t;
if (!x) x = &dummy;
if (!y) y = &dummy;
if (!comp) comp = &dummy;
stbi__rewind(s);
// Get identifier
p = (char)stbi__get8(s);
t = (char)stbi__get8(s);
if (p != 'P' || (t != '5' && t != '6')) {
stbi__rewind(s);
return 0;
}
*comp =
(t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm
c = (char)stbi__get8(s);
stbi__pnm_skip_whitespace(s, &c);
*x = stbi__pnm_getinteger(s, &c); // read width
stbi__pnm_skip_whitespace(s, &c);
*y = stbi__pnm_getinteger(s, &c); // read height
stbi__pnm_skip_whitespace(s, &c);
maxv = stbi__pnm_getinteger(s, &c); // read max value
if (maxv > 255)
return stbi__err("max value > 255", "PPM image not 8-bit");
else {
return 1;
}
}
static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) {
#ifndef STBI_NO_JPEG
if (stbi__jpeg_info(s, x, y, comp)) return 1;
#endif
#ifndef STBI_NO_PNG
if (stbi__png_info(s, x, y, comp)) return 1;
#endif
#ifndef STBI_NO_GIF
if (stbi__gif_info(s, x, y, comp)) return 1;
#endif
#ifndef STBI_NO_PNM
if (stbi__pnm_info(s, x, y, comp)) return 1;
#endif
return stbi__err("unknown image type",
"Image not of any known type, or corrupt");
}
static int stbi__is_16_main(stbi__context *s) {
if (stbi__png_is16(s)) return 1;
return 0;
}
int stbi_info(char const *filename, int *x, int *y, int *comp) {
FILE *f = stbi__fopen(filename, "rb");
int result;
if (!f) return stbi__err("can't fopen", "Unable to open file");
result = stbi_info_from_file(f, x, y, comp);
fclose(f);
return result;
}
int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) {
int r;
stbi__context s;
long pos = ftell(f);
stbi__start_file(&s, f);
r = stbi__info_main(&s, x, y, comp);
fseek(f, pos, SEEK_SET);
return r;
}
int stbi_is_16_bit(char const *filename) {
FILE *f = stbi__fopen(filename, "rb");
int result;
if (!f) return stbi__err("can't fopen", "Unable to open file");
result = stbi_is_16_bit_from_file(f);
fclose(f);
return result;
}
int stbi_is_16_bit_from_file(FILE *f) {
int r;
stbi__context s;
long pos = ftell(f);
stbi__start_file(&s, f);
r = stbi__is_16_main(&s);
fseek(f, pos, SEEK_SET);
return r;
}
int stbi_info_from_memory(unsigned char const *buffer, int len, int *x, int *y,
int *comp) {
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__info_main(&s, x, y, comp);
}
int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x,
int *y, int *comp) {
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks *)c, user);
return stbi__info_main(&s, x, y, comp);
}
int stbi_is_16_bit_from_memory(unsigned char const *buffer, int len) {
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__is_16_main(&s);
}
int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) {
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks *)c, user);
return stbi__is_16_main(&s);
}
| 166,764 | 4,890 | jart/cosmopolitan | false |
cosmopolitan/third_party/stb/stb_vorbis.c | // Ogg Vorbis audio decoder - v1.17 - public domain
// http://nothings.org/stb_vorbis/
//
// Original version written by Sean Barrett in 2007.
//
// Originally sponsored by RAD Game Tools. Seeking implementation
// sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker,
// Elias Software, Aras Pranckevicius, and Sean Barrett.
//
// LICENSE
//
// See end of file for license information.
//
// Limitations:
//
// - floor 0 not supported (used in old ogg vorbis files pre-2004)
// - lossless sample-truncation at beginning ignored
// - cannot concatenate multiple vorbis streams
// - sample positions are 32-bit, limiting seekable 192Khz
// files to around 6 hours (Ogg supports 64-bit)
//
// Feature contributors:
// Dougall Johnson (sample-exact seeking)
//
// Bugfix/warning contributors:
// Terje Mathisen Niklas Frykholm Andy Hill
// Casey Muratori John Bolton Gargaj
// Laurent Gomila Marc LeBlanc Ronny Chevalier
// Bernhard Wodo Evan Balster alxprd@github
// Tom Beaumont Ingo Leitgeb Nicolas Guillemot
// Phillip Bennefall Rohit Thiago Goulart
// manxorist@github saga musix github:infatum
// Timur Gagiev Maxwell Koo
//
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/bits.h"
#include "libc/limits.h"
#include "libc/math.h"
#include "libc/mem/alg.h"
#include "libc/mem/alloca.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "third_party/stb/stb_vorbis.h"
// STB_VORBIS_NO_PUSHDATA_API
// does not compile the code for the various stb_vorbis_*_pushdata()
// functions
// #define STB_VORBIS_NO_PUSHDATA_API
// STB_VORBIS_NO_PULLDATA_API
// does not compile the code for the non-pushdata APIs
// #define STB_VORBIS_NO_PULLDATA_API
// STB_VORBIS_NO_STDIO
// does not compile the code for the APIs that use FILE *s internally
// or externally (implied by STB_VORBIS_NO_PULLDATA_API)
// #define STB_VORBIS_NO_STDIO
// STB_VORBIS_NO_INTEGER_CONVERSION
// does not compile the code for converting audio sample data from
// float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
// #define STB_VORBIS_NO_INTEGER_CONVERSION
// STB_VORBIS_NO_FAST_SCALED_FLOAT
// does not use a fast float-to-int trick to accelerate float-to-int on
// most platforms which requires endianness be defined correctly.
//#define STB_VORBIS_NO_FAST_SCALED_FLOAT
// STB_VORBIS_MAX_CHANNELS [number]
// globally define this to the maximum number of channels you need.
// The spec does not put a restriction on channels except that
// the count is stored in a byte, so 255 is the hard limit.
// Reducing this saves about 16 bytes per value, so using 16 saves
// (255-16)*16 or around 4KB. Plus anything other memory usage
// I forgot to account for. Can probably go as low as 8 (7.1 audio),
// 6 (5.1 audio), or 2 (stereo only).
#ifndef STB_VORBIS_MAX_CHANNELS
#define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?
#endif
// STB_VORBIS_PUSHDATA_CRC_COUNT [number]
// after a flush_pushdata(), stb_vorbis begins scanning for the
// next valid page, without backtracking. when it finds something
// that looks like a page, it streams through it and verifies its
// CRC32. Should that validation fail, it keeps scanning. But it's
// possible that _while_ streaming through to check the CRC32 of
// one candidate page, it sees another candidate page. This #define
// determines how many "overlapping" candidate pages it can search
// at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
// garbage pages could be as big as 64KB, but probably average ~16KB.
// So don't hose ourselves by scanning an apparent 64KB page and
// missing a ton of real ones in the interim; so minimum of 2
#ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
#define STB_VORBIS_PUSHDATA_CRC_COUNT 4
#endif
// STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
// sets the log size of the huffman-acceleration table. Maximum
// supported value is 24. with larger numbers, more decodings are O(1),
// but the table size is larger so worse cache missing, so you'll have
// to probe (and try multiple ogg vorbis files) to find the sweet spot.
#ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
#define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
#endif
// STB_VORBIS_FAST_BINARY_LENGTH [number]
// sets the log size of the binary-search acceleration table. this
// is used in similar fashion to the fast-huffman size to set initial
// parameters for the binary search
// STB_VORBIS_FAST_HUFFMAN_INT
// The fast huffman tables are much more efficient if they can be
// stored as 16-bit results instead of 32-bit results. This restricts
// the codebooks to having only 65535 possible outcomes, though.
// (At least, accelerated by the huffman table.)
#ifndef STB_VORBIS_FAST_HUFFMAN_INT
#define STB_VORBIS_FAST_HUFFMAN_SHORT
#endif
// STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
// If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
// back on binary searching for the correct one. This requires storing
// extra tables with the huffman codes in sorted order. Defining this
// symbol trades off space for speed by forcing a linear search in the
// non-fast case, except for "sparse" codebooks.
// #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
// STB_VORBIS_DIVIDES_IN_RESIDUE
// stb_vorbis precomputes the result of the scalar residue decoding
// that would otherwise require a divide per chunk. you can trade off
// space for time by defining this symbol.
// #define STB_VORBIS_DIVIDES_IN_RESIDUE
// STB_VORBIS_DIVIDES_IN_CODEBOOK
// vorbis VQ codebooks can be encoded two ways: with every case explicitly
// stored, or with all elements being chosen from a small range of values,
// and all values possible in all elements. By default, stb_vorbis expands
// this latter kind out to look like the former kind for ease of decoding,
// because otherwise an integer divide-per-vector-element is required to
// unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
// trade off storage for speed.
//#define STB_VORBIS_DIVIDES_IN_CODEBOOK
#ifdef STB_VORBIS_CODEBOOK_SHORTS
#error \
"STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats"
#endif
// STB_VORBIS_DIVIDE_TABLE
// this replaces small integer divides in the floor decode loop with
// table lookups. made less than 1% difference, so disabled by default.
// STB_VORBIS_NO_INLINE_DECODE
// disables the inlining of the scalar codebook fast-huffman decode.
// might save a little codespace; useful for debugging
// #define STB_VORBIS_NO_INLINE_DECODE
// STB_VORBIS_NO_DEFER_FLOOR
// Normally we only decode the floor without synthesizing the actual
// full curve. We can instead synthesize the curve immediately. This
// requires more memory and is very likely slower, so I don't think
// you'd ever want to do it except for debugging.
// #define STB_VORBIS_NO_DEFER_FLOOR
//////////////////////////////////////////////////////////////////////////////
#ifdef STB_VORBIS_NO_PULLDATA_API
#define STB_VORBIS_NO_INTEGER_CONVERSION
#define STB_VORBIS_NO_STDIO
#endif
#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
#define STB_VORBIS_NO_STDIO 1
#endif
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
// only need endianness for fast-float-to-int, which we don't
// use for pushdata
#ifndef STB_VORBIS_BIG_ENDIAN
#define STB_VORBIS_ENDIAN 0
#else
#define STB_VORBIS_ENDIAN 1
#endif
#endif
#endif
#if STB_VORBIS_MAX_CHANNELS > 256
#error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"
#endif
#if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24
#error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"
#endif
#if 0
#include <crtdbg.h>
#define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1])
#else
#define CHECK(f) ((void)0)
#endif
#define MAX_BLOCKSIZE_LOG 13 // from specification
#define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)
typedef unsigned char uint8;
typedef signed char int8;
typedef unsigned short uint16;
typedef signed short int16;
typedef unsigned int uint32;
typedef signed int int32;
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
typedef float codetype;
// @NOTE
//
// Some arrays below are tagged "//varies", which means it's actually
// a variable-sized piece of data, but rather than malloc I assume it's
// small enough it's better to just allocate it all together with the
// main thing
//
// Most of the variables are specified with the smallest size I could pack
// them into. It might give better performance to make them all full-sized
// integers. It should be safe to freely rearrange the structures or change
// the sizes larger--nothing relies on silently truncating etc., nor the
// order of variables.
#define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
#define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)
typedef struct {
int dimensions, entries;
uint8 *codeword_lengths;
float minimum_value;
float delta_value;
uint8 value_bits;
uint8 lookup_type;
uint8 sequence_p;
uint8 sparse;
uint32 lookup_values;
codetype *multiplicands;
uint32 *codewords;
#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
#else
int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
#endif
uint32 *sorted_codewords;
int *sorted_values;
int sorted_entries;
} Codebook;
typedef struct {
uint8 order;
uint16 rate;
uint16 bark_map_size;
uint8 amplitude_bits;
uint8 amplitude_offset;
uint8 number_of_books;
uint8 book_list[16]; // varies
} Floor0;
typedef struct {
uint8 partitions;
uint8 partition_class_list[32]; // varies
uint8 class_dimensions[16]; // varies
uint8 class_subclasses[16]; // varies
uint8 class_masterbooks[16]; // varies
int16 subclass_books[16][8]; // varies
uint16 Xlist[31 * 8 + 2]; // varies
uint8 sorted_order[31 * 8 + 2];
uint8 neighbors[31 * 8 + 2][2];
uint8 floor1_multiplier;
uint8 rangebits;
int values;
} Floor1;
typedef union {
Floor0 floor0;
Floor1 floor1;
} Floor;
typedef struct {
uint32 begin, end;
uint32 part_size;
uint8 classifications;
uint8 classbook;
uint8 **classdata;
int16 (*residue_books)[8];
} Residue;
typedef struct {
uint8 magnitude;
uint8 angle;
uint8 mux;
} MappingChannel;
typedef struct {
uint16 coupling_steps;
MappingChannel *chan;
uint8 submaps;
uint8 submap_floor[15]; // varies
uint8 submap_residue[15]; // varies
} Mapping;
typedef struct {
uint8 blockflag;
uint8 mapping;
uint16 windowtype;
uint16 transformtype;
} Mode;
typedef struct {
uint32 goal_crc; // expected crc if match
int bytes_left; // bytes left in packet
uint32 crc_so_far; // running crc
int bytes_done; // bytes processed in _current_ chunk
uint32 sample_loc; // granule pos encoded in page
} CRCscan;
typedef struct {
uint32 page_start, page_end;
uint32 last_decoded_sample;
} ProbedPage;
struct stb_vorbis {
// user-accessible info
unsigned int sample_rate;
int channels;
unsigned int setup_memory_required;
unsigned int temp_memory_required;
unsigned int setup_temp_memory_required;
// input config
#ifndef STB_VORBIS_NO_STDIO
FILE *f;
uint32 f_start;
int close_on_free;
#endif
uint8 *stream;
uint8 *stream_start;
uint8 *stream_end;
uint32 stream_len;
uint8 push_mode;
uint32 first_audio_page_offset;
ProbedPage p_first, p_last;
// memory management
stb_vorbis_alloc alloc;
int setup_offset;
int temp_offset;
// run-time results
int eof;
enum STBVorbisError error;
// user-useful data
// header info
int blocksize[2];
int blocksize_0, blocksize_1;
int codebook_count;
Codebook *codebooks;
int floor_count;
uint16 floor_types[64]; // varies
Floor *floor_config;
int residue_count;
uint16 residue_types[64]; // varies
Residue *residue_config;
int mapping_count;
Mapping *mapping;
int mode_count;
Mode mode_config[64]; // varies
uint32 total_samples;
// decode buffer
float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
float *outputs[STB_VORBIS_MAX_CHANNELS];
float *previous_window[STB_VORBIS_MAX_CHANNELS];
int previous_length;
#ifndef STB_VORBIS_NO_DEFER_FLOOR
int16 *finalY[STB_VORBIS_MAX_CHANNELS];
#else
float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
#endif
uint32 current_loc; // sample location of next frame to decode
int current_loc_valid;
// per-blocksize precomputed data
// twiddle factors
float *A[2], *B[2], *C[2];
float *window[2];
uint16 *bit_reverse[2];
// current page/packet/segment streaming info
uint32 serial; // stream serial number for verification
int last_page;
int segment_count;
uint8 segments[255];
uint8 page_flag;
uint8 bytes_in_seg;
uint8 first_decode;
int next_seg;
int last_seg; // flag that we're on the last segment
int last_seg_which; // what was the segment number of the last seg?
uint32 acc;
int valid_bits;
int packet_bytes;
int end_seg_with_known_loc;
uint32 known_loc_for_packet;
int discard_samples_deferred;
uint32 samples_output;
// push mode scanning
int page_crc_tests; // only in push_mode: number of tests active; -1 if not
// searching
#ifndef STB_VORBIS_NO_PUSHDATA_API
CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];
#endif
// sample-access
int channel_buffer_start;
int channel_buffer_end;
};
#if defined(STB_VORBIS_NO_PUSHDATA_API)
#define IS_PUSH_MODE(f) FALSE
#elif defined(STB_VORBIS_NO_PULLDATA_API)
#define IS_PUSH_MODE(f) TRUE
#else
#define IS_PUSH_MODE(f) ((f)->push_mode)
#endif
typedef struct stb_vorbis vorb;
static int error(vorb *f, enum STBVorbisError e) {
f->error = e;
if (!f->eof && e != VORBIS_need_more_data) {
f->error = e; // breakpoint for debugging
}
return 0;
}
// these functions are used for allocating temporary memory
// while decoding. if you can afford the stack space, use
// alloca(); otherwise, provide a temp buffer and it will
// allocate out of those.
#define array_size_required(count, size) (count * (sizeof(void *) + (size)))
#define temp_alloc(f, size) \
(f->alloc.alloc_buffer ? setup_temp_malloc(f, size) : alloca(size))
#define temp_free(f, p) (void)0
#define temp_alloc_save(f) ((f)->temp_offset)
#define temp_alloc_restore(f, p) ((f)->temp_offset = (p))
#define temp_block_array(f, count, size) \
make_block_array(temp_alloc(f, array_size_required(count, size)), count, size)
// given a sufficiently large block of memory, make an array of pointers to
// subblocks of it
static dontinline void *make_block_array(void *mem, int count, int size) {
int i;
void **p = (void **)mem;
char *q = (char *)(p + count);
for (i = 0; i < count; ++i) {
p[i] = q;
q += size;
}
return p;
}
static dontinline void *setup_malloc(vorb *f, int sz) {
sz = (sz + 3) & ~3;
f->setup_memory_required += sz;
if (f->alloc.alloc_buffer) {
void *p = (char *)f->alloc.alloc_buffer + f->setup_offset;
if (f->setup_offset + sz > f->temp_offset) return NULL;
f->setup_offset += sz;
return p;
}
return sz ? malloc(sz) : NULL;
}
static dontinline void setup_free(vorb *f, void *p) {
if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack
free(p);
}
static dontinline void *setup_temp_malloc(vorb *f, int sz) {
sz = (sz + 3) & ~3;
if (f->alloc.alloc_buffer) {
if (f->temp_offset - sz < f->setup_offset) return NULL;
f->temp_offset -= sz;
return (char *)f->alloc.alloc_buffer + f->temp_offset;
}
return malloc(sz);
}
static dontinline void setup_temp_free(vorb *f, void *p, int sz) {
if (f->alloc.alloc_buffer) {
f->temp_offset += (sz + 3) & ~3;
return;
}
free(p);
}
#define CRC32_POLY 0x04c11db7 // from spec
static uint32 crc_table[256];
static void crc32_init(void) {
int i, j;
uint32 s;
for (i = 0; i < 256; i++) {
for (s = (uint32)i << 24, j = 0; j < 8; ++j)
s = (s << 1) ^ (s >= (1U << 31) ? CRC32_POLY : 0);
crc_table[i] = s;
}
}
forceinline uint32 crc32_update(uint32 crc, uint8 byte) {
return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];
}
static float square(float x) {
return x * x;
}
// this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2,
// log2(4) = 3 as required by the specification. fast(?) implementation from
// stb.h
// @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
static dontinline int ilog(int32 n) {
static signed char log2_4[16] = {0, 1, 2, 2, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4};
if (n < 0) return 0; // signed n returns 0
// 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
if (n < (1 << 14))
if (n < (1 << 4))
return 0 + log2_4[n];
else if (n < (1 << 9))
return 5 + log2_4[n >> 5];
else
return 10 + log2_4[n >> 10];
else if (n < (1 << 24))
if (n < (1 << 19))
return 15 + log2_4[n >> 15];
else
return 20 + log2_4[n >> 20];
else if (n < (1 << 29))
return 25 + log2_4[n >> 25];
else
return 30 + log2_4[n >> 30];
}
#ifndef M_PI
#define M_PI 3.14159265358979323846264f // from CRC
#endif
// code length assigned to a value with no huffman encoding
#define NO_CODE 255
/////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
//
// these functions are only called at setup, and only a few times
// per file
static float float32_unpack(uint32 x) {
// from the specification
uint32 mantissa = x & 0x1fffff;
uint32 sign = x & 0x80000000;
uint32 exp = (x & 0x7fe00000) >> 21;
double res = sign ? -(double)mantissa : (double)mantissa;
return (float)ldexp((float)res, exp - 788);
}
// zlib & jpeg huffman tables assume that the output symbols
// can either be arbitrarily arranged, or have monotonically
// increasing frequencies--they rely on the lengths being sorted;
// this makes for a very simple generation algorithm.
// vorbis allows a huffman table with non-sorted lengths. This
// requires a more sophisticated construction, since symbols in
// order do not map to huffman codes "in order".
static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count,
int len, uint32 *values) {
if (!c->sparse) {
c->codewords[symbol] = huff_code;
} else {
c->codewords[count] = huff_code;
c->codeword_lengths[count] = len;
values[count] = symbol;
}
}
static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values) {
int i, k, m = 0;
uint32 available[32];
bzero(available, sizeof(available));
// find the first entry
for (k = 0; k < n; ++k)
if (len[k] < NO_CODE) break;
if (k == n) {
assert(c->sorted_entries == 0);
return TRUE;
}
// add to the list
add_entry(c, 0, k, m++, len[k], values);
// add all available leaves
for (i = 1; i <= len[k]; ++i) available[i] = 1U << (32 - i);
// note that the above code treats the first case specially,
// but it's really the same as the following code, so they
// could probably be combined (except the initial code is 0,
// and I use 0 in available[] to mean 'empty')
for (i = k + 1; i < n; ++i) {
uint32 res;
int z = len[i], y;
if (z == NO_CODE) continue;
// find lowest available leaf (should always be earliest,
// which is what the specification calls for)
// note that this property, and the fact we can never have
// more than one free leaf at a given level, isn't totally
// trivial to prove, but it seems true and the assert never
// fires, so!
while (z > 0 && !available[z]) --z;
if (z == 0) {
return FALSE;
}
res = available[z];
assert(z >= 0 && z < 32);
available[z] = 0;
add_entry(c, _bitreverse32(res), i, m++, len[i], values);
// propagate availability up the tree
if (z != len[i]) {
assert(len[i] >= 0 && len[i] < 32);
for (y = len[i]; y > z; --y) {
assert(available[y] == 0);
available[y] = res + (1 << (32 - y));
}
}
}
return TRUE;
}
// accelerated huffman table allows fast O(1) match of all symbols
// of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
static void compute_accelerated_huffman(Codebook *c) {
int i, len;
for (i = 0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) c->fast_huffman[i] = -1;
len = c->sparse ? c->sorted_entries : c->entries;
#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
if (len > 32767) len = 32767; // largest possible value we can encode!
#endif
for (i = 0; i < len; ++i) {
if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
uint32 z =
c->sparse ? _bitreverse32(c->sorted_codewords[i]) : c->codewords[i];
// set table entries for all bit combinations in the higher bits
while (z < FAST_HUFFMAN_TABLE_SIZE) {
c->fast_huffman[z] = i;
z += 1 << c->codeword_lengths[i];
}
}
}
}
#ifdef _MSC_VER
#define STBV_CDECL __cdecl
#else
#define STBV_CDECL
#endif
static int STBV_CDECL uint32_compare(const void *p, const void *q) {
uint32 x = *(uint32 *)p;
uint32 y = *(uint32 *)q;
return x < y ? -1 : x > y;
}
static int include_in_sort(Codebook *c, uint8 len) {
if (c->sparse) {
assert(len != NO_CODE);
return TRUE;
}
if (len == NO_CODE) return FALSE;
if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;
return FALSE;
}
// if the fast table above doesn't work, we want to binary
// search them... need to reverse the bits
static void compute_sorted_huffman(Codebook *c, uint8 *lengths,
uint32 *values) {
int i, len;
// build a list of all the entries
// OPTIMIZATION: don't include the short ones, since they'll be caught by
// FAST_HUFFMAN. this is kind of a frivolous optimization--I don't see any
// performance improvement, but it's like 4 extra lines of code, so.
if (!c->sparse) {
int k = 0;
for (i = 0; i < c->entries; ++i)
if (include_in_sort(c, lengths[i]))
c->sorted_codewords[k++] = _bitreverse32(c->codewords[i]);
assert(k == c->sorted_entries);
} else {
for (i = 0; i < c->sorted_entries; ++i)
c->sorted_codewords[i] = _bitreverse32(c->codewords[i]);
}
qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]),
uint32_compare);
c->sorted_codewords[c->sorted_entries] = 0xffffffff;
len = c->sparse ? c->sorted_entries : c->entries;
// now we need to indicate how they correspond; we could either
// #1: sort a different data structure that says who they correspond to
// #2: for each sorted entry, search the original list to find who
// corresponds #3: for each original entry, find the sorted entry
// #1 requires extra storage, #2 is slow, #3 can use binary search!
for (i = 0; i < len; ++i) {
int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
if (include_in_sort(c, huff_len)) {
uint32 code = _bitreverse32(c->codewords[i]);
int x = 0, n = c->sorted_entries;
while (n > 1) {
// invariant: sc[x] <= code < sc[x+n]
int m = x + (n >> 1);
if (c->sorted_codewords[m] <= code) {
x = m;
n -= (n >> 1);
} else {
n >>= 1;
}
}
assert(c->sorted_codewords[x] == code);
if (c->sparse) {
c->sorted_values[x] = values[i];
c->codeword_lengths[x] = huff_len;
} else {
c->sorted_values[x] = i;
}
}
}
}
// only run while parsing the header (3 times)
static int vorbis_validate(uint8 *data) {
static uint8 vorbis[6] = {'v', 'o', 'r', 'b', 'i', 's'};
return memcmp(data, vorbis, 6) == 0;
}
// called from setup only, once per code book
// (formula implied by specification)
static int lookup1_values(int entries, int dim) {
int r = (int)floor(exp((float)log((float)entries) / dim));
if ((int)floor(pow((float)r + 1, dim)) <=
entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
if (pow((float)r + 1, dim) <= entries) return -1;
if ((int)floor(pow((float)r, dim)) > entries) return -1;
return r;
}
// called twice per file
static void compute_twiddle_factors(int n, float *A, float *B, float *C) {
int n4 = n >> 2, n8 = n >> 3;
int k, k2;
for (k = k2 = 0; k < n4; ++k, k2 += 2) {
A[k2] = (float)cos(4 * k * M_PI / n);
A[k2 + 1] = (float)-sin(4 * k * M_PI / n);
B[k2] = (float)cos((k2 + 1) * M_PI / n / 2) * 0.5f;
B[k2 + 1] = (float)sin((k2 + 1) * M_PI / n / 2) * 0.5f;
}
for (k = k2 = 0; k < n8; ++k, k2 += 2) {
C[k2] = (float)cos(2 * (k2 + 1) * M_PI / n);
C[k2 + 1] = (float)-sin(2 * (k2 + 1) * M_PI / n);
}
}
static void compute_window(int n, float *window) {
int n2 = n >> 1, i;
for (i = 0; i < n2; ++i)
window[i] = (float)sin(0.5 * M_PI *
square((float)sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
}
static void compute_bitreverse(int n, uint16 *rev) {
int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
int i, n8 = n >> 3;
for (i = 0; i < n8; ++i) rev[i] = (_bitreverse32(i) >> (32 - ld + 3)) << 2;
}
static int init_blocksize(vorb *f, int b, int n) {
int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
f->A[b] = (float *)setup_malloc(f, sizeof(float) * n2);
f->B[b] = (float *)setup_malloc(f, sizeof(float) * n2);
f->C[b] = (float *)setup_malloc(f, sizeof(float) * n4);
if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);
compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
f->window[b] = (float *)setup_malloc(f, sizeof(float) * n2);
if (!f->window[b]) return error(f, VORBIS_outofmem);
compute_window(n, f->window[b]);
f->bit_reverse[b] = (uint16 *)setup_malloc(f, sizeof(uint16) * n8);
if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);
compute_bitreverse(n, f->bit_reverse[b]);
return TRUE;
}
static void neighbors(uint16 *x, int n, int *plow, int *phigh) {
int low = -1;
int high = 65536;
int hindex, lindex;
int i;
hindex = 0;
lindex = 0;
for (i = 0; i < n; ++i) {
if (x[i] > low && x[i] < x[n]) {
lindex = i;
low = x[i];
}
if (x[i] < high && x[i] > x[n]) {
hindex = i;
high = x[i];
}
}
*phigh = hindex;
*plow = lindex;
}
// this has been repurposed so y is now the original index instead of y
typedef struct {
uint16 x, id;
} stbv__floor_ordering;
static int STBV_CDECL point_compare(const void *p, const void *q) {
stbv__floor_ordering *a = (stbv__floor_ordering *)p;
stbv__floor_ordering *b = (stbv__floor_ordering *)q;
return a->x < b->x ? -1 : a->x > b->x;
}
//
/////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
#if defined(STB_VORBIS_NO_STDIO)
#define USE_MEMORY(z) TRUE
#else
#define USE_MEMORY(z) ((z)->stream)
#endif
static uint8 get8(vorb *z) {
if (USE_MEMORY(z)) {
if (z->stream >= z->stream_end) {
z->eof = TRUE;
return 0;
}
return *z->stream++;
}
#ifndef STB_VORBIS_NO_STDIO
{
int c = fgetc(z->f);
if (c == EOF) {
z->eof = TRUE;
return 0;
}
return c;
}
#endif
}
static uint32 get32(vorb *f) {
uint32 x;
x = get8(f);
x += get8(f) << 8;
x += get8(f) << 16;
x += (uint32)get8(f) << 24;
return x;
}
static int getn(vorb *z, uint8 *data, int n) {
if (USE_MEMORY(z)) {
if (z->stream + n > z->stream_end) {
z->eof = 1;
return 0;
}
memcpy(data, z->stream, n);
z->stream += n;
return 1;
}
#ifndef STB_VORBIS_NO_STDIO
if (fread(data, n, 1, z->f) == 1)
return 1;
else {
z->eof = 1;
return 0;
}
#endif
}
static void skip(vorb *z, int n) {
if (USE_MEMORY(z)) {
z->stream += n;
if (z->stream >= z->stream_end) z->eof = 1;
return;
}
#ifndef STB_VORBIS_NO_STDIO
{
long x = ftell(z->f);
fseek(z->f, x + n, SEEK_SET);
}
#endif
}
static int set_file_offset(stb_vorbis *f, unsigned int loc) {
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (f->push_mode) return 0;
#endif
f->eof = 0;
if (USE_MEMORY(f)) {
if (f->stream_start + loc >= f->stream_end ||
f->stream_start + loc < f->stream_start) {
f->stream = f->stream_end;
f->eof = 1;
return 0;
} else {
f->stream = f->stream_start + loc;
return 1;
}
}
#ifndef STB_VORBIS_NO_STDIO
if (loc + f->f_start < loc || loc >= 0x80000000) {
loc = 0x7fffffff;
f->eof = 1;
} else {
loc += f->f_start;
}
if (!fseek(f->f, loc, SEEK_SET)) return 1;
f->eof = 1;
fseek(f->f, f->f_start, SEEK_END);
return 0;
#endif
}
static uint8 ogg_page_header[4] = {0x4f, 0x67, 0x67, 0x53};
static int capture_pattern(vorb *f) {
if (0x4f != get8(f)) return FALSE;
if (0x67 != get8(f)) return FALSE;
if (0x67 != get8(f)) return FALSE;
if (0x53 != get8(f)) return FALSE;
return TRUE;
}
#define PAGEFLAG_continued_packet 1
#define PAGEFLAG_first_page 2
#define PAGEFLAG_last_page 4
static int start_page_no_capturepattern(vorb *f) {
uint32 loc0, loc1, n;
// stream structure version
if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);
// header flag
f->page_flag = get8(f);
// absolute granule position
loc0 = get32(f);
loc1 = get32(f);
// @TODO: validate loc0,loc1 as valid positions?
// stream serial number -- vorbis doesn't interleave, so discard
get32(f);
// if (f->serial != get32(f)) return error(f,
// VORBIS_incorrect_stream_serial_number);
// page sequence number
n = get32(f);
f->last_page = n;
// CRC32
get32(f);
// page_segments
f->segment_count = get8(f);
if (!getn(f, f->segments, f->segment_count))
return error(f, VORBIS_unexpected_eof);
// assume we _don't_ know any the sample position of any segments
f->end_seg_with_known_loc = -2;
if (loc0 != ~0U || loc1 != ~0U) {
int i;
// determine which packet is the last one that will complete
for (i = f->segment_count - 1; i >= 0; --i)
if (f->segments[i] < 255) break;
// 'i' is now the index of the _last_ segment of a packet that ends
if (i >= 0) {
f->end_seg_with_known_loc = i;
f->known_loc_for_packet = loc0;
}
}
if (f->first_decode) {
int i, len;
ProbedPage p;
len = 0;
for (i = 0; i < f->segment_count; ++i) len += f->segments[i];
len += 27 + f->segment_count;
p.page_start = f->first_audio_page_offset;
p.page_end = p.page_start + len;
p.last_decoded_sample = loc0;
f->p_first = p;
}
f->next_seg = 0;
return TRUE;
}
static int start_page(vorb *f) {
if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);
return start_page_no_capturepattern(f);
}
static int start_packet(vorb *f) {
while (f->next_seg == -1) {
if (!start_page(f)) return FALSE;
if (f->page_flag & PAGEFLAG_continued_packet)
return error(f, VORBIS_continued_packet_flag_invalid);
}
f->last_seg = FALSE;
f->valid_bits = 0;
f->packet_bytes = 0;
f->bytes_in_seg = 0;
// f->next_seg is now valid
return TRUE;
}
static int maybe_start_packet(vorb *f) {
if (f->next_seg == -1) {
int x = get8(f);
if (f->eof) return FALSE; // EOF at page boundary is not an error!
if (0x4f != x) return error(f, VORBIS_missing_capture_pattern);
if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (!start_page_no_capturepattern(f)) return FALSE;
if (f->page_flag & PAGEFLAG_continued_packet) {
// set up enough state that we can read this packet if we want,
// e.g. during recovery
f->last_seg = FALSE;
f->bytes_in_seg = 0;
return error(f, VORBIS_continued_packet_flag_invalid);
}
}
return start_packet(f);
}
static int next_segment(vorb *f) {
int len;
if (f->last_seg) return 0;
if (f->next_seg == -1) {
f->last_seg_which = f->segment_count - 1; // in case start_page fails
if (!start_page(f)) {
f->last_seg = 1;
return 0;
}
if (!(f->page_flag & PAGEFLAG_continued_packet))
return error(f, VORBIS_continued_packet_flag_invalid);
}
len = f->segments[f->next_seg++];
if (len < 255) {
f->last_seg = TRUE;
f->last_seg_which = f->next_seg - 1;
}
if (f->next_seg >= f->segment_count) f->next_seg = -1;
assert(f->bytes_in_seg == 0);
f->bytes_in_seg = len;
return len;
}
#define EOP (-1)
#define INVALID_BITS (-1)
static int get8_packet_raw(vorb *f) {
if (!f->bytes_in_seg) { // CLANG!
if (f->last_seg)
return EOP;
else if (!next_segment(f))
return EOP;
}
assert(f->bytes_in_seg > 0);
--f->bytes_in_seg;
++f->packet_bytes;
return get8(f);
}
static int get8_packet(vorb *f) {
int x = get8_packet_raw(f);
f->valid_bits = 0;
return x;
}
static void flush_packet(vorb *f) {
while (get8_packet_raw(f) != EOP)
;
}
// @OPTIMIZE: this is the secondary bit decoder, so it's probably not as
// important as the huffman decoder?
static uint32 get_bits(vorb *f, int n) {
uint32 z;
if (f->valid_bits < 0) return 0;
if (f->valid_bits < n) {
if (n > 24) {
// the accumulator technique below would not work correctly in this case
z = get_bits(f, 24);
z += get_bits(f, n - 24) << 24;
return z;
}
if (f->valid_bits == 0) f->acc = 0;
while (f->valid_bits < n) {
int z = get8_packet_raw(f);
if (z == EOP) {
f->valid_bits = INVALID_BITS;
return 0;
}
f->acc += z << f->valid_bits;
f->valid_bits += 8;
}
}
if (f->valid_bits < 0) return 0;
z = f->acc & ((1 << n) - 1);
f->acc >>= n;
f->valid_bits -= n;
return z;
}
// @OPTIMIZE: primary accumulator for huffman
// expand the buffer to as many bits as possible without reading off end of
// packet it might be nice to allow f->valid_bits and f->acc to be stored in
// registers, e.g. cache them locally and decode locally
forceinline void prep_huffman(vorb *f) {
if (f->valid_bits <= 24) {
if (f->valid_bits == 0) f->acc = 0;
do {
int z;
if (f->last_seg && !f->bytes_in_seg) return;
z = get8_packet_raw(f);
if (z == EOP) return;
f->acc += (unsigned)z << f->valid_bits;
f->valid_bits += 8;
} while (f->valid_bits <= 24);
}
}
enum {
VORBIS_packet_id = 1,
VORBIS_packet_comment = 3,
VORBIS_packet_setup = 5
};
static int codebook_decode_scalar_raw(vorb *f, Codebook *c) {
int i;
prep_huffman(f);
if (c->codewords == NULL && c->sorted_codewords == NULL) return -1;
// cases to use binary search: sorted_codewords && !c->codewords
// sorted_codewords && c->entries > 8
if (c->entries > 8 ? c->sorted_codewords != NULL : !c->codewords) {
// binary search
uint32 code = _bitreverse32(f->acc);
int x = 0, n = c->sorted_entries, len;
while (n > 1) {
// invariant: sc[x] <= code < sc[x+n]
int m = x + (n >> 1);
if (c->sorted_codewords[m] <= code) {
x = m;
n -= (n >> 1);
} else {
n >>= 1;
}
}
// x is now the sorted index
if (!c->sparse) x = c->sorted_values[x];
// x is now sorted index if sparse, or symbol otherwise
len = c->codeword_lengths[x];
if (f->valid_bits >= len) {
f->acc >>= len;
f->valid_bits -= len;
return x;
}
f->valid_bits = 0;
return -1;
}
// if small, linear search
assert(!c->sparse);
for (i = 0; i < c->entries; ++i) {
if (c->codeword_lengths[i] == NO_CODE) continue;
if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i]) - 1))) {
if (f->valid_bits >= c->codeword_lengths[i]) {
f->acc >>= c->codeword_lengths[i];
f->valid_bits -= c->codeword_lengths[i];
return i;
}
f->valid_bits = 0;
return -1;
}
}
error(f, VORBIS_invalid_stream);
f->valid_bits = 0;
return -1;
}
#ifndef STB_VORBIS_NO_INLINE_DECODE
#define DECODE_RAW(var, f, c) \
if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) prep_huffman(f); \
var = f->acc & FAST_HUFFMAN_TABLE_MASK; \
var = c->fast_huffman[var]; \
if (var >= 0) { \
int n = c->codeword_lengths[var]; \
f->acc >>= n; \
f->valid_bits -= n; \
if (f->valid_bits < 0) { \
f->valid_bits = 0; \
var = -1; \
} \
} else { \
var = codebook_decode_scalar_raw(f, c); \
}
#else
static int codebook_decode_scalar(vorb *f, Codebook *c) {
int i;
if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) prep_huffman(f);
// fast huffman table lookup
i = f->acc & FAST_HUFFMAN_TABLE_MASK;
i = c->fast_huffman[i];
if (i >= 0) {
f->acc >>= c->codeword_lengths[i];
f->valid_bits -= c->codeword_lengths[i];
if (f->valid_bits < 0) {
f->valid_bits = 0;
return -1;
}
return i;
}
return codebook_decode_scalar_raw(f, c);
}
#define DECODE_RAW(var, f, c) var = codebook_decode_scalar(f, c);
#endif
#define DECODE(var, f, c) \
DECODE_RAW(var, f, c) \
if (c->sparse) var = c->sorted_values[var];
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
#define DECODE_VQ(var, f, c) DECODE_RAW(var, f, c)
#else
#define DECODE_VQ(var, f, c) DECODE(var, f, c)
#endif
// CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case
// where we avoid one addition
#define CODEBOOK_ELEMENT(c, off) (c->multiplicands[off])
#define CODEBOOK_ELEMENT_FAST(c, off) (c->multiplicands[off])
#define CODEBOOK_ELEMENT_BASE(c) (0)
static int codebook_decode_start(vorb *f, Codebook *c) {
int z = -1;
// type 0 is only legal in a scalar context
if (c->lookup_type == 0)
error(f, VORBIS_invalid_stream);
else {
DECODE_VQ(z, f, c);
if (c->sparse) assert(z < c->sorted_entries);
if (z < 0) { // check for EOP
if (!f->bytes_in_seg)
if (f->last_seg) return z;
error(f, VORBIS_invalid_stream);
}
}
return z;
}
static int codebook_decode(vorb *f, Codebook *c, float *output, int len) {
int i, z = codebook_decode_start(f, c);
if (z < 0) return FALSE;
if (len > c->dimensions) len = c->dimensions;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
float last = CODEBOOK_ELEMENT_BASE(c);
int div = 1;
for (i = 0; i < len; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c, off) + last;
output[i] += val;
if (c->sequence_p) last = val + c->minimum_value;
div *= c->lookup_values;
}
return TRUE;
}
#endif
z *= c->dimensions;
if (c->sequence_p) {
float last = CODEBOOK_ELEMENT_BASE(c);
for (i = 0; i < len; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last;
output[i] += val;
last = val + c->minimum_value;
}
} else {
float last = CODEBOOK_ELEMENT_BASE(c);
for (i = 0; i < len; ++i) {
output[i] += CODEBOOK_ELEMENT_FAST(c, z + i) + last;
}
}
return TRUE;
}
static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len,
int step) {
int i, z = codebook_decode_start(f, c);
float last = CODEBOOK_ELEMENT_BASE(c);
if (z < 0) return FALSE;
if (len > c->dimensions) len = c->dimensions;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int div = 1;
for (i = 0; i < len; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c, off) + last;
output[i * step] += val;
if (c->sequence_p) last = val;
div *= c->lookup_values;
}
return TRUE;
}
#endif
z *= c->dimensions;
for (i = 0; i < len; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last;
output[i * step] += val;
if (c->sequence_p) last = val;
}
return TRUE;
}
static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c,
float **outputs, int ch,
int *c_inter_p, int *p_inter_p,
int len, int total_decode) {
int c_inter = *c_inter_p;
int p_inter = *p_inter_p;
int i, z, effective = c->dimensions;
// type 0 is only legal in a scalar context
if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
while (total_decode > 0) {
float last = CODEBOOK_ELEMENT_BASE(c);
DECODE_VQ(z, f, c);
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
assert(!c->sparse || z < c->sorted_entries);
#endif
if (z < 0) {
if (!f->bytes_in_seg)
if (f->last_seg) return FALSE;
return error(f, VORBIS_invalid_stream);
}
// if this will take us off the end of the buffers, stop short!
// we check by computing the length of the virtual interleaved
// buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
// and the length we'll be using (effective)
if (c_inter + p_inter * ch + effective > len * ch) {
effective = len * ch - (p_inter * ch - c_inter);
}
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int div = 1;
for (i = 0; i < effective; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c, off) + last;
if (outputs[c_inter]) outputs[c_inter][p_inter] += val;
if (++c_inter == ch) {
c_inter = 0;
++p_inter;
}
if (c->sequence_p) last = val;
div *= c->lookup_values;
}
} else
#endif
{
z *= c->dimensions;
if (c->sequence_p) {
for (i = 0; i < effective; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last;
if (outputs[c_inter]) outputs[c_inter][p_inter] += val;
if (++c_inter == ch) {
c_inter = 0;
++p_inter;
}
last = val;
}
} else {
for (i = 0; i < effective; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last;
if (outputs[c_inter]) outputs[c_inter][p_inter] += val;
if (++c_inter == ch) {
c_inter = 0;
++p_inter;
}
}
}
}
total_decode -= effective;
}
*c_inter_p = c_inter;
*p_inter_p = p_inter;
return TRUE;
}
static int predict_point(int x, int x0, int x1, int y0, int y1) {
int dy = y1 - y0;
int adx = x1 - x0;
// @OPTIMIZE: force int division to round in the right direction... is this
// necessary on x86?
int err = abs(dy) * (x - x0);
int off = err / adx;
return dy < 0 ? y0 - off : y0 + off;
}
// the following table is block-copied from the specification
static float inverse_db_table[256] = {
1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,
0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,
0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,
0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,
0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,
0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,
0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,
0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,
0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,
0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,
0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,
0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,
0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,
0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,
0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,
0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,
0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,
0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,
0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,
0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,
0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,
0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,
0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,
0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,
0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,
0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,
0.82788260f, 0.88168307f, 0.9389798f, 1.0f};
// @OPTIMIZE: if you want to replace this bresenham line-drawing routine,
// note that you must produce bit-identical output to decode correctly;
// this specific sequence of operations is specified in the spec (it's
// drawing integer-quantized frequency-space lines that the encoder
// expects to be exactly the same)
// ... also, isn't the whole point of Bresenham's algorithm to NOT
// have to divide in the setup? sigh.
#ifndef STB_VORBIS_NO_DEFER_FLOOR
#define LINE_OP(a, b) a *= b
#else
#define LINE_OP(a, b) a = b
#endif
#ifdef STB_VORBIS_DIVIDE_TABLE
#define DIVTAB_NUMER 32
#define DIVTAB_DENOM 64
int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB
#endif
forceinline void draw_line(float *output, int x0, int y0, int x1, int y1,
int n) {
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x = x0, y = y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base - 1;
} else {
base = integer_divide_table[ady][adx];
sy = base + 1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base + 1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base + 1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y & 255]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y & 255]);
}
}
}
static int residue_decode(vorb *f, Codebook *book, float *target, int offset,
int n, int rtype) {
int k;
if (rtype == 0) {
int step = n / book->dimensions;
for (k = 0; k < step; ++k)
if (!codebook_decode_step(f, book, target + offset + k, n - offset - k,
step))
return FALSE;
} else {
for (k = 0; k < n;) {
if (!codebook_decode(f, book, target + offset, n - k)) return FALSE;
k += book->dimensions;
offset += book->dimensions;
}
}
return TRUE;
}
// n is 1/2 of the blocksize --
// specification: "Correct per-vector decode length is [n]/2"
static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n,
int rn, uint8 *do_not_decode) {
int i, j, pass_;
Residue *r = f->residue_config + rn;
int rtype = f->residue_types[rn];
int c = r->classbook;
int classwords = f->codebooks[c].dimensions;
unsigned int actual_size = rtype == 2 ? n * 2 : n;
unsigned int limit_r_begin =
(r->begin < actual_size ? r->begin : actual_size);
unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size);
int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
int temp_alloc_point = temp_alloc_save(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
uint8 ***part_classdata = (uint8 ***)temp_block_array(
f, f->channels, part_read * sizeof(**part_classdata));
#else
int **classifications = (int **)temp_block_array(
f, f->channels, part_read * sizeof(**classifications));
#endif
CHECK(f);
for (i = 0; i < ch; ++i) {
if (!do_not_decode[i]) {
bzero(residue_buffers[i], sizeof(float) * n);
}
}
if (rtype == 2 && ch != 1) {
for (j = 0; j < ch; ++j)
if (!do_not_decode[j]) break;
if (j == ch) goto done;
for (pass_ = 0; pass_ < 8; ++pass_) {
int pcount = 0, class_set = 0;
if (ch == 2) {
while (pcount < part_read) {
int z = r->begin + pcount * r->part_size;
int c_inter = (z & 1), p_inter = z >> 1;
if (pass_ == 0) {
Codebook *c = f->codebooks + r->classbook;
int q;
DECODE(q, f, c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i = classwords - 1; i >= 0; --i) {
classifications[0][i + pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i = 0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount * r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass_];
if (b >= 0) {
Codebook *book = f->codebooks + b;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers,
ch, &c_inter, &p_inter,
n, r->part_size))
goto done;
#else
// saves 1%
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers,
ch, &c_inter, &p_inter,
n, r->part_size))
goto done;
#endif
} else {
z += r->part_size;
c_inter = z & 1;
p_inter = z >> 1;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
} else if (ch == 1) {
while (pcount < part_read) {
int z = r->begin + pcount * r->part_size;
int c_inter = 0, p_inter = z;
if (pass_ == 0) {
Codebook *c = f->codebooks + r->classbook;
int q;
DECODE(q, f, c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i = classwords - 1; i >= 0; --i) {
classifications[0][i + pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i = 0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount * r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass_];
if (b >= 0) {
Codebook *book = f->codebooks + b;
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers,
ch, &c_inter, &p_inter,
n, r->part_size))
goto done;
} else {
z += r->part_size;
c_inter = 0;
p_inter = z;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
} else {
while (pcount < part_read) {
int z = r->begin + pcount * r->part_size;
int c_inter = z % ch, p_inter = z / ch;
if (pass_ == 0) {
Codebook *c = f->codebooks + r->classbook;
int q;
DECODE(q, f, c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i = classwords - 1; i >= 0; --i) {
classifications[0][i + pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i = 0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount * r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass_];
if (b >= 0) {
Codebook *book = f->codebooks + b;
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers,
ch, &c_inter, &p_inter,
n, r->part_size))
goto done;
} else {
z += r->part_size;
c_inter = z % ch;
p_inter = z / ch;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
}
goto done;
}
CHECK(f);
for (pass_ = 0; pass_ < 8; ++pass_) {
int pcount = 0, class_set = 0;
while (pcount < part_read) {
if (pass_ == 0) {
for (j = 0; j < ch; ++j) {
if (!do_not_decode[j]) {
Codebook *c = f->codebooks + r->classbook;
int temp;
DECODE(temp, f, c);
if (temp == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[j][class_set] = r->classdata[temp];
#else
for (i = classwords - 1; i >= 0; --i) {
classifications[j][i + pcount] = temp % r->classifications;
temp /= r->classifications;
}
#endif
}
}
}
for (i = 0; i < classwords && pcount < part_read; ++i, ++pcount) {
for (j = 0; j < ch; ++j) {
if (!do_not_decode[j]) {
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[j][class_set][i];
#else
int c = classifications[j][pcount];
#endif
int b = r->residue_books[c][pass_];
if (b >= 0) {
float *target = residue_buffers[j];
int offset = r->begin + pcount * r->part_size;
int n = r->part_size;
Codebook *book = f->codebooks + b;
if (!residue_decode(f, book, target, offset, n, rtype)) goto done;
}
}
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
done:
CHECK(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
temp_free(f, part_classdata);
#else
temp_free(f, classifications);
#endif
temp_alloc_restore(f, temp_alloc_point);
}
#if 0
// slow way for debugging
void inverse_mdct_slow(float *buffer, int n)
{
int i,j;
int n2 = n >> 1;
float *x = (float *) malloc(sizeof(*x) * n2);
memcpy(x, buffer, sizeof(*x) * n2);
for (i=0; i < n; ++i) {
float acc = 0;
for (j=0; j < n2; ++j)
// formula from paper:
//acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
// formula from wikipedia
//acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
// these are equivalent, except the formula from the paper inverts the multiplier!
// however, what actually works is NO MULTIPLIER!?!
//acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
buffer[i] = acc;
}
free(x);
}
#elif 0
// same as above, but just barely able to run in real time on modern machines
void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) {
float mcos[16384];
int i, j;
int n2 = n >> 1, nmask = (n << 2) - 1;
float *x = (float *)malloc(sizeof(*x) * n2);
memcpy(x, buffer, sizeof(*x) * n2);
for (i = 0; i < 4 * n; ++i) mcos[i] = (float)cos(M_PI / 2 * i / n);
for (i = 0; i < n; ++i) {
float acc = 0;
for (j = 0; j < n2; ++j)
acc += x[j] * mcos[(2 * i + 1 + n2) * (2 * j + 1) & nmask];
buffer[i] = acc;
}
free(x);
}
#elif 0
// transform to use a slow dct-iv; this is STILL basically trivial,
// but only requires half as many ops
void dct_iv_slow(float *buffer, int n) {
float mcos[16384];
float x[2048];
int i, j;
int n2 = n >> 1, nmask = (n << 3) - 1;
memcpy(x, buffer, sizeof(*x) * n);
for (i = 0; i < 8 * n; ++i) mcos[i] = (float)cos(M_PI / 4 * i / n);
for (i = 0; i < n; ++i) {
float acc = 0;
for (j = 0; j < n; ++j)
acc += x[j] * mcos[((2 * i + 1) * (2 * j + 1)) & nmask];
buffer[i] = acc;
}
}
void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) {
int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;
float temp[4096];
memcpy(temp, buffer, n2 * sizeof(float));
dct_iv_slow(temp, n2); // returns -c'-d, a-b'
for (i = 0; i < n4; ++i) buffer[i] = temp[i + n4]; // a-b'
for (; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d'
for (; i < n; ++i) buffer[i] = -temp[i - n3_4]; // c'+d
}
#endif
#ifndef LIBVORBIS_MDCT
#define LIBVORBIS_MDCT 0
#endif
#if LIBVORBIS_MDCT
// directly call the vorbis MDCT using an interface documented
// by Jeff Roberts... useful for performance comparison
typedef struct {
int n;
int log2n;
float *trig;
int *bitrev;
float scale;
} mdct_lookup;
extern void mdct_init(mdct_lookup *lookup, int n);
extern void mdct_clear(mdct_lookup *l);
extern void mdct_backward(mdct_lookup *init, float *in, float *out);
mdct_lookup M1, M2;
void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) {
mdct_lookup *M;
if (M1.n == n)
M = &M1;
else if (M2.n == n)
M = &M2;
else if (M1.n == 0) {
mdct_init(&M1, n);
M = &M1;
} else {
if (M2.n) __asm int 3;
mdct_init(&M2, n);
M = &M2;
}
mdct_backward(M, buffer, buffer);
}
#endif
// the following were split out into separate functions while optimizing;
// they could be pushed back up but eh. forceinline showed no change;
// they're probably already being inlined.
static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off,
float *A) {
float *ee0 = e + i_off;
float *ee2 = ee0 + k_off;
int i;
assert((n & 3) == 0);
for (i = (n >> 2); i > 0; --i) {
float k00_20, k01_21;
k00_20 = ee0[0] - ee2[0];
k01_21 = ee0[-1] - ee2[-1];
ee0[0] += ee2[0]; // ee0[ 0] = ee0[ 0] + ee2[ 0];
ee0[-1] += ee2[-1]; // ee0[-1] = ee0[-1] + ee2[-1];
ee2[0] = k00_20 * A[0] - k01_21 * A[1];
ee2[-1] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-2] - ee2[-2];
k01_21 = ee0[-3] - ee2[-3];
ee0[-2] += ee2[-2]; // ee0[-2] = ee0[-2] + ee2[-2];
ee0[-3] += ee2[-3]; // ee0[-3] = ee0[-3] + ee2[-3];
ee2[-2] = k00_20 * A[0] - k01_21 * A[1];
ee2[-3] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-4] - ee2[-4];
k01_21 = ee0[-5] - ee2[-5];
ee0[-4] += ee2[-4]; // ee0[-4] = ee0[-4] + ee2[-4];
ee0[-5] += ee2[-5]; // ee0[-5] = ee0[-5] + ee2[-5];
ee2[-4] = k00_20 * A[0] - k01_21 * A[1];
ee2[-5] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-6] - ee2[-6];
k01_21 = ee0[-7] - ee2[-7];
ee0[-6] += ee2[-6]; // ee0[-6] = ee0[-6] + ee2[-6];
ee0[-7] += ee2[-7]; // ee0[-7] = ee0[-7] + ee2[-7];
ee2[-6] = k00_20 * A[0] - k01_21 * A[1];
ee2[-7] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
ee0 -= 8;
ee2 -= 8;
}
}
static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off,
float *A, int k1) {
int i;
float k00_20, k01_21;
float *e0 = e + d0;
float *e2 = e0 + k_off;
for (i = lim >> 2; i > 0; --i) {
k00_20 = e0[-0] - e2[-0];
k01_21 = e0[-1] - e2[-1];
e0[-0] += e2[-0]; // e0[-0] = e0[-0] + e2[-0];
e0[-1] += e2[-1]; // e0[-1] = e0[-1] + e2[-1];
e2[-0] = (k00_20)*A[0] - (k01_21)*A[1];
e2[-1] = (k01_21)*A[0] + (k00_20)*A[1];
A += k1;
k00_20 = e0[-2] - e2[-2];
k01_21 = e0[-3] - e2[-3];
e0[-2] += e2[-2]; // e0[-2] = e0[-2] + e2[-2];
e0[-3] += e2[-3]; // e0[-3] = e0[-3] + e2[-3];
e2[-2] = (k00_20)*A[0] - (k01_21)*A[1];
e2[-3] = (k01_21)*A[0] + (k00_20)*A[1];
A += k1;
k00_20 = e0[-4] - e2[-4];
k01_21 = e0[-5] - e2[-5];
e0[-4] += e2[-4]; // e0[-4] = e0[-4] + e2[-4];
e0[-5] += e2[-5]; // e0[-5] = e0[-5] + e2[-5];
e2[-4] = (k00_20)*A[0] - (k01_21)*A[1];
e2[-5] = (k01_21)*A[0] + (k00_20)*A[1];
A += k1;
k00_20 = e0[-6] - e2[-6];
k01_21 = e0[-7] - e2[-7];
e0[-6] += e2[-6]; // e0[-6] = e0[-6] + e2[-6];
e0[-7] += e2[-7]; // e0[-7] = e0[-7] + e2[-7];
e2[-6] = (k00_20)*A[0] - (k01_21)*A[1];
e2[-7] = (k01_21)*A[0] + (k00_20)*A[1];
e0 -= 8;
e2 -= 8;
A += k1;
}
}
static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off,
float *A, int a_off, int k0) {
int i;
float A0 = A[0];
float A1 = A[0 + 1];
float A2 = A[0 + a_off];
float A3 = A[0 + a_off + 1];
float A4 = A[0 + a_off * 2 + 0];
float A5 = A[0 + a_off * 2 + 1];
float A6 = A[0 + a_off * 3 + 0];
float A7 = A[0 + a_off * 3 + 1];
float k00, k11;
float *ee0 = e + i_off;
float *ee2 = ee0 + k_off;
for (i = n; i > 0; --i) {
k00 = ee0[0] - ee2[0];
k11 = ee0[-1] - ee2[-1];
ee0[0] = ee0[0] + ee2[0];
ee0[-1] = ee0[-1] + ee2[-1];
ee2[0] = (k00)*A0 - (k11)*A1;
ee2[-1] = (k11)*A0 + (k00)*A1;
k00 = ee0[-2] - ee2[-2];
k11 = ee0[-3] - ee2[-3];
ee0[-2] = ee0[-2] + ee2[-2];
ee0[-3] = ee0[-3] + ee2[-3];
ee2[-2] = (k00)*A2 - (k11)*A3;
ee2[-3] = (k11)*A2 + (k00)*A3;
k00 = ee0[-4] - ee2[-4];
k11 = ee0[-5] - ee2[-5];
ee0[-4] = ee0[-4] + ee2[-4];
ee0[-5] = ee0[-5] + ee2[-5];
ee2[-4] = (k00)*A4 - (k11)*A5;
ee2[-5] = (k11)*A4 + (k00)*A5;
k00 = ee0[-6] - ee2[-6];
k11 = ee0[-7] - ee2[-7];
ee0[-6] = ee0[-6] + ee2[-6];
ee0[-7] = ee0[-7] + ee2[-7];
ee2[-6] = (k00)*A6 - (k11)*A7;
ee2[-7] = (k11)*A6 + (k00)*A7;
ee0 -= k0;
ee2 -= k0;
}
}
forceinline void iter_54(float *z) {
float k00, k11, k22, k33;
float y0, y1, y2, y3;
k00 = z[0] - z[-4];
y0 = z[0] + z[-4];
y2 = z[-2] + z[-6];
k22 = z[-2] - z[-6];
z[-0] = y0 + y2; // z0 + z4 + z2 + z6
z[-2] = y0 - y2; // z0 + z4 - z2 - z6
// done with y0,y2
k33 = z[-3] - z[-7];
z[-4] = k00 + k33; // z0 - z4 + z3 - z7
z[-6] = k00 - k33; // z0 - z4 - z3 + z7
// done with k33
k11 = z[-1] - z[-5];
y1 = z[-1] + z[-5];
y3 = z[-3] + z[-7];
z[-1] = y1 + y3; // z1 + z5 + z3 + z7
z[-3] = y1 - y3; // z1 + z5 - z3 - z7
z[-5] = k11 - k22; // z1 - z5 + z2 - z6
z[-7] = k11 + k22; // z1 - z5 - z2 + z6
}
static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A,
int base_n) {
int a_off = base_n >> 3;
float A2 = A[0 + a_off];
float *z = e + i_off;
float *base = z - 16 * n;
while (z > base) {
float k00, k11;
k00 = z[-0] - z[-8];
k11 = z[-1] - z[-9];
z[-0] = z[-0] + z[-8];
z[-1] = z[-1] + z[-9];
z[-8] = k00;
z[-9] = k11;
k00 = z[-2] - z[-10];
k11 = z[-3] - z[-11];
z[-2] = z[-2] + z[-10];
z[-3] = z[-3] + z[-11];
z[-10] = (k00 + k11) * A2;
z[-11] = (k11 - k00) * A2;
k00 = z[-12] - z[-4]; // reverse to avoid a unary negation
k11 = z[-5] - z[-13];
z[-4] = z[-4] + z[-12];
z[-5] = z[-5] + z[-13];
z[-12] = k11;
z[-13] = k00;
k00 = z[-14] - z[-6]; // reverse to avoid a unary negation
k11 = z[-7] - z[-15];
z[-6] = z[-6] + z[-14];
z[-7] = z[-7] + z[-15];
z[-14] = (k00 + k11) * A2;
z[-15] = (k00 - k11) * A2;
iter_54(z);
iter_54(z - 8);
z -= 16;
}
}
static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) {
int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
int ld;
// @OPTIMIZE: reduce register pressure by using fewer variables?
int save_point = temp_alloc_save(f);
float *buf2 = (float *)temp_alloc(f, n2 * sizeof(*buf2));
float *u = NULL, *v = NULL;
// twiddle factors
float *A = f->A[blocktype];
// IMDCT algorithm from "The use of multirate filter banks for coding of high
// quality digital audio" See notes about bugs in that paper in less-optimal
// implementation 'inverse_mdct_old' after this function.
// kernel from paper
// merged:
// copy and reflect spectral data
// step 0
// note that it turns out that the items added together during
// this step are, in fact, being added to themselves (as reflected
// by step 0). inexplicable inefficiency! this became obvious
// once I combined the passes.
// so there's a missing 'times 2' here (for adding X to itself).
// this propagates through linearly to the end, where the numbers
// are 1/2 too small, and need to be compensated for.
{
float *d, *e, *AA, *e_stop;
d = &buf2[n2 - 2];
AA = A;
e = &buffer[0];
e_stop = &buffer[n2];
while (e != e_stop) {
d[1] = (e[0] * AA[0] - e[2] * AA[1]);
d[0] = (e[0] * AA[1] + e[2] * AA[0]);
d -= 2;
AA += 2;
e += 4;
}
e = &buffer[n2 - 3];
while (d >= buf2) {
d[1] = (-e[2] * AA[0] - -e[0] * AA[1]);
d[0] = (-e[2] * AA[1] + -e[0] * AA[0]);
d -= 2;
AA += 2;
e -= 4;
}
}
// now we use symbolic names for these, so that we can
// possibly swap their meaning as we change which operations
// are in place
u = buffer;
v = buf2;
// step 2 (paper output is w, now u)
// this could be in place, but the data ends up in the wrong
// place... _somebody_'s got to swap it, so this is nominated
{
float *AA = &A[n2 - 8];
float *d0, *d1, *e0, *e1;
e0 = &v[n4];
e1 = &v[0];
d0 = &u[n4];
d1 = &u[0];
while (AA >= A) {
float v40_20, v41_21;
v41_21 = e0[1] - e1[1];
v40_20 = e0[0] - e1[0];
d0[1] = e0[1] + e1[1];
d0[0] = e0[0] + e1[0];
d1[1] = v41_21 * AA[4] - v40_20 * AA[5];
d1[0] = v40_20 * AA[4] + v41_21 * AA[5];
v41_21 = e0[3] - e1[3];
v40_20 = e0[2] - e1[2];
d0[3] = e0[3] + e1[3];
d0[2] = e0[2] + e1[2];
d1[3] = v41_21 * AA[0] - v40_20 * AA[1];
d1[2] = v40_20 * AA[0] + v41_21 * AA[1];
AA -= 8;
d0 += 4;
d1 += 4;
e0 += 4;
e1 += 4;
}
}
// step 3
ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
// optimized step 3:
// the original step3 loop can be nested r inside s or s inside r;
// it's written originally as s inside r, but this is dumb when r
// iterates many times, and s few. So I have two copies of it and
// switch between them halfway.
// this is iteration 0 of step 3
imdct_step3_iter0_loop(n >> 4, u, n2 - 1 - n4 * 0, -(n >> 3), A);
imdct_step3_iter0_loop(n >> 4, u, n2 - 1 - n4 * 1, -(n >> 3), A);
// this is iteration 1 of step 3
imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 0, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 1, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 2, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 3, -(n >> 4), A, 16);
l = 2;
for (; l < ((ld - 3) >> 1); ++l) {
int k0 = n >> (l + 2), k0_2 = k0 >> 1;
int lim = 1 << (l + 1);
int i;
for (i = 0; i < lim; ++i)
imdct_step3_inner_r_loop(n >> (l + 4), u, n2 - 1 - k0 * i, -k0_2, A,
1 << (l + 3));
}
for (; l < ld - 6; ++l) {
int k0 = n >> (l + 2), k1 = 1 << (l + 3), k0_2 = k0 >> 1;
int rlim = n >> (l + 6), r;
int lim = 1 << (l + 1);
int i_off;
float *A0 = A;
i_off = n2 - 1;
for (r = rlim; r > 0; --r) {
imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
A0 += k1 * 4;
i_off -= 8;
}
}
// iterations with count:
// ld-6,-5,-4 all interleaved together
// the big win comes from getting rid of needless flops
// due to the constants on pass 5 & 4 being all 1 and 0;
// combining them to be simultaneous to improve cache made little
// difference
imdct_step3_inner_s_loop_ld654(n >> 5, u, n2 - 1, A, n);
// output is u
// step 4, 5, and 6
// cannot be in-place because of step 5
{
uint16 *bitrev = f->bit_reverse[blocktype];
// weirdly, I'd have thought reading sequentially and writing
// erratically would have been better than vice-versa, but in
// fact that's not what my testing showed. (That is, with
// j = bitreverse(i), do you read i and write j, or read j and write i.)
float *d0 = &v[n4 - 4];
float *d1 = &v[n2 - 4];
while (d0 >= v) {
int k4;
k4 = bitrev[0];
d1[3] = u[k4 + 0];
d1[2] = u[k4 + 1];
d0[3] = u[k4 + 2];
d0[2] = u[k4 + 3];
k4 = bitrev[1];
d1[1] = u[k4 + 0];
d1[0] = u[k4 + 1];
d0[1] = u[k4 + 2];
d0[0] = u[k4 + 3];
d0 -= 4;
d1 -= 4;
bitrev += 2;
}
}
// (paper output is u, now v)
// data must be in buf2
assert(v == buf2);
// step 7 (paper output is v, now v)
// this is now in place
{
float *C = f->C[blocktype];
float *d, *e;
d = v;
e = v + n2 - 4;
while (d < e) {
float a02, a11, b0, b1, b2, b3;
a02 = d[0] - e[2];
a11 = d[1] + e[3];
b0 = C[1] * a02 + C[0] * a11;
b1 = C[1] * a11 - C[0] * a02;
b2 = d[0] + e[2];
b3 = d[1] - e[3];
d[0] = b2 + b0;
d[1] = b3 + b1;
e[2] = b2 - b0;
e[3] = b1 - b3;
a02 = d[2] - e[0];
a11 = d[3] + e[1];
b0 = C[3] * a02 + C[2] * a11;
b1 = C[3] * a11 - C[2] * a02;
b2 = d[2] + e[0];
b3 = d[3] - e[1];
d[2] = b2 + b0;
d[3] = b3 + b1;
e[0] = b2 - b0;
e[1] = b1 - b3;
C += 4;
d += 4;
e -= 4;
}
}
// data must be in buf2
// step 8+decode (paper output is X, now buffer)
// this generates pairs of data a la 8 and pushes them directly through
// the decode kernel (pushing rather than pulling) to avoid having
// to make another pass later
// this cannot POSSIBLY be in place, so we refer to the buffers directly
{
float *d0, *d1, *d2, *d3;
float *B = f->B[blocktype] + n2 - 8;
float *e = buf2 + n2 - 8;
d0 = &buffer[0];
d1 = &buffer[n2 - 4];
d2 = &buffer[n2];
d3 = &buffer[n - 4];
while (e >= v) {
float p0, p1, p2, p3;
p3 = e[6] * B[7] - e[7] * B[6];
p2 = -e[6] * B[6] - e[7] * B[7];
d0[0] = p3;
d1[3] = -p3;
d2[0] = p2;
d3[3] = p2;
p1 = e[4] * B[5] - e[5] * B[4];
p0 = -e[4] * B[4] - e[5] * B[5];
d0[1] = p1;
d1[2] = -p1;
d2[1] = p0;
d3[2] = p0;
p3 = e[2] * B[3] - e[3] * B[2];
p2 = -e[2] * B[2] - e[3] * B[3];
d0[2] = p3;
d1[1] = -p3;
d2[2] = p2;
d3[1] = p2;
p1 = e[0] * B[1] - e[1] * B[0];
p0 = -e[0] * B[0] - e[1] * B[1];
d0[3] = p1;
d1[0] = -p1;
d2[3] = p0;
d3[0] = p0;
B -= 8;
e -= 8;
d0 += 4;
d2 += 4;
d1 -= 4;
d3 -= 4;
}
}
temp_free(f, buf2);
temp_alloc_restore(f, save_point);
}
#if 0
// this is the original version of the above code, if you want to optimize it from scratch
void inverse_mdct_naive(float *buffer, int n)
{
float s;
float A[1 << 12], B[1 << 12], C[1 << 11];
int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
int n3_4 = n - n4, ld;
// how can they claim this only uses N words?!
// oh, because they're only used sparsely, whoops
float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];
// set up twiddle factors
for (k=k2=0; k < n4; ++k,k2+=2) {
A[k2 ] = (float) cos(4*k*M_PI/n);
A[k2+1] = (float) -sin(4*k*M_PI/n);
B[k2 ] = (float) cos((k2+1)*M_PI/n/2);
B[k2+1] = (float) sin((k2+1)*M_PI/n/2);
}
for (k=k2=0; k < n8; ++k,k2+=2) {
C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
}
// IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
// Note there are bugs in that pseudocode, presumably due to them attempting
// to rename the arrays nicely rather than representing the way their actual
// implementation bounces buffers back and forth. As a result, even in the
// "some formulars corrected" version, a direct implementation fails. These
// are noted below as "paper bug".
// copy and reflect spectral data
for (k=0; k < n2; ++k) u[k] = buffer[k];
for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];
// kernel from paper
// step 1
for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {
v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];
v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];
}
// step 2
for (k=k4=0; k < n8; k+=1, k4+=4) {
w[n2+3+k4] = v[n2+3+k4] + v[k4+3];
w[n2+1+k4] = v[n2+1+k4] + v[k4+1];
w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4];
w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4];
}
// step 3
ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
for (l=0; l < ld-3; ++l) {
int k0 = n >> (l+2), k1 = 1 << (l+3);
int rlim = n >> (l+4), r4, r;
int s2lim = 1 << (l+2), s2;
for (r=r4=0; r < rlim; r4+=4,++r) {
for (s2=0; s2 < s2lim; s2+=2) {
u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];
u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];
u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]
- (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];
u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]
+ (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];
}
}
if (l+1 < ld-3) {
// paper bug: ping-ponging of u&w here is omitted
memcpy(w, u, sizeof(u));
}
}
// step 4
for (i=0; i < n8; ++i) {
int j = _bitreverse32(i) >> (32-ld+3);
assert(j < n8);
if (i == j) {
// paper bug: original code probably swapped in place; if copying,
// need to directly copy in this case
int i8 = i << 3;
v[i8+1] = u[i8+1];
v[i8+3] = u[i8+3];
v[i8+5] = u[i8+5];
v[i8+7] = u[i8+7];
} else if (i < j) {
int i8 = i << 3, j8 = j << 3;
v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];
v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];
v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];
v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];
}
}
// step 5
for (k=0; k < n2; ++k) {
w[k] = v[k*2+1];
}
// step 6
for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {
u[n-1-k2] = w[k4];
u[n-2-k2] = w[k4+1];
u[n3_4 - 1 - k2] = w[k4+2];
u[n3_4 - 2 - k2] = w[k4+3];
}
// step 7
for (k=k2=0; k < n8; ++k, k2 += 2) {
v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
}
// step 8
for (k=k2=0; k < n4; ++k,k2 += 2) {
X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];
X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];
}
// decode kernel to output
// determined the following value experimentally
// (by first figuring out what made inverse_mdct_slow work); then matching that here
// (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)
s = 0.5; // theoretically would be n4
// [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,
// so it needs to use the "old" B values to behave correctly, or else
// set s to 1.0 ]]]
for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];
for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];
for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];
}
#endif
static float *get_window(vorb *f, int len) {
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
return NULL;
}
#ifndef STB_VORBIS_NO_DEFER_FLOOR
typedef int16 YTYPE;
#else
typedef int YTYPE;
#endif
static int do_floor(vorb *f, Mapping *map, int i, int n, float *target,
YTYPE *finalY, uint8 *step2_flag) {
int n2 = n >> 1;
int s = map->chan[i].mux, floor;
floor = map->submap_floor[s];
if (f->floor_types[floor] == 0) {
return error(f, VORBIS_invalid_stream);
} else {
Floor1 *g = &f->floor_config[floor].floor1;
int j, q;
int lx = 0, ly = finalY[0] * g->floor1_multiplier;
for (q = 1; q < g->values; ++q) {
j = g->sorted_order[q];
#ifndef STB_VORBIS_NO_DEFER_FLOOR
if (finalY[j] >= 0)
#else
if (step2_flag[j])
#endif
{
int hy = finalY[j] * g->floor1_multiplier;
int hx = g->Xlist[j];
if (lx != hx) draw_line(target, lx, ly, hx, hy, n2);
CHECK(f);
lx = hx, ly = hy;
}
}
if (lx < n2) {
// optimization of: draw_line(target, lx,ly, n,ly, n2);
for (j = lx; j < n2; ++j) LINE_OP(target[j], inverse_db_table[ly]);
CHECK(f);
}
}
return TRUE;
}
// The meaning of "left" and "right"
//
// For a given frame:
// we compute samples from 0..n
// window_center is n/2
// we'll window and mix the samples from left_start to left_end with data
// from the previous frame all of the samples from left_end to right_start
// can be output without mixing; however,
// this interval is 0-length except when transitioning between short and
// long frames
// all of the samples from right_start to right_end need to be mixed with
// the next frame,
// which we don't have, so those get saved in a buffer
// frame N's right_end-right_start, the number of samples to mix with the
// next frame,
// has to be the same as frame N+1's left_end-left_start (which they are
// by construction)
static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end,
int *p_right_start, int *p_right_end,
int *mode) {
Mode *m;
int i, n, prev, next, window_center;
f->channel_buffer_start = f->channel_buffer_end = 0;
retry:
if (f->eof) return FALSE;
if (!maybe_start_packet(f)) return FALSE;
// check packet type
if (get_bits(f, 1) != 0) {
if (IS_PUSH_MODE(f)) return error(f, VORBIS_bad_packet_type);
while (EOP != get8_packet(f))
;
goto retry;
}
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
i = get_bits(f, ilog(f->mode_count - 1));
if (i == EOP) return FALSE;
if (i >= f->mode_count) return FALSE;
*mode = i;
m = f->mode_config + i;
if (m->blockflag) {
n = f->blocksize_1;
prev = get_bits(f, 1);
next = get_bits(f, 1);
} else {
prev = next = 0;
n = f->blocksize_0;
}
// WINDOWING
window_center = n >> 1;
if (m->blockflag && !prev) {
*p_left_start = (n - f->blocksize_0) >> 2;
*p_left_end = (n + f->blocksize_0) >> 2;
} else {
*p_left_start = 0;
*p_left_end = window_center;
}
if (m->blockflag && !next) {
*p_right_start = (n * 3 - f->blocksize_0) >> 2;
*p_right_end = (n * 3 + f->blocksize_0) >> 2;
} else {
*p_right_start = window_center;
*p_right_end = n;
}
return TRUE;
}
static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start,
int left_end, int right_start,
int right_end, int *p_left) {
Mapping *map;
int i, j, k, n, n2;
int zero_channel[256];
int really_zero_channel[256];
// WINDOWING
n = f->blocksize[m->blockflag];
map = &f->mapping[m->mapping];
// FLOORS
n2 = n >> 1;
CHECK(f);
for (i = 0; i < f->channels; ++i) {
int s = map->chan[i].mux, floor;
zero_channel[i] = FALSE;
floor = map->submap_floor[s];
if (f->floor_types[floor] == 0) {
return error(f, VORBIS_invalid_stream);
} else {
Floor1 *g = &f->floor_config[floor].floor1;
if (get_bits(f, 1)) {
short *finalY;
uint8 step2_flag[256];
static int range_list[4] = {256, 128, 86, 64};
int range = range_list[g->floor1_multiplier - 1];
int offset = 2;
finalY = f->finalY[i];
finalY[0] = get_bits(f, ilog(range) - 1);
finalY[1] = get_bits(f, ilog(range) - 1);
for (j = 0; j < g->partitions; ++j) {
int pclass = g->partition_class_list[j];
int cdim = g->class_dimensions[pclass];
int cbits = g->class_subclasses[pclass];
int csub = (1 << cbits) - 1;
int cval = 0;
if (cbits) {
Codebook *c = f->codebooks + g->class_masterbooks[pclass];
DECODE(cval, f, c);
}
for (k = 0; k < cdim; ++k) {
int book = g->subclass_books[pclass][cval & csub];
cval = cval >> cbits;
if (book >= 0) {
int temp;
Codebook *c = f->codebooks + book;
DECODE(temp, f, c);
finalY[offset++] = temp;
} else
finalY[offset++] = 0;
}
}
if (f->valid_bits == INVALID_BITS)
goto error; // behavior according to spec
step2_flag[0] = step2_flag[1] = 1;
for (j = 2; j < g->values; ++j) {
int low, high, pred, highroom, lowroom, room, val;
low = g->neighbors[j][0];
high = g->neighbors[j][1];
// neighbors(g->Xlist, j, &low, &high);
pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high],
finalY[low], finalY[high]);
val = finalY[j];
highroom = range - pred;
lowroom = pred;
if (highroom < lowroom)
room = highroom * 2;
else
room = lowroom * 2;
if (val) {
step2_flag[low] = step2_flag[high] = 1;
step2_flag[j] = 1;
if (val >= room)
if (highroom > lowroom)
finalY[j] = val - lowroom + pred;
else
finalY[j] = pred - val + highroom - 1;
else if (val & 1)
finalY[j] = pred - ((val + 1) >> 1);
else
finalY[j] = pred + (val >> 1);
} else {
step2_flag[j] = 0;
finalY[j] = pred;
}
}
#ifdef STB_VORBIS_NO_DEFER_FLOOR
do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);
#else
// defer final floor computation until _after_ residue
for (j = 0; j < g->values; ++j) {
if (!step2_flag[j]) finalY[j] = -1;
}
#endif
} else {
error:
zero_channel[i] = TRUE;
}
// So we just defer everything else to later
// at this point we've decoded the floor into buffer
}
}
CHECK(f);
// at this point we've decoded all floors
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
// re-enable coupled channels if necessary
memcpy(really_zero_channel, zero_channel,
sizeof(really_zero_channel[0]) * f->channels);
for (i = 0; i < map->coupling_steps; ++i)
if (!zero_channel[map->chan[i].magnitude] ||
!zero_channel[map->chan[i].angle]) {
zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] =
FALSE;
}
CHECK(f);
// RESIDUE DECODE
for (i = 0; i < map->submaps; ++i) {
float *residue_buffers[STB_VORBIS_MAX_CHANNELS];
int r;
uint8 do_not_decode[256];
int ch = 0;
for (j = 0; j < f->channels; ++j) {
if (map->chan[j].mux == i) {
if (zero_channel[j]) {
do_not_decode[ch] = TRUE;
residue_buffers[ch] = NULL;
} else {
do_not_decode[ch] = FALSE;
residue_buffers[ch] = f->channel_buffers[j];
}
++ch;
}
}
r = map->submap_residue[i];
decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);
}
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
CHECK(f);
// INVERSE COUPLING
for (i = map->coupling_steps - 1; i >= 0; --i) {
int n2 = n >> 1;
float *m = f->channel_buffers[map->chan[i].magnitude];
float *a = f->channel_buffers[map->chan[i].angle];
for (j = 0; j < n2; ++j) {
float a2, m2;
if (m[j] > 0)
if (a[j] > 0)
m2 = m[j], a2 = m[j] - a[j];
else
a2 = m[j], m2 = m[j] + a[j];
else if (a[j] > 0)
m2 = m[j], a2 = m[j] + a[j];
else
a2 = m[j], m2 = m[j] - a[j];
m[j] = m2;
a[j] = a2;
}
}
CHECK(f);
// finish decoding the floors
#ifndef STB_VORBIS_NO_DEFER_FLOOR
for (i = 0; i < f->channels; ++i) {
if (really_zero_channel[i]) {
bzero(f->channel_buffers[i], sizeof(*f->channel_buffers[i]) * n2);
} else {
do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);
}
}
#else
for (i = 0; i < f->channels; ++i) {
if (really_zero_channel[i]) {
memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
} else {
for (j = 0; j < n2; ++j)
f->channel_buffers[i][j] *= f->floor_buffers[i][j];
}
}
#endif
// INVERSE MDCT
CHECK(f);
for (i = 0; i < f->channels; ++i)
inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);
CHECK(f);
// this shouldn't be necessary, unless we exited on an error
// and want to flush to get to the next packet
flush_packet(f);
if (f->first_decode) {
// assume we start so first non-discarded sample is sample 0
// this isn't to spec, but spec would require us to read ahead
// and decode the size of all current frames--could be done,
// but presumably it's not a commonly used feature
f->current_loc = -n2; // start of first frame is positioned for discard
// we might have to discard samples "from" the next frame too,
// if we're lapping a large block then a small at the start?
f->discard_samples_deferred = n - right_end;
f->current_loc_valid = TRUE;
f->first_decode = FALSE;
} else if (f->discard_samples_deferred) {
if (f->discard_samples_deferred >= right_start - left_start) {
f->discard_samples_deferred -= (right_start - left_start);
left_start = right_start;
*p_left = left_start;
} else {
left_start += f->discard_samples_deferred;
*p_left = left_start;
f->discard_samples_deferred = 0;
}
} else if (f->previous_length == 0 && f->current_loc_valid) {
// we're recovering from a seek... that means we're going to discard
// the samples from this packet even though we know our position from
// the last page header, so we need to update the position based on
// the discarded samples here
// but wait, the code below is going to add this in itself even
// on a discard, so we don't need to do it here...
}
// check if we have ogg information about the sample # for this packet
if (f->last_seg_which == f->end_seg_with_known_loc) {
// if we have a valid current loc, and this is final:
if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {
uint32 current_end = f->known_loc_for_packet;
// then let's infer the size of the (probably) short final frame
if (current_end < f->current_loc + (right_end - left_start)) {
if (current_end < f->current_loc) {
// negative truncation, that's impossible!
*len = 0;
} else {
*len = current_end - f->current_loc;
}
*len += left_start; // this doesn't seem right, but has no ill effect
// on my test files
if (*len > right_end) *len = right_end; // this should never happen
f->current_loc += *len;
return TRUE;
}
}
// otherwise, just set our sample loc
// guess that the ogg granule pos refers to the _middle_ of the
// last frame?
// set f->current_loc to the position of left_start
f->current_loc = f->known_loc_for_packet - (n2 - left_start);
f->current_loc_valid = TRUE;
}
if (f->current_loc_valid) f->current_loc += (right_start - left_start);
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
*len = right_end; // ignore samples after the window goes to 0
CHECK(f);
return TRUE;
}
static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right) {
int mode, left_end, right_end;
if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode))
return 0;
return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left,
left_end, *p_right, right_end, p_left);
}
static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right) {
int prev, i, j;
// we use right&left (the start of the right- and left-window sin()-regions)
// to determine how much to return, rather than inferring from the rules
// (same result, clearer code); 'left' indicates where our sin() window
// starts, therefore where the previous window's right edge starts, and
// therefore where to start mixing from the previous buffer. 'right'
// indicates where our sin() ending-window starts, therefore that's where
// we start saving, and where our returned-data ends.
// mixin from previous window
if (f->previous_length) {
int i, j, n = f->previous_length;
float *w = get_window(f, n);
if (w == NULL) return 0;
for (i = 0; i < f->channels; ++i) {
for (j = 0; j < n; ++j)
f->channel_buffers[i][left + j] =
f->channel_buffers[i][left + j] * w[j] +
f->previous_window[i][j] * w[n - 1 - j];
}
}
prev = f->previous_length;
// last half of this data becomes previous window
f->previous_length = len - right;
// @OPTIMIZE: could avoid this copy by double-buffering the
// output (flipping previous_window with channel_buffers), but
// then previous_window would have to be 2x as large, and
// channel_buffers couldn't be temp mem (although they're NOT
// currently temp mem, they could be (unless we want to level
// performance by spreading out the computation))
for (i = 0; i < f->channels; ++i)
for (j = 0; right + j < len; ++j)
f->previous_window[i][j] = f->channel_buffers[i][right + j];
if (!prev)
// there was no previous packet, so this data isn't valid...
// this isn't entirely true, only the would-have-overlapped data
// isn't valid, but this seems to be what the spec requires
return 0;
// truncate a short frame
if (len < right) right = len;
f->samples_output += right - left;
return right - left;
}
static int vorbis_pump_first_frame(stb_vorbis *f) {
int len, right, left, res;
res = vorbis_decode_packet(f, &len, &left, &right);
if (res) vorbis_finish_frame(f, len, left, right);
return res;
}
#ifndef STB_VORBIS_NO_PUSHDATA_API
static int is_whole_packet_present(stb_vorbis *f, int end_page) {
// make sure that we have the packet available before continuing...
// this requires a full ogg parse, but we know we can fetch from f->stream
// instead of coding this out explicitly, we could save the current read
// state, read the next packet with get8() until end-of-packet, check f->eof,
// then reset the state? but that would be slower, esp. since we'd have over
// 256 bytes of state to restore (primarily the page segment table)
int s = f->next_seg, first = TRUE;
uint8 *p = f->stream;
if (s != -1) { // if we're not starting the packet with a 'continue on next
// page' flag
for (; s < f->segment_count; ++s) {
p += f->segments[s];
if (f->segments[s] < 255) // stop at first short segment
break;
}
// either this continues, or it ends it...
if (end_page)
if (s < f->segment_count - 1) return error(f, VORBIS_invalid_stream);
if (s == f->segment_count) s = -1; // set 'crosses page' flag
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
first = FALSE;
}
for (; s == -1;) {
uint8 *q;
int n;
// check that we have the page header ready
if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data);
// validate the page
if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream);
if (p[4] != 0) return error(f, VORBIS_invalid_stream);
if (first) { // the first segment must NOT have 'continued_packet', later
// ones MUST
if (f->previous_length)
if ((p[5] & PAGEFLAG_continued_packet))
return error(f, VORBIS_invalid_stream);
// if no previous length, we're resynching, so we can come in on a
// continued-packet, which we'll just drop
} else {
if (!(p[5] & PAGEFLAG_continued_packet))
return error(f, VORBIS_invalid_stream);
}
n = p[26]; // segment counts
q = p + 27; // q points to segment table
p = q + n; // advance past header
// make sure we've read the segment table
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
for (s = 0; s < n; ++s) {
p += q[s];
if (q[s] < 255) break;
}
if (end_page)
if (s < n - 1) return error(f, VORBIS_invalid_stream);
if (s == n) s = -1; // set 'crosses page' flag
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
first = FALSE;
}
return TRUE;
}
#endif // !STB_VORBIS_NO_PUSHDATA_API
static int start_decoder(vorb *f) {
uint8 header[6], x, y;
int len, i, j, k, max_submaps = 0;
int longest_floorlist = 0;
// first page, first packet
if (!start_page(f)) return FALSE;
// validate page flag
if (!(f->page_flag & PAGEFLAG_first_page))
return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_last_page)
return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_continued_packet)
return error(f, VORBIS_invalid_first_page);
// check for expected packet length
if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
if (f->segments[0] != 30) {
// check for the Ogg skeleton fishead identifying header to refine our error
if (f->segments[0] == 64 && getn(f, header, 6) && header[0] == 'f' &&
header[1] == 'i' && header[2] == 's' && header[3] == 'h' &&
header[4] == 'e' && header[5] == 'a' && get8(f) == 'd' &&
get8(f) == '\0')
return error(f, VORBIS_ogg_skeleton_not_supported);
else
return error(f, VORBIS_invalid_first_page);
}
// read packet
// check packet header
if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
// vorbis_version
if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
f->channels = get8(f);
if (!f->channels) return error(f, VORBIS_invalid_first_page);
if (f->channels > STB_VORBIS_MAX_CHANNELS)
return error(f, VORBIS_too_many_channels);
f->sample_rate = get32(f);
if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
get32(f); // bitrate_maximum
get32(f); // bitrate_nominal
get32(f); // bitrate_minimum
x = get8(f);
{
int log0, log1;
log0 = x & 15;
log1 = x >> 4;
f->blocksize_0 = 1 << log0;
f->blocksize_1 = 1 << log1;
if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
if (log0 > log1) return error(f, VORBIS_invalid_setup);
}
// framing_flag
x = get8(f);
if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
// second packet!
if (!start_page(f)) return FALSE;
if (!start_packet(f)) return FALSE;
do {
len = next_segment(f);
skip(f, len);
f->bytes_in_seg = 0;
} while (len);
// third packet!
if (!start_packet(f)) return FALSE;
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (IS_PUSH_MODE(f)) {
if (!is_whole_packet_present(f, TRUE)) {
// convert error in ogg header to write type
if (f->error == VORBIS_invalid_stream) f->error = VORBIS_invalid_setup;
return FALSE;
}
}
#endif
crc32_init(); // always init it, to avoid multithread race conditions
if (get8_packet(f) != VORBIS_packet_setup)
return error(f, VORBIS_invalid_setup);
for (i = 0; i < 6; ++i) header[i] = get8_packet(f);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
// codebooks
f->codebook_count = get_bits(f, 8) + 1;
f->codebooks =
(Codebook *)setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
for (i = 0; i < f->codebook_count; ++i) {
uint32 *values;
int ordered, sorted_count;
int total = 0;
uint8 *lengths;
Codebook *c = f->codebooks + i;
CHECK(f);
x = get_bits(f, 8);
if (x != 0x42) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8);
if (x != 0x43) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8);
if (x != 0x56) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8);
c->dimensions = (get_bits(f, 8) << 8) + x;
x = get_bits(f, 8);
y = get_bits(f, 8);
c->entries = (get_bits(f, 8) << 16) + (y << 8) + x;
ordered = get_bits(f, 1);
c->sparse = ordered ? 0 : get_bits(f, 1);
if (c->dimensions == 0 && c->entries != 0)
return error(f, VORBIS_invalid_setup);
if (c->sparse)
lengths = (uint8 *)setup_temp_malloc(f, c->entries);
else
lengths = c->codeword_lengths = (uint8 *)setup_malloc(f, c->entries);
if (!lengths) return error(f, VORBIS_outofmem);
if (ordered) {
int current_entry = 0;
int current_length = get_bits(f, 5) + 1;
while (current_entry < c->entries) {
int limit = c->entries - current_entry;
int n = get_bits(f, ilog(limit));
if (current_length >= 32) return error(f, VORBIS_invalid_setup);
if (current_entry + n > (int)c->entries) {
return error(f, VORBIS_invalid_setup);
}
memset(lengths + current_entry, current_length, n);
current_entry += n;
++current_length;
}
} else {
for (j = 0; j < c->entries; ++j) {
int present = c->sparse ? get_bits(f, 1) : 1;
if (present) {
lengths[j] = get_bits(f, 5) + 1;
++total;
if (lengths[j] == 32) return error(f, VORBIS_invalid_setup);
} else {
lengths[j] = NO_CODE;
}
}
}
if (c->sparse && total >= c->entries >> 2) {
// convert sparse items to non-sparse!
if (c->entries > (int)f->setup_temp_memory_required)
f->setup_temp_memory_required = c->entries;
c->codeword_lengths = (uint8 *)setup_malloc(f, c->entries);
if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
memcpy(c->codeword_lengths, lengths, c->entries);
setup_temp_free(f, lengths,
c->entries); // note this is only safe if there have been
// no intervening temp mallocs!
lengths = c->codeword_lengths;
c->sparse = 0;
}
// compute the size of the sorted tables
if (c->sparse) {
sorted_count = total;
} else {
sorted_count = 0;
#ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
for (j = 0; j < c->entries; ++j)
if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH &&
lengths[j] != NO_CODE)
++sorted_count;
#endif
}
c->sorted_entries = sorted_count;
values = NULL;
CHECK(f);
if (!c->sparse) {
c->codewords =
(uint32 *)setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
} else {
unsigned int size;
if (c->sorted_entries) {
c->codeword_lengths = (uint8 *)setup_malloc(f, c->sorted_entries);
if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
c->codewords = (uint32 *)setup_temp_malloc(
f, sizeof(*c->codewords) * c->sorted_entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
values =
(uint32 *)setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
if (!values) return error(f, VORBIS_outofmem);
}
size = c->entries +
(sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
if (size > f->setup_temp_memory_required)
f->setup_temp_memory_required = size;
}
if (!compute_codewords(c, lengths, c->entries, values)) {
if (c->sparse) setup_temp_free(f, values, 0);
return error(f, VORBIS_invalid_setup);
}
if (c->sorted_entries) {
// allocate an extra slot for sentinels
c->sorted_codewords = (uint32 *)setup_malloc(
f, sizeof(*c->sorted_codewords) * (c->sorted_entries + 1));
if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
// allocate an extra slot at the front so that c->sorted_values[-1] is
// defined so that we can catch that case without an extra if
c->sorted_values = (int *)setup_malloc(
f, sizeof(*c->sorted_values) * (c->sorted_entries + 1));
if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
++c->sorted_values;
c->sorted_values[-1] = -1;
compute_sorted_huffman(c, lengths, values);
}
if (c->sparse) {
setup_temp_free(f, values, sizeof(*values) * c->sorted_entries);
setup_temp_free(f, c->codewords,
sizeof(*c->codewords) * c->sorted_entries);
setup_temp_free(f, lengths, c->entries);
c->codewords = NULL;
}
compute_accelerated_huffman(c);
CHECK(f);
c->lookup_type = get_bits(f, 4);
if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
if (c->lookup_type > 0) {
uint16 *mults;
c->minimum_value = float32_unpack(get_bits(f, 32));
c->delta_value = float32_unpack(get_bits(f, 32));
c->value_bits = get_bits(f, 4) + 1;
c->sequence_p = get_bits(f, 1);
if (c->lookup_type == 1) {
int values = lookup1_values(c->entries, c->dimensions);
if (values < 0) return error(f, VORBIS_invalid_setup);
c->lookup_values = (uint32)values;
} else {
c->lookup_values = c->entries * c->dimensions;
}
if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
mults =
(uint16 *)setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
if (mults == NULL) return error(f, VORBIS_outofmem);
for (j = 0; j < (int)c->lookup_values; ++j) {
int q = get_bits(f, c->value_bits);
if (q == EOP) {
setup_temp_free(f, mults, sizeof(mults[0]) * c->lookup_values);
return error(f, VORBIS_invalid_setup);
}
mults[j] = q;
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int len, sparse = c->sparse;
float last = 0;
// pre-expand the lookup1-style multiplicands, to avoid a divide in the
// inner loop
if (sparse) {
if (c->sorted_entries == 0) goto skip;
c->multiplicands = (codetype *)setup_malloc(
f,
sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
} else
c->multiplicands = (codetype *)setup_malloc(
f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
if (c->multiplicands == NULL) {
setup_temp_free(f, mults, sizeof(mults[0]) * c->lookup_values);
return error(f, VORBIS_outofmem);
}
len = sparse ? c->sorted_entries : c->entries;
for (j = 0; j < len; ++j) {
unsigned int z = sparse ? c->sorted_values[j] : j;
unsigned int div = 1;
for (k = 0; k < c->dimensions; ++k) {
int off = (z / div) % c->lookup_values;
float val = mults[off];
val = mults[off] * c->delta_value + c->minimum_value + last;
c->multiplicands[j * c->dimensions + k] = val;
if (c->sequence_p) last = val;
if (k + 1 < c->dimensions) {
if (div > UINT_MAX / (unsigned int)c->lookup_values) {
setup_temp_free(f, mults, sizeof(mults[0]) * c->lookup_values);
return error(f, VORBIS_invalid_setup);
}
div *= c->lookup_values;
}
}
}
c->lookup_type = 2;
} else
#endif
{
float last = 0;
CHECK(f);
c->multiplicands = (codetype *)setup_malloc(
f, sizeof(c->multiplicands[0]) * c->lookup_values);
if (c->multiplicands == NULL) {
setup_temp_free(f, mults, sizeof(mults[0]) * c->lookup_values);
return error(f, VORBIS_outofmem);
}
for (j = 0; j < (int)c->lookup_values; ++j) {
float val = mults[j] * c->delta_value + c->minimum_value + last;
c->multiplicands[j] = val;
if (c->sequence_p) last = val;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
skip:;
#endif
setup_temp_free(f, mults, sizeof(mults[0]) * c->lookup_values);
CHECK(f);
}
CHECK(f);
}
// time domain transfers (notused)
x = get_bits(f, 6) + 1;
for (i = 0; i < x; ++i) {
uint32 z = get_bits(f, 16);
if (z != 0) return error(f, VORBIS_invalid_setup);
}
// Floors
f->floor_count = get_bits(f, 6) + 1;
f->floor_config =
(Floor *)setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
for (i = 0; i < f->floor_count; ++i) {
f->floor_types[i] = get_bits(f, 16);
if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
if (f->floor_types[i] == 0) {
Floor0 *g = &f->floor_config[i].floor0;
g->order = get_bits(f, 8);
g->rate = get_bits(f, 16);
g->bark_map_size = get_bits(f, 16);
g->amplitude_bits = get_bits(f, 6);
g->amplitude_offset = get_bits(f, 8);
g->number_of_books = get_bits(f, 4) + 1;
for (j = 0; j < g->number_of_books; ++j) g->book_list[j] = get_bits(f, 8);
return error(f, VORBIS_feature_not_supported);
} else {
stbv__floor_ordering p[31 * 8 + 2];
Floor1 *g = &f->floor_config[i].floor1;
int max_class = -1;
g->partitions = get_bits(f, 5);
for (j = 0; j < g->partitions; ++j) {
g->partition_class_list[j] = get_bits(f, 4);
if (g->partition_class_list[j] > max_class)
max_class = g->partition_class_list[j];
}
for (j = 0; j <= max_class; ++j) {
g->class_dimensions[j] = get_bits(f, 3) + 1;
g->class_subclasses[j] = get_bits(f, 2);
if (g->class_subclasses[j]) {
g->class_masterbooks[j] = get_bits(f, 8);
if (g->class_masterbooks[j] >= f->codebook_count)
return error(f, VORBIS_invalid_setup);
}
for (k = 0; k < 1 << g->class_subclasses[j]; ++k) {
g->subclass_books[j][k] = get_bits(f, 8) - 1;
if (g->subclass_books[j][k] >= f->codebook_count)
return error(f, VORBIS_invalid_setup);
}
}
g->floor1_multiplier = get_bits(f, 2) + 1;
g->rangebits = get_bits(f, 4);
g->Xlist[0] = 0;
g->Xlist[1] = 1 << g->rangebits;
g->values = 2;
for (j = 0; j < g->partitions; ++j) {
int c = g->partition_class_list[j];
for (k = 0; k < g->class_dimensions[c]; ++k) {
g->Xlist[g->values] = get_bits(f, g->rangebits);
++g->values;
}
}
// precompute the sorting
for (j = 0; j < g->values; ++j) {
p[j].x = g->Xlist[j];
p[j].id = j;
}
qsort(p, g->values, sizeof(p[0]), point_compare);
for (j = 0; j < g->values - 1; ++j)
if (p[j].x == p[j + 1].x) return error(f, VORBIS_invalid_setup);
for (j = 0; j < g->values; ++j) g->sorted_order[j] = (uint8)p[j].id;
// precompute the neighbors
for (j = 2; j < g->values; ++j) {
int low, hi;
neighbors(g->Xlist, j, &low, &hi);
g->neighbors[j][0] = low;
g->neighbors[j][1] = hi;
}
if (g->values > longest_floorlist) longest_floorlist = g->values;
}
}
// Residue
f->residue_count = get_bits(f, 6) + 1;
f->residue_config = (Residue *)setup_malloc(
f, f->residue_count * sizeof(f->residue_config[0]));
if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
for (i = 0; i < f->residue_count; ++i) {
uint8 residue_cascade[64];
Residue *r = f->residue_config + i;
f->residue_types[i] = get_bits(f, 16);
if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
r->begin = get_bits(f, 24);
r->end = get_bits(f, 24);
if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
r->part_size = get_bits(f, 24) + 1;
r->classifications = get_bits(f, 6) + 1;
r->classbook = get_bits(f, 8);
if (r->classbook >= f->codebook_count)
return error(f, VORBIS_invalid_setup);
for (j = 0; j < r->classifications; ++j) {
uint8 high_bits = 0;
uint8 low_bits = get_bits(f, 3);
if (get_bits(f, 1)) high_bits = get_bits(f, 5);
residue_cascade[j] = high_bits * 8 + low_bits;
}
r->residue_books = (short(*)[8])setup_malloc(
f, sizeof(r->residue_books[0]) * r->classifications);
if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
for (j = 0; j < r->classifications; ++j) {
for (k = 0; k < 8; ++k) {
if (residue_cascade[j] & (1 << k)) {
r->residue_books[j][k] = get_bits(f, 8);
if (r->residue_books[j][k] >= f->codebook_count)
return error(f, VORBIS_invalid_setup);
} else {
r->residue_books[j][k] = -1;
}
}
}
// precompute the classifications[] array to avoid inner-loop mod/divide
// call it 'classdata' since we already have r->classifications
r->classdata = (uint8 **)setup_malloc(
f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
if (!r->classdata) return error(f, VORBIS_outofmem);
memset(r->classdata, 0,
sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
for (j = 0; j < f->codebooks[r->classbook].entries; ++j) {
int classwords = f->codebooks[r->classbook].dimensions;
int temp = j;
r->classdata[j] =
(uint8 *)setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
for (k = classwords - 1; k >= 0; --k) {
r->classdata[j][k] = temp % r->classifications;
temp /= r->classifications;
}
}
}
f->mapping_count = get_bits(f, 6) + 1;
f->mapping =
(Mapping *)setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
if (f->mapping == NULL) return error(f, VORBIS_outofmem);
memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
for (i = 0; i < f->mapping_count; ++i) {
Mapping *m = f->mapping + i;
int mapping_type = get_bits(f, 16);
if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
m->chan = (MappingChannel *)setup_malloc(f, f->channels * sizeof(*m->chan));
if (m->chan == NULL) return error(f, VORBIS_outofmem);
if (get_bits(f, 1))
m->submaps = get_bits(f, 4) + 1;
else
m->submaps = 1;
if (m->submaps > max_submaps) max_submaps = m->submaps;
if (get_bits(f, 1)) {
m->coupling_steps = get_bits(f, 8) + 1;
if (m->coupling_steps > f->channels)
return error(f, VORBIS_invalid_setup);
for (k = 0; k < m->coupling_steps; ++k) {
m->chan[k].magnitude = get_bits(f, ilog(f->channels - 1));
m->chan[k].angle = get_bits(f, ilog(f->channels - 1));
if (m->chan[k].magnitude >= f->channels)
return error(f, VORBIS_invalid_setup);
if (m->chan[k].angle >= f->channels)
return error(f, VORBIS_invalid_setup);
if (m->chan[k].magnitude == m->chan[k].angle)
return error(f, VORBIS_invalid_setup);
}
} else
m->coupling_steps = 0;
// reserved field
if (get_bits(f, 2)) return error(f, VORBIS_invalid_setup);
if (m->submaps > 1) {
for (j = 0; j < f->channels; ++j) {
m->chan[j].mux = get_bits(f, 4);
if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
}
} else
// @SPECIFICATION: this case is missing from the spec
for (j = 0; j < f->channels; ++j) m->chan[j].mux = 0;
for (j = 0; j < m->submaps; ++j) {
get_bits(f, 8); // discard
m->submap_floor[j] = get_bits(f, 8);
m->submap_residue[j] = get_bits(f, 8);
if (m->submap_floor[j] >= f->floor_count)
return error(f, VORBIS_invalid_setup);
if (m->submap_residue[j] >= f->residue_count)
return error(f, VORBIS_invalid_setup);
}
}
// Modes
f->mode_count = get_bits(f, 6) + 1;
for (i = 0; i < f->mode_count; ++i) {
Mode *m = f->mode_config + i;
m->blockflag = get_bits(f, 1);
m->windowtype = get_bits(f, 16);
m->transformtype = get_bits(f, 16);
m->mapping = get_bits(f, 8);
if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
}
flush_packet(f);
f->previous_length = 0;
for (i = 0; i < f->channels; ++i) {
f->channel_buffers[i] =
(float *)setup_malloc(f, sizeof(float) * f->blocksize_1);
f->previous_window[i] =
(float *)setup_malloc(f, sizeof(float) * f->blocksize_1 / 2);
f->finalY[i] = (int16 *)setup_malloc(f, sizeof(int16) * longest_floorlist);
if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL ||
f->finalY[i] == NULL)
return error(f, VORBIS_outofmem);
memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
f->floor_buffers[i] =
(float *)setup_malloc(f, sizeof(float) * f->blocksize_1 / 2);
if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
#endif
}
if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
f->blocksize[0] = f->blocksize_0;
f->blocksize[1] = f->blocksize_1;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (integer_divide_table[1][1] == 0)
for (i = 0; i < DIVTAB_NUMER; ++i)
for (j = 1; j < DIVTAB_DENOM; ++j) integer_divide_table[i][j] = i / j;
#endif
// compute how much temporary memory is needed
// 1.
{
uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
uint32 classify_mem;
int i, max_part_read = 0;
for (i = 0; i < f->residue_count; ++i) {
Residue *r = f->residue_config + i;
unsigned int actual_size = f->blocksize_1 / 2;
unsigned int limit_r_begin =
r->begin < actual_size ? r->begin : actual_size;
unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size;
int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
if (part_read > max_part_read) max_part_read = part_read;
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
classify_mem =
f->channels * (sizeof(void *) + max_part_read * sizeof(uint8 *));
#else
classify_mem =
f->channels * (sizeof(void *) + max_part_read * sizeof(int *));
#endif
// maximum reasonable partition size is f->blocksize_1
f->temp_memory_required = classify_mem;
if (imdct_mem > f->temp_memory_required)
f->temp_memory_required = imdct_mem;
}
f->first_decode = TRUE;
if (f->alloc.alloc_buffer) {
assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
// check if there's enough temp memory so we don't error later
if (f->setup_offset + sizeof(*f) + f->temp_memory_required >
(unsigned)f->temp_offset)
return error(f, VORBIS_outofmem);
}
f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
return TRUE;
}
static void vorbis_deinit(stb_vorbis *p) {
int i, j;
if (p->residue_config) {
for (i = 0; i < p->residue_count; ++i) {
Residue *r = p->residue_config + i;
if (r->classdata) {
for (j = 0; j < p->codebooks[r->classbook].entries; ++j)
setup_free(p, r->classdata[j]);
setup_free(p, r->classdata);
}
setup_free(p, r->residue_books);
}
}
if (p->codebooks) {
CHECK(p);
for (i = 0; i < p->codebook_count; ++i) {
Codebook *c = p->codebooks + i;
setup_free(p, c->codeword_lengths);
setup_free(p, c->multiplicands);
setup_free(p, c->codewords);
setup_free(p, c->sorted_codewords);
// c->sorted_values[-1] is the first entry in the array
setup_free(p, c->sorted_values ? c->sorted_values - 1 : NULL);
}
setup_free(p, p->codebooks);
}
setup_free(p, p->floor_config);
setup_free(p, p->residue_config);
if (p->mapping) {
for (i = 0; i < p->mapping_count; ++i) setup_free(p, p->mapping[i].chan);
setup_free(p, p->mapping);
}
CHECK(p);
for (i = 0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) {
setup_free(p, p->channel_buffers[i]);
setup_free(p, p->previous_window[i]);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
setup_free(p, p->floor_buffers[i]);
#endif
setup_free(p, p->finalY[i]);
}
for (i = 0; i < 2; ++i) {
setup_free(p, p->A[i]);
setup_free(p, p->B[i]);
setup_free(p, p->C[i]);
setup_free(p, p->window[i]);
setup_free(p, p->bit_reverse[i]);
}
#ifndef STB_VORBIS_NO_STDIO
if (p->close_on_free) fclose(p->f);
#endif
}
void stb_vorbis_close(stb_vorbis *p) {
if (p == NULL) return;
vorbis_deinit(p);
setup_free(p, p);
}
static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z) {
memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start
if (z) {
p->alloc = *z;
p->alloc.alloc_buffer_length_in_bytes =
(p->alloc.alloc_buffer_length_in_bytes + 3) & ~3;
p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;
}
p->eof = 0;
p->error = VORBIS__no_error;
p->stream = NULL;
p->codebooks = NULL;
p->page_crc_tests = -1;
#ifndef STB_VORBIS_NO_STDIO
p->close_on_free = FALSE;
p->f = NULL;
#endif
}
int stb_vorbis_get_sample_offset(stb_vorbis *f) {
if (f->current_loc_valid)
return f->current_loc;
else
return -1;
}
stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f) {
stb_vorbis_info d;
d.channels = f->channels;
d.sample_rate = f->sample_rate;
d.setup_memory_required = f->setup_memory_required;
d.setup_temp_memory_required = f->setup_temp_memory_required;
d.temp_memory_required = f->temp_memory_required;
d.max_frame_size = f->blocksize_1 >> 1;
return d;
}
int stb_vorbis_get_error(stb_vorbis *f) {
int e = f->error;
f->error = VORBIS__no_error;
return e;
}
static stb_vorbis *vorbis_alloc(stb_vorbis *f) {
stb_vorbis *p = (stb_vorbis *)setup_malloc(f, sizeof(*p));
return p;
}
#ifndef STB_VORBIS_NO_PUSHDATA_API
void stb_vorbis_flush_pushdata(stb_vorbis *f) {
f->previous_length = 0;
f->page_crc_tests = 0;
f->discard_samples_deferred = 0;
f->current_loc_valid = FALSE;
f->first_decode = FALSE;
f->samples_output = 0;
f->channel_buffer_start = 0;
f->channel_buffer_end = 0;
}
static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len) {
int i, n;
for (i = 0; i < f->page_crc_tests; ++i) f->scan[i].bytes_done = 0;
// if we have room for more scans, search for them first, because
// they may cause us to stop early if their header is incomplete
if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
if (data_len < 4) return 0;
data_len -= 3; // need to look for 4-byte sequence, so don't miss
// one that straddles a boundary
for (i = 0; i < data_len; ++i) {
if (data[i] == 0x4f) {
if (0 == memcmp(data + i, ogg_page_header, 4)) {
int j, len;
uint32 crc;
// make sure we have the whole page header
if (i + 26 >= data_len || i + 27 + data[i + 26] >= data_len) {
// only read up to this page start, so hopefully we'll
// have the whole page header start next time
data_len = i;
break;
}
// ok, we have it all; compute the length of the page
len = 27 + data[i + 26];
for (j = 0; j < data[i + 26]; ++j) len += data[i + 27 + j];
// scan everything up to the embedded crc (which we must 0)
crc = 0;
for (j = 0; j < 22; ++j) crc = crc32_update(crc, data[i + j]);
// now process 4 0-bytes
for (; j < 26; ++j) crc = crc32_update(crc, 0);
// len is the total number of bytes we need to scan
n = f->page_crc_tests++;
f->scan[n].bytes_left = len - j;
f->scan[n].crc_so_far = crc;
f->scan[n].goal_crc = data[i + 22] + (data[i + 23] << 8) +
(data[i + 24] << 16) + (data[i + 25] << 24);
// if the last frame on a page is continued to the next, then
// we can't recover the sample_loc immediately
if (data[i + 27 + data[i + 26] - 1] == 255)
f->scan[n].sample_loc = ~0;
else
f->scan[n].sample_loc = data[i + 6] + (data[i + 7] << 8) +
(data[i + 8] << 16) + (data[i + 9] << 24);
f->scan[n].bytes_done = i + j;
if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) break;
// keep going if we still have room for more
}
}
}
}
for (i = 0; i < f->page_crc_tests;) {
uint32 crc;
int j;
int n = f->scan[i].bytes_done;
int m = f->scan[i].bytes_left;
if (m > data_len - n) m = data_len - n;
// m is the bytes to scan in the current chunk
crc = f->scan[i].crc_so_far;
for (j = 0; j < m; ++j) crc = crc32_update(crc, data[n + j]);
f->scan[i].bytes_left -= m;
f->scan[i].crc_so_far = crc;
if (f->scan[i].bytes_left == 0) {
// does it match?
if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {
// Houston, we have page
data_len = n + m; // consumption amount is wherever that scan ended
f->page_crc_tests = -1; // drop out of page scan mode
f->previous_length = 0; // decode-but-don't-output one frame
f->next_seg = -1; // start a new page
f->current_loc =
f->scan[i].sample_loc; // set the current sample location
// to the amount we'd have decoded had we
// decoded this page
f->current_loc_valid = f->current_loc != ~0U;
return data_len;
}
// delete entry
f->scan[i] = f->scan[--f->page_crc_tests];
} else {
++i;
}
}
return data_len;
}
// return value: number of bytes we used
int stb_vorbis_decode_frame_pushdata(
stb_vorbis *f, // the file we're decoding
const uint8 *data, int data_len, // the memory available for decoding
int *channels, // place to write number of float * buffers
float ***output, // place to write float ** array of float * buffers
int *samples // place to write number of output samples
) {
int i;
int len, right, left;
if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (f->page_crc_tests >= 0) {
*samples = 0;
return vorbis_search_for_page_pushdata(f, (uint8 *)data, data_len);
}
f->stream = (uint8 *)data;
f->stream_end = (uint8 *)data + data_len;
f->error = VORBIS__no_error;
// check that we have the entire packet in memory
if (!is_whole_packet_present(f, FALSE)) {
*samples = 0;
return 0;
}
if (!vorbis_decode_packet(f, &len, &left, &right)) {
// save the actual error we encountered
enum STBVorbisError error = f->error;
if (error == VORBIS_bad_packet_type) {
// flush and resynch
f->error = VORBIS__no_error;
while (get8_packet(f) != EOP)
if (f->eof) break;
*samples = 0;
return (int)(f->stream - data);
}
if (error == VORBIS_continued_packet_flag_invalid) {
if (f->previous_length == 0) {
// we may be resynching, in which case it's ok to hit one
// of these; just discard the packet
f->error = VORBIS__no_error;
while (get8_packet(f) != EOP)
if (f->eof) break;
*samples = 0;
return (int)(f->stream - data);
}
}
// if we get an error while parsing, what to do?
// well, it DEFINITELY won't work to continue from where we are!
stb_vorbis_flush_pushdata(f);
// restore the error that actually made us bail
f->error = error;
*samples = 0;
return 1;
}
// success!
len = vorbis_finish_frame(f, len, left, right);
for (i = 0; i < f->channels; ++i)
f->outputs[i] = f->channel_buffers[i] + left;
if (channels) *channels = f->channels;
*samples = len;
*output = f->outputs;
return (int)(f->stream - data);
}
stb_vorbis *stb_vorbis_open_pushdata(
const unsigned char *data,
int data_len, // the memory available for decoding
int *data_used, // only defined if result is not NULL
int *error, const stb_vorbis_alloc *alloc) {
stb_vorbis *f, p;
vorbis_init(&p, alloc);
p.stream = (uint8 *)data;
p.stream_end = (uint8 *)data + data_len;
p.push_mode = TRUE;
if (!start_decoder(&p)) {
if (p.eof)
*error = VORBIS_need_more_data;
else
*error = p.error;
return NULL;
}
f = vorbis_alloc(&p);
if (f) {
*f = p;
*data_used = (int)(f->stream - data);
*error = 0;
return f;
} else {
vorbis_deinit(&p);
return NULL;
}
}
#endif // STB_VORBIS_NO_PUSHDATA_API
unsigned int stb_vorbis_get_file_offset(stb_vorbis *f) {
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (f->push_mode) return 0;
#endif
if (USE_MEMORY(f)) return (unsigned int)(f->stream - f->stream_start);
#ifndef STB_VORBIS_NO_STDIO
return (unsigned int)(ftell(f->f) - f->f_start);
#endif
}
#ifndef STB_VORBIS_NO_PULLDATA_API
//
// DATA-PULLING API
//
static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last) {
for (;;) {
int n;
if (f->eof) return 0;
n = get8(f);
if (n == 0x4f) { // page header candidate
unsigned int retry_loc = stb_vorbis_get_file_offset(f);
int i;
// check if we're off the end of a file_section stream
if (retry_loc - 25 > f->stream_len) return 0;
// check the rest of the header
for (i = 1; i < 4; ++i)
if (get8(f) != ogg_page_header[i]) break;
if (f->eof) return 0;
if (i == 4) {
uint8 header[27];
uint32 i, crc, goal, len;
for (i = 0; i < 4; ++i) header[i] = ogg_page_header[i];
for (; i < 27; ++i) header[i] = get8(f);
if (f->eof) return 0;
if (header[4] != 0) goto invalid;
goal = header[22] + (header[23] << 8) + (header[24] << 16) +
(header[25] << 24);
for (i = 22; i < 26; ++i) header[i] = 0;
crc = 0;
for (i = 0; i < 27; ++i) crc = crc32_update(crc, header[i]);
len = 0;
for (i = 0; i < header[26]; ++i) {
int s = get8(f);
crc = crc32_update(crc, s);
len += s;
}
if (len && f->eof) return 0;
for (i = 0; i < len; ++i) crc = crc32_update(crc, get8(f));
// finished parsing probable page
if (crc == goal) {
// we could now check that it's either got the last
// page flag set, OR it's followed by the capture
// pattern, but I guess TECHNICALLY you could have
// a file with garbage between each ogg page and recover
// from it automatically? So even though that paranoia
// might decrease the chance of an invalid decode by
// another 2^32, not worth it since it would hose those
// invalid-but-useful files?
if (end) *end = stb_vorbis_get_file_offset(f);
if (last) {
if (header[5] & 0x04)
*last = 1;
else
*last = 0;
}
set_file_offset(f, retry_loc - 1);
return 1;
}
}
invalid:
// not a valid page, so rewind and look for next one
set_file_offset(f, retry_loc);
}
}
}
#define SAMPLE_unknown 0xffffffff
// seeking is implemented with a binary search, which narrows down the range to
// 64K, before using a linear search (because finding the synchronization
// pattern can be expensive, and the chance we'd find the end page again is
// relatively high for small ranges)
//
// two initial interpolation-style probes are used at the start of the search
// to try to bound either side of the binary search sensibly, while still
// working in O(log n) time if they fail.
static int get_seek_page_info(stb_vorbis *f, ProbedPage *z) {
uint8 header[27], lacing[255];
int i, len;
// record where the page starts
z->page_start = stb_vorbis_get_file_offset(f);
// parse the header
getn(f, header, 27);
if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' ||
header[3] != 'S')
return 0;
getn(f, lacing, header[26]);
// determine the length of the payload
len = 0;
for (i = 0; i < header[26]; ++i) len += lacing[i];
// this implies where the page ends
z->page_end = z->page_start + 27 + header[26] + len;
// read the last-decoded sample out of the data
z->last_decoded_sample =
header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24);
// restore file state to where we were
set_file_offset(f, z->page_start);
return 1;
}
// rarely used function to seek back to the preceding page while finding the
// start of a packet
static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset) {
unsigned int previous_safe, end;
// now we want to seek back 64K from the limit
if (limit_offset >= 65536 &&
limit_offset - 65536 >= f->first_audio_page_offset)
previous_safe = limit_offset - 65536;
else
previous_safe = f->first_audio_page_offset;
set_file_offset(f, previous_safe);
while (vorbis_find_page(f, &end, NULL)) {
if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset)
return 1;
set_file_offset(f, end);
}
return 0;
}
// implements the search logic for finding a page and starting decoding. if
// the function succeeds, current_loc_valid will be true and current_loc will
// be less than or equal to the provided sample number (the closer the
// better).
static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number) {
ProbedPage left, right, mid;
int i, start_seg_with_known_loc, end_pos, page_start;
uint32 delta, stream_length, padding;
double offset, bytes_per_sample;
int probe = 0;
bytes_per_sample = 2; /* TODO(jart): ???? */
offset = 0; /* TODO(jart): ???? */
// find the last page and validate the target sample
stream_length = stb_vorbis_stream_length_in_samples(f);
if (stream_length == 0) return error(f, VORBIS_seek_without_length);
if (sample_number > stream_length) return error(f, VORBIS_seek_invalid);
// this is the maximum difference between the window-center (which is the
// actual granule position value), and the right-start (which the spec
// indicates should be the granule position (give or take one)).
padding = ((f->blocksize_1 - f->blocksize_0) >> 2);
if (sample_number < padding)
sample_number = 0;
else
sample_number -= padding;
left = f->p_first;
while (left.last_decoded_sample == ~0U) {
// (untested) the first page does not have a 'last_decoded_sample'
set_file_offset(f, left.page_end);
if (!get_seek_page_info(f, &left)) goto error;
}
right = f->p_last;
assert(right.last_decoded_sample != ~0U);
// starting from the start is handled differently
if (sample_number <= left.last_decoded_sample) {
if (stb_vorbis_seek_start(f)) return 1;
return 0;
}
while (left.page_end != right.page_start) {
assert(left.page_end < right.page_start);
// search range in bytes
delta = right.page_start - left.page_end;
if (delta <= 65536) {
// there's only 64K left to search - handle it linearly
set_file_offset(f, left.page_end);
} else {
if (probe < 2) {
if (probe == 0) {
// first probe (interpolate)
double data_bytes = right.page_end - left.page_start;
bytes_per_sample = data_bytes / right.last_decoded_sample;
offset =
left.page_start +
bytes_per_sample * (sample_number - left.last_decoded_sample);
} else {
// second probe (try to bound the other side)
double error = ((double)sample_number - mid.last_decoded_sample) *
bytes_per_sample;
if (error >= 0 && error < 8000) error = 8000;
if (error < 0 && error > -8000) error = -8000;
offset += error * 2;
}
// ensure the offset is valid
if (offset < left.page_end) offset = left.page_end;
if (offset > right.page_start - 65536)
offset = right.page_start - 65536;
set_file_offset(f, (unsigned int)offset);
} else {
// binary search for large ranges (offset by 32K to ensure
// we don't hit the right page)
set_file_offset(f, left.page_end + (delta / 2) - 32768);
}
if (!vorbis_find_page(f, NULL, NULL)) goto error;
}
for (;;) {
if (!get_seek_page_info(f, &mid)) goto error;
if (mid.last_decoded_sample != ~0U) break;
// (untested) no frames end on this page
set_file_offset(f, mid.page_end);
assert(mid.page_start < right.page_start);
}
// if we've just found the last page again then we're in a tricky file,
// and we're close enough.
if (mid.page_start == right.page_start) break;
if (sample_number < mid.last_decoded_sample)
right = mid;
else
left = mid;
++probe;
}
// seek back to start of the last packet
page_start = left.page_start;
set_file_offset(f, page_start);
if (!start_page(f)) return error(f, VORBIS_seek_failed);
end_pos = f->end_seg_with_known_loc;
assert(end_pos >= 0);
for (;;) {
for (i = end_pos; i > 0; --i)
if (f->segments[i - 1] != 255) break;
start_seg_with_known_loc = i;
if (start_seg_with_known_loc > 0 ||
!(f->page_flag & PAGEFLAG_continued_packet))
break;
// (untested) the final packet begins on an earlier page
if (!go_to_page_before(f, page_start)) goto error;
page_start = stb_vorbis_get_file_offset(f);
if (!start_page(f)) goto error;
end_pos = f->segment_count - 1;
}
// prepare to start decoding
f->current_loc_valid = FALSE;
f->last_seg = FALSE;
f->valid_bits = 0;
f->packet_bytes = 0;
f->bytes_in_seg = 0;
f->previous_length = 0;
f->next_seg = start_seg_with_known_loc;
for (i = 0; i < start_seg_with_known_loc; i++) skip(f, f->segments[i]);
// start decoding (optimizable - this frame is generally discarded)
if (!vorbis_pump_first_frame(f)) return 0;
if (f->current_loc > sample_number) return error(f, VORBIS_seek_failed);
return 1;
error:
// try to restore the file to a valid state
stb_vorbis_seek_start(f);
return error(f, VORBIS_seek_failed);
}
// the same as vorbis_decode_initial, but without advancing
static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end,
int *p_right_start, int *p_right_end,
int *mode) {
int bits_read, bytes_read;
if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start,
p_right_end, mode))
return 0;
// either 1 or 2 bytes were read, figure out which so we can rewind
bits_read = 1 + ilog(f->mode_count - 1);
if (f->mode_config[*mode].blockflag) bits_read += 2;
bytes_read = (bits_read + 7) / 8;
f->bytes_in_seg += bytes_read;
f->packet_bytes -= bytes_read;
skip(f, -bytes_read);
if (f->next_seg == -1)
f->next_seg = f->segment_count - 1;
else
f->next_seg--;
f->valid_bits = 0;
return 1;
}
int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number) {
uint32 max_frame_samples;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
// fast page-level search
if (!seek_to_sample_coarse(f, sample_number)) return 0;
assert(f->current_loc_valid);
assert(f->current_loc <= sample_number);
// linear search for the relevant packet
max_frame_samples = (f->blocksize_1 * 3 - f->blocksize_0) >> 2;
while (f->current_loc < sample_number) {
int left_start, left_end, right_start, right_end, mode, frame_samples;
if (!peek_decode_initial(f, &left_start, &left_end, &right_start,
&right_end, &mode))
return error(f, VORBIS_seek_failed);
// calculate the number of samples returned by the next frame
frame_samples = right_start - left_start;
if (f->current_loc + frame_samples > sample_number) {
return 1; // the next frame will contain the sample
} else if (f->current_loc + frame_samples + max_frame_samples >
sample_number) {
// there's a chance the frame after this could contain the sample
vorbis_pump_first_frame(f);
} else {
// this frame is too early to be relevant
f->current_loc += frame_samples;
f->previous_length = 0;
maybe_start_packet(f);
flush_packet(f);
}
}
// the next frame will start with the sample
assert(f->current_loc == sample_number);
return 1;
}
int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number) {
if (!stb_vorbis_seek_frame(f, sample_number)) return 0;
if (sample_number != f->current_loc) {
int n;
uint32 frame_start = f->current_loc;
stb_vorbis_get_frame_float(f, &n, NULL);
assert(sample_number > frame_start);
assert(f->channel_buffer_start + (int)(sample_number - frame_start) <=
f->channel_buffer_end);
f->channel_buffer_start += (sample_number - frame_start);
}
return 1;
}
int stb_vorbis_seek_start(stb_vorbis *f) {
if (IS_PUSH_MODE(f)) {
return error(f, VORBIS_invalid_api_mixing);
}
set_file_offset(f, f->first_audio_page_offset);
f->previous_length = 0;
f->first_decode = TRUE;
f->next_seg = -1;
return vorbis_pump_first_frame(f);
}
unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f) {
unsigned int restore_offset, previous_safe;
unsigned int end, last_page_loc;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (!f->total_samples) {
unsigned int last;
uint32 lo, hi;
char header[6];
// first, store the current decode position so we can restore it
restore_offset = stb_vorbis_get_file_offset(f);
// now we want to seek back 64K from the end (the last page must
// be at most a little less than 64K, but let's allow a little slop)
if (f->stream_len >= 65536 &&
f->stream_len - 65536 >= f->first_audio_page_offset)
previous_safe = f->stream_len - 65536;
else
previous_safe = f->first_audio_page_offset;
set_file_offset(f, previous_safe);
// previous_safe is now our candidate 'earliest known place that seeking
// to will lead to the final page'
if (!vorbis_find_page(f, &end, &last)) {
// if we can't find a page, we're hosed!
f->error = VORBIS_cant_find_last_page;
f->total_samples = 0xffffffff;
goto done;
}
// check if there are more pages
last_page_loc = stb_vorbis_get_file_offset(f);
// stop when the last_page flag is set, not when we reach eof;
// this allows us to stop short of a 'file_section' end without
// explicitly checking the length of the section
while (!last) {
set_file_offset(f, end);
if (!vorbis_find_page(f, &end, &last)) {
// the last page we found didn't have the 'last page' flag
// set. whoops!
break;
}
previous_safe = last_page_loc + 1;
last_page_loc = stb_vorbis_get_file_offset(f);
}
set_file_offset(f, last_page_loc);
// parse the header
getn(f, (unsigned char *)header, 6);
// extract the absolute granule position
lo = get32(f);
hi = get32(f);
if (lo == 0xffffffff && hi == 0xffffffff) {
f->error = VORBIS_cant_find_last_page;
f->total_samples = SAMPLE_unknown;
goto done;
}
if (hi) lo = 0xfffffffe; // saturate
f->total_samples = lo;
f->p_last.page_start = last_page_loc;
f->p_last.page_end = end;
f->p_last.last_decoded_sample = lo;
done:
set_file_offset(f, restore_offset);
}
return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;
}
float stb_vorbis_stream_length_in_seconds(stb_vorbis *f) {
return stb_vorbis_stream_length_in_samples(f) / (float)f->sample_rate;
}
int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output) {
int len, right, left, i;
if (output) *output = NULL;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (!vorbis_decode_packet(f, &len, &left, &right)) {
f->channel_buffer_start = f->channel_buffer_end = 0;
return 0;
}
len = vorbis_finish_frame(f, len, left, right);
for (i = 0; i < f->channels; ++i) {
f->outputs[i] = f->channel_buffers[i] + left;
}
f->channel_buffer_start = left;
f->channel_buffer_end = left + len;
if (channels) *channels = f->channels;
if (output) *output = f->outputs;
return len;
}
#ifndef STB_VORBIS_NO_STDIO
stb_vorbis *stb_vorbis_open_file_section(FILE *file, int close_on_free,
int *error,
const stb_vorbis_alloc *alloc,
unsigned int length) {
stb_vorbis *f, p;
vorbis_init(&p, alloc);
p.f = file;
p.f_start = (uint32)ftell(file);
p.stream_len = length;
p.close_on_free = close_on_free;
if (start_decoder(&p)) {
f = vorbis_alloc(&p);
if (f) {
*f = p;
vorbis_pump_first_frame(f);
return f;
}
}
if (error) *error = p.error;
vorbis_deinit(&p);
return NULL;
}
stb_vorbis *stb_vorbis_open_file(FILE *file, int close_on_free, int *error,
const stb_vorbis_alloc *alloc) {
unsigned int len, start;
start = (unsigned int)ftell(file);
fseek(file, 0, SEEK_END);
len = (unsigned int)(ftell(file) - start);
fseek(file, start, SEEK_SET);
return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);
}
stb_vorbis *stb_vorbis_open_filename(const char *filename, int *error,
const stb_vorbis_alloc *alloc) {
FILE *f;
#if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)
if (0 != fopen_s(&f, filename, "rb")) f = NULL;
#else
f = fopen(filename, "rb");
#endif
if (f) return stb_vorbis_open_file(f, TRUE, error, alloc);
if (error) *error = VORBIS_file_open_failure;
return NULL;
}
#endif // STB_VORBIS_NO_STDIO
stb_vorbis *stb_vorbis_open_memory(const unsigned char *data, int len,
int *error, const stb_vorbis_alloc *alloc) {
stb_vorbis *f, p;
if (data == NULL) return NULL;
vorbis_init(&p, alloc);
p.stream = (uint8 *)data;
p.stream_end = (uint8 *)data + len;
p.stream_start = (uint8 *)p.stream;
p.stream_len = len;
p.push_mode = FALSE;
if (start_decoder(&p)) {
f = vorbis_alloc(&p);
if (f) {
*f = p;
vorbis_pump_first_frame(f);
if (error) *error = VORBIS__no_error;
return f;
}
}
if (error) *error = p.error;
vorbis_deinit(&p);
return NULL;
}
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
#define PLAYBACK_MONO 1
#define PLAYBACK_LEFT 2
#define PLAYBACK_RIGHT 4
#define L (PLAYBACK_LEFT | PLAYBACK_MONO)
#define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO)
#define R (PLAYBACK_RIGHT | PLAYBACK_MONO)
static int8 channel_position[7][6] = {
{0},
{C},
{L, R},
{L, C, R},
{L, R, L, R},
{L, C, R, L, R},
{L, C, R, L, R, C},
};
#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
typedef union {
float f;
int i;
} float_conv;
typedef char stb_vorbis_float_size_test[sizeof(float) == 4 && sizeof(int) == 4];
#define FASTDEF(x) float_conv x
// add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT
// to round
#define MAGIC(SHIFT) (1.5f * (1 << (23 - SHIFT)) + 0.5f / (1 << SHIFT))
#define ADDEND(SHIFT) (((150 - SHIFT) << 23) + (1 << 22))
#define FAST_SCALED_FLOAT_TO_INT(temp, x, s) \
(temp.f = (x) + MAGIC(s), temp.i - ADDEND(s))
#define check_endianness()
#else
#define FAST_SCALED_FLOAT_TO_INT(temp, x, s) ((int)((x) * (1 << (s))))
#define check_endianness()
#define FASTDEF(x)
#endif
static void copy_samples(short *dest, float *src, int len) {
int i;
check_endianness();
for (i = 0; i < len; ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i], 15);
if ((unsigned int)(v + 32768) > 65535) v = v < 0 ? -32768 : 32767;
dest[i] = v;
}
}
static void compute_samples(int mask, short *output, int num_c, float **data,
int d_offset, int len) {
#define BUFFER_SIZE 32
float buffer[BUFFER_SIZE];
int i, j, o, n = BUFFER_SIZE;
check_endianness();
for (o = 0; o < len; o += BUFFER_SIZE) {
memset(buffer, 0, sizeof(buffer));
if (o + n > len) n = len - o;
for (j = 0; j < num_c; ++j) {
if (channel_position[num_c][j] & mask) {
for (i = 0; i < n; ++i) buffer[i] += data[j][d_offset + o + i];
}
}
for (i = 0; i < n; ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp, buffer[i], 15);
if ((unsigned int)(v + 32768) > 65535) v = v < 0 ? -32768 : 32767;
output[o + i] = v;
}
}
}
static void compute_stereo_samples(short *output, int num_c, float **data,
int d_offset, int len) {
#define BUFFER_SIZE 32
float buffer[BUFFER_SIZE];
int i, j, o, n = BUFFER_SIZE >> 1;
// o is the offset in the source data
check_endianness();
for (o = 0; o < len; o += (BUFFER_SIZE >> 1)) {
// o2 is the offset in the output data
int o2 = o << 1;
memset(buffer, 0, sizeof(buffer));
if (o + n > len) n = len - o;
for (j = 0; j < num_c; ++j) {
int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);
if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {
for (i = 0; i < n; ++i) {
buffer[i * 2 + 0] += data[j][d_offset + o + i];
buffer[i * 2 + 1] += data[j][d_offset + o + i];
}
} else if (m == PLAYBACK_LEFT) {
for (i = 0; i < n; ++i) {
buffer[i * 2 + 0] += data[j][d_offset + o + i];
}
} else if (m == PLAYBACK_RIGHT) {
for (i = 0; i < n; ++i) {
buffer[i * 2 + 1] += data[j][d_offset + o + i];
}
}
}
for (i = 0; i < (n << 1); ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp, buffer[i], 15);
if ((unsigned int)(v + 32768) > 65535) v = v < 0 ? -32768 : 32767;
output[o2 + i] = v;
}
}
}
static void convert_samples_short(int buf_c, short **buffer, int b_offset,
int data_c, float **data, int d_offset,
int samples) {
int i;
if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
static int channel_selector[3][2] = {
{0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT}};
for (i = 0; i < buf_c; ++i)
compute_samples(channel_selector[buf_c][i], buffer[i] + b_offset, data_c,
data, d_offset, samples);
} else {
int limit = buf_c < data_c ? buf_c : data_c;
for (i = 0; i < limit; ++i)
copy_samples(buffer[i] + b_offset, data[i] + d_offset, samples);
for (; i < buf_c; ++i)
memset(buffer[i] + b_offset, 0, sizeof(short) * samples);
}
}
int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer,
int num_samples) {
float **output;
int len = stb_vorbis_get_frame_float(f, NULL, &output);
if (len > num_samples) len = num_samples;
if (len) convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);
return len;
}
static void convert_channels_short_interleaved(int buf_c, short *buffer,
int data_c, float **data,
int d_offset, int len) {
int i;
check_endianness();
if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
assert(buf_c == 2);
for (i = 0; i < buf_c; ++i)
compute_stereo_samples(buffer, data_c, data, d_offset, len);
} else {
int limit = buf_c < data_c ? buf_c : data_c;
int j;
for (j = 0; j < len; ++j) {
for (i = 0; i < limit; ++i) {
FASTDEF(temp);
float f = data[i][d_offset + j];
int v =
FAST_SCALED_FLOAT_TO_INT(temp, f, 15); // data[i][d_offset+j],15);
if ((unsigned int)(v + 32768) > 65535) v = v < 0 ? -32768 : 32767;
*buffer++ = v;
}
for (; i < buf_c; ++i) *buffer++ = 0;
}
}
}
int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c,
short *buffer, int num_shorts) {
float **output;
int len;
if (num_c == 1)
return stb_vorbis_get_frame_short(f, num_c, &buffer, num_shorts);
len = stb_vorbis_get_frame_float(f, NULL, &output);
if (len) {
if (len * num_c > num_shorts) len = num_shorts / num_c;
convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0,
len);
}
return len;
}
int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels,
short *buffer, int num_shorts) {
float **outputs;
int len = num_shorts / channels;
int n = 0;
int z = f->channels;
if (z > channels) z = channels;
while (n < len) {
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n + k >= len) k = len - n;
if (k)
convert_channels_short_interleaved(channels, buffer, f->channels,
f->channel_buffers,
f->channel_buffer_start, k);
buffer += k * channels;
n += k;
f->channel_buffer_start += k;
if (n == len) break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
}
return n;
}
int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer,
int len) {
float **outputs;
int n = 0;
int z = f->channels;
if (z > channels) z = channels;
while (n < len) {
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n + k >= len) k = len - n;
if (k)
convert_samples_short(channels, buffer, n, f->channels,
f->channel_buffers, f->channel_buffer_start, k);
n += k;
f->channel_buffer_start += k;
if (n == len) break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
}
return n;
}
#ifndef STB_VORBIS_NO_STDIO
int stb_vorbis_decode_filename(const char *filename, int *channels,
int *sample_rate, short **output) {
int data_len, offset, total, limit, error;
short *data;
stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);
if (v == NULL) return -1;
limit = v->channels * 4096;
*channels = v->channels;
if (sample_rate) *sample_rate = v->sample_rate;
offset = data_len = 0;
total = limit;
data = (short *)malloc(total * sizeof(*data));
if (data == NULL) {
stb_vorbis_close(v);
return -2;
}
for (;;) {
int n = stb_vorbis_get_frame_short_interleaved(
v, v->channels, data + offset, total - offset);
if (n == 0) break;
data_len += n;
offset += n * v->channels;
if (offset + limit > total) {
short *data2;
total *= 2;
data2 = (short *)realloc(data, total * sizeof(*data));
if (data2 == NULL) {
free(data);
stb_vorbis_close(v);
return -2;
}
data = data2;
}
}
*output = data;
stb_vorbis_close(v);
return data_len;
}
#endif // NO_STDIO
int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels,
int *sample_rate, short **output) {
int data_len, offset, total, limit, error;
short *data;
stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);
if (v == NULL) return -1;
limit = v->channels * 4096;
*channels = v->channels;
if (sample_rate) *sample_rate = v->sample_rate;
offset = data_len = 0;
total = limit;
data = (short *)malloc(total * sizeof(*data));
if (data == NULL) {
stb_vorbis_close(v);
return -2;
}
for (;;) {
int n = stb_vorbis_get_frame_short_interleaved(
v, v->channels, data + offset, total - offset);
if (n == 0) break;
data_len += n;
offset += n * v->channels;
if (offset + limit > total) {
short *data2;
total *= 2;
data2 = (short *)realloc(data, total * sizeof(*data));
if (data2 == NULL) {
free(data);
stb_vorbis_close(v);
return -2;
}
data = data2;
}
}
*output = data;
stb_vorbis_close(v);
return data_len;
}
#endif // STB_VORBIS_NO_INTEGER_CONVERSION
int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels,
float *buffer, int num_floats) {
float **outputs;
int len = num_floats / channels;
int n = 0;
int z = f->channels;
if (z > channels) z = channels;
while (n < len) {
int i, j;
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n + k >= len) k = len - n;
for (j = 0; j < k; ++j) {
for (i = 0; i < z; ++i)
*buffer++ = f->channel_buffers[i][f->channel_buffer_start + j];
for (; i < channels; ++i) *buffer++ = 0;
}
n += k;
f->channel_buffer_start += k;
if (n == len) break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
}
return n;
}
int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer,
int num_samples) {
float **outputs;
int n = 0;
int z = f->channels;
if (z > channels) z = channels;
while (n < num_samples) {
int i;
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n + k >= num_samples) k = num_samples - n;
if (k) {
for (i = 0; i < z; ++i)
memcpy(buffer[i] + n, f->channel_buffers[i] + f->channel_buffer_start,
sizeof(float) * k);
for (; i < channels; ++i) memset(buffer[i] + n, 0, sizeof(float) * k);
}
n += k;
f->channel_buffer_start += k;
if (n == num_samples) break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
}
return n;
}
#endif // STB_VORBIS_NO_PULLDATA_API
| 159,428 | 4,982 | jart/cosmopolitan | false |
cosmopolitan/third_party/stb/stb_image_write.c | /* stb_image_write - v1.13 - public domain - http://nothings.org/stb
* writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015
* no warranty implied; use at your own risk
*
* ABOUT:
*
* This file is a library for writing images to stdio or a callback.
*
* The PNG output is not optimal; it is 20-50% larger than the file
* written by a decent optimizing implementation; though providing a
* custom zlib compress function (see STBIW_ZLIB_COMPRESS) can
* mitigate that. This library is designed for source code
* compactness and simplicity, not optimal image file size or
* run-time performance.
*
* USAGE:
*
* There are five functions, one for each image file format:
*
* stbi_write_png
* stbi_write_bmp
* stbi_write_tga
* stbi_write_jpg
* stbi_write_hdr
*
* stbi_flip_vertically_on_write
*
* There are also five equivalent functions that use an arbitrary
* write function. You are expected to open/close your
* file-equivalent before and after calling these:
*
* stbi_write_png_to_func
* stbi_write_bmp_to_func
* stbi_write_tga_to_func
* stbi_write_hdr_to_func
* stbi_write_jpg_to_func
*
* where the callback is:
* void stbi_write_func(void *context, void *data, int size);
*
* You can configure it with these:
* stbi_write_tga_with_rle
* stbi_write_png_compression_level
* stbi_write_force_png_filter
*
* Each function returns 0 on failure and non-0 on success.
*
* The functions create an image file defined by the parameters. The
* image is a rectangle of pixels stored from left-to-right,
* top-to-bottom. Each pixel contains 'comp' channels of data stored
* interleaved with 8-bits per channel, in the following order: 1=Y,
* 2=YA, 3=RGB, 4=RGBA. (Y is monochrome color.) The rectangle is 'w'
* pixels wide and 'h' pixels tall. The *data pointer points to the
* first byte of the top-left-most pixel. For PNG, "stride_in_bytes"
* is the distance in bytes from the first byte of a row of pixels to
* the first byte of the next row of pixels.
*
* PNG creates output files with the same number of components as the
* input. The BMP format expands Y to RGB in the file format and does
* not output alpha.
*
* PNG supports writing rectangles of data even when the bytes
* storing rows of data are not consecutive in memory (e.g.
* sub-rectangles of a larger image), by supplying the stride between
* the beginning of adjacent rows. The other formats do not. (Thus
* you cannot write a native-format BMP through the BMP writer, both
* because it is in BGR order and because it may have padding at the
* end of the line.)
*
* PNG allows you to set the deflate compression level by setting the
* global variable 'stbi_write_png_compression_level' (it defaults to
* 8).
*
* HDR expects linear float data. Since the format is always 32-bit
* rgb(e) data, alpha (if provided) is discarded, and for monochrome
* data it is replicated across all three channels.
*
* TGA supports RLE or non-RLE compressed data. To use
* non-RLE-compressed data, set the global variable
* 'stbi_write_tga_with_rle' to 0.
*
* JPEG does ignore alpha channels in input data; quality is between
* 1 and 100. Higher quality looks better but results in a bigger
* image. JPEG baseline (no JPEG progressive).
*
* CREDITS:
*
*
* Sean Barrett - PNG/BMP/TGA
* Baldur Karlsson - HDR
* Jean-Sebastien Guay - TGA monochrome
* Tim Kelsey - misc enhancements
* Alan Hickman - TGA RLE
* Emmanuel Julien - initial file IO callback implementation
* Jon Olick - original jo_jpeg.cpp code
* Daniel Gibson - integrate JPEG, allow external zlib
* Aarni Koskela - allow choosing PNG filter
*
* bugfixes:
* github:Chribba
* Guillaume Chereau
* github:jry2
* github:romigrou
* Sergio Gonzalez
* Jonas Karlsson
* Filip Wasil
* Thatcher Ulrich
* github:poppolopoppo
* Patrick Boettcher
* github:xeekworx
* Cap Petschulat
* Simon Rodriguez
* Ivan Tikhonov
* github:ignotion
* Adam Schackart
*
* LICENSE
*
* Public Domain (www.unlicense.org)
*/
#include "dsp/core/core.h"
#include "libc/assert.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/fmt.h"
#include "libc/limits.h"
#include "libc/macros.internal.h"
#include "libc/math.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/nexgen32e.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "third_party/stb/stb_image_write.h"
#include "third_party/zlib/zlib.h"
#define STBIW_UCHAR(x) (unsigned char)((x)&0xff)
#define STBIW_REALLOC_SIZED(p, oldsz, newsz) realloc(p, newsz)
typedef struct {
stbi_write_func *func;
void *context;
} stbi__write_context;
int stbi__flip_vertically_on_write = 0;
int stbi_write_tga_with_rle = 1;
void stbi_flip_vertically_on_write(int flag) {
stbi__flip_vertically_on_write = flag;
}
// initialize a callback-based context
static void stbi__start_write_callbacks(stbi__write_context *s,
stbi_write_func *c, void *context) {
s->func = c;
s->context = context;
}
static void stbi__stdio_write(void *context, void *data, int size) {
fwrite(data, 1, size, (FILE *)context);
}
static int stbi__start_write_file(stbi__write_context *s,
const char *filename) {
FILE *f = fopen(filename, "wb");
stbi__start_write_callbacks(s, stbi__stdio_write, (void *)f);
return f != NULL;
}
static void stbi__end_write_file(stbi__write_context *s) {
fclose((FILE *)s->context);
}
typedef unsigned int stbiw_uint32;
typedef int stb_image_write_test[sizeof(stbiw_uint32) == 4 ? 1 : -1];
static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) {
while (*fmt) {
switch (*fmt++) {
case ' ':
break;
case '1': {
unsigned char x = STBIW_UCHAR(va_arg(v, int));
s->func(s->context, &x, 1);
break;
}
case '2': {
int x = va_arg(v, int);
unsigned char b[2];
b[0] = STBIW_UCHAR(x);
b[1] = STBIW_UCHAR(x >> 8);
s->func(s->context, b, 2);
break;
}
case '4': {
stbiw_uint32 x = va_arg(v, int);
unsigned char b[4];
b[0] = STBIW_UCHAR(x);
b[1] = STBIW_UCHAR(x >> 8);
b[2] = STBIW_UCHAR(x >> 16);
b[3] = STBIW_UCHAR(x >> 24);
s->func(s->context, b, 4);
break;
}
default:
unreachable;
}
}
}
static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) {
va_list v;
va_start(v, fmt);
stbiw__writefv(s, fmt, v);
va_end(v);
}
static void stbiw__putc(stbi__write_context *s, unsigned char c) {
s->func(s->context, &c, 1);
}
static void stbiw__write3(stbi__write_context *s, unsigned char a,
unsigned char b, unsigned char c) {
unsigned char arr[3];
arr[0] = a;
arr[1] = b;
arr[2] = c;
s->func(s->context, arr, 3);
}
static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp,
int write_alpha, int expand_mono,
unsigned char *d) {
unsigned char bg[3] = {255, 0, 255}, px[3];
int k;
if (write_alpha < 0) s->func(s->context, &d[comp - 1], 1);
switch (comp) {
case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as
// 1-channel case
case 1:
if (expand_mono)
stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp
else
s->func(s->context, d, 1); // monochrome TGA
break;
case 4:
if (!write_alpha) {
// composite against pink background
for (k = 0; k < 3; ++k) px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255;
stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]);
break;
}
/* FALLTHROUGH */
case 3:
stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]);
break;
}
if (write_alpha > 0) s->func(s->context, &d[comp - 1], 1);
}
static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir,
int x, int y, int comp, void *data,
int write_alpha, int scanline_pad,
int expand_mono) {
stbiw_uint32 zero = 0;
int i, j, j_end;
if (y <= 0) return;
if (stbi__flip_vertically_on_write) vdir *= -1;
if (vdir < 0) {
j_end = -1;
j = y - 1;
} else {
j_end = y;
j = 0;
}
for (; j != j_end; j += vdir) {
for (i = 0; i < x; ++i) {
unsigned char *d = (unsigned char *)data + (j * x + i) * comp;
stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d);
}
s->func(s->context, &zero, scanline_pad);
}
}
static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x,
int y, int comp, int expand_mono, void *data,
int alpha, int pad, const char *fmt, ...) {
if (y < 0 || x < 0) {
return 0;
} else {
va_list v;
va_start(v, fmt);
stbiw__writefv(s, fmt, v);
va_end(v);
stbiw__write_pixels(s, rgb_dir, vdir, x, y, comp, data, alpha, pad,
expand_mono);
return 1;
}
}
static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp,
const void *data) {
int pad = (-x * 3) & 3;
return stbiw__outfile(s, -1, -1, x, y, comp, 1, (void *)data, 0, pad,
"11 4 22 4"
"4 44 22 444444",
'B', 'M', 14 + 40 + (x * 3 + pad) * y, 0, 0,
14 + 40, // file header
40, x, y, 1, 24, 0, 0, 0, 0, 0, 0); // bitmap header
}
int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y,
int comp, const void *data) {
stbi__write_context s;
stbi__start_write_callbacks(&s, func, context);
return stbi_write_bmp_core(&s, x, y, comp, data);
}
int stbi_write_bmp(char const *filename, int x, int y, int comp,
const void *data) {
stbi__write_context s;
if (stbi__start_write_file(&s, filename)) {
int r = stbi_write_bmp_core(&s, x, y, comp, data);
stbi__end_write_file(&s);
return r;
} else
return 0;
}
static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp,
void *data) {
int has_alpha = (comp == 2 || comp == 4);
int colorbytes = has_alpha ? comp - 1 : comp;
int format =
colorbytes < 2
? 3
: 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3
if (y < 0 || x < 0) return 0;
if (!stbi_write_tga_with_rle) {
return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *)data, has_alpha, 0,
"111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y,
(colorbytes + has_alpha) * 8, has_alpha * 8);
} else {
int i, j, k;
int jend, jdir;
stbiw__writef(s, "111 221 2222 11", 0, 0, format + 8, 0, 0, 0, 0, 0, x, y,
(colorbytes + has_alpha) * 8, has_alpha * 8);
if (stbi__flip_vertically_on_write) {
j = 0;
jend = y;
jdir = 1;
} else {
j = y - 1;
jend = -1;
jdir = -1;
}
for (; j != jend; j += jdir) {
unsigned char *row = (unsigned char *)data + j * x * comp;
int len;
for (i = 0; i < x; i += len) {
unsigned char *begin = row + i * comp;
int diff = 1;
len = 1;
if (i < x - 1) {
++len;
diff = memcmp(begin, row + (i + 1) * comp, comp);
if (diff) {
const unsigned char *prev = begin;
for (k = i + 2; k < x && len < 128; ++k) {
if (memcmp(prev, row + k * comp, comp)) {
prev += comp;
++len;
} else {
--len;
break;
}
}
} else {
for (k = i + 2; k < x && len < 128; ++k) {
if (!memcmp(begin, row + k * comp, comp)) {
++len;
} else {
break;
}
}
}
}
if (diff) {
unsigned char header = STBIW_UCHAR(len - 1);
s->func(s->context, &header, 1);
for (k = 0; k < len; ++k) {
stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp);
}
} else {
unsigned char header = STBIW_UCHAR(len - 129);
s->func(s->context, &header, 1);
stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin);
}
}
}
}
return 1;
}
int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y,
int comp, const void *data) {
stbi__write_context s;
stbi__start_write_callbacks(&s, func, context);
return stbi_write_tga_core(&s, x, y, comp, (void *)data);
}
int stbi_write_tga(char const *filename, int x, int y, int comp,
const void *data) {
stbi__write_context s;
if (stbi__start_write_file(&s, filename)) {
int r = stbi_write_tga_core(&s, x, y, comp, (void *)data);
stbi__end_write_file(&s);
return r;
} else
return 0;
}
/* JPEG writer
*
* This is based on Jon Olick's jo_jpeg.cpp:
* public domain Simple, Minimalistic JPEG writer -
* http://www.jonolick.com/code.html
*/
static const unsigned char stbiw__jpg_ZigZag[] = {
0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63,
};
static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP,
int *bitCntP, const unsigned short *bs) {
unsigned char c;
unsigned bitBuf, bitCnt;
bitBuf = *bitBufP;
bitCnt = *bitCntP;
bitCnt += bs[1];
bitBuf |= bs[0] << (24 - bitCnt);
while (bitCnt >= 8) {
c = (bitBuf >> 16) & 255;
stbiw__putc(s, c);
if (c == 255) {
stbiw__putc(s, 0);
}
bitBuf <<= 8;
bitCnt -= 8;
}
*bitBufP = bitBuf;
*bitCntP = bitCnt;
}
static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) {
int tmp1 = val < 0 ? -val : val;
val = val < 0 ? val - 1 : val;
bits[1] = 1;
while (tmp1 >>= 1) {
++bits[1];
}
bits[0] = val & ((1u << bits[1]) - 1);
}
static int stbiw__jpg_processDU(stbi__write_context *s, int *bitBuf,
int *bitCnt, float *CDU, float *fdtbl, int DC,
const unsigned short HTDC[256][2],
const unsigned short HTAC[256][2]) {
const unsigned short EOB[2] = {HTAC[0x00][0], HTAC[0x00][1]};
const unsigned short M16zeroes[2] = {HTAC[0xF0][0], HTAC[0xF0][1]};
unsigned i, diff, end0pos;
int DU[64];
dctjpeg((void *)CDU);
// Quantize/descale/zigzag the coefficients
for (i = 0; i < 64; ++i) {
float v = CDU[i] * fdtbl[i];
DU[stbiw__jpg_ZigZag[i]] = v < 0 ? ceilf(v - 0.5f) : floorf(v + 0.5f);
// DU[stbiw__jpg_ZigZag[i]] = (int)(v < 0 ? ceilf(v - 0.5f) : floorf(v +
// 0.5f)); ceilf() and floorf() are C99, not C89, but I /think/ they're not
// needed here anyway?
/* DU[stbiw__jpg_ZigZag[i]] = (int)(v < 0 ? v - 0.5f : v + 0.5f); */
}
// Encode DC
diff = DU[0] - DC;
if (diff == 0) {
stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[0]);
} else {
unsigned short bits[2];
stbiw__jpg_calcBits(diff, bits);
stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[bits[1]]);
stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits);
}
// Encode ACs
end0pos = 63;
for (; (end0pos > 0) && (DU[end0pos] == 0); --end0pos) {
}
// end0pos = first element in reverse order !=0
if (end0pos == 0) {
stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB);
return DU[0];
}
for (i = 1; i <= end0pos; ++i) {
unsigned startpos = i;
unsigned nrzeroes;
unsigned short bits[2];
for (; DU[i] == 0 && i <= end0pos; ++i) {
}
nrzeroes = i - startpos;
if (nrzeroes >= 16) {
unsigned lng = nrzeroes >> 4;
unsigned nrmarker;
for (nrmarker = 1; nrmarker <= lng; ++nrmarker) {
stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes);
}
nrzeroes &= 15;
}
stbiw__jpg_calcBits(DU[i], bits);
stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes << 4) + bits[1]]);
stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits);
}
if (end0pos != 63) {
stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB);
}
return DU[0];
}
static int stbi_write_jpg_core(stbi__write_context *s, int width, int height,
int comp, const void *data, int quality) {
static const unsigned char std_dc_luminance_nrcodes[] = {
0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0};
static const unsigned char std_dc_luminance_values[] = {0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11};
static const unsigned char std_ac_luminance_nrcodes[] = {
0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d};
static const unsigned char std_ac_luminance_values[] = {
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06,
0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72,
0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45,
0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75,
0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3,
0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9,
0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4,
0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa};
static const unsigned char std_dc_chrominance_nrcodes[] = {
0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0};
static const unsigned char std_dc_chrominance_values[] = {0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11};
static const unsigned char std_ac_chrominance_nrcodes[] = {
0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77};
static const unsigned char std_ac_chrominance_values[] = {
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41,
0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1,
0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44,
0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74,
0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a,
0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4,
0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa};
// Huffman tables
static const unsigned short YDC_HT[256][2] = {
{0, 2}, {2, 3}, {3, 3}, {4, 3}, {5, 3}, {6, 3},
{14, 4}, {30, 5}, {62, 6}, {126, 7}, {254, 8}, {510, 9}};
static const unsigned short UVDC_HT[256][2] = {
{0, 2}, {1, 2}, {2, 2}, {6, 3}, {14, 4}, {30, 5},
{62, 6}, {126, 7}, {254, 8}, {510, 9}, {1022, 10}, {2046, 11}};
static const unsigned short YAC_HT[256][2] = {
{10, 4}, {0, 2}, {1, 2}, {4, 3}, {11, 4},
{26, 5}, {120, 7}, {248, 8}, {1014, 10}, {65410, 16},
{65411, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {12, 4}, {27, 5}, {121, 7},
{502, 9}, {2038, 11}, {65412, 16}, {65413, 16}, {65414, 16},
{65415, 16}, {65416, 16}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {28, 5}, {249, 8},
{1015, 10}, {4084, 12}, {65417, 16}, {65418, 16}, {65419, 16},
{65420, 16}, {65421, 16}, {65422, 16}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {58, 6},
{503, 9}, {4085, 12}, {65423, 16}, {65424, 16}, {65425, 16},
{65426, 16}, {65427, 16}, {65428, 16}, {65429, 16}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{59, 6}, {1016, 10}, {65430, 16}, {65431, 16}, {65432, 16},
{65433, 16}, {65434, 16}, {65435, 16}, {65436, 16}, {65437, 16},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {122, 7}, {2039, 11}, {65438, 16}, {65439, 16},
{65440, 16}, {65441, 16}, {65442, 16}, {65443, 16}, {65444, 16},
{65445, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {123, 7}, {4086, 12}, {65446, 16},
{65447, 16}, {65448, 16}, {65449, 16}, {65450, 16}, {65451, 16},
{65452, 16}, {65453, 16}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {250, 8}, {4087, 12},
{65454, 16}, {65455, 16}, {65456, 16}, {65457, 16}, {65458, 16},
{65459, 16}, {65460, 16}, {65461, 16}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {504, 9},
{32704, 15}, {65462, 16}, {65463, 16}, {65464, 16}, {65465, 16},
{65466, 16}, {65467, 16}, {65468, 16}, {65469, 16}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{505, 9}, {65470, 16}, {65471, 16}, {65472, 16}, {65473, 16},
{65474, 16}, {65475, 16}, {65476, 16}, {65477, 16}, {65478, 16},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {506, 9}, {65479, 16}, {65480, 16}, {65481, 16},
{65482, 16}, {65483, 16}, {65484, 16}, {65485, 16}, {65486, 16},
{65487, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {1017, 10}, {65488, 16}, {65489, 16},
{65490, 16}, {65491, 16}, {65492, 16}, {65493, 16}, {65494, 16},
{65495, 16}, {65496, 16}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {1018, 10}, {65497, 16},
{65498, 16}, {65499, 16}, {65500, 16}, {65501, 16}, {65502, 16},
{65503, 16}, {65504, 16}, {65505, 16}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {2040, 11},
{65506, 16}, {65507, 16}, {65508, 16}, {65509, 16}, {65510, 16},
{65511, 16}, {65512, 16}, {65513, 16}, {65514, 16}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{65515, 16}, {65516, 16}, {65517, 16}, {65518, 16}, {65519, 16},
{65520, 16}, {65521, 16}, {65522, 16}, {65523, 16}, {65524, 16},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{2041, 11}, {65525, 16}, {65526, 16}, {65527, 16}, {65528, 16},
{65529, 16}, {65530, 16}, {65531, 16}, {65532, 16}, {65533, 16},
{65534, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}};
static const unsigned short UVAC_HT[256][2] = {
{0, 2}, {1, 2}, {4, 3}, {10, 4}, {24, 5},
{25, 5}, {56, 6}, {120, 7}, {500, 9}, {1014, 10},
{4084, 12}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {11, 4}, {57, 6}, {246, 8},
{501, 9}, {2038, 11}, {4085, 12}, {65416, 16}, {65417, 16},
{65418, 16}, {65419, 16}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {26, 5}, {247, 8},
{1015, 10}, {4086, 12}, {32706, 15}, {65420, 16}, {65421, 16},
{65422, 16}, {65423, 16}, {65424, 16}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {27, 5},
{248, 8}, {1016, 10}, {4087, 12}, {65425, 16}, {65426, 16},
{65427, 16}, {65428, 16}, {65429, 16}, {65430, 16}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{58, 6}, {502, 9}, {65431, 16}, {65432, 16}, {65433, 16},
{65434, 16}, {65435, 16}, {65436, 16}, {65437, 16}, {65438, 16},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {59, 6}, {1017, 10}, {65439, 16}, {65440, 16},
{65441, 16}, {65442, 16}, {65443, 16}, {65444, 16}, {65445, 16},
{65446, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {121, 7}, {2039, 11}, {65447, 16},
{65448, 16}, {65449, 16}, {65450, 16}, {65451, 16}, {65452, 16},
{65453, 16}, {65454, 16}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {122, 7}, {2040, 11},
{65455, 16}, {65456, 16}, {65457, 16}, {65458, 16}, {65459, 16},
{65460, 16}, {65461, 16}, {65462, 16}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {249, 8},
{65463, 16}, {65464, 16}, {65465, 16}, {65466, 16}, {65467, 16},
{65468, 16}, {65469, 16}, {65470, 16}, {65471, 16}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{503, 9}, {65472, 16}, {65473, 16}, {65474, 16}, {65475, 16},
{65476, 16}, {65477, 16}, {65478, 16}, {65479, 16}, {65480, 16},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {504, 9}, {65481, 16}, {65482, 16}, {65483, 16},
{65484, 16}, {65485, 16}, {65486, 16}, {65487, 16}, {65488, 16},
{65489, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {505, 9}, {65490, 16}, {65491, 16},
{65492, 16}, {65493, 16}, {65494, 16}, {65495, 16}, {65496, 16},
{65497, 16}, {65498, 16}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {506, 9}, {65499, 16},
{65500, 16}, {65501, 16}, {65502, 16}, {65503, 16}, {65504, 16},
{65505, 16}, {65506, 16}, {65507, 16}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {2041, 11},
{65508, 16}, {65509, 16}, {65510, 16}, {65511, 16}, {65512, 16},
{65513, 16}, {65514, 16}, {65515, 16}, {65516, 16}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{16352, 14}, {65517, 16}, {65518, 16}, {65519, 16}, {65520, 16},
{65521, 16}, {65522, 16}, {65523, 16}, {65524, 16}, {65525, 16},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{1018, 10}, {32707, 15}, {65526, 16}, {65527, 16}, {65528, 16},
{65529, 16}, {65530, 16}, {65531, 16}, {65532, 16}, {65533, 16},
{65534, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}};
static const int YQT[] = {
16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92,
49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99};
static const int UVQT[] = {17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99,
99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66,
99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99};
static const float aasf[] = {
1.0f * 2.828427125f, 1.387039845f * 2.828427125f,
1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f,
1.0f * 2.828427125f, 0.785694958f * 2.828427125f,
0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f};
int row, col, i, k;
float fdtbl_Y[64], fdtbl_UV[64];
unsigned char YTable[64], UVTable[64];
if (!data || !width || !height || comp > 4 || comp < 1) {
return 0;
}
quality = quality ? quality : 97;
quality = quality < 1 ? 1 : quality > 100 ? 100 : quality;
quality = quality < 50 ? 5000 / quality : 200 - quality * 2;
for (i = 0; i < 64; ++i) {
int uvti, yti = (YQT[i] * quality + 50) / 100;
YTable[stbiw__jpg_ZigZag[i]] = (unsigned char)(yti < 1 ? 1
: yti > 255 ? 255
: yti);
uvti = (UVQT[i] * quality + 50) / 100;
UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char)(uvti < 1 ? 1
: uvti > 255 ? 255
: uvti);
}
for (row = 0, k = 0; row < 8; ++row) {
for (col = 0; col < 8; ++col, ++k) {
fdtbl_Y[k] = 1 / (YTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]);
fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]);
}
}
// Write Headers
{
static const unsigned char head0[] = {
0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, 'J', 'F', 'I', 'F', 0, 1, 1,
0, 0, 1, 0, 1, 0, 0, 0xFF, 0xDB, 0, 0x84, 0};
static const unsigned char head2[] = {0xFF, 0xDA, 0, 0xC, 3, 1, 0,
2, 0x11, 3, 0x11, 0, 0x3F, 0};
const unsigned char head1[] = {
0xFF,
0xC0,
0,
0x11,
8,
(unsigned char)(height >> 8),
STBIW_UCHAR(height),
(unsigned char)(width >> 8),
STBIW_UCHAR(width),
3,
1,
0x11,
0,
2,
0x11,
1,
3,
0x11,
1,
0xFF,
0xC4,
0x01,
0xA2,
0,
};
s->func(s->context, (void *)head0, sizeof(head0));
s->func(s->context, (void *)YTable, sizeof(YTable));
stbiw__putc(s, 1);
s->func(s->context, UVTable, sizeof(UVTable));
s->func(s->context, (void *)head1, sizeof(head1));
s->func(s->context, (void *)(std_dc_luminance_nrcodes + 1),
sizeof(std_dc_luminance_nrcodes) - 1);
s->func(s->context, (void *)std_dc_luminance_values,
sizeof(std_dc_luminance_values));
stbiw__putc(s, 0x10); // HTYACinfo
s->func(s->context, (void *)(std_ac_luminance_nrcodes + 1),
sizeof(std_ac_luminance_nrcodes) - 1);
s->func(s->context, (void *)std_ac_luminance_values,
sizeof(std_ac_luminance_values));
stbiw__putc(s, 1); // HTUDCinfo
s->func(s->context, (void *)(std_dc_chrominance_nrcodes + 1),
sizeof(std_dc_chrominance_nrcodes) - 1);
s->func(s->context, (void *)std_dc_chrominance_values,
sizeof(std_dc_chrominance_values));
stbiw__putc(s, 0x11); // HTUACinfo
s->func(s->context, (void *)(std_ac_chrominance_nrcodes + 1),
sizeof(std_ac_chrominance_nrcodes) - 1);
s->func(s->context, (void *)std_ac_chrominance_values,
sizeof(std_ac_chrominance_values));
s->func(s->context, (void *)head2, sizeof(head2));
}
// Encode 8x8 macroblocks
{
static const unsigned short fillBits[] = {0x7F, 7};
const unsigned char *imageData = (const unsigned char *)data;
int DCY = 0, DCU = 0, DCV = 0;
int bitBuf = 0, bitCnt = 0;
// comp == 2 is grey+alpha (alpha is ignored)
int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0;
int x, y, pos;
for (y = 0; y < height; y += 8) {
for (x = 0; x < width; x += 8) {
float YDU[64], UDU[64], VDU[64];
for (row = y, pos = 0; row < y + 8; ++row) {
// row >= height => use last input row
int clamped_row = (row < height) ? row : height - 1;
int base_p =
(stbi__flip_vertically_on_write ? (height - 1 - clamped_row)
: clamped_row) *
width * comp;
for (col = x; col < x + 8; ++col, ++pos) {
float r, g, b;
// if col >= width => use pixel from last input column
int p = base_p + ((col < width) ? col : (width - 1)) * comp;
r = imageData[p + 0];
g = imageData[p + ofsG];
b = imageData[p + ofsB];
YDU[pos] = +0.29900f * r + 0.58700f * g + 0.11400f * b - 128;
UDU[pos] = -0.16874f * r - 0.33126f * g + 0.50000f * b;
VDU[pos] = +0.50000f * r - 0.41869f * g - 0.08131f * b;
}
}
DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, YDU, fdtbl_Y, DCY,
YDC_HT, YAC_HT);
DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, UDU, fdtbl_UV, DCU,
UVDC_HT, UVAC_HT);
DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, VDU, fdtbl_UV, DCV,
UVDC_HT, UVAC_HT);
}
}
// Do the bit alignment of the EOI marker
stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits);
}
// EOI
stbiw__putc(s, 0xFF);
stbiw__putc(s, 0xD9);
return 1;
}
int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y,
int comp, const void *data, int quality) {
stbi__write_context s;
stbi__start_write_callbacks(&s, func, context);
return stbi_write_jpg_core(&s, x, y, comp, (void *)data, quality);
}
int stbi_write_jpg(char const *filename, int x, int y, int comp,
const void *data, int quality) {
stbi__write_context s;
if (stbi__start_write_file(&s, filename)) {
int r = stbi_write_jpg_core(&s, x, y, comp, data, quality);
stbi__end_write_file(&s);
return r;
} else
return 0;
}
/*
********************************************************************************
Radiance RGBE HDR writer
by Baldur Karlsson */
static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) {
int exponent;
float normalize, maxcomp;
maxcomp = MAX(linear[0], MAX(linear[1], linear[2]));
if (maxcomp < 1e-32f) {
rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0;
} else {
/* no idea what HDR is but this could probably use clamping */
normalize = (float)frexp(maxcomp, &exponent) * 256.0f / maxcomp;
rgbe[0] = (unsigned char)(linear[0] * normalize);
rgbe[1] = (unsigned char)(linear[1] * normalize);
rgbe[2] = (unsigned char)(linear[2] * normalize);
rgbe[3] = (unsigned char)(exponent + 128);
}
}
static void stbiw__write_run_data(stbi__write_context *s, int length,
unsigned char databyte) {
unsigned char lengthbyte = STBIW_UCHAR(length + 128);
assert(length + 128 <= 255);
s->func(s->context, &lengthbyte, 1);
s->func(s->context, &databyte, 1);
}
static void stbiw__write_dump_data(stbi__write_context *s, int length,
unsigned char *data) {
unsigned char lengthbyte = STBIW_UCHAR(length);
assert(length <=
128); // inconsistent with spec but consistent with official code
s->func(s->context, &lengthbyte, 1);
s->func(s->context, data, length);
}
static void stbiw__write_hdr_scanline(stbi__write_context *s, int width,
int ncomp, unsigned char *scratch,
float *scanline) {
unsigned char scanlineheader[4] = {2, 2, 0, 0};
unsigned char rgbe[4];
float linear[3];
int x;
scanlineheader[2] = (width & 0xff00) >> 8;
scanlineheader[3] = (width & 0x00ff);
/* skip RLE for images too small or large */
if (width < 8 || width >= 32768) {
for (x = 0; x < width; x++) {
switch (ncomp) {
case 4: /* fallthrough */
case 3:
linear[2] = scanline[x * ncomp + 2];
linear[1] = scanline[x * ncomp + 1];
linear[0] = scanline[x * ncomp + 0];
break;
default:
linear[0] = linear[1] = linear[2] = scanline[x * ncomp + 0];
break;
}
stbiw__linear_to_rgbe(rgbe, linear);
s->func(s->context, rgbe, 4);
}
} else {
int c, r;
/* encode into scratch buffer */
for (x = 0; x < width; x++) {
switch (ncomp) {
case 4: /* fallthrough */
case 3:
linear[2] = scanline[x * ncomp + 2];
linear[1] = scanline[x * ncomp + 1];
linear[0] = scanline[x * ncomp + 0];
break;
default:
linear[0] = linear[1] = linear[2] = scanline[x * ncomp + 0];
break;
}
stbiw__linear_to_rgbe(rgbe, linear);
scratch[x + width * 0] = rgbe[0];
scratch[x + width * 1] = rgbe[1];
scratch[x + width * 2] = rgbe[2];
scratch[x + width * 3] = rgbe[3];
}
s->func(s->context, scanlineheader, 4);
/* RLE each component separately */
for (c = 0; c < 4; c++) {
unsigned char *comp = &scratch[width * c];
x = 0;
while (x < width) {
// find first run
r = x;
while (r + 2 < width) {
if (comp[r] == comp[r + 1] && comp[r] == comp[r + 2]) break;
++r;
}
if (r + 2 >= width) r = width;
// dump up to first run
while (x < r) {
int len = r - x;
if (len > 128) len = 128;
stbiw__write_dump_data(s, len, &comp[x]);
x += len;
}
// if there's a run, output it
if (r + 2 < width) { // same test as what we break out of in search
// loop, so only true if we break'd
// find next byte after run
while (r < width && comp[r] == comp[x]) ++r;
// output run up to r
while (x < r) {
int len = r - x;
if (len > 127) len = 127;
stbiw__write_run_data(s, len, comp[x]);
x += len;
}
}
}
}
}
}
static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp,
float *data) {
if (y <= 0 || x <= 0 || data == NULL)
return 0;
else {
// Each component is stored separately. Allocate scratch space for full
// output scanline.
unsigned char *scratch = malloc(x * 4);
int i, len;
char buffer[128];
char header[] =
"#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n";
s->func(s->context, header, sizeof(header) - 1);
len = (snprintf)(buffer, sizeof(buffer), "%s\n\n%s%d%s%d\n",
"EXPOSURE= 1.0000000000000", "-Y ", y, " +X ", x);
s->func(s->context, buffer, len);
for (i = 0; i < y; i++) {
stbiw__write_hdr_scanline(
s, x, comp, scratch,
data + comp * x * (stbi__flip_vertically_on_write ? y - 1 - i : i));
}
free(scratch);
return 1;
}
}
int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y,
int comp, const float *data) {
stbi__write_context s;
stbi__start_write_callbacks(&s, func, context);
return stbi_write_hdr_core(&s, x, y, comp, (float *)data);
}
int stbi_write_hdr(char const *filename, int x, int y, int comp,
const float *data) {
stbi__write_context s;
if (stbi__start_write_file(&s, filename)) {
int r = stbi_write_hdr_core(&s, x, y, comp, (float *)data);
stbi__end_write_file(&s);
return r;
} else
return 0;
}
| 40,264 | 1,045 | jart/cosmopolitan | false |
cosmopolitan/third_party/stb/stb_image_write.h | #ifndef COSMOPOLITAN_THIRD_PARTY_STB_STB_IMAGE_WRITE_H_
#define COSMOPOLITAN_THIRD_PARTY_STB_STB_IMAGE_WRITE_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern int stbi_write_png_compression_level;
extern int stbi__flip_vertically_on_write;
extern int stbi_write_tga_with_rle;
extern int stbi_write_force_png_filter;
int stbi_write_png(const char *, int, int, int, const void *, int);
int stbi_write_bmp(const char *, int, int, int, const void *);
int stbi_write_tga(const char *, int, int, int, const void *);
int stbi_write_hdr(const char *, int, int, int, const float *);
int stbi_write_jpg(const char *, int, int, int, const void *, int);
typedef void stbi_write_func(void *, void *, int);
int stbi_write_png_to_func(stbi_write_func *, void *, int, int, int,
const void *, int);
int stbi_write_bmp_to_func(stbi_write_func *, void *, int, int, int,
const void *);
int stbi_write_tga_to_func(stbi_write_func *, void *, int, int, int,
const void *);
int stbi_write_hdr_to_func(stbi_write_func *, void *, int, int, int,
const float *);
int stbi_write_jpg_to_func(stbi_write_func *, void *, int, int, int,
const void *, int);
unsigned char *stbi_write_png_to_mem(const unsigned char *, int, int, int, int,
int *);
void stbi_flip_vertically_on_write(int);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_THIRD_PARTY_STB_STB_IMAGE_WRITE_H_ */
| 1,579 | 37 | jart/cosmopolitan | false |
cosmopolitan/third_party/stb/README.cosmo | LOCAL CHANGES
- Rewrite endian code so it's optimizable
- Add malloc() to functions w/ frames greater than PAGESIZE
- Removed undefined behavior
- Removed BMP [endian code made it 100x slower than PNG/JPEG]
- Removed PIC [never heard of it]
- Removed TGA [consider imaagemagick convert command]
- Removed PSD [consider imaagemagick convert command]
- Removed HDR [mine eyes and wikipedia agree stb gamma math is off]
- Patched PNG loading edge case
- Fixed code C standard says is undefined
- PNG now uses ultra-fast Chromium zlib w/ CLMUL crc32
- Removed unnecessary ifdefs
- Removed MSVC torture code
SYNCHRONIZATION POINT
commit f67165c2bb2af3060ecae7d20d6f731173485ad0
Author: Sean Barrett <[email protected]>
Date: Mon Oct 28 09:30:02 2019 -0700
Update README.md
| 813 | 24 | jart/cosmopolitan | false |
cosmopolitan/third_party/stb/stb.mk | #-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-â
#âââvi: set et ft=make ts=8 tw=8 fenc=utf-8 :viââââââââââââââââââââââââ
PKGS += THIRD_PARTY_STB
THIRD_PARTY_STB_SRCS = $(THIRD_PARTY_STB_A_SRCS)
THIRD_PARTY_STB_HDRS = $(THIRD_PARTY_STB_A_HDRS)
THIRD_PARTY_STB_ARTIFACTS += THIRD_PARTY_STB_A
THIRD_PARTY_STB = $(THIRD_PARTY_STB_A_DEPS) $(THIRD_PARTY_STB_A)
THIRD_PARTY_STB_A = o/$(MODE)/third_party/stb/stb.a
THIRD_PARTY_STB_A_FILES := $(wildcard third_party/stb/*)
THIRD_PARTY_STB_A_HDRS = $(filter %.h,$(THIRD_PARTY_STB_A_FILES))
THIRD_PARTY_STB_A_SRCS_S = $(filter %.S,$(THIRD_PARTY_STB_A_FILES))
THIRD_PARTY_STB_A_SRCS_C = $(filter %.c,$(THIRD_PARTY_STB_A_FILES))
THIRD_PARTY_STB_A_OBJS_S = $(THIRD_PARTY_STB_A_SRCS_S:%.S=o/$(MODE)/%.o)
THIRD_PARTY_STB_A_OBJS_C = $(THIRD_PARTY_STB_A_SRCS_C:%.c=o/$(MODE)/%.o)
THIRD_PARTY_STB_A_SRCS = \
$(THIRD_PARTY_STB_A_SRCS_S) \
$(THIRD_PARTY_STB_A_SRCS_C)
THIRD_PARTY_STB_A_OBJS = \
$(THIRD_PARTY_STB_A_OBJS_S) \
$(THIRD_PARTY_STB_A_OBJS_C)
THIRD_PARTY_STB_A_DIRECTDEPS = \
DSP_CORE \
LIBC_FMT \
LIBC_INTRIN \
LIBC_LOG \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_RUNTIME \
LIBC_STDIO \
LIBC_STR \
LIBC_STUBS \
LIBC_TINYMATH \
LIBC_X \
THIRD_PARTY_ZLIB
THIRD_PARTY_STB_A_DEPS := \
$(call uniq,$(foreach x,$(THIRD_PARTY_STB_A_DIRECTDEPS),$($(x))))
THIRD_PARTY_STB_A_CHECKS = \
$(THIRD_PARTY_STB_A).pkg \
$(THIRD_PARTY_STB_A_HDRS:%=o/$(MODE)/%.ok)
$(THIRD_PARTY_STB_A): \
third_party/stb/ \
$(THIRD_PARTY_STB_A).pkg \
$(THIRD_PARTY_STB_A_OBJS)
$(THIRD_PARTY_STB_A).pkg: \
$(THIRD_PARTY_STB_A_OBJS) \
$(foreach x,$(THIRD_PARTY_STB_A_DIRECTDEPS),$($(x)_A).pkg)
$(THIRD_PARTY_STB_A_OBJS): private \
OVERRIDE_CFLAGS += \
-ffunction-sections \
-fdata-sections
o/$(MODE)/third_party/stb/stb_vorbis.o: private \
OVERRIDE_CPPFLAGS += \
-DSTACK_FRAME_UNLIMITED
o/$(MODE)/third_party/stb/stb_truetype.o: private \
OVERRIDE_CFLAGS += \
-Os
THIRD_PARTY_STB_LIBS = $(foreach x,$(THIRD_PARTY_STB_ARTIFACTS),$($(x)))
THIRD_PARTY_STB_SRCS = $(foreach x,$(THIRD_PARTY_STB_ARTIFACTS),$($(x)_SRCS))
THIRD_PARTY_STB_CHECKS = $(foreach x,$(THIRD_PARTY_STB_ARTIFACTS),$($(x)_CHECKS))
THIRD_PARTY_STB_OBJS = $(foreach x,$(THIRD_PARTY_STB_ARTIFACTS),$($(x)_OBJS))
$(THIRD_PARTY_STB_OBJS): $(BUILD_FILES) third_party/stb/stb.mk
.PHONY: o/$(MODE)/third_party/stb
o/$(MODE)/third_party/stb: $(THIRD_PARTY_STB_CHECKS)
| 2,552 | 79 | jart/cosmopolitan | false |
cosmopolitan/third_party/stb/stb_image_write_png.c | /* stb_image_write - v1.13 - public domain - http://nothings.org/stb
* writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015
* no warranty implied; use at your own risk
*
* ABOUT:
*
* This file is a library for writing images to stdio or a callback.
*
* The PNG output is not optimal; it is 20-50% larger than the file
* written by a decent optimizing implementation; though providing a
* custom zlib compress function (see STBIW_ZLIB_COMPRESS) can
* mitigate that. This library is designed for source code
* compactness and simplicity, not optimal image file size or
* run-time performance.
*
* USAGE:
*
* There are five functions, one for each image file format:
*
* stbi_write_png
* stbi_write_bmp
* stbi_write_tga
* stbi_write_jpg
* stbi_write_hdr
*
* stbi_flip_vertically_on_write
*
* There are also five equivalent functions that use an arbitrary
* write function. You are expected to open/close your
* file-equivalent before and after calling these:
*
* stbi_write_png_to_func
* stbi_write_bmp_to_func
* stbi_write_tga_to_func
* stbi_write_hdr_to_func
* stbi_write_jpg_to_func
*
* where the callback is:
* void stbi_write_func(void *context, void *data, int size);
*
* You can configure it with these:
* stbi_write_tga_with_rle
* stbi_write_png_compression_level
* stbi_write_force_png_filter
*
* Each function returns 0 on failure and non-0 on success.
*
* The functions create an image file defined by the parameters. The
* image is a rectangle of pixels stored from left-to-right,
* top-to-bottom. Each pixel contains 'comp' channels of data stored
* interleaved with 8-bits per channel, in the following order: 1=Y,
* 2=YA, 3=RGB, 4=RGBA. (Y is monochrome color.) The rectangle is 'w'
* pixels wide and 'h' pixels tall. The *data pointer points to the
* first byte of the top-left-most pixel. For PNG, "stride_in_bytes"
* is the distance in bytes from the first byte of a row of pixels to
* the first byte of the next row of pixels.
*
* PNG creates output files with the same number of components as the
* input. The BMP format expands Y to RGB in the file format and does
* not output alpha.
*
* PNG supports writing rectangles of data even when the bytes
* storing rows of data are not consecutive in memory (e.g.
* sub-rectangles of a larger image), by supplying the stride between
* the beginning of adjacent rows. The other formats do not. (Thus
* you cannot write a native-format BMP through the BMP writer, both
* because it is in BGR order and because it may have padding at the
* end of the line.)
*
* PNG allows you to set the deflate compression level by setting the
* global variable 'stbi_write_png_compression_level' (it defaults to
* 8).
*
* HDR expects linear float data. Since the format is always 32-bit
* rgb(e) data, alpha (if provided) is discarded, and for monochrome
* data it is replicated across all three channels.
*
* TGA supports RLE or non-RLE compressed data. To use
* non-RLE-compressed data, set the global variable
* 'stbi_write_tga_with_rle' to 0.
*
* JPEG does ignore alpha channels in input data; quality is between
* 1 and 100. Higher quality looks better but results in a bigger
* image. JPEG baseline (no JPEG progressive).
*
* CREDITS:
*
*
* Sean Barrett - PNG/BMP/TGA
* Baldur Karlsson - HDR
* Jean-Sebastien Guay - TGA monochrome
* Tim Kelsey - misc enhancements
* Alan Hickman - TGA RLE
* Emmanuel Julien - initial file IO callback implementation
* Jon Olick - original jo_jpeg.cpp code
* Daniel Gibson - integrate JPEG, allow external zlib
* Aarni Koskela - allow choosing PNG filter
*
* bugfixes:
* github:Chribba
* Guillaume Chereau
* github:jry2
* github:romigrou
* Sergio Gonzalez
* Jonas Karlsson
* Filip Wasil
* Thatcher Ulrich
* github:poppolopoppo
* Patrick Boettcher
* github:xeekworx
* Cap Petschulat
* Simon Rodriguez
* Ivan Tikhonov
* github:ignotion
* Adam Schackart
*
* LICENSE
*
* Public Domain (www.unlicense.org)
*/
#include "libc/assert.h"
#include "libc/fmt/conv.h"
#include "libc/limits.h"
#include "libc/mem/mem.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "third_party/stb/stb_image_write.h"
#include "third_party/zlib/zlib.h"
#define STBIW_UCHAR(x) (unsigned char)((x)&0xff)
#define stbiw__wpng4(o, a, b, c, d) \
((o)[0] = STBIW_UCHAR(a), (o)[1] = STBIW_UCHAR(b), (o)[2] = STBIW_UCHAR(c), \
(o)[3] = STBIW_UCHAR(d), (o) += 4)
#define stbiw__wp32(data, v) \
stbiw__wpng4(data, (v) >> 24, (v) >> 16, (v) >> 8, (v));
#define stbiw__wptag(data, s) stbiw__wpng4(data, s[0], s[1], s[2], s[3])
int stbi_write_png_compression_level = 4;
int stbi_write_force_png_filter = -1;
static unsigned char *stbi_zlib_compress(unsigned char *data, int size,
int *out_len, int quality) {
unsigned long newsize;
unsigned char *newdata, *trimdata;
assert(0 <= size && size <= INT_MAX);
if ((newdata = malloc((newsize = compressBound(size)))) &&
compress2(newdata, &newsize, data, size,
stbi_write_png_compression_level) == Z_OK) {
*out_len = newsize;
if ((trimdata = realloc(newdata, newsize))) {
return trimdata;
} else {
return newdata;
}
}
free(newdata);
return NULL;
}
static void stbiw__wpcrc(unsigned char **data, int len) {
unsigned int crc = crc32(0, *data - len - 4, len + 4);
stbiw__wp32(*data, crc);
}
forceinline unsigned char stbiw__paeth(int a, int b, int c) {
int p = a + b - c, pa = abs(p - a), pb = abs(p - b), pc = abs(p - c);
if (pa <= pb && pa <= pc) return STBIW_UCHAR(a);
if (pb <= pc) return STBIW_UCHAR(b);
return STBIW_UCHAR(c);
}
// @OPTIMIZE: provide an option that always forces left-predict or paeth predict
static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes,
int width, int height, int y, int n,
int filter_type, signed char *line_buffer) {
const int mapping[] = {0, 1, 2, 3, 4};
const int firstmap[] = {0, 1, 0, 5, 6};
unsigned char *z;
int *mymap, i, type, signed_stride;
mymap = (y != 0) ? mapping : firstmap;
type = mymap[filter_type];
z = pixels +
stride_bytes * (stbi__flip_vertically_on_write ? height - 1 - y : y);
signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes;
if (type == 0) {
memcpy(line_buffer, z, width * n);
return;
}
for (i = 0; i < n; ++i) {
switch (type) {
case 1:
line_buffer[i] = z[i];
break;
case 2:
line_buffer[i] = z[i] - z[i - signed_stride];
break;
case 3:
line_buffer[i] = z[i] - (z[i - signed_stride] >> 1);
break;
case 4:
line_buffer[i] =
(signed char)(z[i] - stbiw__paeth(0, z[i - signed_stride], 0));
break;
case 5:
line_buffer[i] = z[i];
break;
case 6:
line_buffer[i] = z[i];
break;
}
}
switch (type) {
case 1:
for (i = n; i < width * n; ++i) {
line_buffer[i] = z[i] - z[i - n];
}
break;
case 2:
for (i = n; i < width * n; ++i) {
line_buffer[i] = z[i] - z[i - signed_stride];
}
break;
case 3:
for (i = n; i < width * n; ++i) {
line_buffer[i] = z[i] - ((z[i - n] + z[i - signed_stride]) >> 1);
}
break;
case 4:
for (i = n; i < width * n; ++i) {
line_buffer[i] = z[i] - stbiw__paeth(z[i - n], z[i - signed_stride],
z[i - signed_stride - n]);
}
break;
case 5:
for (i = n; i < width * n; ++i) {
line_buffer[i] = z[i] - (z[i - n] >> 1);
}
break;
case 6:
for (i = n; i < width * n; ++i) {
line_buffer[i] = z[i] - stbiw__paeth(z[i - n], 0, 0);
}
break;
}
}
unsigned char *stbi_write_png_to_mem(const unsigned char *pixels,
int stride_bytes, int x, int y, int n,
int *out_len) {
int force_filter = stbi_write_force_png_filter;
int ctype[5] = {-1, 0, 4, 2, 6};
unsigned char sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
unsigned char *out, *o, *filt, *zlib;
signed char *line_buffer;
int j, zlen;
if (stride_bytes == 0) stride_bytes = x * n;
if (force_filter >= 5) {
force_filter = -1;
}
filt = malloc((x * n + 1) * y);
if (!filt) return 0;
line_buffer = malloc(x * n);
if (!line_buffer) {
free(filt);
return 0;
}
for (j = 0; j < y; ++j) {
int filter_type;
if (force_filter > -1) {
filter_type = force_filter;
stbiw__encode_png_line(pixels, stride_bytes, x, y, j, n, force_filter,
line_buffer);
} else { // Estimate the best filter by running through all of them:
int best_filter = 0, best_filter_val = 0x7fffffff, est, i;
for (filter_type = 0; filter_type < 5; filter_type++) {
stbiw__encode_png_line(pixels, stride_bytes, x, y, j, n, filter_type,
line_buffer);
// Estimate the entropy of the line using this filter; the less, the
// better.
est = 0;
for (i = 0; i < x * n; ++i) {
est += abs((signed char)line_buffer[i]);
}
if (est < best_filter_val) {
best_filter_val = est;
best_filter = filter_type;
}
}
if (filter_type != best_filter) { // If the last iteration already got us
// the best filter, don't redo it
stbiw__encode_png_line(pixels, stride_bytes, x, y, j, n, best_filter,
line_buffer);
filter_type = best_filter;
}
}
// when we get here, filter_type contains the filter type, and line_buffer
// contains the data
filt[j * (x * n + 1)] = (unsigned char)filter_type;
memmove(filt + j * (x * n + 1) + 1, line_buffer, x * n);
}
free(line_buffer);
zlib = stbi_zlib_compress(filt, y * (x * n + 1), &zlen,
stbi_write_png_compression_level);
free(filt);
if (!zlib) return 0;
// each tag requires 12 bytes of overhead
out = malloc(8 + 12 + 13 + 12 + zlen + 12);
if (!out) return 0;
*out_len = 8 + 12 + 13 + 12 + zlen + 12;
o = out;
memmove(o, sig, 8);
o += 8;
stbiw__wp32(o, 13); // header length
stbiw__wptag(o, "IHDR");
stbiw__wp32(o, x);
stbiw__wp32(o, y);
*o++ = 8;
*o++ = STBIW_UCHAR(ctype[n]);
*o++ = 0;
*o++ = 0;
*o++ = 0;
stbiw__wpcrc(&o, 13);
stbiw__wp32(o, zlen);
stbiw__wptag(o, "IDAT");
memmove(o, zlib, zlen);
o += zlen;
free(zlib);
stbiw__wpcrc(&o, zlen);
stbiw__wp32(o, 0);
stbiw__wptag(o, "IEND");
stbiw__wpcrc(&o, 0);
assert(o == out + *out_len);
return out;
}
int stbi_write_png(const char *filename, int x, int y, int comp,
const void *data, int stride_bytes) {
int len;
FILE *f;
unsigned char *png;
png = stbi_write_png_to_mem(data, stride_bytes, x, y, comp, &len);
if (png == NULL) return 0;
f = fopen(filename, "wb");
if (!f) {
free(png);
return 0;
}
fwrite(png, 1, len, f);
fclose(f);
free(png);
return 1;
}
int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y,
int comp, const void *data, int stride_bytes) {
int len;
unsigned char *png;
png = stbi_write_png_to_mem((const unsigned char *)data, stride_bytes, x, y,
comp, &len);
if (png == NULL) return 0;
func(context, png, len);
free(png);
return 1;
}
| 12,193 | 379 | jart/cosmopolitan | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.