id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_good_2019_3 | /* src/interfaces/ecpg/pgtypeslib/dt_common.c */
#include "postgres_fe.h"
#include <time.h>
#include <ctype.h>
#include <math.h>
#include "extern.h"
#include "dt.h"
#include "pgtypes_timestamp.h"
int day_tab[2][13] = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}};
typedef long AbsoluteTime;
#define ABS_SIGNBIT ((char) 0200)
#define POS(n) (n)
#define NEG(n) ((n)|ABS_SIGNBIT)
#define FROMVAL(tp) (-SIGNEDCHAR((tp)->value) * 15) /* uncompress */
#define VALMASK ((char) 0177)
#define SIGNEDCHAR(c) ((c)&ABS_SIGNBIT? -((c)&VALMASK): (c))
static datetkn datetktbl[] = {
/* text, token, lexval */
{EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
{"acsst", DTZ, POS(42)}, /* Cent. Australia */
{"acst", DTZ, NEG(16)}, /* Atlantic/Porto Acre */
{"act", TZ, NEG(20)}, /* Atlantic/Porto Acre */
{DA_D, ADBC, AD}, /* "ad" for years >= 0 */
{"adt", DTZ, NEG(12)}, /* Atlantic Daylight Time */
{"aesst", DTZ, POS(44)}, /* E. Australia */
{"aest", TZ, POS(40)}, /* Australia Eastern Std Time */
{"aft", TZ, POS(18)}, /* Kabul */
{"ahst", TZ, NEG(40)}, /* Alaska-Hawaii Std Time */
{"akdt", DTZ, NEG(32)}, /* Alaska Daylight Time */
{"akst", DTZ, NEG(36)}, /* Alaska Standard Time */
{"allballs", RESERV, DTK_ZULU}, /* 00:00:00 */
{"almst", TZ, POS(28)}, /* Almaty Savings Time */
{"almt", TZ, POS(24)}, /* Almaty Time */
{"am", AMPM, AM},
{"amst", DTZ, POS(20)}, /* Armenia Summer Time (Yerevan) */
#if 0
{"amst", DTZ, NEG(12)}, /* Porto Velho */
#endif
{"amt", TZ, POS(16)}, /* Armenia Time (Yerevan) */
{"anast", DTZ, POS(52)}, /* Anadyr Summer Time (Russia) */
{"anat", TZ, POS(48)}, /* Anadyr Time (Russia) */
{"apr", MONTH, 4},
{"april", MONTH, 4},
#if 0
aqtst
aqtt
arst
#endif
{"art", TZ, NEG(12)}, /* Argentina Time */
#if 0
ashst
ast /* Atlantic Standard Time, Arabia Standard
* Time, Acre Standard Time */
#endif
{"ast", TZ, NEG(16)}, /* Atlantic Std Time (Canada) */
{"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
{"aug", MONTH, 8},
{"august", MONTH, 8},
{"awsst", DTZ, POS(36)}, /* W. Australia */
{"awst", TZ, POS(32)}, /* W. Australia */
{"awt", DTZ, NEG(12)},
{"azost", DTZ, POS(0)}, /* Azores Summer Time */
{"azot", TZ, NEG(4)}, /* Azores Time */
{"azst", DTZ, POS(20)}, /* Azerbaijan Summer Time */
{"azt", TZ, POS(16)}, /* Azerbaijan Time */
{DB_C, ADBC, BC}, /* "bc" for years < 0 */
{"bdst", TZ, POS(8)}, /* British Double Summer Time */
{"bdt", TZ, POS(24)}, /* Dacca */
{"bnt", TZ, POS(32)}, /* Brunei Darussalam Time */
{"bort", TZ, POS(32)}, /* Borneo Time (Indonesia) */
#if 0
bortst
bost
#endif
{"bot", TZ, NEG(16)}, /* Bolivia Time */
{"bra", TZ, NEG(12)}, /* Brazil Time */
#if 0
brst
brt
#endif
{"bst", DTZ, POS(4)}, /* British Summer Time */
#if 0
{"bst", TZ, NEG(12)}, /* Brazil Standard Time */
{"bst", DTZ, NEG(44)}, /* Bering Summer Time */
#endif
{"bt", TZ, POS(12)}, /* Baghdad Time */
{"btt", TZ, POS(24)}, /* Bhutan Time */
{"cadt", DTZ, POS(42)}, /* Central Australian DST */
{"cast", TZ, POS(38)}, /* Central Australian ST */
{"cat", TZ, NEG(40)}, /* Central Alaska Time */
{"cct", TZ, POS(32)}, /* China Coast Time */
#if 0
{"cct", TZ, POS(26)}, /* Indian Cocos (Island) Time */
#endif
{"cdt", DTZ, NEG(20)}, /* Central Daylight Time */
{"cest", DTZ, POS(8)}, /* Central European Dayl.Time */
{"cet", TZ, POS(4)}, /* Central European Time */
{"cetdst", DTZ, POS(8)}, /* Central European Dayl.Time */
{"chadt", DTZ, POS(55)}, /* Chatham Island Daylight Time (13:45) */
{"chast", TZ, POS(51)}, /* Chatham Island Time (12:45) */
#if 0
ckhst
#endif
{"ckt", TZ, POS(48)}, /* Cook Islands Time */
{"clst", DTZ, NEG(12)}, /* Chile Summer Time */
{"clt", TZ, NEG(16)}, /* Chile Time */
#if 0
cost
#endif
{"cot", TZ, NEG(20)}, /* Columbia Time */
{"cst", TZ, NEG(24)}, /* Central Standard Time */
{DCURRENT, RESERV, DTK_CURRENT}, /* "current" is always now */
#if 0
cvst
#endif
{"cvt", TZ, POS(28)}, /* Christmas Island Time (Indian Ocean) */
{"cxt", TZ, POS(28)}, /* Christmas Island Time (Indian Ocean) */
{"d", UNITS, DTK_DAY}, /* "day of month" for ISO input */
{"davt", TZ, POS(28)}, /* Davis Time (Antarctica) */
{"ddut", TZ, POS(40)}, /* Dumont-d'Urville Time (Antarctica) */
{"dec", MONTH, 12},
{"december", MONTH, 12},
{"dnt", TZ, POS(4)}, /* Dansk Normal Tid */
{"dow", RESERV, DTK_DOW}, /* day of week */
{"doy", RESERV, DTK_DOY}, /* day of year */
{"dst", DTZMOD, 6},
#if 0
{"dusst", DTZ, POS(24)}, /* Dushanbe Summer Time */
#endif
{"easst", DTZ, NEG(20)}, /* Easter Island Summer Time */
{"east", TZ, NEG(24)}, /* Easter Island Time */
{"eat", TZ, POS(12)}, /* East Africa Time */
#if 0
{"east", DTZ, POS(16)}, /* Indian Antananarivo Savings Time */
{"eat", TZ, POS(12)}, /* Indian Antananarivo Time */
{"ect", TZ, NEG(16)}, /* Eastern Caribbean Time */
{"ect", TZ, NEG(20)}, /* Ecuador Time */
#endif
{"edt", DTZ, NEG(16)}, /* Eastern Daylight Time */
{"eest", DTZ, POS(12)}, /* Eastern Europe Summer Time */
{"eet", TZ, POS(8)}, /* East. Europe, USSR Zone 1 */
{"eetdst", DTZ, POS(12)}, /* Eastern Europe Daylight Time */
{"egst", DTZ, POS(0)}, /* East Greenland Summer Time */
{"egt", TZ, NEG(4)}, /* East Greenland Time */
#if 0
ehdt
#endif
{EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
{"est", TZ, NEG(20)}, /* Eastern Standard Time */
{"feb", MONTH, 2},
{"february", MONTH, 2},
{"fjst", DTZ, NEG(52)}, /* Fiji Summer Time (13 hour offset!) */
{"fjt", TZ, NEG(48)}, /* Fiji Time */
{"fkst", DTZ, NEG(12)}, /* Falkland Islands Summer Time */
{"fkt", TZ, NEG(8)}, /* Falkland Islands Time */
#if 0
fnst
fnt
#endif
{"fri", DOW, 5},
{"friday", DOW, 5},
{"fst", TZ, POS(4)}, /* French Summer Time */
{"fwt", DTZ, POS(8)}, /* French Winter Time */
{"galt", TZ, NEG(24)}, /* Galapagos Time */
{"gamt", TZ, NEG(36)}, /* Gambier Time */
{"gest", DTZ, POS(20)}, /* Georgia Summer Time */
{"get", TZ, POS(16)}, /* Georgia Time */
{"gft", TZ, NEG(12)}, /* French Guiana Time */
#if 0
ghst
#endif
{"gilt", TZ, POS(48)}, /* Gilbert Islands Time */
{"gmt", TZ, POS(0)}, /* Greenwish Mean Time */
{"gst", TZ, POS(40)}, /* Guam Std Time, USSR Zone 9 */
{"gyt", TZ, NEG(16)}, /* Guyana Time */
{"h", UNITS, DTK_HOUR}, /* "hour" */
#if 0
hadt
hast
#endif
{"hdt", DTZ, NEG(36)}, /* Hawaii/Alaska Daylight Time */
#if 0
hkst
#endif
{"hkt", TZ, POS(32)}, /* Hong Kong Time */
#if 0
{"hmt", TZ, POS(12)}, /* Hellas ? ? */
hovst
hovt
#endif
{"hst", TZ, NEG(40)}, /* Hawaii Std Time */
#if 0
hwt
#endif
{"ict", TZ, POS(28)}, /* Indochina Time */
{"idle", TZ, POS(48)}, /* Intl. Date Line, East */
{"idlw", TZ, NEG(48)}, /* Intl. Date Line, West */
#if 0
idt /* Israeli, Iran, Indian Daylight Time */
#endif
{LATE, RESERV, DTK_LATE}, /* "infinity" reserved for "late time" */
{INVALID, RESERV, DTK_INVALID}, /* "invalid" reserved for bad time */
{"iot", TZ, POS(20)}, /* Indian Chagos Time */
{"irkst", DTZ, POS(36)}, /* Irkutsk Summer Time */
{"irkt", TZ, POS(32)}, /* Irkutsk Time */
{"irt", TZ, POS(14)}, /* Iran Time */
{"isodow", RESERV, DTK_ISODOW}, /* ISO day of week, Sunday == 7 */
#if 0
isst
#endif
{"ist", TZ, POS(8)}, /* Israel */
{"it", TZ, POS(14)}, /* Iran Time */
{"j", UNITS, DTK_JULIAN},
{"jan", MONTH, 1},
{"january", MONTH, 1},
{"javt", TZ, POS(28)}, /* Java Time (07:00? see JT) */
{"jayt", TZ, POS(36)}, /* Jayapura Time (Indonesia) */
{"jd", UNITS, DTK_JULIAN},
{"jst", TZ, POS(36)}, /* Japan Std Time,USSR Zone 8 */
{"jt", TZ, POS(30)}, /* Java Time (07:30? see JAVT) */
{"jul", MONTH, 7},
{"julian", UNITS, DTK_JULIAN},
{"july", MONTH, 7},
{"jun", MONTH, 6},
{"june", MONTH, 6},
{"kdt", DTZ, POS(40)}, /* Korea Daylight Time */
{"kgst", DTZ, POS(24)}, /* Kyrgyzstan Summer Time */
{"kgt", TZ, POS(20)}, /* Kyrgyzstan Time */
{"kost", TZ, POS(48)}, /* Kosrae Time */
{"krast", DTZ, POS(28)}, /* Krasnoyarsk Summer Time */
{"krat", TZ, POS(32)}, /* Krasnoyarsk Standard Time */
{"kst", TZ, POS(36)}, /* Korea Standard Time */
{"lhdt", DTZ, POS(44)}, /* Lord Howe Daylight Time, Australia */
{"lhst", TZ, POS(42)}, /* Lord Howe Standard Time, Australia */
{"ligt", TZ, POS(40)}, /* From Melbourne, Australia */
{"lint", TZ, POS(56)}, /* Line Islands Time (Kiribati; +14 hours!) */
{"lkt", TZ, POS(24)}, /* Lanka Time */
{"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
{"magst", DTZ, POS(48)}, /* Magadan Summer Time */
{"magt", TZ, POS(44)}, /* Magadan Time */
{"mar", MONTH, 3},
{"march", MONTH, 3},
{"mart", TZ, NEG(38)}, /* Marquesas Time */
{"mawt", TZ, POS(24)}, /* Mawson, Antarctica */
{"may", MONTH, 5},
{"mdt", DTZ, NEG(24)}, /* Mountain Daylight Time */
{"mest", DTZ, POS(8)}, /* Middle Europe Summer Time */
{"met", TZ, POS(4)}, /* Middle Europe Time */
{"metdst", DTZ, POS(8)}, /* Middle Europe Daylight Time */
{"mewt", TZ, POS(4)}, /* Middle Europe Winter Time */
{"mez", TZ, POS(4)}, /* Middle Europe Zone */
{"mht", TZ, POS(48)}, /* Kwajalein */
{"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
{"mmt", TZ, POS(26)}, /* Myannar Time */
{"mon", DOW, 1},
{"monday", DOW, 1},
#if 0
most
#endif
{"mpt", TZ, POS(40)}, /* North Mariana Islands Time */
{"msd", DTZ, POS(16)}, /* Moscow Summer Time */
{"msk", TZ, POS(12)}, /* Moscow Time */
{"mst", TZ, NEG(28)}, /* Mountain Standard Time */
{"mt", TZ, POS(34)}, /* Moluccas Time */
{"mut", TZ, POS(16)}, /* Mauritius Island Time */
{"mvt", TZ, POS(20)}, /* Maldives Island Time */
{"myt", TZ, POS(32)}, /* Malaysia Time */
#if 0
ncst
#endif
{"nct", TZ, POS(44)}, /* New Caledonia Time */
{"ndt", DTZ, NEG(10)}, /* Nfld. Daylight Time */
{"nft", TZ, NEG(14)}, /* Newfoundland Standard Time */
{"nor", TZ, POS(4)}, /* Norway Standard Time */
{"nov", MONTH, 11},
{"november", MONTH, 11},
{"novst", DTZ, POS(28)}, /* Novosibirsk Summer Time */
{"novt", TZ, POS(24)}, /* Novosibirsk Standard Time */
{NOW, RESERV, DTK_NOW}, /* current transaction time */
{"npt", TZ, POS(23)}, /* Nepal Standard Time (GMT-5:45) */
{"nst", TZ, NEG(14)}, /* Nfld. Standard Time */
{"nt", TZ, NEG(44)}, /* Nome Time */
{"nut", TZ, NEG(44)}, /* Niue Time */
{"nzdt", DTZ, POS(52)}, /* New Zealand Daylight Time */
{"nzst", TZ, POS(48)}, /* New Zealand Standard Time */
{"nzt", TZ, POS(48)}, /* New Zealand Time */
{"oct", MONTH, 10},
{"october", MONTH, 10},
{"omsst", DTZ, POS(28)}, /* Omsk Summer Time */
{"omst", TZ, POS(24)}, /* Omsk Time */
{"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
{"pdt", DTZ, NEG(28)}, /* Pacific Daylight Time */
#if 0
pest
#endif
{"pet", TZ, NEG(20)}, /* Peru Time */
{"petst", DTZ, POS(52)}, /* Petropavlovsk-Kamchatski Summer Time */
{"pett", TZ, POS(48)}, /* Petropavlovsk-Kamchatski Time */
{"pgt", TZ, POS(40)}, /* Papua New Guinea Time */
{"phot", TZ, POS(52)}, /* Phoenix Islands (Kiribati) Time */
#if 0
phst
#endif
{"pht", TZ, POS(32)}, /* Philippine Time */
{"pkt", TZ, POS(20)}, /* Pakistan Time */
{"pm", AMPM, PM},
{"pmdt", DTZ, NEG(8)}, /* Pierre & Miquelon Daylight Time */
#if 0
pmst
#endif
{"pont", TZ, POS(44)}, /* Ponape Time (Micronesia) */
{"pst", TZ, NEG(32)}, /* Pacific Standard Time */
{"pwt", TZ, POS(36)}, /* Palau Time */
{"pyst", DTZ, NEG(12)}, /* Paraguay Summer Time */
{"pyt", TZ, NEG(16)}, /* Paraguay Time */
{"ret", DTZ, POS(16)}, /* Reunion Island Time */
{"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
{"sadt", DTZ, POS(42)}, /* S. Australian Dayl. Time */
#if 0
samst
samt
#endif
{"sast", TZ, POS(38)}, /* South Australian Std Time */
{"sat", DOW, 6},
{"saturday", DOW, 6},
#if 0
sbt
#endif
{"sct", DTZ, POS(16)}, /* Mahe Island Time */
{"sep", MONTH, 9},
{"sept", MONTH, 9},
{"september", MONTH, 9},
{"set", TZ, NEG(4)}, /* Seychelles Time ?? */
#if 0
sgt
#endif
{"sst", DTZ, POS(8)}, /* Swedish Summer Time */
{"sun", DOW, 0},
{"sunday", DOW, 0},
{"swt", TZ, POS(4)}, /* Swedish Winter Time */
#if 0
syot
#endif
{"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
{"tft", TZ, POS(20)}, /* Kerguelen Time */
{"that", TZ, NEG(40)}, /* Tahiti Time */
{"thu", DOW, 4},
{"thur", DOW, 4},
{"thurs", DOW, 4},
{"thursday", DOW, 4},
{"tjt", TZ, POS(20)}, /* Tajikistan Time */
{"tkt", TZ, NEG(40)}, /* Tokelau Time */
{"tmt", TZ, POS(20)}, /* Turkmenistan Time */
{TODAY, RESERV, DTK_TODAY}, /* midnight */
{TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
#if 0
tost
#endif
{"tot", TZ, POS(52)}, /* Tonga Time */
#if 0
tpt
#endif
{"truk", TZ, POS(40)}, /* Truk Time */
{"tue", DOW, 2},
{"tues", DOW, 2},
{"tuesday", DOW, 2},
{"tvt", TZ, POS(48)}, /* Tuvalu Time */
#if 0
uct
#endif
{"ulast", DTZ, POS(36)}, /* Ulan Bator Summer Time */
{"ulat", TZ, POS(32)}, /* Ulan Bator Time */
{"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
{"ut", TZ, POS(0)},
{"utc", TZ, POS(0)},
{"uyst", DTZ, NEG(8)}, /* Uruguay Summer Time */
{"uyt", TZ, NEG(12)}, /* Uruguay Time */
{"uzst", DTZ, POS(24)}, /* Uzbekistan Summer Time */
{"uzt", TZ, POS(20)}, /* Uzbekistan Time */
{"vet", TZ, NEG(16)}, /* Venezuela Time */
{"vlast", DTZ, POS(44)}, /* Vladivostok Summer Time */
{"vlat", TZ, POS(40)}, /* Vladivostok Time */
#if 0
vust
#endif
{"vut", TZ, POS(44)}, /* Vanuata Time */
{"wadt", DTZ, POS(32)}, /* West Australian DST */
{"wakt", TZ, POS(48)}, /* Wake Time */
#if 0
warst
#endif
{"wast", TZ, POS(28)}, /* West Australian Std Time */
{"wat", TZ, NEG(4)}, /* West Africa Time */
{"wdt", DTZ, POS(36)}, /* West Australian DST */
{"wed", DOW, 3},
{"wednesday", DOW, 3},
{"weds", DOW, 3},
{"west", DTZ, POS(4)}, /* Western Europe Summer Time */
{"wet", TZ, POS(0)}, /* Western Europe */
{"wetdst", DTZ, POS(4)}, /* Western Europe Daylight Savings Time */
{"wft", TZ, POS(48)}, /* Wallis and Futuna Time */
{"wgst", DTZ, NEG(8)}, /* West Greenland Summer Time */
{"wgt", TZ, NEG(12)}, /* West Greenland Time */
{"wst", TZ, POS(32)}, /* West Australian Standard Time */
{"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
{"yakst", DTZ, POS(40)}, /* Yakutsk Summer Time */
{"yakt", TZ, POS(36)}, /* Yakutsk Time */
{"yapt", TZ, POS(40)}, /* Yap Time (Micronesia) */
{"ydt", DTZ, NEG(32)}, /* Yukon Daylight Time */
{"yekst", DTZ, POS(24)}, /* Yekaterinburg Summer Time */
{"yekt", TZ, POS(20)}, /* Yekaterinburg Time */
{YESTERDAY, RESERV, DTK_YESTERDAY}, /* yesterday midnight */
{"yst", TZ, NEG(36)}, /* Yukon Standard Time */
{"z", TZ, POS(0)}, /* time zone tag per ISO-8601 */
{"zp4", TZ, NEG(16)}, /* UTC +4 hours. */
{"zp5", TZ, NEG(20)}, /* UTC +5 hours. */
{"zp6", TZ, NEG(24)}, /* UTC +6 hours. */
{ZULU, TZ, POS(0)}, /* UTC */
};
static datetkn deltatktbl[] = {
/* text, token, lexval */
{"@", IGNORE_DTF, 0}, /* postgres relative prefix */
{DAGO, AGO, 0}, /* "ago" indicates negative time offset */
{"c", UNITS, DTK_CENTURY}, /* "century" relative */
{"cent", UNITS, DTK_CENTURY}, /* "century" relative */
{"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
{DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
{"d", UNITS, DTK_DAY}, /* "day" relative */
{DDAY, UNITS, DTK_DAY}, /* "day" relative */
{"days", UNITS, DTK_DAY}, /* "days" relative */
{"dec", UNITS, DTK_DECADE}, /* "decade" relative */
{DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
{"decades", UNITS, DTK_DECADE}, /* "decades" relative */
{"decs", UNITS, DTK_DECADE}, /* "decades" relative */
{"h", UNITS, DTK_HOUR}, /* "hour" relative */
{DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
{"hours", UNITS, DTK_HOUR}, /* "hours" relative */
{"hr", UNITS, DTK_HOUR}, /* "hour" relative */
{"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
{INVALID, RESERV, DTK_INVALID}, /* reserved for invalid time */
{"m", UNITS, DTK_MINUTE}, /* "minute" relative */
{"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
{"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
{"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
{DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
{"millisecon", UNITS, DTK_MILLISEC}, /* relative */
{"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
{"min", UNITS, DTK_MINUTE}, /* "minute" relative */
{"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
{DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
{"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
{"mon", UNITS, DTK_MONTH}, /* "months" relative */
{"mons", UNITS, DTK_MONTH}, /* "months" relative */
{DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
{"months", UNITS, DTK_MONTH},
{"ms", UNITS, DTK_MILLISEC},
{"msec", UNITS, DTK_MILLISEC},
{DMILLISEC, UNITS, DTK_MILLISEC},
{"mseconds", UNITS, DTK_MILLISEC},
{"msecs", UNITS, DTK_MILLISEC},
{"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
{DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
{"s", UNITS, DTK_SECOND},
{"sec", UNITS, DTK_SECOND},
{DSECOND, UNITS, DTK_SECOND},
{"seconds", UNITS, DTK_SECOND},
{"secs", UNITS, DTK_SECOND},
{DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
{"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
{"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
{"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
{"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
{"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
{DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
{"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
{"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
{"w", UNITS, DTK_WEEK}, /* "week" relative */
{DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
{"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
{"y", UNITS, DTK_YEAR}, /* "year" relative */
{DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
{"years", UNITS, DTK_YEAR}, /* "years" relative */
{"yr", UNITS, DTK_YEAR}, /* "year" relative */
{"yrs", UNITS, DTK_YEAR}, /* "years" relative */
};
static const unsigned int szdatetktbl = lengthof(datetktbl);
static const unsigned int szdeltatktbl = lengthof(deltatktbl);
static datetkn *datecache[MAXDATEFIELDS] = {NULL};
static datetkn *deltacache[MAXDATEFIELDS] = {NULL};
char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", NULL};
char *pgtypes_date_weekdays_short[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL};
char *pgtypes_date_months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", NULL};
static datetkn *
datebsearch(char *key, datetkn *base, unsigned int nel)
{
if (nel > 0)
{
datetkn *last = base + nel - 1,
*position;
int result;
while (last >= base)
{
position = base + ((last - base) >> 1);
result = key[0] - position->token[0];
if (result == 0)
{
result = strncmp(key, position->token, TOKMAXLEN);
if (result == 0)
return position;
}
if (result < 0)
last = position - 1;
else
base = position + 1;
}
}
return NULL;
}
/* DecodeUnits()
* Decode text string using lookup table.
* This routine supports time interval decoding.
*/
int
DecodeUnits(int field, char *lowtoken, int *val)
{
int type;
datetkn *tp;
if (deltacache[field] != NULL &&
strncmp(lowtoken, deltacache[field]->token, TOKMAXLEN) == 0)
tp = deltacache[field];
else
tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
deltacache[field] = tp;
if (tp == NULL)
{
type = UNKNOWN_FIELD;
*val = 0;
}
else
{
type = tp->type;
if (type == TZ || type == DTZ)
*val = FROMVAL(tp);
else
*val = tp->value;
}
return type;
} /* DecodeUnits() */
/*
* Calendar time to Julian date conversions.
* Julian date is commonly used in astronomical applications,
* since it is numerically accurate and computationally simple.
* The algorithms here will accurately convert between Julian day
* and calendar date for all non-negative Julian days
* (i.e. from Nov 24, -4713 on).
*
* These routines will be used by other date/time packages
* - thomas 97/02/25
*
* Rewritten to eliminate overflow problems. This now allows the
* routines to work correctly for all Julian day counts from
* 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
* a 32-bit integer. Longer types should also work to the limits
* of their precision.
*/
int
date2j(int y, int m, int d)
{
int julian;
int century;
if (m > 2)
{
m += 1;
y += 4800;
}
else
{
m += 13;
y += 4799;
}
century = y / 100;
julian = y * 365 - 32167;
julian += y / 4 - century + century / 4;
julian += 7834 * m / 256 + d;
return julian;
} /* date2j() */
void
j2date(int jd, int *year, int *month, int *day)
{
unsigned int julian;
unsigned int quad;
unsigned int extra;
int y;
julian = jd;
julian += 32044;
quad = julian / 146097;
extra = (julian - quad * 146097) * 4 + 3;
julian += 60 + quad * 3 + extra / 146097;
quad = julian / 1461;
julian -= quad * 1461;
y = julian * 4 / 1461;
julian = ((y != 0) ? (julian + 305) % 365 : (julian + 306) % 366) + 123;
y += quad * 4;
*year = y - 4800;
quad = julian * 2141 / 65536;
*day = julian - 7834 * quad / 256;
*month = (quad + 10) % 12 + 1;
return;
} /* j2date() */
/* DecodeSpecial()
* Decode text string using lookup table.
* Implement a cache lookup since it is likely that dates
* will be related in format.
*/
static int
DecodeSpecial(int field, char *lowtoken, int *val)
{
int type;
datetkn *tp;
if (datecache[field] != NULL &&
strncmp(lowtoken, datecache[field]->token, TOKMAXLEN) == 0)
tp = datecache[field];
else
{
tp = NULL;
if (!tp)
tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
}
datecache[field] = tp;
if (tp == NULL)
{
type = UNKNOWN_FIELD;
*val = 0;
}
else
{
type = tp->type;
switch (type)
{
case TZ:
case DTZ:
case DTZMOD:
*val = FROMVAL(tp);
break;
default:
*val = tp->value;
break;
}
}
return type;
} /* DecodeSpecial() */
/* EncodeDateOnly()
* Encode date as local time.
*/
int
EncodeDateOnly(struct tm * tm, int style, char *str, bool EuroDates)
{
if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
return -1;
switch (style)
{
case USE_ISO_DATES:
/* compatible with ISO date formats */
if (tm->tm_year > 0)
sprintf(str, "%04d-%02d-%02d",
tm->tm_year, tm->tm_mon, tm->tm_mday);
else
sprintf(str, "%04d-%02d-%02d %s",
-(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
break;
case USE_SQL_DATES:
/* compatible with Oracle/Ingres date formats */
if (EuroDates)
sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
else
sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
if (tm->tm_year > 0)
sprintf(str + 5, "/%04d", tm->tm_year);
else
sprintf(str + 5, "/%04d %s", -(tm->tm_year - 1), "BC");
break;
case USE_GERMAN_DATES:
/* German-style date format */
sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
if (tm->tm_year > 0)
sprintf(str + 5, ".%04d", tm->tm_year);
else
sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
break;
case USE_POSTGRES_DATES:
default:
/* traditional date-only style for Postgres */
if (EuroDates)
sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
else
sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
if (tm->tm_year > 0)
sprintf(str + 5, "-%04d", tm->tm_year);
else
sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
break;
}
return TRUE;
} /* EncodeDateOnly() */
void
TrimTrailingZeros(char *str)
{
int len = strlen(str);
/* chop off trailing zeros... but leave at least 2 fractional digits */
while (*(str + len - 1) == '0' && *(str + len - 3) != '.')
{
len--;
*(str + len) = '\0';
}
}
/* EncodeDateTime()
* Encode date and time interpreted as local time.
*
* tm and fsec are the value to encode, print_tz determines whether to include
* a time zone (the difference between timestamp and timestamptz types), tz is
* the numeric time zone offset, tzn is the textual time zone, which if
* specified will be used instead of tz by some styles, style is the date
* style, str is where to write the output.
*
* Supported date styles:
* Postgres - day mon hh:mm:ss yyyy tz
* SQL - mm/dd/yyyy hh:mm:ss.ss tz
* ISO - yyyy-mm-dd hh:mm:ss+/-tz
* German - dd.mm.yyyy hh:mm:ss tz
* Variants (affects order of month and day for Postgres and SQL styles):
* US - mm/dd/yyyy
* European - dd/mm/yyyy
*/
int
EncodeDateTime(struct tm * tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str, bool EuroDates)
{
int day,
hour,
min;
/*
* Negative tm_isdst means we have no valid time zone translation.
*/
if (tm->tm_isdst < 0)
print_tz = false;
switch (style)
{
case USE_ISO_DATES:
/* Compatible with ISO-8601 date formats */
sprintf(str, "%04d-%02d-%02d %02d:%02d",
(tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
/*
* Print fractional seconds if any. The field widths here should
* be at least equal to MAX_TIMESTAMP_PRECISION.
*
* In float mode, don't print fractional seconds before 1 AD,
* since it's unlikely there's any precision left ...
*/
#ifdef HAVE_INT64_TIMESTAMP
if (fsec != 0)
{
sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
#else
if ((fsec != 0) && (tm->tm_year > 0))
{
sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
#endif
TrimTrailingZeros(str);
}
else
sprintf(str + strlen(str), ":%02d", tm->tm_sec);
if (tm->tm_year <= 0)
sprintf(str + strlen(str), " BC");
if (print_tz)
{
hour = -(tz / SECS_PER_HOUR);
min = (abs(tz) / MINS_PER_HOUR) % MINS_PER_HOUR;
if (min != 0)
sprintf(str + strlen(str), "%+03d:%02d", hour, min);
else
sprintf(str + strlen(str), "%+03d", hour);
}
break;
case USE_SQL_DATES:
/* Compatible with Oracle/Ingres date formats */
if (EuroDates)
sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
else
sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
sprintf(str + 5, "/%04d %02d:%02d",
(tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
tm->tm_hour, tm->tm_min);
/*
* Print fractional seconds if any. The field widths here should
* be at least equal to MAX_TIMESTAMP_PRECISION.
*
* In float mode, don't print fractional seconds before 1 AD,
* since it's unlikely there's any precision left ...
*/
#ifdef HAVE_INT64_TIMESTAMP
if (fsec != 0)
{
sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
#else
if (fsec != 0 && tm->tm_year > 0)
{
sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
#endif
TrimTrailingZeros(str);
}
else
sprintf(str + strlen(str), ":%02d", tm->tm_sec);
if (tm->tm_year <= 0)
sprintf(str + strlen(str), " BC");
/*
* Note: the uses of %.*s in this function would be risky if the
* timezone names ever contain non-ASCII characters. However, all
* TZ abbreviations in the Olson database are plain ASCII.
*/
if (print_tz)
{
if (tzn)
sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
else
{
hour = -(tz / SECS_PER_HOUR);
min = (abs(tz) / MINS_PER_HOUR) % MINS_PER_HOUR;
if (min != 0)
sprintf(str + strlen(str), "%+03d:%02d", hour, min);
else
sprintf(str + strlen(str), "%+03d", hour);
}
}
break;
case USE_GERMAN_DATES:
/* German variant on European style */
sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
sprintf(str + 5, ".%04d %02d:%02d",
(tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
tm->tm_hour, tm->tm_min);
/*
* Print fractional seconds if any. The field widths here should
* be at least equal to MAX_TIMESTAMP_PRECISION.
*
* In float mode, don't print fractional seconds before 1 AD,
* since it's unlikely there's any precision left ...
*/
#ifdef HAVE_INT64_TIMESTAMP
if (fsec != 0)
{
sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
#else
if (fsec != 0 && tm->tm_year > 0)
{
sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
#endif
TrimTrailingZeros(str);
}
else
sprintf(str + strlen(str), ":%02d", tm->tm_sec);
if (tm->tm_year <= 0)
sprintf(str + strlen(str), " BC");
if (print_tz)
{
if (tzn)
sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
else
{
hour = -(tz / SECS_PER_HOUR);
min = (abs(tz) / MINS_PER_HOUR) % MINS_PER_HOUR;
if (min != 0)
sprintf(str + strlen(str), "%+03d:%02d", hour, min);
else
sprintf(str + strlen(str), "%+03d", hour);
}
}
break;
case USE_POSTGRES_DATES:
default:
/* Backward-compatible with traditional Postgres abstime dates */
day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
tm->tm_wday = (int) ((day + date2j(2000, 1, 1) + 1) % 7);
strncpy(str, days[tm->tm_wday], 3);
strcpy(str + 3, " ");
if (EuroDates)
sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
else
sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
sprintf(str + 10, " %02d:%02d", tm->tm_hour, tm->tm_min);
/*
* Print fractional seconds if any. The field widths here should
* be at least equal to MAX_TIMESTAMP_PRECISION.
*
* In float mode, don't print fractional seconds before 1 AD,
* since it's unlikely there's any precision left ...
*/
#ifdef HAVE_INT64_TIMESTAMP
if (fsec != 0)
{
sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
#else
if (fsec != 0 && tm->tm_year > 0)
{
sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
#endif
TrimTrailingZeros(str);
}
else
sprintf(str + strlen(str), ":%02d", tm->tm_sec);
sprintf(str + strlen(str), " %04d",
(tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
if (tm->tm_year <= 0)
sprintf(str + strlen(str), " BC");
if (print_tz)
{
if (tzn)
sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
else
{
/*
* We have a time zone, but no string version. Use the
* numeric form, but be sure to include a leading space to
* avoid formatting something which would be rejected by
* the date/time parser later. - thomas 2001-10-19
*/
hour = -(tz / SECS_PER_HOUR);
min = (abs(tz) / MINS_PER_HOUR) % MINS_PER_HOUR;
if (min != 0)
sprintf(str + strlen(str), " %+03d:%02d", hour, min);
else
sprintf(str + strlen(str), " %+03d", hour);
}
}
break;
}
return TRUE;
} /* EncodeDateTime() */
int
GetEpochTime(struct tm * tm)
{
struct tm *t0;
time_t epoch = 0;
t0 = gmtime(&epoch);
if (t0)
{
tm->tm_year = t0->tm_year + 1900;
tm->tm_mon = t0->tm_mon + 1;
tm->tm_mday = t0->tm_mday;
tm->tm_hour = t0->tm_hour;
tm->tm_min = t0->tm_min;
tm->tm_sec = t0->tm_sec;
return 0;
}
return -1;
} /* GetEpochTime() */
static void
abstime2tm(AbsoluteTime _time, int *tzp, struct tm * tm, char **tzn)
{
time_t time = (time_t) _time;
struct tm *tx;
errno = 0;
if (tzp != NULL)
tx = localtime((time_t *) &time);
else
tx = gmtime((time_t *) &time);
if (!tx)
{
errno = PGTYPES_TS_BAD_TIMESTAMP;
return;
}
tm->tm_year = tx->tm_year + 1900;
tm->tm_mon = tx->tm_mon + 1;
tm->tm_mday = tx->tm_mday;
tm->tm_hour = tx->tm_hour;
tm->tm_min = tx->tm_min;
tm->tm_sec = tx->tm_sec;
tm->tm_isdst = tx->tm_isdst;
#if defined(HAVE_TM_ZONE)
tm->tm_gmtoff = tx->tm_gmtoff;
tm->tm_zone = tx->tm_zone;
if (tzp != NULL)
{
/*
* We have a brute force time zone per SQL99? Then use it without
* change since we have already rotated to the time zone.
*/
*tzp = -tm->tm_gmtoff; /* tm_gmtoff is Sun/DEC-ism */
/*
* FreeBSD man pages indicate that this should work - tgl 97/04/23
*/
if (tzn != NULL)
{
/*
* Copy no more than MAXTZLEN bytes of timezone to tzn, in case it
* contains an error message, which doesn't fit in the buffer
*/
StrNCpy(*tzn, tm->tm_zone, MAXTZLEN + 1);
if (strlen(tm->tm_zone) > MAXTZLEN)
tm->tm_isdst = -1;
}
}
else
tm->tm_isdst = -1;
#elif defined(HAVE_INT_TIMEZONE)
if (tzp != NULL)
{
*tzp = (tm->tm_isdst > 0) ? TIMEZONE_GLOBAL - SECS_PER_HOUR : TIMEZONE_GLOBAL;
if (tzn != NULL)
{
/*
* Copy no more than MAXTZLEN bytes of timezone to tzn, in case it
* contains an error message, which doesn't fit in the buffer
*/
StrNCpy(*tzn, TZNAME_GLOBAL[tm->tm_isdst], MAXTZLEN + 1);
if (strlen(TZNAME_GLOBAL[tm->tm_isdst]) > MAXTZLEN)
tm->tm_isdst = -1;
}
}
else
tm->tm_isdst = -1;
#else /* not (HAVE_TM_ZONE || HAVE_INT_TIMEZONE) */
if (tzp != NULL)
{
/* default to UTC */
*tzp = 0;
if (tzn != NULL)
*tzn = NULL;
}
else
tm->tm_isdst = -1;
#endif
}
void
GetCurrentDateTime(struct tm * tm)
{
int tz;
abstime2tm(time(NULL), &tz, tm, NULL);
}
void
dt2time(double jd, int *hour, int *min, int *sec, fsec_t *fsec)
{
#ifdef HAVE_INT64_TIMESTAMP
int64 time;
#else
double time;
#endif
time = jd;
#ifdef HAVE_INT64_TIMESTAMP
*hour = time / USECS_PER_HOUR;
time -= (*hour) * USECS_PER_HOUR;
*min = time / USECS_PER_MINUTE;
time -= (*min) * USECS_PER_MINUTE;
*sec = time / USECS_PER_SEC;
*fsec = time - (*sec * USECS_PER_SEC);
#else
*hour = time / SECS_PER_HOUR;
time -= (*hour) * SECS_PER_HOUR;
*min = time / SECS_PER_MINUTE;
time -= (*min) * SECS_PER_MINUTE;
*sec = time;
*fsec = time - *sec;
#endif
} /* dt2time() */
/* DecodeNumberField()
* Interpret numeric string as a concatenated date or time field.
* Use the context of previously decoded fields to help with
* the interpretation.
*/
static int
DecodeNumberField(int len, char *str, int fmask,
int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits)
{
char *cp;
/*
* Have a decimal point? Then this is a date or something with a seconds
* field...
*/
if ((cp = strchr(str, '.')) != NULL)
{
#ifdef HAVE_INT64_TIMESTAMP
char fstr[7];
int i;
cp++;
/*
* OK, we have at most six digits to care about. Let's construct a
* string with those digits, zero-padded on the right, and then do
* the conversion to an integer.
*
* XXX This truncates the seventh digit, unlike rounding it as do
* the backend and the !HAVE_INT64_TIMESTAMP case.
*/
for (i = 0; i < 6; i++)
fstr[i] = *cp != '\0' ? *cp++ : '0';
fstr[i] = '\0';
*fsec = strtol(fstr, NULL, 10);
#else
*fsec = strtod(cp, NULL);
#endif
*cp = '\0';
len = strlen(str);
}
/* No decimal point and no complete date yet? */
else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
{
/* yyyymmdd? */
if (len == 8)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 6);
*(str + 6) = '\0';
tm->tm_mon = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_year = atoi(str + 0);
return DTK_DATE;
}
/* yymmdd? */
else if (len == 6)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_mon = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_year = atoi(str + 0);
*is2digits = TRUE;
return DTK_DATE;
}
/* yyddd? */
else if (len == 5)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_mon = 1;
tm->tm_year = atoi(str + 0);
*is2digits = TRUE;
return DTK_DATE;
}
}
/* not all time fields are specified? */
if ((fmask & DTK_TIME_M) != DTK_TIME_M)
{
/* hhmmss */
if (len == 6)
{
*tmask = DTK_TIME_M;
tm->tm_sec = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_min = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_hour = atoi(str + 0);
return DTK_TIME;
}
/* hhmm? */
else if (len == 4)
{
*tmask = DTK_TIME_M;
tm->tm_sec = 0;
tm->tm_min = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_hour = atoi(str + 0);
return DTK_TIME;
}
}
return -1;
} /* DecodeNumberField() */
/* DecodeNumber()
* Interpret plain numeric field as a date value in context.
*/
static int
DecodeNumber(int flen, char *str, int fmask,
int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits, bool EuroDates)
{
int val;
char *cp;
*tmask = 0;
val = strtol(str, &cp, 10);
if (cp == str)
return -1;
if (*cp == '.')
{
/*
* More than two digits? Then could be a date or a run-together time:
* 2001.360 20011225 040506.789
*/
if (cp - str > 2)
return DecodeNumberField(flen, str, (fmask | DTK_DATE_M),
tmask, tm, fsec, is2digits);
*fsec = strtod(cp, &cp);
if (*cp != '\0')
return -1;
}
else if (*cp != '\0')
return -1;
/* Special case day of year? */
if (flen == 3 && (fmask & DTK_M(YEAR)) && val >= 1 && val <= 366)
{
*tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
tm->tm_yday = val;
j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
&tm->tm_year, &tm->tm_mon, &tm->tm_mday);
}
/***
* Enough digits to be unequivocal year? Used to test for 4 digits or
* more, but we now test first for a three-digit doy so anything
* bigger than two digits had better be an explicit year.
* - thomas 1999-01-09
* Back to requiring a 4 digit year. We accept a two digit
* year farther down. - thomas 2000-03-28
***/
else if (flen >= 4)
{
*tmask = DTK_M(YEAR);
/* already have a year? then see if we can substitute... */
if ((fmask & DTK_M(YEAR)) && !(fmask & DTK_M(DAY)) &&
tm->tm_year >= 1 && tm->tm_year <= 31)
{
tm->tm_mday = tm->tm_year;
*tmask = DTK_M(DAY);
}
tm->tm_year = val;
}
/* already have year? then could be month */
else if ((fmask & DTK_M(YEAR)) && !(fmask & DTK_M(MONTH)) && val >= 1 && val <= MONTHS_PER_YEAR)
{
*tmask = DTK_M(MONTH);
tm->tm_mon = val;
}
/* no year and EuroDates enabled? then could be day */
else if ((EuroDates || (fmask & DTK_M(MONTH))) &&
!(fmask & DTK_M(YEAR)) && !(fmask & DTK_M(DAY)) &&
val >= 1 && val <= 31)
{
*tmask = DTK_M(DAY);
tm->tm_mday = val;
}
else if (!(fmask & DTK_M(MONTH)) && val >= 1 && val <= MONTHS_PER_YEAR)
{
*tmask = DTK_M(MONTH);
tm->tm_mon = val;
}
else if (!(fmask & DTK_M(DAY)) && val >= 1 && val <= 31)
{
*tmask = DTK_M(DAY);
tm->tm_mday = val;
}
/*
* Check for 2 or 4 or more digits, but currently we reach here only if
* two digits. - thomas 2000-03-28
*/
else if (!(fmask & DTK_M(YEAR)) && (flen >= 4 || flen == 2))
{
*tmask = DTK_M(YEAR);
tm->tm_year = val;
/* adjust ONLY if exactly two digits... */
*is2digits = (flen == 2);
}
else
return -1;
return 0;
} /* DecodeNumber() */
/* DecodeDate()
* Decode date string which includes delimiters.
* Insist on a complete set of fields.
*/
static int
DecodeDate(char *str, int fmask, int *tmask, struct tm * tm, bool EuroDates)
{
fsec_t fsec;
int nf = 0;
int i,
len;
int bc = FALSE;
int is2digits = FALSE;
int type,
val,
dmask = 0;
char *field[MAXDATEFIELDS];
/* parse this string... */
while (*str != '\0' && nf < MAXDATEFIELDS)
{
/* skip field separators */
while (!isalnum((unsigned char) *str))
str++;
field[nf] = str;
if (isdigit((unsigned char) *str))
{
while (isdigit((unsigned char) *str))
str++;
}
else if (isalpha((unsigned char) *str))
{
while (isalpha((unsigned char) *str))
str++;
}
/* Just get rid of any non-digit, non-alpha characters... */
if (*str != '\0')
*str++ = '\0';
nf++;
}
#if 0
/* don't allow too many fields */
if (nf > 3)
return -1;
#endif
*tmask = 0;
/* look first for text fields, since that will be unambiguous month */
for (i = 0; i < nf; i++)
{
if (isalpha((unsigned char) *field[i]))
{
type = DecodeSpecial(i, field[i], &val);
if (type == IGNORE_DTF)
continue;
dmask = DTK_M(type);
switch (type)
{
case MONTH:
tm->tm_mon = val;
break;
case ADBC:
bc = (val == BC);
break;
default:
return -1;
}
if (fmask & dmask)
return -1;
fmask |= dmask;
*tmask |= dmask;
/* mark this field as being completed */
field[i] = NULL;
}
}
/* now pick up remaining numeric fields */
for (i = 0; i < nf; i++)
{
if (field[i] == NULL)
continue;
if ((len = strlen(field[i])) <= 0)
return -1;
if (DecodeNumber(len, field[i], fmask, &dmask, tm, &fsec, &is2digits, EuroDates) != 0)
return -1;
if (fmask & dmask)
return -1;
fmask |= dmask;
*tmask |= dmask;
}
if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
return -1;
/* there is no year zero in AD/BC notation; i.e. "1 BC" == year 0 */
if (bc)
{
if (tm->tm_year > 0)
tm->tm_year = -(tm->tm_year - 1);
else
return -1;
}
else if (is2digits)
{
if (tm->tm_year < 70)
tm->tm_year += 2000;
else if (tm->tm_year < 100)
tm->tm_year += 1900;
}
return 0;
} /* DecodeDate() */
/* DecodeTime()
* Decode time string which includes delimiters.
* Only check the lower limit on hours, since this same code
* can be used to represent time spans.
*/
int
DecodeTime(char *str, int *tmask, struct tm * tm, fsec_t *fsec)
{
char *cp;
*tmask = DTK_TIME_M;
tm->tm_hour = strtol(str, &cp, 10);
if (*cp != ':')
return -1;
str = cp + 1;
tm->tm_min = strtol(str, &cp, 10);
if (*cp == '\0')
{
tm->tm_sec = 0;
*fsec = 0;
}
else if (*cp != ':')
return -1;
else
{
str = cp + 1;
tm->tm_sec = strtol(str, &cp, 10);
if (*cp == '\0')
*fsec = 0;
else if (*cp == '.')
{
#ifdef HAVE_INT64_TIMESTAMP
char fstr[7];
int i;
cp++;
/*
* OK, we have at most six digits to care about. Let's construct a
* string with those digits, zero-padded on the right, and then do
* the conversion to an integer.
*
* XXX This truncates the seventh digit, unlike rounding it as do
* the backend and the !HAVE_INT64_TIMESTAMP case.
*/
for (i = 0; i < 6; i++)
fstr[i] = *cp != '\0' ? *cp++ : '0';
fstr[i] = '\0';
*fsec = strtol(fstr, &cp, 10);
#else
str = cp;
*fsec = strtod(str, &cp);
#endif
if (*cp != '\0')
return -1;
}
else
return -1;
}
/* do a sanity check */
#ifdef HAVE_INT64_TIMESTAMP
if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= USECS_PER_SEC)
return -1;
#else
if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= 1)
return -1;
#endif
return 0;
} /* DecodeTime() */
/* DecodeTimezone()
* Interpret string as a numeric timezone.
*
* Note: we allow timezone offsets up to 13:59. There are places that
* use +1300 summer time.
*/
static int
DecodeTimezone(char *str, int *tzp)
{
int tz;
int hr,
min;
char *cp;
int len;
/* assume leading character is "+" or "-" */
hr = strtol(str + 1, &cp, 10);
/* explicit delimiter? */
if (*cp == ':')
min = strtol(cp + 1, &cp, 10);
/* otherwise, might have run things together... */
else if (*cp == '\0' && (len = strlen(str)) > 3)
{
min = strtol(str + len - 2, &cp, 10);
if (min < 0 || min >= 60)
return -1;
*(str + len - 2) = '\0';
hr = strtol(str + 1, &cp, 10);
if (hr < 0 || hr > 13)
return -1;
}
else
min = 0;
tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE;
if (*str == '-')
tz = -tz;
*tzp = -tz;
return *cp != '\0';
} /* DecodeTimezone() */
/* DecodePosixTimezone()
* Interpret string as a POSIX-compatible timezone:
* PST-hh:mm
* PST+h
* - thomas 2000-03-15
*/
static int
DecodePosixTimezone(char *str, int *tzp)
{
int val,
tz;
int type;
char *cp;
char delim;
cp = str;
while (*cp != '\0' && isalpha((unsigned char) *cp))
cp++;
if (DecodeTimezone(cp, &tz) != 0)
return -1;
delim = *cp;
*cp = '\0';
type = DecodeSpecial(MAXDATEFIELDS - 1, str, &val);
*cp = delim;
switch (type)
{
case DTZ:
case TZ:
*tzp = (val * MINS_PER_HOUR) - tz;
break;
default:
return -1;
}
return 0;
} /* DecodePosixTimezone() */
/* ParseDateTime()
* Break string into tokens based on a date/time context.
* Several field types are assigned:
* DTK_NUMBER - digits and (possibly) a decimal point
* DTK_DATE - digits and two delimiters, or digits and text
* DTK_TIME - digits, colon delimiters, and possibly a decimal point
* DTK_STRING - text (no digits)
* DTK_SPECIAL - leading "+" or "-" followed by text
* DTK_TZ - leading "+" or "-" followed by digits
* Note that some field types can hold unexpected items:
* DTK_NUMBER can hold date fields (yy.ddd)
* DTK_STRING can hold months (January) and time zones (PST)
* DTK_DATE can hold Posix time zones (GMT-8)
*
* The "lowstr" work buffer must have at least strlen(timestr) + MAXDATEFIELDS
* bytes of space. On output, field[] entries will point into it.
*/
int
ParseDateTime(char *timestr, char *lowstr,
char **field, int *ftype, int *numfields, char **endstr)
{
int nf = 0;
char *lp = lowstr;
*endstr = timestr;
/* outer loop through fields */
while (*(*endstr) != '\0')
{
/* Record start of current field */
field[nf] = lp;
if (nf >= MAXDATEFIELDS)
return -1;
/* leading digit? then date or time */
if (isdigit((unsigned char) *(*endstr)))
{
*lp++ = *(*endstr)++;
while (isdigit((unsigned char) *(*endstr)))
*lp++ = *(*endstr)++;
/* time field? */
if (*(*endstr) == ':')
{
ftype[nf] = DTK_TIME;
*lp++ = *(*endstr)++;
while (isdigit((unsigned char) *(*endstr)) ||
(*(*endstr) == ':') || (*(*endstr) == '.'))
*lp++ = *(*endstr)++;
}
/* date field? allow embedded text month */
else if (*(*endstr) == '-' || *(*endstr) == '/' || *(*endstr) == '.')
{
/* save delimiting character to use later */
char *dp = (*endstr);
*lp++ = *(*endstr)++;
/* second field is all digits? then no embedded text month */
if (isdigit((unsigned char) *(*endstr)))
{
ftype[nf] = (*dp == '.') ? DTK_NUMBER : DTK_DATE;
while (isdigit((unsigned char) *(*endstr)))
*lp++ = *(*endstr)++;
/*
* insist that the delimiters match to get a three-field
* date.
*/
if (*(*endstr) == *dp)
{
ftype[nf] = DTK_DATE;
*lp++ = *(*endstr)++;
while (isdigit((unsigned char) *(*endstr)) || (*(*endstr) == *dp))
*lp++ = *(*endstr)++;
}
}
else
{
ftype[nf] = DTK_DATE;
while (isalnum((unsigned char) *(*endstr)) || (*(*endstr) == *dp))
*lp++ = pg_tolower((unsigned char) *(*endstr)++);
}
}
/*
* otherwise, number only and will determine year, month, day, or
* concatenated fields later...
*/
else
ftype[nf] = DTK_NUMBER;
}
/* Leading decimal point? Then fractional seconds... */
else if (*(*endstr) == '.')
{
*lp++ = *(*endstr)++;
while (isdigit((unsigned char) *(*endstr)))
*lp++ = *(*endstr)++;
ftype[nf] = DTK_NUMBER;
}
/*
* text? then date string, month, day of week, special, or timezone
*/
else if (isalpha((unsigned char) *(*endstr)))
{
ftype[nf] = DTK_STRING;
*lp++ = pg_tolower((unsigned char) *(*endstr)++);
while (isalpha((unsigned char) *(*endstr)))
*lp++ = pg_tolower((unsigned char) *(*endstr)++);
/*
* Full date string with leading text month? Could also be a POSIX
* time zone...
*/
if (*(*endstr) == '-' || *(*endstr) == '/' || *(*endstr) == '.')
{
char *dp = (*endstr);
ftype[nf] = DTK_DATE;
*lp++ = *(*endstr)++;
while (isdigit((unsigned char) *(*endstr)) || *(*endstr) == *dp)
*lp++ = *(*endstr)++;
}
}
/* skip leading spaces */
else if (isspace((unsigned char) *(*endstr)))
{
(*endstr)++;
continue;
}
/* sign? then special or numeric timezone */
else if (*(*endstr) == '+' || *(*endstr) == '-')
{
*lp++ = *(*endstr)++;
/* soak up leading whitespace */
while (isspace((unsigned char) *(*endstr)))
(*endstr)++;
/* numeric timezone? */
if (isdigit((unsigned char) *(*endstr)))
{
ftype[nf] = DTK_TZ;
*lp++ = *(*endstr)++;
while (isdigit((unsigned char) *(*endstr)) ||
(*(*endstr) == ':') || (*(*endstr) == '.'))
*lp++ = *(*endstr)++;
}
/* special? */
else if (isalpha((unsigned char) *(*endstr)))
{
ftype[nf] = DTK_SPECIAL;
*lp++ = pg_tolower((unsigned char) *(*endstr)++);
while (isalpha((unsigned char) *(*endstr)))
*lp++ = pg_tolower((unsigned char) *(*endstr)++);
}
/* otherwise something wrong... */
else
return -1;
}
/* ignore punctuation but use as delimiter */
else if (ispunct((unsigned char) *(*endstr)))
{
(*endstr)++;
continue;
}
/* otherwise, something is not right... */
else
return -1;
/* force in a delimiter after each field */
*lp++ = '\0';
nf++;
}
*numfields = nf;
return 0;
} /* ParseDateTime() */
/* DecodeDateTime()
* Interpret previously parsed fields for general date and time.
* Return 0 if full date, 1 if only time, and -1 if problems.
* External format(s):
* "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
* "Fri Feb-7-1997 15:23:27"
* "Feb-7-1997 15:23:27"
* "2-7-1997 15:23:27"
* "1997-2-7 15:23:27"
* "1997.038 15:23:27" (day of year 1-366)
* Also supports input in compact time:
* "970207 152327"
* "97038 152327"
* "20011225T040506.789-07"
*
* Use the system-provided functions to get the current time zone
* if not specified in the input string.
* If the date is outside the time_t system-supported time range,
* then assume UTC time zone. - thomas 1997-05-27
*/
int
DecodeDateTime(char **field, int *ftype, int nf,
int *dtype, struct tm * tm, fsec_t *fsec, bool EuroDates)
{
int fmask = 0,
tmask,
type;
int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
int i;
int val;
int mer = HR24;
int haveTextMonth = FALSE;
int is2digits = FALSE;
int bc = FALSE;
int t = 0;
int *tzp = &t;
/***
* We'll insist on at least all of the date fields, but initialize the
* remaining fields in case they are not set later...
***/
*dtype = DTK_DATE;
tm->tm_hour = 0;
tm->tm_min = 0;
tm->tm_sec = 0;
*fsec = 0;
/* don't know daylight savings time status apriori */
tm->tm_isdst = -1;
if (tzp != NULL)
*tzp = 0;
for (i = 0; i < nf; i++)
{
switch (ftype[i])
{
case DTK_DATE:
/***
* Integral julian day with attached time zone?
* All other forms with JD will be separated into
* distinct fields, so we handle just this case here.
***/
if (ptype == DTK_JULIAN)
{
char *cp;
int val;
if (tzp == NULL)
return -1;
val = strtol(field[i], &cp, 10);
if (*cp != '-')
return -1;
j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
/* Get the time zone from the end of the string */
if (DecodeTimezone(cp, tzp) != 0)
return -1;
tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
ptype = 0;
break;
}
/***
* Already have a date? Then this might be a POSIX time
* zone with an embedded dash (e.g. "PST-3" == "EST") or
* a run-together time with trailing time zone (e.g. hhmmss-zz).
* - thomas 2001-12-25
***/
else if (((fmask & DTK_DATE_M) == DTK_DATE_M)
|| (ptype != 0))
{
/* No time zone accepted? Then quit... */
if (tzp == NULL)
return -1;
if (isdigit((unsigned char) *field[i]) || ptype != 0)
{
char *cp;
if (ptype != 0)
{
/* Sanity check; should not fail this test */
if (ptype != DTK_TIME)
return -1;
ptype = 0;
}
/*
* Starts with a digit but we already have a time
* field? Then we are in trouble with a date and time
* already...
*/
if ((fmask & DTK_TIME_M) == DTK_TIME_M)
return -1;
if ((cp = strchr(field[i], '-')) == NULL)
return -1;
/* Get the time zone from the end of the string */
if (DecodeTimezone(cp, tzp) != 0)
return -1;
*cp = '\0';
/*
* Then read the rest of the field as a concatenated
* time
*/
if ((ftype[i] = DecodeNumberField(strlen(field[i]), field[i], fmask,
&tmask, tm, fsec, &is2digits)) < 0)
return -1;
/*
* modify tmask after returning from
* DecodeNumberField()
*/
tmask |= DTK_M(TZ);
}
else
{
if (DecodePosixTimezone(field[i], tzp) != 0)
return -1;
ftype[i] = DTK_TZ;
tmask = DTK_M(TZ);
}
}
else if (DecodeDate(field[i], fmask, &tmask, tm, EuroDates) != 0)
return -1;
break;
case DTK_TIME:
if (DecodeTime(field[i], &tmask, tm, fsec) != 0)
return -1;
/*
* Check upper limit on hours; other limits checked in
* DecodeTime()
*/
/* test for > 24:00:00 */
if (tm->tm_hour > 24 ||
(tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0)))
return -1;
break;
case DTK_TZ:
{
int tz;
if (tzp == NULL)
return -1;
if (DecodeTimezone(field[i], &tz) != 0)
return -1;
/*
* Already have a time zone? Then maybe this is the second
* field of a POSIX time: EST+3 (equivalent to PST)
*/
if (i > 0 && (fmask & DTK_M(TZ)) != 0 &&
ftype[i - 1] == DTK_TZ &&
isalpha((unsigned char) *field[i - 1]))
{
*tzp -= tz;
tmask = 0;
}
else
{
*tzp = tz;
tmask = DTK_M(TZ);
}
}
break;
case DTK_NUMBER:
/*
* Was this an "ISO date" with embedded field labels? An
* example is "y2001m02d04" - thomas 2001-02-04
*/
if (ptype != 0)
{
char *cp;
int val;
val = strtol(field[i], &cp, 10);
/*
* only a few kinds are allowed to have an embedded
* decimal
*/
if (*cp == '.')
switch (ptype)
{
case DTK_JULIAN:
case DTK_TIME:
case DTK_SECOND:
break;
default:
return 1;
break;
}
else if (*cp != '\0')
return -1;
switch (ptype)
{
case DTK_YEAR:
tm->tm_year = val;
tmask = DTK_M(YEAR);
break;
case DTK_MONTH:
/*
* already have a month and hour? then assume
* minutes
*/
if ((fmask & DTK_M(MONTH)) != 0 &&
(fmask & DTK_M(HOUR)) != 0)
{
tm->tm_min = val;
tmask = DTK_M(MINUTE);
}
else
{
tm->tm_mon = val;
tmask = DTK_M(MONTH);
}
break;
case DTK_DAY:
tm->tm_mday = val;
tmask = DTK_M(DAY);
break;
case DTK_HOUR:
tm->tm_hour = val;
tmask = DTK_M(HOUR);
break;
case DTK_MINUTE:
tm->tm_min = val;
tmask = DTK_M(MINUTE);
break;
case DTK_SECOND:
tm->tm_sec = val;
tmask = DTK_M(SECOND);
if (*cp == '.')
{
double frac;
frac = strtod(cp, &cp);
if (*cp != '\0')
return -1;
#ifdef HAVE_INT64_TIMESTAMP
*fsec = frac * 1000000;
#else
*fsec = frac;
#endif
}
break;
case DTK_TZ:
tmask = DTK_M(TZ);
if (DecodeTimezone(field[i], tzp) != 0)
return -1;
break;
case DTK_JULIAN:
/***
* previous field was a label for "julian date"?
***/
tmask = DTK_DATE_M;
j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
/* fractional Julian Day? */
if (*cp == '.')
{
double time;
time = strtod(cp, &cp);
if (*cp != '\0')
return -1;
tmask |= DTK_TIME_M;
#ifdef HAVE_INT64_TIMESTAMP
dt2time((time * USECS_PER_DAY), &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
#else
dt2time((time * SECS_PER_DAY), &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
#endif
}
break;
case DTK_TIME:
/* previous field was "t" for ISO time */
if ((ftype[i] = DecodeNumberField(strlen(field[i]), field[i], (fmask | DTK_DATE_M),
&tmask, tm, fsec, &is2digits)) < 0)
return -1;
if (tmask != DTK_TIME_M)
return -1;
break;
default:
return -1;
break;
}
ptype = 0;
*dtype = DTK_DATE;
}
else
{
char *cp;
int flen;
flen = strlen(field[i]);
cp = strchr(field[i], '.');
/* Embedded decimal and no date yet? */
if (cp != NULL && !(fmask & DTK_DATE_M))
{
if (DecodeDate(field[i], fmask, &tmask, tm, EuroDates) != 0)
return -1;
}
/* embedded decimal and several digits before? */
else if (cp != NULL && flen - strlen(cp) > 2)
{
/*
* Interpret as a concatenated date or time Set the
* type field to allow decoding other fields later.
* Example: 20011223 or 040506
*/
if ((ftype[i] = DecodeNumberField(flen, field[i], fmask,
&tmask, tm, fsec, &is2digits)) < 0)
return -1;
}
else if (flen > 4)
{
if ((ftype[i] = DecodeNumberField(flen, field[i], fmask,
&tmask, tm, fsec, &is2digits)) < 0)
return -1;
}
/* otherwise it is a single date/time field... */
else if (DecodeNumber(flen, field[i], fmask,
&tmask, tm, fsec, &is2digits, EuroDates) != 0)
return -1;
}
break;
case DTK_STRING:
case DTK_SPECIAL:
type = DecodeSpecial(i, field[i], &val);
if (type == IGNORE_DTF)
continue;
tmask = DTK_M(type);
switch (type)
{
case RESERV:
switch (val)
{
case DTK_NOW:
tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
*dtype = DTK_DATE;
GetCurrentDateTime(tm);
break;
case DTK_YESTERDAY:
tmask = DTK_DATE_M;
*dtype = DTK_DATE;
GetCurrentDateTime(tm);
j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1,
&tm->tm_year, &tm->tm_mon, &tm->tm_mday);
tm->tm_hour = 0;
tm->tm_min = 0;
tm->tm_sec = 0;
break;
case DTK_TODAY:
tmask = DTK_DATE_M;
*dtype = DTK_DATE;
GetCurrentDateTime(tm);
tm->tm_hour = 0;
tm->tm_min = 0;
tm->tm_sec = 0;
break;
case DTK_TOMORROW:
tmask = DTK_DATE_M;
*dtype = DTK_DATE;
GetCurrentDateTime(tm);
j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1,
&tm->tm_year, &tm->tm_mon, &tm->tm_mday);
tm->tm_hour = 0;
tm->tm_min = 0;
tm->tm_sec = 0;
break;
case DTK_ZULU:
tmask = (DTK_TIME_M | DTK_M(TZ));
*dtype = DTK_DATE;
tm->tm_hour = 0;
tm->tm_min = 0;
tm->tm_sec = 0;
if (tzp != NULL)
*tzp = 0;
break;
default:
*dtype = val;
}
break;
case MONTH:
/*
* already have a (numeric) month? then see if we can
* substitute...
*/
if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
!(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 && tm->tm_mon <= 31)
{
tm->tm_mday = tm->tm_mon;
tmask = DTK_M(DAY);
}
haveTextMonth = TRUE;
tm->tm_mon = val;
break;
case DTZMOD:
/*
* daylight savings time modifier (solves "MET DST"
* syntax)
*/
tmask |= DTK_M(DTZ);
tm->tm_isdst = 1;
if (tzp == NULL)
return -1;
*tzp += val * MINS_PER_HOUR;
break;
case DTZ:
/*
* set mask for TZ here _or_ check for DTZ later when
* getting default timezone
*/
tmask |= DTK_M(TZ);
tm->tm_isdst = 1;
if (tzp == NULL)
return -1;
*tzp = val * MINS_PER_HOUR;
ftype[i] = DTK_TZ;
break;
case TZ:
tm->tm_isdst = 0;
if (tzp == NULL)
return -1;
*tzp = val * MINS_PER_HOUR;
ftype[i] = DTK_TZ;
break;
case IGNORE_DTF:
break;
case AMPM:
mer = val;
break;
case ADBC:
bc = (val == BC);
break;
case DOW:
tm->tm_wday = val;
break;
case UNITS:
tmask = 0;
ptype = val;
break;
case ISOTIME:
/*
* This is a filler field "t" indicating that the next
* field is time. Try to verify that this is sensible.
*/
tmask = 0;
/* No preceding date? Then quit... */
if ((fmask & DTK_DATE_M) != DTK_DATE_M)
return -1;
/***
* We will need one of the following fields:
* DTK_NUMBER should be hhmmss.fff
* DTK_TIME should be hh:mm:ss.fff
* DTK_DATE should be hhmmss-zz
***/
if (i >= nf - 1 ||
(ftype[i + 1] != DTK_NUMBER &&
ftype[i + 1] != DTK_TIME &&
ftype[i + 1] != DTK_DATE))
return -1;
ptype = val;
break;
default:
return -1;
}
break;
default:
return -1;
}
if (tmask & fmask)
return -1;
fmask |= tmask;
}
/* there is no year zero in AD/BC notation; i.e. "1 BC" == year 0 */
if (bc)
{
if (tm->tm_year > 0)
tm->tm_year = -(tm->tm_year - 1);
else
return -1;
}
else if (is2digits)
{
if (tm->tm_year < 70)
tm->tm_year += 2000;
else if (tm->tm_year < 100)
tm->tm_year += 1900;
}
if (mer != HR24 && tm->tm_hour > 12)
return -1;
if (mer == AM && tm->tm_hour == 12)
tm->tm_hour = 0;
else if (mer == PM && tm->tm_hour != 12)
tm->tm_hour += 12;
/* do additional checking for full date specs... */
if (*dtype == DTK_DATE)
{
if ((fmask & DTK_DATE_M) != DTK_DATE_M)
return ((fmask & DTK_TIME_M) == DTK_TIME_M) ? 1 : -1;
/*
* check for valid day of month, now that we know for sure the month
* and year...
*/
if (tm->tm_mday < 1 || tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
return -1;
/*
* backend tried to find local timezone here but we don't use the
* result afterwards anyway so we only check for this error: daylight
* savings time modifier but no standard timezone?
*/
if ((fmask & DTK_DATE_M) == DTK_DATE_M && tzp != NULL && !(fmask & DTK_M(TZ)) && (fmask & DTK_M(DTZMOD)))
return -1;
}
return 0;
} /* DecodeDateTime() */
/* Function works as follows:
*
*
* */
static char *
find_end_token(char *str, char *fmt)
{
/*
* str: here is28the day12the hour fmt: here is%dthe day%hthe hour
*
* we extract the 28, we read the percent sign and the type "d" then this
* functions gets called as find_end_token("28the day12the hour", "the
* day%hthehour")
*
* fmt points to "the day%hthehour", next_percent points to %hthehour and
* we have to find a match for everything between these positions ("the
* day"). We look for "the day" in str and know that the pattern we are
* about to scan ends where this string starts (right after the "28")
*
* At the end, *fmt is '\0' and *str isn't. end_position then is
* unchanged.
*/
char *end_position = NULL;
char *next_percent,
*subst_location = NULL;
int scan_offset = 0;
char last_char;
/* are we at the end? */
if (!*fmt)
{
end_position = fmt;
return end_position;
}
/* not at the end */
while (fmt[scan_offset] == '%' && fmt[scan_offset + 1])
{
/*
* there is no delimiter, skip to the next delimiter if we're reading
* a number and then something that is not a number "9:15pm", we might
* be able to recover with the strtol end pointer. Go for the next
* percent sign
*/
scan_offset += 2;
}
next_percent = strchr(fmt + scan_offset, '%');
if (next_percent)
{
/*
* we don't want to allocate extra memory, so we temporarily set the
* '%' sign to '\0' and call strstr However since we allow whitespace
* to float around everything, we have to shorten the pattern until we
* reach a non-whitespace character
*/
subst_location = next_percent;
while (*(subst_location - 1) == ' ' && subst_location - 1 > fmt + scan_offset)
subst_location--;
last_char = *subst_location;
*subst_location = '\0';
/*
* the haystack is the str and the needle is the original fmt but it
* ends at the position where the next percent sign would be
*/
/*
* There is one special case. Imagine: str = " 2", fmt = "%d %...",
* since we want to allow blanks as "dynamic" padding we have to
* accept this. Now, we are called with a fmt of " %..." and look for
* " " in str. We find it at the first position and never read the
* 2...
*/
while (*str == ' ')
str++;
end_position = strstr(str, fmt + scan_offset);
*subst_location = last_char;
}
else
{
/*
* there is no other percent sign. So everything up to the end has to
* match.
*/
end_position = str + strlen(str);
}
if (!end_position)
{
/*
* maybe we have the following case:
*
* str = "4:15am" fmt = "%M:%S %p"
*
* at this place we could have
*
* str = "15am" fmt = " %p"
*
* and have set fmt to " " because overwrote the % sign with a NULL
*
* In this case where we would have to match a space but can't find
* it, set end_position to the end of the string
*/
if ((fmt + scan_offset)[0] == ' ' && fmt + scan_offset + 1 == subst_location)
end_position = str + strlen(str);
}
return end_position;
}
static int
pgtypes_defmt_scan(union un_fmt_comb * scan_val, int scan_type, char **pstr, char *pfmt)
{
/*
* scan everything between pstr and pstr_end. This is not including the
* last character so we might set it to '\0' for the parsing
*/
char last_char;
int err = 0;
char *pstr_end;
char *strtol_end = NULL;
while (**pstr == ' ')
pstr++;
pstr_end = find_end_token(*pstr, pfmt);
if (!pstr_end)
{
/* there was an error, no match */
return 1;
}
last_char = *pstr_end;
*pstr_end = '\0';
switch (scan_type)
{
case PGTYPES_TYPE_UINT:
/*
* numbers may be blank-padded, this is the only deviation from
* the fmt-string we accept
*/
while (**pstr == ' ')
(*pstr)++;
errno = 0;
scan_val->uint_val = (unsigned int) strtol(*pstr, &strtol_end, 10);
if (errno)
err = 1;
break;
case PGTYPES_TYPE_UINT_LONG:
while (**pstr == ' ')
(*pstr)++;
errno = 0;
scan_val->luint_val = (unsigned long int) strtol(*pstr, &strtol_end, 10);
if (errno)
err = 1;
break;
case PGTYPES_TYPE_STRING_MALLOCED:
scan_val->str_val = pgtypes_strdup(*pstr);
if (scan_val->str_val == NULL)
err = 1;
break;
}
if (strtol_end && *strtol_end)
*pstr = strtol_end;
else
*pstr = pstr_end;
*pstr_end = last_char;
return err;
}
/* XXX range checking */
int
PGTYPEStimestamp_defmt_scan(char **str, char *fmt, timestamp * d,
int *year, int *month, int *day,
int *hour, int *minute, int *second,
int *tz)
{
union un_fmt_comb scan_val;
int scan_type;
char *pstr,
*pfmt,
*tmp;
int err = 1;
unsigned int j;
struct tm tm;
pfmt = fmt;
pstr = *str;
while (*pfmt)
{
err = 0;
while (*pfmt == ' ')
pfmt++;
while (*pstr == ' ')
pstr++;
if (*pfmt != '%')
{
if (*pfmt == *pstr)
{
pfmt++;
pstr++;
}
else
{
/* Error: no match */
err = 1;
return err;
}
continue;
}
/* here *pfmt equals '%' */
pfmt++;
switch (*pfmt)
{
case 'a':
pfmt++;
/*
* we parse the day and see if it is a week day but we do not
* check if the week day really matches the date
*/
err = 1;
j = 0;
while (pgtypes_date_weekdays_short[j])
{
if (strncmp(pgtypes_date_weekdays_short[j], pstr,
strlen(pgtypes_date_weekdays_short[j])) == 0)
{
/* found it */
err = 0;
pstr += strlen(pgtypes_date_weekdays_short[j]);
break;
}
j++;
}
break;
case 'A':
/* see note above */
pfmt++;
err = 1;
j = 0;
while (days[j])
{
if (strncmp(days[j], pstr, strlen(days[j])) == 0)
{
/* found it */
err = 0;
pstr += strlen(days[j]);
break;
}
j++;
}
break;
case 'b':
case 'h':
pfmt++;
err = 1;
j = 0;
while (months[j])
{
if (strncmp(months[j], pstr, strlen(months[j])) == 0)
{
/* found it */
err = 0;
pstr += strlen(months[j]);
*month = j + 1;
break;
}
j++;
}
break;
case 'B':
/* see note above */
pfmt++;
err = 1;
j = 0;
while (pgtypes_date_months[j])
{
if (strncmp(pgtypes_date_months[j], pstr, strlen(pgtypes_date_months[j])) == 0)
{
/* found it */
err = 0;
pstr += strlen(pgtypes_date_months[j]);
*month = j + 1;
break;
}
j++;
}
break;
case 'c':
/* XXX */
break;
case 'C':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
*year = scan_val.uint_val * 100;
break;
case 'd':
case 'e':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
*day = scan_val.uint_val;
break;
case 'D':
/*
* we have to concatenate the strings in order to be able to
* find the end of the substitution
*/
pfmt++;
tmp = pgtypes_alloc(strlen("%m/%d/%y") + strlen(pstr) + 1);
strcpy(tmp, "%m/%d/%y");
strcat(tmp, pfmt);
err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
free(tmp);
return err;
case 'm':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
*month = scan_val.uint_val;
break;
case 'y':
case 'g': /* XXX difference to y (ISO) */
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
if (*year < 0)
{
/* not yet set */
*year = scan_val.uint_val;
}
else
*year += scan_val.uint_val;
if (*year < 100)
*year += 1900;
break;
case 'G':
/* XXX difference to %V (ISO) */
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
*year = scan_val.uint_val;
break;
case 'H':
case 'I':
case 'k':
case 'l':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
*hour += scan_val.uint_val;
break;
case 'j':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
/*
* XXX what should we do with that? We could say that it's
* sufficient if we have the year and the day within the year
* to get at least a specific day.
*/
break;
case 'M':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
*minute = scan_val.uint_val;
break;
case 'n':
pfmt++;
if (*pstr == '\n')
pstr++;
else
err = 1;
break;
case 'p':
err = 1;
pfmt++;
if (strncmp(pstr, "am", 2) == 0)
{
*hour += 0;
err = 0;
pstr += 2;
}
if (strncmp(pstr, "a.m.", 4) == 0)
{
*hour += 0;
err = 0;
pstr += 4;
}
if (strncmp(pstr, "pm", 2) == 0)
{
*hour += 12;
err = 0;
pstr += 2;
}
if (strncmp(pstr, "p.m.", 4) == 0)
{
*hour += 12;
err = 0;
pstr += 4;
}
break;
case 'P':
err = 1;
pfmt++;
if (strncmp(pstr, "AM", 2) == 0)
{
*hour += 0;
err = 0;
pstr += 2;
}
if (strncmp(pstr, "A.M.", 4) == 0)
{
*hour += 0;
err = 0;
pstr += 4;
}
if (strncmp(pstr, "PM", 2) == 0)
{
*hour += 12;
err = 0;
pstr += 2;
}
if (strncmp(pstr, "P.M.", 4) == 0)
{
*hour += 12;
err = 0;
pstr += 4;
}
break;
case 'r':
pfmt++;
tmp = pgtypes_alloc(strlen("%I:%M:%S %p") + strlen(pstr) + 1);
strcpy(tmp, "%I:%M:%S %p");
strcat(tmp, pfmt);
err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
free(tmp);
return err;
case 'R':
pfmt++;
tmp = pgtypes_alloc(strlen("%H:%M") + strlen(pstr) + 1);
strcpy(tmp, "%H:%M");
strcat(tmp, pfmt);
err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
free(tmp);
return err;
case 's':
pfmt++;
scan_type = PGTYPES_TYPE_UINT_LONG;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
/* number of seconds in scan_val.luint_val */
{
struct tm *tms;
time_t et = (time_t) scan_val.luint_val;
tms = gmtime(&et);
if (tms)
{
*year = tms->tm_year + 1900;
*month = tms->tm_mon + 1;
*day = tms->tm_mday;
*hour = tms->tm_hour;
*minute = tms->tm_min;
*second = tms->tm_sec;
}
else
err = 1;
}
break;
case 'S':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
*second = scan_val.uint_val;
break;
case 't':
pfmt++;
if (*pstr == '\t')
pstr++;
else
err = 1;
break;
case 'T':
pfmt++;
tmp = pgtypes_alloc(strlen("%H:%M:%S") + strlen(pstr) + 1);
strcpy(tmp, "%H:%M:%S");
strcat(tmp, pfmt);
err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
free(tmp);
return err;
case 'u':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
if (scan_val.uint_val < 1 || scan_val.uint_val > 7)
err = 1;
break;
case 'U':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
if (scan_val.uint_val > 53)
err = 1;
break;
case 'V':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
if (scan_val.uint_val < 1 || scan_val.uint_val > 53)
err = 1;
break;
case 'w':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
if (scan_val.uint_val > 6)
err = 1;
break;
case 'W':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
if (scan_val.uint_val > 53)
err = 1;
break;
case 'x':
case 'X':
/* XXX */
break;
case 'Y':
pfmt++;
scan_type = PGTYPES_TYPE_UINT;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
*year = scan_val.uint_val;
break;
case 'z':
pfmt++;
scan_type = PGTYPES_TYPE_STRING_MALLOCED;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
if (!err)
{
err = DecodeTimezone(scan_val.str_val, tz);
free(scan_val.str_val);
}
break;
case 'Z':
pfmt++;
scan_type = PGTYPES_TYPE_STRING_MALLOCED;
err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
/*
* XXX use DecodeSpecial instead ? - it's declared static but
* the arrays as well. :-(
*/
for (j = 0; !err && j < szdatetktbl; j++)
{
if (pg_strcasecmp(datetktbl[j].token, scan_val.str_val) == 0)
{
/*
* tz calculates the offset for the seconds, the
* timezone value of the datetktbl table is in quarter
* hours
*/
*tz = -15 * MINS_PER_HOUR * datetktbl[j].value;
break;
}
}
free(scan_val.str_val);
break;
case '+':
/* XXX */
break;
case '%':
pfmt++;
if (*pstr == '%')
pstr++;
else
err = 1;
break;
default:
err = 1;
}
}
if (!err)
{
if (*second < 0)
*second = 0;
if (*minute < 0)
*minute = 0;
if (*hour < 0)
*hour = 0;
if (*day < 0)
{
err = 1;
*day = 1;
}
if (*month < 0)
{
err = 1;
*month = 1;
}
if (*year < 0)
{
err = 1;
*year = 1970;
}
if (*second > 59)
{
err = 1;
*second = 0;
}
if (*minute > 59)
{
err = 1;
*minute = 0;
}
if (*hour > 24 || /* test for > 24:00:00 */
(*hour == 24 && (*minute > 0 || *second > 0)))
{
err = 1;
*hour = 0;
}
if (*month > MONTHS_PER_YEAR)
{
err = 1;
*month = 1;
}
if (*day > day_tab[isleap(*year)][*month - 1])
{
*day = day_tab[isleap(*year)][*month - 1];
err = 1;
}
tm.tm_sec = *second;
tm.tm_min = *minute;
tm.tm_hour = *hour;
tm.tm_mday = *day;
tm.tm_mon = *month;
tm.tm_year = *year;
tm2timestamp(&tm, 0, tz, d);
}
return err;
}
/* XXX: 1900 is compiled in as the base for years */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2019_3 |
crossvul-cpp_data_good_344_6 | /*
* pkcs15-sc-hsm.c : Initialize PKCS#15 emulation
*
* Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "internal.h"
#include "pkcs15.h"
#include "asn1.h"
#include "common/compat_strlcpy.h"
#include "common/compat_strnlen.h"
#include "card-sc-hsm.h"
extern struct sc_aid sc_hsm_aid;
void sc_hsm_set_serialnr(sc_card_t *card, char *serial);
static struct ec_curve curves[] = {
{
{ (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24},
{ (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24},
{ (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32},
{ (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32},
{ (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1
{ (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24},
{ (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24},
{ (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24},
{ (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49},
{ (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1
{ (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28},
{ (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28},
{ (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28},
{ (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57},
{ (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1
{ (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32},
{ (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32},
{ (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32},
{ (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65},
{ (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1
{ (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40},
{ (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40},
{ (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40},
{ (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81},
{ (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24},
{ (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32},
{ (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0}
}
};
#define C_ASN1_CVC_PUBKEY_SIZE 10
static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = {
{ "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL },
{ "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVC_BODY_SIZE 5
static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = {
{ "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL },
{ "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL },
{ "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL },
{ "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVCERT_SIZE 3
static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = {
{ "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL },
{ "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVC_SIZE 2
static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = {
{ "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_AUTHREQ_SIZE 4
static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = {
{ "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL },
{ "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL },
{ "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_REQ_SIZE 2
static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = {
{ "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2],
u8 *efbin, size_t *len, int optional)
{
sc_path_t path;
int r;
sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0);
/* look this up with our AID */
path.aid = sc_hsm_aid;
/* we don't have a pre-known size of the file */
path.count = -1;
if (!p15card->opts.use_file_cache || !efbin
|| SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) {
/* avoid re-selection of SC-HSM */
path.aid.len = 0;
r = sc_select_file(p15card->card, &path, NULL);
if (r < 0) {
sc_log(p15card->card->ctx, "Could not select EF");
} else {
r = sc_read_binary(p15card->card, 0, efbin, *len, 0);
}
if (r < 0) {
sc_log(p15card->card->ctx, "Could not read EF");
if (!optional) {
return r;
}
/* optional files are saved as empty files to avoid card
* transactions. Parsing the file's data will reveal that they were
* missing. */
*len = 0;
} else {
*len = r;
}
if (p15card->opts.use_file_cache) {
/* save this with our AID */
path.aid = sc_hsm_aid;
sc_pkcs15_cache_file(p15card, &path, efbin, *len);
}
}
return SC_SUCCESS;
}
/*
* Decode a card verifiable certificate as defined in TR-03110.
*/
int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card,
const u8 ** buf, size_t *buflen,
sc_cvc_t *cvc)
{
sc_card_t *card = p15card->card;
struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE];
struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE];
struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE];
struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE];
struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE];
struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE];
unsigned int cla,tag;
size_t taglen;
size_t lenchr = sizeof(cvc->chr);
size_t lencar = sizeof(cvc->car);
size_t lenoutercar = sizeof(cvc->outer_car);
const u8 *tbuf;
int r;
memset(cvc, 0, sizeof(*cvc));
sc_copy_asn1_entry(c_asn1_req, asn1_req);
sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq);
sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc);
sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert);
sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body);
sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey);
sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0);
sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0);
sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0);
sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0);
sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0);
sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0);
sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0);
sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0);
sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0);
/* sc_asn1_print_tags(*buf, *buflen); */
tbuf = *buf;
r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen);
LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate");
/* Determine if we deal with an authenticated request, plain request or certificate */
if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) {
r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen);
} else {
r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen);
}
LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/*
* Encode a card verifiable certificate as defined in TR-03110.
*/
int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card,
sc_cvc_t *cvc,
u8 ** buf, size_t *buflen)
{
sc_card_t *card = p15card->card;
struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE];
struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE];
struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE];
struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE];
size_t lenchr;
size_t lencar;
int r;
sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc);
sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert);
sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body);
sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey);
asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL;
asn1_cvcert[1].flags = SC_ASN1_OPTIONAL;
sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1);
if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1);
}
sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1);
if (cvc->coefficientB && (cvc->coefficientBlen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1);
sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1);
sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1);
if (cvc->publicPoint && (cvc->publicPointlen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1);
}
sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1);
}
if (cvc->modulusSize > 0) {
sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1);
}
sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1);
lencar = strnlen(cvc->car, sizeof cvc->car);
sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1);
sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1);
lenchr = strnlen(cvc->chr, sizeof cvc->chr);
sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1);
sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1);
if (cvc->signature && (cvc->signatureLen > 0)) {
sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1);
}
sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1);
r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen);
LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen)
{
int i;
for (i = 0; curves[i].oid.value; i++) {
if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) {
*curve = &curves[i];
return SC_SUCCESS;
}
}
return SC_ERROR_INVALID_DATA;
}
int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid)
{
int i;
for (i = 0; curves[i].oid.value; i++) {
if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) {
*oid = &curves[i].oid;
return SC_SUCCESS;
}
}
return SC_ERROR_INVALID_DATA;
}
static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
pubkey->algorithm = SC_ALGORITHM_RSA;
pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id));
if (!pubkey->alg_id)
return SC_ERROR_OUT_OF_MEMORY;
pubkey->alg_id->algorithm = SC_ALGORITHM_RSA;
pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen;
pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len);
pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen;
pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len);
if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len);
memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len);
return SC_SUCCESS;
}
static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
struct sc_ec_parameters *ecp;
const struct sc_lv_data *oid;
int r;
pubkey->algorithm = SC_ALGORITHM_EC;
r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid);
if (r != SC_SUCCESS)
return r;
ecp = calloc(1, sizeof(struct sc_ec_parameters));
if (!ecp)
return SC_ERROR_OUT_OF_MEMORY;
ecp->der.len = oid->len + 2;
ecp->der.value = calloc(ecp->der.len, 1);
if (!ecp->der.value) {
free(ecp);
return SC_ERROR_OUT_OF_MEMORY;
}
*(ecp->der.value + 0) = 0x06;
*(ecp->der.value + 1) = (u8)oid->len;
memcpy(ecp->der.value + 2, oid->value, oid->len);
ecp->type = 1; // Named curve
pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id));
if (!pubkey->alg_id) {
free(ecp->der.value);
free(ecp);
return SC_ERROR_OUT_OF_MEMORY;
}
pubkey->alg_id->algorithm = SC_ALGORITHM_EC;
pubkey->alg_id->params = ecp;
pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen);
if (!pubkey->u.ec.ecpointQ.value)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen);
pubkey->u.ec.ecpointQ.len = cvc->publicPointlen;
pubkey->u.ec.params.der.value = malloc(ecp->der.len);
if (!pubkey->u.ec.params.der.value)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len);
pubkey->u.ec.params.der.len = ecp->der.len;
/* FIXME: check return value? */
sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params);
return SC_SUCCESS;
}
int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
if (cvc->publicPoint && cvc->publicPointlen) {
return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey);
} else {
return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey);
}
}
void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc)
{
if (cvc->signature) {
free(cvc->signature);
cvc->signature = NULL;
}
if (cvc->primeOrModulus) {
free(cvc->primeOrModulus);
cvc->primeOrModulus = NULL;
}
if (cvc->coefficientAorExponent) {
free(cvc->coefficientAorExponent);
cvc->coefficientAorExponent = NULL;
}
if (cvc->coefficientB) {
free(cvc->coefficientB);
cvc->coefficientB = NULL;
}
if (cvc->basePointG) {
free(cvc->basePointG);
cvc->basePointG = NULL;
}
if (cvc->order) {
free(cvc->order);
cvc->order = NULL;
}
if (cvc->publicPoint) {
free(cvc->publicPoint);
cvc->publicPoint = NULL;
}
if (cvc->cofactor) {
free(cvc->cofactor);
cvc->cofactor = NULL;
}
}
static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label)
{
struct sc_context *ctx = p15card->card->ctx;
sc_card_t *card = p15card->card;
sc_pkcs15_pubkey_info_t pubkey_info;
sc_pkcs15_object_t pubkey_obj;
struct sc_pkcs15_pubkey pubkey;
sc_cvc_t cvc;
u8 *cvcpo;
int r;
cvcpo = efbin;
memset(&cvc, 0, sizeof(cvc));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc);
LOG_TEST_RET(ctx, r, "Could decode certificate signing request");
memset(&pubkey, 0, sizeof(pubkey));
r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey);
LOG_TEST_RET(card->ctx, r, "Could not extract public key");
memset(&pubkey_info, 0, sizeof(pubkey_info));
memset(&pubkey_obj, 0, sizeof(pubkey_obj));
r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
pubkey_info.id = key_info->id;
strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label));
if (pubkey.algorithm == SC_ALGORITHM_RSA) {
pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3;
pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP;
r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info);
} else {
/* TODO fix if support of non multiple of 8 curves are added */
pubkey_info.field_length = cvc.primeOrModuluslen << 3;
pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY;
r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info);
}
LOG_TEST_RET(ctx, r, "Could not add public key");
sc_pkcs15emu_sc_hsm_free_cvc(&cvc);
sc_pkcs15_erase_pubkey(&pubkey);
return SC_SUCCESS;
}
/*
* Add a key and the key description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) {
sc_card_t *card = p15card->card;
sc_pkcs15_cert_info_t cert_info;
sc_pkcs15_object_t cert_obj;
struct sc_pkcs15_object prkd;
sc_pkcs15_prkey_info_t *key_info;
u8 fid[2];
/* enough to hold a complete certificate */
u8 efbin[4096];
u8 *ptr;
size_t len;
int r;
fid[0] = PRKD_PREFIX;
fid[1] = keyid;
/* Try to select a related EF containing the PKCS#15 description of the key */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD");
ptr = efbin;
memset(&prkd, 0, sizeof(prkd));
r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD");
/* All keys require user PIN authentication */
prkd.auth_id.len = 1;
prkd.auth_id.value[0] = 1;
/*
* Set private key flag as all keys are private anyway
*/
prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE;
key_info = (sc_pkcs15_prkey_info_t *)prkd.data;
key_info->key_reference = keyid;
key_info->path.aid.len = 0;
if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) {
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info);
} else {
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info);
}
LOG_TEST_RET(card->ctx, r, "Could not add private key to framework");
/* Check if we also have a certificate for the private key */
fid[0] = EE_CERTIFICATE_PREFIX;
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 0);
LOG_TEST_RET(card->ctx, r, "Could not read EF");
if (efbin[0] == 0x67) { /* Decode CSR and create public key object */
sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label);
free(key_info);
return SC_SUCCESS; /* Ignore any errors */
}
if (efbin[0] != 0x30) {
free(key_info);
return SC_SUCCESS;
}
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id = key_info->id;
sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0);
cert_info.path.count = -1;
if (p15card->opts.use_file_cache) {
/* look this up with our AID, which should already be cached from the
* call to `read_file`. This may have the side effect that OpenSC's
* caching layer re-selects our applet *if the cached file cannot be
* found/used* and we may loose the authentication status. We assume
* that caching works perfectly without this side effect. */
cert_info.path.aid = sc_hsm_aid;
}
strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
free(key_info);
LOG_TEST_RET(card->ctx, r, "Could not add certificate");
return SC_SUCCESS;
}
/*
* Add a data object and description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) {
sc_card_t *card = p15card->card;
sc_pkcs15_data_info_t *data_info;
sc_pkcs15_object_t data_obj;
u8 fid[2];
u8 efbin[512];
const u8 *ptr;
size_t len;
int r;
fid[0] = DCOD_PREFIX;
fid[1] = id;
/* Try to select a related EF containing the PKCS#15 description of the data */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD");
ptr = efbin;
memset(&data_obj, 0, sizeof(data_obj));
r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len);
LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD");
data_info = (sc_pkcs15_data_info_t *)data_obj.data;
r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info);
LOG_TEST_RET(card->ctx, r, "Could not add data object to framework");
return SC_SUCCESS;
}
/*
* Add a unrelated certificate object and description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) {
sc_card_t *card = p15card->card;
sc_pkcs15_cert_info_t *cert_info;
sc_pkcs15_object_t obj;
u8 fid[2];
u8 efbin[512];
const u8 *ptr;
size_t len;
int r;
fid[0] = CD_PREFIX;
fid[1] = id;
/* Try to select a related EF containing the PKCS#15 description of the data */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD");
ptr = efbin;
memset(&obj, 0, sizeof(obj));
r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD");
cert_info = (sc_pkcs15_cert_info_t *)obj.data;
r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info);
LOG_TEST_RET(card->ctx, r, "Could not add data object to framework");
return SC_SUCCESS;
}
static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
int r;
u8 efbin[512];
size_t len;
LOG_FUNC_CALLED(card->ctx);
/* Read token info */
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo");
r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/*
* Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects
*
*/
static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data;
sc_file_t *file = NULL;
sc_path_t path;
u8 filelist[MAX_EXT_APDU_LENGTH];
int filelistlength;
int r, i;
sc_cvc_t devcert;
struct sc_app_info *appinfo;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
struct sc_pin_cmd_data pindata;
u8 efbin[1024];
u8 *ptr;
size_t len;
LOG_FUNC_CALLED(card->ctx);
appinfo = calloc(1, sizeof(struct sc_app_info));
if (appinfo == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->aid = sc_hsm_aid;
appinfo->ddo.aid = sc_hsm_aid;
p15card->app = appinfo;
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0);
r = sc_select_file(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application");
p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */
p15card->card->version.hw_minor = 13;
if (file && file->prop_attr && file->prop_attr_len >= 2) {
p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2];
p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1];
}
sc_file_free(file);
/* Read device certificate to determine serial number */
if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) {
ptr = priv->EF_C_DevAut;
len = priv->EF_C_DevAut_len;
} else {
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut");
if (len > 0) {
/* save EF_C_DevAut for further use */
ptr = realloc(priv->EF_C_DevAut, len);
if (ptr) {
memcpy(ptr, efbin, len);
priv->EF_C_DevAut = ptr;
priv->EF_C_DevAut_len = len;
}
}
ptr = efbin;
}
memset(&devcert, 0 ,sizeof(devcert));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert);
LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut");
sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card);
if (p15card->tokeninfo->label == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->label = strdup("GoID");
} else {
p15card->tokeninfo->label = strdup("SmartCard-HSM");
}
if (p15card->tokeninfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) {
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = NULL;
}
if (p15card->tokeninfo->manufacturer_id == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH");
} else {
p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de");
}
if (p15card->tokeninfo->manufacturer_id == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->label = strdup(p15card->tokeninfo->label);
if (appinfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */
assert(len >= 8);
len -= 5;
p15card->tokeninfo->serial_number = calloc(len + 1, 1);
if (p15card->tokeninfo->serial_number == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(p15card->tokeninfo->serial_number, devcert.chr, len);
*(p15card->tokeninfo->serial_number + len) = 0;
sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number);
sc_pkcs15emu_sc_hsm_free_cvc(&devcert);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 1;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x81;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = 6;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 15;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 3;
pin_info.max_tries = 3;
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 2;
strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 2;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x88;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD;
pin_info.attrs.pin.min_length = 16;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 15;
pin_info.max_tries = 15;
strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
if (card->type == SC_CARD_TYPE_SC_HSM_SOC
|| card->type == SC_CARD_TYPE_SC_HSM_GOID) {
/* SC-HSM of this type always has a PIN-Pad */
r = SC_SUCCESS;
} else {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x85;
r = sc_pin_cmd(card, &pindata, NULL);
}
if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x86;
r = sc_pin_cmd(card, &pindata, NULL);
}
if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS))
card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH;
filelistlength = sc_list_files(card, filelist, sizeof(filelist));
LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier");
for (i = 0; i < filelistlength; i += 2) {
switch(filelist[i]) {
case KEY_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]);
break;
case DCOD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]);
break;
case CD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]);
break;
}
if (r != SC_SUCCESS) {
sc_log(card->ctx, "Error %d adding elements to framework", r);
}
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) {
return sc_pkcs15emu_sc_hsm_init(p15card);
} else {
if (p15card->card->type != SC_CARD_TYPE_SC_HSM
&& p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC
&& p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) {
return SC_ERROR_WRONG_CARD;
}
return sc_pkcs15emu_sc_hsm_init(p15card);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_344_6 |
crossvul-cpp_data_bad_937_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP N N M M %
% P P NN N MM MM %
% PPPP N N N M M M %
% P N NN M M %
% P N N M M %
% %
% %
% Read/Write PBMPlus Portable Anymap Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
/*
Typedef declarations.
*/
typedef struct _CommentInfo
{
char
*comment;
size_t
extent;
} CommentInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePNMImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P N M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPNM() returns MagickTrue if the image format type, identified by the
% magick string, is PNM.
%
% The format of the IsPNM method is:
%
% MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o extent: Specifies the extent of the magick string.
%
*/
static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
{
if (extent < 2)
return(MagickFalse);
if ((*magick == (unsigned char) 'P') &&
((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') ||
(magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') ||
(magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f')))
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPNMImage() reads a Portable Anymap image file and returns it.
% It allocates the memory necessary for the new Image structure and returns
% a pointer to the new image.
%
% The format of the ReadPNMImage method is:
%
% Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static int PNMComment(Image *image,CommentInfo *comment_info)
{
int
c;
register char
*p;
/*
Read comment.
*/
p=comment_info->comment+strlen(comment_info->comment);
for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++)
{
if ((size_t) (p-comment_info->comment+1) >= comment_info->extent)
{
comment_info->extent<<=1;
comment_info->comment=(char *) ResizeQuantumMemory(
comment_info->comment,comment_info->extent,
sizeof(*comment_info->comment));
if (comment_info->comment == (char *) NULL)
return(-1);
p=comment_info->comment+strlen(comment_info->comment);
}
c=ReadBlobByte(image);
if (c != EOF)
{
*p=(char) c;
*(p+1)='\0';
}
}
return(c);
}
static unsigned int PNMInteger(Image *image,CommentInfo *comment_info,
const unsigned int base)
{
int
c;
unsigned int
value;
/*
Skip any leading whitespace.
*/
do
{
c=ReadBlobByte(image);
if (c == EOF)
return(0);
if (c == (int) '#')
c=PNMComment(image,comment_info);
} while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'));
if (base == 2)
return((unsigned int) (c-(int) '0'));
/*
Evaluate number.
*/
value=0;
while (isdigit(c) != 0)
{
if (value <= (unsigned int) (INT_MAX/10))
{
value*=10;
if (value <= (unsigned int) (INT_MAX-(c-(int) '0')))
value+=c-(int) '0';
}
c=ReadBlobByte(image);
if (c == EOF)
return(0);
}
if (c == (int) '#')
c=PNMComment(image,comment_info);
return(value);
}
static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowPNMException(exception,message) \
{ \
if (comment_info.comment != (char *) NULL) \
comment_info.comment=DestroyString(comment_info.comment); \
ThrowReaderException((exception),(message)); \
}
char
format;
CommentInfo
comment_info;
double
quantum_scale;
Image
*image;
MagickBooleanType
status;
QuantumAny
max_value;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
depth,
extent,
packet_size;
ssize_t
count,
row,
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PNM image.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
do
{
/*
Initialize image structure.
*/
comment_info.comment=AcquireString(NULL);
comment_info.extent=MagickPathExtent;
if ((count != 1) || (format != 'P'))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
max_value=1;
quantum_type=RGBQuantum;
quantum_scale=1.0;
format=(char) ReadBlobByte(image);
if (format != '7')
{
/*
PBM, PGM, PPM, and PNM.
*/
image->columns=PNMInteger(image,&comment_info,10);
image->rows=PNMInteger(image,&comment_info,10);
if ((format == 'f') || (format == 'F'))
{
char
scale[MaxTextExtent];
if (ReadBlobString(image,scale) != (char *) NULL)
quantum_scale=StringToDouble(scale,(char **) NULL);
}
else
{
if ((format == '1') || (format == '4'))
max_value=1; /* bitmap */
else
max_value=PNMInteger(image,&comment_info,10);
}
}
else
{
char
keyword[MaxTextExtent],
value[MaxTextExtent];
int
c;
register char
*p;
/*
PAM.
*/
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == '#')
{
/*
Comment.
*/
c=PNMComment(image,&comment_info);
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c));
*p='\0';
if (LocaleCompare(keyword,"endhdr") == 0)
break;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
p=value;
while (isalnum(c) || (c == '_'))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"depth") == 0)
packet_size=StringToUnsignedLong(value);
(void) packet_size;
if (LocaleCompare(keyword,"height") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"maxval") == 0)
max_value=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"TUPLTYPE") == 0)
{
if (LocaleCompare(value,"BLACKANDWHITE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
image->matte=MagickTrue;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"GRAYSCALE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
image->matte=MagickTrue;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"RGB_ALPHA") == 0)
{
quantum_type=RGBAQuantum;
image->matte=MagickTrue;
}
if (LocaleCompare(value,"CMYK") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace);
quantum_type=CMYKQuantum;
}
if (LocaleCompare(value,"CMYK_ALPHA") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace);
image->matte=MagickTrue;
quantum_type=CMYKAQuantum;
}
}
if (LocaleCompare(keyword,"width") == 0)
image->columns=StringToUnsignedLong(value);
}
}
if ((image->columns == 0) || (image->rows == 0))
ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize");
if ((max_value == 0) || (max_value > 4294967295U))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
for (depth=1; GetQuantumRange(depth) < max_value; depth++) ;
image->depth=depth;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image))
ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile");
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
(void) ResetImagePixels(image,exception);
/*
Convert PNM pixels.
*/
row=0;
switch (format)
{
case '1':
{
/*
Convert PBM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,PNMInteger(image,&comment_info,2) == 0 ?
QuantumRange : 0);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=BilevelType;
break;
}
case '2':
{
size_t
intensity;
/*
Convert PGM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelRed(q,intensity);
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=GrayscaleType;
break;
}
case '3':
{
/*
Convert PNM image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
QuantumAny
pixel;
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelRed(q,pixel);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
SetPixelGreen(q,pixel);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
SetPixelBlue(q,pixel);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
break;
}
case '4':
{
/*
Convert PBM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
if (image->storage_class == PseudoClass)
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumMinIsWhite(quantum_info,MagickTrue);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '5':
{
/*
Convert PGM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '6':
{
/*
Convert PNM raster image to pixel packets.
*/
quantum_type=RGBQuantum;
extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
{
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
q->opacity=OpaqueOpacity;
q++;
}
break;
}
case 16:
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleShortToQuantum(pixel));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleShortToQuantum(pixel));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleShortToQuantum(pixel));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
case 32:
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleLongToQuantum(pixel));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleLongToQuantum(pixel));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleLongToQuantum(pixel));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
break;
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register IndexPacket
*indexes;
size_t
channels;
/*
Convert PAM raster image to pixel packets.
*/
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
channels=1;
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
channels=4;
break;
}
default:
{
channels=3;
break;
}
}
if (image->matte != MagickFalse)
channels++;
extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
if (image->depth != 1)
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
else
SetPixelOpacity(q,QuantumRange-ScaleAnyToQuantum(
pixel,max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,
max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,
max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case 'F':
case 'f':
{
/*
Convert PFM raster image to pixel packets.
*/
if (format == 'f')
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian;
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumDepth(image,quantum_info,32);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumScale(quantum_info,(MagickRealType) QuantumRange*
fabs(quantum_scale));
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if ((size_t) count != extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1),
image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
default:
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
}
if (*comment_info.comment != '\0')
(void) SetImageProperty(image,"comment",comment_info.comment);
comment_info.comment=DestroyString(comment_info.comment);
if (y < (ssize_t) image->rows)
ThrowPNMException(CorruptImageError,"UnableToReadImageData");
if (EOFBlob(image) != MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((format == '1') || (format == '2') || (format == '3'))
do
{
/*
Skip to end of line.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
if (count != 1)
break;
if (format == 'P')
break;
} while (format != '\n');
count=ReadBlob(image,1,(unsigned char *) &format);
if ((count == 1) && (format == 'P'))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count == 1) && (format == 'P'));
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPNMImage() adds properties for the PNM image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPNMImage method is:
%
% size_t RegisterPNMImage(void)
%
*/
ModuleExport size_t RegisterPNMImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("PAM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Common 2-dimensional bitmap format");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PBM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable bitmap format (black and white)");
entry->mime_type=ConstantString("image/x-portable-bitmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PFM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Portable float format");
entry->module=ConstantString("PFM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PGM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable graymap format (gray scale)");
entry->mime_type=ConstantString("image/x-portable-greymap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->magick=(IsImageFormatHandler *) IsPNM;
entry->description=ConstantString("Portable anymap");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PPM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable pixmap format (color)");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPNMImage() removes format registrations made by the
% PNM module from the list of supported formats.
%
% The format of the UnregisterPNMImage method is:
%
% UnregisterPNMImage(void)
%
*/
ModuleExport void UnregisterPNMImage(void)
{
(void) UnregisterMagickInfo("PAM");
(void) UnregisterMagickInfo("PBM");
(void) UnregisterMagickInfo("PGM");
(void) UnregisterMagickInfo("PNM");
(void) UnregisterMagickInfo("PPM");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePNMImage() writes an image to a file in the PNM rasterfile format.
%
% The format of the WritePNMImage method is:
%
% MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
format,
magick[MaxTextExtent];
const char
*value;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*pixels,
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
max_value=GetQuantumRange(image->depth);
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MaxTextExtent);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,&image->exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MaxTextExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,&image->exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MaxTextExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent);
if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MaxTextExtent);
break;
}
}
if (image->matte != MagickFalse)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n",
type);
(void) WriteBlobString(image,buffer);
}
/*
Convert to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)),
ScaleQuantumToChar(GetPixelGreen(p)),
ScaleQuantumToChar(GetPixelBlue(p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)),
ScaleQuantumToShort(GetPixelGreen(p)),
ScaleQuantumToShort(GetPixelBlue(p)));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)),
ScaleQuantumToLong(GetPixelGreen(p)),
ScaleQuantumToLong(GetPixelBlue(p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 32)
pixel=ScaleQuantumToLong(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_937_0 |
crossvul-cpp_data_bad_4863_2 | #include "queue.ih"
void queue_push(register Queue *qp, size_t extra_length, char const *info)
{
register char *cp;
size_t memory_length;
size_t available_length;
size_t begin_length;
size_t n_begin;
size_t q_length;
if (!extra_length)
return;
memory_length = qp->d_memory_end - qp->d_memory;
q_length =
qp->d_read <= qp->d_write ?
(size_t)(qp->d_write - qp->d_read)
:
memory_length - (qp->d_read - qp->d_write);
available_length = memory_length - q_length - 1;
/* -1, as the Q cannot completely fill up all */
/* available memory in the buffer */
if (message_show(MSG_INFO))
message("push_front %u bytes in `%s'", (unsigned)extra_length, info);
if (extra_length > available_length)
{
/* enlarge the buffer: */
memory_length += extra_length - available_length + BLOCK_QUEUE;
cp = new_memory(memory_length, sizeof(char));
if (message_show(MSG_INFO))
message("Reallocating queue at %p to %p", qp->d_memory, cp);
if (qp->d_read > qp->d_write) /* q wraps around end */
{
size_t tail_len = qp->d_memory_end - qp->d_read;
memcpy(cp, qp->d_read, tail_len); /* first part -> begin */
/* 2nd part beyond */
memcpy(cp + tail_len, qp->d_memory,
(size_t)(qp->d_write - qp->d_memory));
qp->d_write = cp + q_length;
qp->d_read = cp;
}
else /* q as one block */
{
memcpy(cp, qp->d_memory, memory_length);/* cp existing buffer */
qp->d_read = cp + (qp->d_read - qp->d_memory);
qp->d_write = cp + (qp->d_write - qp->d_memory);
}
free(qp->d_memory); /* free old memory */
qp->d_memory_end = cp + memory_length; /* update d_memory_end */
qp->d_memory = cp; /* update d_memory */
}
/*
Write as much as possible at the begin of the buffer, then write
the remaining chars at the end.
q_length is increased by the length of the info string
The first chars to write are at the end of info, and the 2nd part to
write are the initial chars of info, since the initial part of info
is then read first.
*/
/* # chars available at the */
begin_length = qp->d_read - qp->d_memory; /* begin of the buffer */
n_begin = extra_length <= begin_length ? /* determine # to write at */
extra_length /* the begin of the buffer */
:
begin_length;
memcpy /* write trailing part of */
( /* info first */
qp->d_read -= n_begin,
info + extra_length - n_begin,
n_begin
);
if (extra_length > begin_length) /* not yet all chars written*/
{
/* continue with the remaining number of characters. Insert these at*/
/* the end of the buffer */
extra_length -= begin_length; /* reduce # to write */
memcpy /* d_read wraps to the end */
( /* write info's rest */
qp->d_read = qp->d_memory_end - extra_length,
info,
extra_length
);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4863_2 |
crossvul-cpp_data_good_5_0 | // Ogg Vorbis audio decoder - v1.11 - 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
//
// Partial history:
// 1.12 - 2017/11/21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
// 1.11 - 2017/07/23 - fix MinGW compilation
// 1.10 - 2017/03/03 - more robust seeking; fix negative ilog(); clear error in open_memory
// 1.09 - 2016/04/04 - back out 'truncation of last frame' fix from previous version
// 1.08 - 2016/04/02 - warnings; setup memory leaks; truncation of last frame
// 1.07 - 2015/01/16 - fixes for crashes on invalid files; warning fixes; const
// 1.06 - 2015/08/31 - full, correct support for seeking API (Dougall Johnson)
// some crash fixes when out of memory or with corrupt files
// fix some inappropriately signed shifts
// 1.05 - 2015/04/19 - don't define __forceinline if it's redundant
// 1.04 - 2014/08/27 - fix missing const-correct case in API
// 1.03 - 2014/08/07 - warning fixes
// 1.02 - 2014/07/09 - declare qsort comparison as explicitly _cdecl in Windows
// 1.01 - 2014/06/18 - fix stb_vorbis_get_samples_float (interleaved was correct)
// 1.0 - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in >2-channel;
// (API change) report sample rate for decode-full-file funcs
//
// See end of file for full version history.
//////////////////////////////////////////////////////////////////////////////
//
// HEADER BEGINS HERE
//
#ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H
#define STB_VORBIS_INCLUDE_STB_VORBIS_H
#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
#define STB_VORBIS_NO_STDIO 1
#endif
#ifndef STB_VORBIS_NO_STDIO
#include <stdio.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/////////// THREAD SAFETY
// Individual stb_vorbis* handles are not thread-safe; you cannot decode from
// them from multiple threads at the same time. However, you can have multiple
// stb_vorbis* handles and decode from them independently in multiple thrads.
/////////// MEMORY ALLOCATION
// normally stb_vorbis uses malloc() to allocate memory at startup,
// and alloca() to allocate temporary memory during a frame on the
// stack. (Memory consumption will depend on the amount of setup
// data in the file and how you set the compile flags for speed
// vs. size. In my test files the maximal-size usage is ~150KB.)
//
// You can modify the wrapper functions in the source (setup_malloc,
// setup_temp_malloc, temp_malloc) to change this behavior, or you
// can use a simpler allocation model: you pass in a buffer from
// which stb_vorbis will allocate _all_ its memory (including the
// temp memory). "open" may fail with a VORBIS_outofmem if you
// do not pass in enough data; there is no way to determine how
// much you do need except to succeed (at which point you can
// query get_info to find the exact amount required. yes I know
// this is lame).
//
// If you pass in a non-NULL buffer of the type below, allocation
// will occur from it as described above. Otherwise just pass NULL
// to use malloc()/alloca()
typedef struct
{
char *alloc_buffer;
int alloc_buffer_length_in_bytes;
} stb_vorbis_alloc;
/////////// FUNCTIONS USEABLE WITH ALL INPUT MODES
typedef struct stb_vorbis stb_vorbis;
typedef struct
{
unsigned int sample_rate;
int channels;
unsigned int setup_memory_required;
unsigned int setup_temp_memory_required;
unsigned int temp_memory_required;
int max_frame_size;
} stb_vorbis_info;
// get general information about the file
extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);
// get the last error detected (clears it, too)
extern int stb_vorbis_get_error(stb_vorbis *f);
// close an ogg vorbis file and free all memory in use
extern void stb_vorbis_close(stb_vorbis *f);
// this function returns the offset (in samples) from the beginning of the
// file that will be returned by the next decode, if it is known, or -1
// otherwise. after a flush_pushdata() call, this may take a while before
// it becomes valid again.
// NOT WORKING YET after a seek with PULLDATA API
extern int stb_vorbis_get_sample_offset(stb_vorbis *f);
// returns the current seek point within the file, or offset from the beginning
// of the memory buffer. In pushdata mode it returns 0.
extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);
/////////// PUSHDATA API
#ifndef STB_VORBIS_NO_PUSHDATA_API
// this API allows you to get blocks of data from any source and hand
// them to stb_vorbis. you have to buffer them; stb_vorbis will tell
// you how much it used, and you have to give it the rest next time;
// and stb_vorbis may not have enough data to work with and you will
// need to give it the same data again PLUS more. Note that the Vorbis
// specification does not bound the size of an individual frame.
extern stb_vorbis *stb_vorbis_open_pushdata(
const unsigned char * datablock, int datablock_length_in_bytes,
int *datablock_memory_consumed_in_bytes,
int *error,
const stb_vorbis_alloc *alloc_buffer);
// create a vorbis decoder by passing in the initial data block containing
// the ogg&vorbis headers (you don't need to do parse them, just provide
// the first N bytes of the file--you're told if it's not enough, see below)
// on success, returns an stb_vorbis *, does not set error, returns the amount of
// data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;
// on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed
// if returns NULL and *error is VORBIS_need_more_data, then the input block was
// incomplete and you need to pass in a larger block from the start of the file
extern int stb_vorbis_decode_frame_pushdata(
stb_vorbis *f,
const unsigned char *datablock, int datablock_length_in_bytes,
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
);
// decode a frame of audio sample data if possible from the passed-in data block
//
// return value: number of bytes we used from datablock
//
// possible cases:
// 0 bytes used, 0 samples output (need more data)
// N bytes used, 0 samples output (resynching the stream, keep going)
// N bytes used, M samples output (one frame of data)
// note that after opening a file, you will ALWAYS get one N-bytes,0-sample
// frame, because Vorbis always "discards" the first frame.
//
// Note that on resynch, stb_vorbis will rarely consume all of the buffer,
// instead only datablock_length_in_bytes-3 or less. This is because it wants
// to avoid missing parts of a page header if they cross a datablock boundary,
// without writing state-machiney code to record a partial detection.
//
// The number of channels returned are stored in *channels (which can be
// NULL--it is always the same as the number of channels reported by
// get_info). *output will contain an array of float* buffers, one per
// channel. In other words, (*output)[0][0] contains the first sample from
// the first channel, and (*output)[1][0] contains the first sample from
// the second channel.
extern void stb_vorbis_flush_pushdata(stb_vorbis *f);
// inform stb_vorbis that your next datablock will not be contiguous with
// previous ones (e.g. you've seeked in the data); future attempts to decode
// frames will cause stb_vorbis to resynchronize (as noted above), and
// once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it
// will begin decoding the _next_ frame.
//
// if you want to seek using pushdata, you need to seek in your file, then
// call stb_vorbis_flush_pushdata(), then start calling decoding, then once
// decoding is returning you data, call stb_vorbis_get_sample_offset, and
// if you don't like the result, seek your file again and repeat.
#endif
////////// PULLING INPUT API
#ifndef STB_VORBIS_NO_PULLDATA_API
// This API assumes stb_vorbis is allowed to pull data from a source--
// either a block of memory containing the _entire_ vorbis stream, or a
// FILE * that you or it create, or possibly some other reading mechanism
// if you go modify the source to replace the FILE * case with some kind
// of callback to your code. (But if you don't support seeking, you may
// just want to go ahead and use pushdata.)
#if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output);
#endif
#if !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output);
#endif
// decode an entire file and output the data interleaved into a malloc()ed
// buffer stored in *output. The return value is the number of samples
// decoded, or -1 if the file could not be opened or was not an ogg vorbis file.
// When you're done with it, just free() the pointer returned in *output.
extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from an ogg vorbis stream in memory (note
// this must be the entire stream!). on failure, returns NULL and sets *error
#ifndef STB_VORBIS_NO_STDIO
extern stb_vorbis * stb_vorbis_open_filename(const char *filename,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from a filename via fopen(). on failure,
// returns NULL and sets *error (possibly to VORBIS_file_open_failure).
extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from an open FILE *, looking for a stream at
// the _current_ seek point (ftell). on failure, returns NULL and sets *error.
// note that stb_vorbis must "own" this stream; if you seek it in between
// calls to stb_vorbis, it will become confused. Morever, if you attempt to
// perform stb_vorbis_seek_*() operations on this file, it will assume it
// owns the _entire_ rest of the file after the start point. Use the next
// function, stb_vorbis_open_file_section(), to limit it.
extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,
int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len);
// create an ogg vorbis decoder from an open FILE *, looking for a stream at
// the _current_ seek point (ftell); the stream will be of length 'len' bytes.
// on failure, returns NULL and sets *error. note that stb_vorbis must "own"
// this stream; if you seek it in between calls to stb_vorbis, it will become
// confused.
#endif
extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);
extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);
// these functions seek in the Vorbis file to (approximately) 'sample_number'.
// after calling seek_frame(), the next call to get_frame_*() will include
// the specified sample. after calling stb_vorbis_seek(), the next call to
// stb_vorbis_get_samples_* will start with the specified sample. If you
// do not need to seek to EXACTLY the target sample when using get_samples_*,
// you can also use seek_frame().
extern int stb_vorbis_seek_start(stb_vorbis *f);
// this function is equivalent to stb_vorbis_seek(f,0)
extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);
extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);
// these functions return the total length of the vorbis stream
extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);
// decode the next frame and return the number of samples. the number of
// channels returned are stored in *channels (which can be NULL--it is always
// the same as the number of channels reported by get_info). *output will
// contain an array of float* buffers, one per channel. These outputs will
// be overwritten on the next call to stb_vorbis_get_frame_*.
//
// You generally should not intermix calls to stb_vorbis_get_frame_*()
// and stb_vorbis_get_samples_*(), since the latter calls the former.
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);
extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);
#endif
// decode the next frame and return the number of *samples* per channel.
// Note that for interleaved data, you pass in the number of shorts (the
// size of your array), but the return value is the number of samples per
// channel, not the total number of samples.
//
// The data is coerced to the number of channels you request according to the
// channel coercion rules (see below). You must pass in the size of your
// buffer(s) so that stb_vorbis will not overwrite the end of the buffer.
// The maximum buffer size needed can be gotten from get_info(); however,
// the Vorbis I specification implies an absolute maximum of 4096 samples
// per channel.
// Channel coercion rules:
// Let M be the number of channels requested, and N the number of channels present,
// and Cn be the nth channel; let stereo L be the sum of all L and center channels,
// and stereo R be the sum of all R and center channels (channel assignment from the
// vorbis spec).
// M N output
// 1 k sum(Ck) for all k
// 2 * stereo L, stereo R
// k l k > l, the first l channels, then 0s
// k l k <= l, the first k channels
// Note that this is not _good_ surround etc. mixing at all! It's just so
// you get something useful.
extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);
extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);
// gets num_samples samples, not necessarily on a frame boundary--this requires
// buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.
// Returns the number of samples stored per channel; it may be less than requested
// at the end of the file. If there are no more samples in the file, returns 0.
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);
extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);
#endif
// gets num_samples samples, not necessarily on a frame boundary--this requires
// buffering so you have to supply the buffers. Applies the coercion rules above
// to produce 'channels' channels. Returns the number of samples stored per channel;
// it may be less than requested at the end of the file. If there are no more
// samples in the file, returns 0.
#endif
//////// ERROR CODES
enum STBVorbisError
{
VORBIS__no_error,
VORBIS_need_more_data=1, // not a real error
VORBIS_invalid_api_mixing, // can't mix API modes
VORBIS_outofmem, // not enough memory
VORBIS_feature_not_supported, // uses floor 0
VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small
VORBIS_file_open_failure, // fopen() failed
VORBIS_seek_without_length, // can't seek in unknown-length file
VORBIS_unexpected_eof=10, // file is truncated?
VORBIS_seek_invalid, // seek past EOF
// decoding errors (corrupt/invalid stream) -- you probably
// don't care about the exact details of these
// vorbis errors:
VORBIS_invalid_setup=20,
VORBIS_invalid_stream,
// ogg errors:
VORBIS_missing_capture_pattern=30,
VORBIS_invalid_stream_structure_version,
VORBIS_continued_packet_flag_invalid,
VORBIS_incorrect_stream_serial_number,
VORBIS_invalid_first_page,
VORBIS_bad_packet_type,
VORBIS_cant_find_last_page,
VORBIS_seek_failed
};
#ifdef __cplusplus
}
#endif
#endif // STB_VORBIS_INCLUDE_STB_VORBIS_H
//
// HEADER ENDS HERE
//
//////////////////////////////////////////////////////////////////////////////
#ifndef STB_VORBIS_HEADER_ONLY
// global configuration settings (e.g. set these in the project/makefile),
// or just set them in this file at the top (although ideally the first few
// should be visible when the header file is compiled too, although it's not
// crucial)
// 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
#ifndef STB_VORBIS_NO_STDIO
#include <stdio.h>
#endif
#ifndef STB_VORBIS_NO_CRT
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
// find definition of alloca if it's not in stdlib.h:
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <malloc.h>
#endif
#if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__)
#include <alloca.h>
#endif
#else // STB_VORBIS_NO_CRT
#define NULL 0
#define malloc(s) 0
#define free(s) ((void) 0)
#define realloc(s) 0
#endif // STB_VORBIS_NO_CRT
#include <limits.h>
#ifdef __MINGW32__
// eff you mingw:
// "fixed":
// http://sourceforge.net/p/mingw-w64/mailman/message/32882927/
// "no that broke the build, reverted, who cares about C":
// http://sourceforge.net/p/mingw-w64/mailman/message/32890381/
#ifdef __forceinline
#undef __forceinline
#endif
#define __forceinline
#define alloca __builtin_alloca
#elif !defined(_MSC_VER)
#if __GNUC__
#define __forceinline inline
#else
#define __forceinline
#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))
#ifdef dealloca
#define temp_free(f,p) (f->alloc.alloc_buffer ? 0 : dealloca(size))
#else
#define temp_free(f,p) 0
#endif
#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 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 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 void setup_free(vorb *f, void *p)
{
if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack
free(p);
}
static 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 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;
}
}
static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)
{
return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];
}
// used in setup, and for huffman that doesn't go fast path
static unsigned int bit_reverse(unsigned int n)
{
n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
return (n >> 16) | (n << 16);
}
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 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];
memset(available, 0, 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, bit_reverse(res), i, m++, len[i], values);
// propogate 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 ? bit_reverse(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++] = bit_reverse(c->codewords[i]);
assert(k == c->sorted_entries);
} else {
for (i=0; i < c->sorted_entries; ++i)
c->sorted_codewords[i] = bit_reverse(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 = bit_reverse(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
assert(pow((float) r+1, dim) > entries);
assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
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] = (bit_reverse(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 i;
for (i=0; i < n; ++i) {
if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
}
}
// 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
static __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 = bit_reverse(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
static __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]);
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]);
}
}
}
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])
memset(residue_buffers[i], 0, 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;
}
}
static __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 propogates 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 = bit_reverse(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];
assert(0);
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]) {
memset(f->channel_buffers[i], 0, 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 - (n-right_end);
// 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;
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);
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) 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_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) {
c->lookup_values = lookup1_values(c->entries, c->dimensions);
} 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; ++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;
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);
#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 preceeding 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;
// 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 (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 = fopen(filename, "rb");
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
/* Version history
1.12 - 2017/11/21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
1.11 - 2017/07/23 - fix MinGW compilation
1.10 - 2017/03/03 - more robust seeking; fix negative ilog(); clear error in open_memory
1.09 - 2016/04/04 - back out 'avoid discarding last frame' fix from previous version
1.08 - 2016/04/02 - fixed multiple warnings; fix setup memory leaks;
avoid discarding last frame of audio data
1.07 - 2015/01/16 - fixed some warnings, fix mingw, const-correct API
some more crash fixes when out of memory or with corrupt files
1.06 - 2015/08/31 - full, correct support for seeking API (Dougall Johnson)
some crash fixes when out of memory or with corrupt files
1.05 - 2015/04/19 - don't define __forceinline if it's redundant
1.04 - 2014/08/27 - fix missing const-correct case in API
1.03 - 2014/08/07 - Warning fixes
1.02 - 2014/07/09 - Declare qsort compare function _cdecl on windows
1.01 - 2014/06/18 - fix stb_vorbis_get_samples_float
1.0 - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in multichannel
(API change) report sample rate for decode-full-file funcs
0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila
0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem
0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence
0.99993 - remove assert that fired on legal files with empty tables
0.99992 - rewind-to-start
0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo
0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++
0.9998 - add a full-decode function with a memory source
0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition
0.9996 - query length of vorbis stream in samples/seconds
0.9995 - bugfix to another optimization that only happened in certain files
0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors
0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation
0.9992 - performance improvement of IMDCT; now performs close to reference implementation
0.9991 - performance improvement of IMDCT
0.999 - (should have been 0.9990) performance improvement of IMDCT
0.998 - no-CRT support from Casey Muratori
0.997 - bugfixes for bugs found by Terje Mathisen
0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen
0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen
0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen
0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen
0.992 - fixes for MinGW warning
0.991 - turn fast-float-conversion on by default
0.990 - fix push-mode seek recovery if you seek into the headers
0.98b - fix to bad release of 0.98
0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode
0.97 - builds under c++ (typecasting, don't use 'class' keyword)
0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code
0.95 - clamping code for 16-bit functions
0.94 - not publically released
0.93 - fixed all-zero-floor case (was decoding garbage)
0.92 - fixed a memory leak
0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION
0.90 - first public release
*/
#endif // STB_VORBIS_HEADER_ONLY
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5_0 |
crossvul-cpp_data_good_3502_0 | /*
* SCSI Device emulation
*
* Copyright (c) 2006 CodeSourcery.
* Based on code by Fabrice Bellard
*
* Written by Paul Brook
* Modifications:
* 2009-Dec-12 Artyom Tarasenko : implemented stamdard inquiry for the case
* when the allocation length of CDB is smaller
* than 36.
* 2009-Oct-13 Artyom Tarasenko : implemented the block descriptor in the
* MODE SENSE response.
*
* This code is licensed under the LGPL.
*
* Note that this file only handles the SCSI architecture model and device
* commands. Emulation of interface/link layer protocols is handled by
* the host adapter emulator.
*/
//#define DEBUG_SCSI
#ifdef DEBUG_SCSI
#define DPRINTF(fmt, ...) \
do { printf("scsi-disk: " fmt , ## __VA_ARGS__); } while (0)
#else
#define DPRINTF(fmt, ...) do {} while(0)
#endif
#define BADF(fmt, ...) \
do { fprintf(stderr, "scsi-disk: " fmt , ## __VA_ARGS__); } while (0)
#include "qemu-common.h"
#include "qemu-error.h"
#include "scsi.h"
#include "scsi-defs.h"
#include "sysemu.h"
#include "blockdev.h"
#include "block_int.h"
#define SCSI_DMA_BUF_SIZE 131072
#define SCSI_MAX_INQUIRY_LEN 256
#define SCSI_REQ_STATUS_RETRY 0x01
#define SCSI_REQ_STATUS_RETRY_TYPE_MASK 0x06
#define SCSI_REQ_STATUS_RETRY_READ 0x00
#define SCSI_REQ_STATUS_RETRY_WRITE 0x02
#define SCSI_REQ_STATUS_RETRY_FLUSH 0x04
typedef struct SCSIDiskState SCSIDiskState;
typedef struct SCSIDiskReq {
SCSIRequest req;
/* Both sector and sector_count are in terms of qemu 512 byte blocks. */
uint64_t sector;
uint32_t sector_count;
uint32_t buflen;
struct iovec iov;
QEMUIOVector qiov;
uint32_t status;
BlockAcctCookie acct;
} SCSIDiskReq;
struct SCSIDiskState
{
SCSIDevice qdev;
BlockDriverState *bs;
/* The qemu block layer uses a fixed 512 byte sector size.
This is the number of 512 byte blocks in a single scsi sector. */
int cluster_size;
uint32_t removable;
uint64_t max_lba;
QEMUBH *bh;
char *version;
char *serial;
bool tray_open;
bool tray_locked;
};
static int scsi_handle_rw_error(SCSIDiskReq *r, int error, int type);
static int scsi_disk_emulate_command(SCSIDiskReq *r);
static void scsi_free_request(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
if (r->iov.iov_base) {
qemu_vfree(r->iov.iov_base);
}
}
/* Helper function for command completion with sense. */
static void scsi_check_condition(SCSIDiskReq *r, SCSISense sense)
{
DPRINTF("Command complete tag=0x%x sense=%d/%d/%d\n",
r->req.tag, sense.key, sense.asc, sense.ascq);
scsi_req_build_sense(&r->req, sense);
scsi_req_complete(&r->req, CHECK_CONDITION);
}
/* Cancel a pending data transfer. */
static void scsi_cancel_io(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
DPRINTF("Cancel tag=0x%x\n", req->tag);
if (r->req.aiocb) {
bdrv_aio_cancel(r->req.aiocb);
}
r->req.aiocb = NULL;
}
static uint32_t scsi_init_iovec(SCSIDiskReq *r)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
if (!r->iov.iov_base) {
r->buflen = SCSI_DMA_BUF_SIZE;
r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);
}
r->iov.iov_len = MIN(r->sector_count * 512, r->buflen);
qemu_iovec_init_external(&r->qiov, &r->iov, 1);
return r->qiov.size / 512;
}
static void scsi_read_complete(void * opaque, int ret)
{
SCSIDiskReq *r = (SCSIDiskReq *)opaque;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
int n;
if (r->req.aiocb != NULL) {
r->req.aiocb = NULL;
bdrv_acct_done(s->bs, &r->acct);
}
if (ret) {
if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_READ)) {
return;
}
}
DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->qiov.size);
n = r->qiov.size / 512;
r->sector += n;
r->sector_count -= n;
scsi_req_data(&r->req, r->qiov.size);
}
static void scsi_flush_complete(void * opaque, int ret)
{
SCSIDiskReq *r = (SCSIDiskReq *)opaque;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
if (r->req.aiocb != NULL) {
r->req.aiocb = NULL;
bdrv_acct_done(s->bs, &r->acct);
}
if (ret < 0) {
if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_FLUSH)) {
return;
}
}
scsi_req_complete(&r->req, GOOD);
}
/* Read more data from scsi device into buffer. */
static void scsi_read_data(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
if (r->sector_count == (uint32_t)-1) {
DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);
r->sector_count = 0;
scsi_req_data(&r->req, r->iov.iov_len);
return;
}
DPRINTF("Read sector_count=%d\n", r->sector_count);
if (r->sector_count == 0) {
/* This also clears the sense buffer for REQUEST SENSE. */
scsi_req_complete(&r->req, GOOD);
return;
}
/* No data transfer may already be in progress */
assert(r->req.aiocb == NULL);
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
DPRINTF("Data transfer direction invalid\n");
scsi_read_complete(r, -EINVAL);
return;
}
if (s->tray_open) {
scsi_read_complete(r, -ENOMEDIUM);
}
n = scsi_init_iovec(r);
bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,
scsi_read_complete, r);
if (r->req.aiocb == NULL) {
scsi_read_complete(r, -EIO);
}
}
static int scsi_handle_rw_error(SCSIDiskReq *r, int error, int type)
{
int is_read = (type == SCSI_REQ_STATUS_RETRY_READ);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
BlockErrorAction action = bdrv_get_on_error(s->bs, is_read);
if (action == BLOCK_ERR_IGNORE) {
bdrv_mon_event(s->bs, BDRV_ACTION_IGNORE, is_read);
return 0;
}
if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
|| action == BLOCK_ERR_STOP_ANY) {
type &= SCSI_REQ_STATUS_RETRY_TYPE_MASK;
r->status |= SCSI_REQ_STATUS_RETRY | type;
bdrv_mon_event(s->bs, BDRV_ACTION_STOP, is_read);
vm_stop(VMSTOP_DISKFULL);
} else {
switch (error) {
case ENOMEM:
scsi_check_condition(r, SENSE_CODE(TARGET_FAILURE));
break;
case EINVAL:
scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
break;
default:
scsi_check_condition(r, SENSE_CODE(IO_ERROR));
break;
}
bdrv_mon_event(s->bs, BDRV_ACTION_REPORT, is_read);
}
return 1;
}
static void scsi_write_complete(void * opaque, int ret)
{
SCSIDiskReq *r = (SCSIDiskReq *)opaque;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
if (r->req.aiocb != NULL) {
r->req.aiocb = NULL;
bdrv_acct_done(s->bs, &r->acct);
}
if (ret) {
if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_WRITE)) {
return;
}
}
n = r->qiov.size / 512;
r->sector += n;
r->sector_count -= n;
if (r->sector_count == 0) {
scsi_req_complete(&r->req, GOOD);
} else {
scsi_init_iovec(r);
DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, r->qiov.size);
scsi_req_data(&r->req, r->qiov.size);
}
}
static void scsi_write_data(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
/* No data transfer may already be in progress */
assert(r->req.aiocb == NULL);
if (r->req.cmd.mode != SCSI_XFER_TO_DEV) {
DPRINTF("Data transfer direction invalid\n");
scsi_write_complete(r, -EINVAL);
return;
}
n = r->qiov.size / 512;
if (n) {
if (s->tray_open) {
scsi_write_complete(r, -ENOMEDIUM);
}
bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE);
r->req.aiocb = bdrv_aio_writev(s->bs, r->sector, &r->qiov, n,
scsi_write_complete, r);
if (r->req.aiocb == NULL) {
scsi_write_complete(r, -ENOMEM);
}
} else {
/* Called for the first time. Ask the driver to send us more data. */
scsi_write_complete(r, 0);
}
}
static void scsi_dma_restart_bh(void *opaque)
{
SCSIDiskState *s = opaque;
SCSIRequest *req;
SCSIDiskReq *r;
qemu_bh_delete(s->bh);
s->bh = NULL;
QTAILQ_FOREACH(req, &s->qdev.requests, next) {
r = DO_UPCAST(SCSIDiskReq, req, req);
if (r->status & SCSI_REQ_STATUS_RETRY) {
int status = r->status;
int ret;
r->status &=
~(SCSI_REQ_STATUS_RETRY | SCSI_REQ_STATUS_RETRY_TYPE_MASK);
switch (status & SCSI_REQ_STATUS_RETRY_TYPE_MASK) {
case SCSI_REQ_STATUS_RETRY_READ:
scsi_read_data(&r->req);
break;
case SCSI_REQ_STATUS_RETRY_WRITE:
scsi_write_data(&r->req);
break;
case SCSI_REQ_STATUS_RETRY_FLUSH:
ret = scsi_disk_emulate_command(r);
if (ret == 0) {
scsi_req_complete(&r->req, GOOD);
}
}
}
}
}
static void scsi_dma_restart_cb(void *opaque, int running, int reason)
{
SCSIDiskState *s = opaque;
if (!running)
return;
if (!s->bh) {
s->bh = qemu_bh_new(scsi_dma_restart_bh, s);
qemu_bh_schedule(s->bh);
}
}
/* Return a pointer to the data buffer. */
static uint8_t *scsi_get_buf(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
return (uint8_t *)r->iov.iov_base;
}
static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
int buflen = 0;
if (req->cmd.buf[1] & 0x2) {
/* Command support data - optional, not implemented */
BADF("optional INQUIRY command support request not implemented\n");
return -1;
}
if (req->cmd.buf[1] & 0x1) {
/* Vital product data */
uint8_t page_code = req->cmd.buf[2];
if (req->cmd.xfer < 4) {
BADF("Error: Inquiry (EVPD[%02X]) buffer size %zd is "
"less than 4\n", page_code, req->cmd.xfer);
return -1;
}
if (s->qdev.type == TYPE_ROM) {
outbuf[buflen++] = 5;
} else {
outbuf[buflen++] = 0;
}
outbuf[buflen++] = page_code ; // this page
outbuf[buflen++] = 0x00;
switch (page_code) {
case 0x00: /* Supported page codes, mandatory */
{
int pages;
DPRINTF("Inquiry EVPD[Supported pages] "
"buffer size %zd\n", req->cmd.xfer);
pages = buflen++;
outbuf[buflen++] = 0x00; // list of supported pages (this page)
if (s->serial)
outbuf[buflen++] = 0x80; // unit serial number
outbuf[buflen++] = 0x83; // device identification
if (s->qdev.type == TYPE_DISK) {
outbuf[buflen++] = 0xb0; // block limits
outbuf[buflen++] = 0xb2; // thin provisioning
}
outbuf[pages] = buflen - pages - 1; // number of pages
break;
}
case 0x80: /* Device serial number, optional */
{
int l;
if (!s->serial) {
DPRINTF("Inquiry (EVPD[Serial number] not supported\n");
return -1;
}
l = strlen(s->serial);
if (l > req->cmd.xfer)
l = req->cmd.xfer;
if (l > 20)
l = 20;
DPRINTF("Inquiry EVPD[Serial number] "
"buffer size %zd\n", req->cmd.xfer);
outbuf[buflen++] = l;
memcpy(outbuf+buflen, s->serial, l);
buflen += l;
break;
}
case 0x83: /* Device identification page, mandatory */
{
int max_len = 255 - 8;
int id_len = strlen(bdrv_get_device_name(s->bs));
if (id_len > max_len)
id_len = max_len;
DPRINTF("Inquiry EVPD[Device identification] "
"buffer size %zd\n", req->cmd.xfer);
outbuf[buflen++] = 4 + id_len;
outbuf[buflen++] = 0x2; // ASCII
outbuf[buflen++] = 0; // not officially assigned
outbuf[buflen++] = 0; // reserved
outbuf[buflen++] = id_len; // length of data following
memcpy(outbuf+buflen, bdrv_get_device_name(s->bs), id_len);
buflen += id_len;
break;
}
case 0xb0: /* block limits */
{
unsigned int unmap_sectors =
s->qdev.conf.discard_granularity / s->qdev.blocksize;
unsigned int min_io_size =
s->qdev.conf.min_io_size / s->qdev.blocksize;
unsigned int opt_io_size =
s->qdev.conf.opt_io_size / s->qdev.blocksize;
if (s->qdev.type == TYPE_ROM) {
DPRINTF("Inquiry (EVPD[%02X] not supported for CDROM\n",
page_code);
return -1;
}
/* required VPD size with unmap support */
outbuf[3] = buflen = 0x3c;
memset(outbuf + 4, 0, buflen - 4);
/* optimal transfer length granularity */
outbuf[6] = (min_io_size >> 8) & 0xff;
outbuf[7] = min_io_size & 0xff;
/* optimal transfer length */
outbuf[12] = (opt_io_size >> 24) & 0xff;
outbuf[13] = (opt_io_size >> 16) & 0xff;
outbuf[14] = (opt_io_size >> 8) & 0xff;
outbuf[15] = opt_io_size & 0xff;
/* optimal unmap granularity */
outbuf[28] = (unmap_sectors >> 24) & 0xff;
outbuf[29] = (unmap_sectors >> 16) & 0xff;
outbuf[30] = (unmap_sectors >> 8) & 0xff;
outbuf[31] = unmap_sectors & 0xff;
break;
}
case 0xb2: /* thin provisioning */
{
outbuf[3] = buflen = 8;
outbuf[4] = 0;
outbuf[5] = 0x40; /* write same with unmap supported */
outbuf[6] = 0;
outbuf[7] = 0;
break;
}
default:
BADF("Error: unsupported Inquiry (EVPD[%02X]) "
"buffer size %zd\n", page_code, req->cmd.xfer);
return -1;
}
/* done with EVPD */
return buflen;
}
/* Standard INQUIRY data */
if (req->cmd.buf[2] != 0) {
BADF("Error: Inquiry (STANDARD) page or code "
"is non-zero [%02X]\n", req->cmd.buf[2]);
return -1;
}
/* PAGE CODE == 0 */
if (req->cmd.xfer < 5) {
BADF("Error: Inquiry (STANDARD) buffer size %zd "
"is less than 5\n", req->cmd.xfer);
return -1;
}
buflen = req->cmd.xfer;
if (buflen > SCSI_MAX_INQUIRY_LEN)
buflen = SCSI_MAX_INQUIRY_LEN;
memset(outbuf, 0, buflen);
outbuf[0] = s->qdev.type & 0x1f;
if (s->qdev.type == TYPE_ROM) {
outbuf[1] = 0x80;
memcpy(&outbuf[16], "QEMU CD-ROM ", 16);
} else {
outbuf[1] = s->removable ? 0x80 : 0;
memcpy(&outbuf[16], "QEMU HARDDISK ", 16);
}
memcpy(&outbuf[8], "QEMU ", 8);
memset(&outbuf[32], 0, 4);
memcpy(&outbuf[32], s->version, MIN(4, strlen(s->version)));
/*
* We claim conformance to SPC-3, which is required for guests
* to ask for modern features like READ CAPACITY(16) or the
* block characteristics VPD page by default. Not all of SPC-3
* is actually implemented, but we're good enough.
*/
outbuf[2] = 5;
outbuf[3] = 2; /* Format 2 */
if (buflen > 36) {
outbuf[4] = buflen - 5; /* Additional Length = (Len - 1) - 4 */
} else {
/* If the allocation length of CDB is too small,
the additional length is not adjusted */
outbuf[4] = 36 - 5;
}
/* Sync data transfer and TCQ. */
outbuf[7] = 0x10 | (req->bus->tcq ? 0x02 : 0);
return buflen;
}
static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
int page_control)
{
BlockDriverState *bdrv = s->bs;
int cylinders, heads, secs;
uint8_t *p = *p_outbuf;
/*
* If Changeable Values are requested, a mask denoting those mode parameters
* that are changeable shall be returned. As we currently don't support
* parameter changes via MODE_SELECT all bits are returned set to zero.
* The buffer was already menset to zero by the caller of this function.
*/
switch (page) {
case 4: /* Rigid disk device geometry page. */
if (s->qdev.type == TYPE_ROM) {
return -1;
}
p[0] = 4;
p[1] = 0x16;
if (page_control == 1) { /* Changeable Values */
break;
}
/* if a geometry hint is available, use it */
bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
p[2] = (cylinders >> 16) & 0xff;
p[3] = (cylinders >> 8) & 0xff;
p[4] = cylinders & 0xff;
p[5] = heads & 0xff;
/* Write precomp start cylinder, disabled */
p[6] = (cylinders >> 16) & 0xff;
p[7] = (cylinders >> 8) & 0xff;
p[8] = cylinders & 0xff;
/* Reduced current start cylinder, disabled */
p[9] = (cylinders >> 16) & 0xff;
p[10] = (cylinders >> 8) & 0xff;
p[11] = cylinders & 0xff;
/* Device step rate [ns], 200ns */
p[12] = 0;
p[13] = 200;
/* Landing zone cylinder */
p[14] = 0xff;
p[15] = 0xff;
p[16] = 0xff;
/* Medium rotation rate [rpm], 5400 rpm */
p[20] = (5400 >> 8) & 0xff;
p[21] = 5400 & 0xff;
break;
case 5: /* Flexible disk device geometry page. */
if (s->qdev.type == TYPE_ROM) {
return -1;
}
p[0] = 5;
p[1] = 0x1e;
if (page_control == 1) { /* Changeable Values */
break;
}
/* Transfer rate [kbit/s], 5Mbit/s */
p[2] = 5000 >> 8;
p[3] = 5000 & 0xff;
/* if a geometry hint is available, use it */
bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
p[4] = heads & 0xff;
p[5] = secs & 0xff;
p[6] = s->cluster_size * 2;
p[8] = (cylinders >> 8) & 0xff;
p[9] = cylinders & 0xff;
/* Write precomp start cylinder, disabled */
p[10] = (cylinders >> 8) & 0xff;
p[11] = cylinders & 0xff;
/* Reduced current start cylinder, disabled */
p[12] = (cylinders >> 8) & 0xff;
p[13] = cylinders & 0xff;
/* Device step rate [100us], 100us */
p[14] = 0;
p[15] = 1;
/* Device step pulse width [us], 1us */
p[16] = 1;
/* Device head settle delay [100us], 100us */
p[17] = 0;
p[18] = 1;
/* Motor on delay [0.1s], 0.1s */
p[19] = 1;
/* Motor off delay [0.1s], 0.1s */
p[20] = 1;
/* Medium rotation rate [rpm], 5400 rpm */
p[28] = (5400 >> 8) & 0xff;
p[29] = 5400 & 0xff;
break;
case 8: /* Caching page. */
p[0] = 8;
p[1] = 0x12;
if (page_control == 1) { /* Changeable Values */
break;
}
if (bdrv_enable_write_cache(s->bs)) {
p[2] = 4; /* WCE */
}
break;
case 0x2a: /* CD Capabilities and Mechanical Status page. */
if (s->qdev.type != TYPE_ROM) {
return -1;
}
p[0] = 0x2a;
p[1] = 0x14;
if (page_control == 1) { /* Changeable Values */
break;
}
p[2] = 3; // CD-R & CD-RW read
p[3] = 0; // Writing not supported
p[4] = 0x7f; /* Audio, composite, digital out,
mode 2 form 1&2, multi session */
p[5] = 0xff; /* CD DA, DA accurate, RW supported,
RW corrected, C2 errors, ISRC,
UPC, Bar code */
p[6] = 0x2d | (s->tray_locked ? 2 : 0);
/* Locking supported, jumper present, eject, tray */
p[7] = 0; /* no volume & mute control, no
changer */
p[8] = (50 * 176) >> 8; // 50x read speed
p[9] = (50 * 176) & 0xff;
p[10] = 0 >> 8; // No volume
p[11] = 0 & 0xff;
p[12] = 2048 >> 8; // 2M buffer
p[13] = 2048 & 0xff;
p[14] = (16 * 176) >> 8; // 16x read speed current
p[15] = (16 * 176) & 0xff;
p[18] = (16 * 176) >> 8; // 16x write speed
p[19] = (16 * 176) & 0xff;
p[20] = (16 * 176) >> 8; // 16x write speed current
p[21] = (16 * 176) & 0xff;
break;
default:
return -1;
}
*p_outbuf += p[1] + 2;
return p[1] + 2;
}
static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint64_t nb_sectors;
int page, dbd, buflen, ret, page_control;
uint8_t *p;
uint8_t dev_specific_param;
dbd = r->req.cmd.buf[1] & 0x8;
page = r->req.cmd.buf[2] & 0x3f;
page_control = (r->req.cmd.buf[2] & 0xc0) >> 6;
DPRINTF("Mode Sense(%d) (page %d, xfer %zd, page_control %d)\n",
(r->req.cmd.buf[0] == MODE_SENSE) ? 6 : 10, page, r->req.cmd.xfer, page_control);
memset(outbuf, 0, r->req.cmd.xfer);
p = outbuf;
if (bdrv_is_read_only(s->bs)) {
dev_specific_param = 0x80; /* Readonly. */
} else {
dev_specific_param = 0x00;
}
if (r->req.cmd.buf[0] == MODE_SENSE) {
p[1] = 0; /* Default media type. */
p[2] = dev_specific_param;
p[3] = 0; /* Block descriptor length. */
p += 4;
} else { /* MODE_SENSE_10 */
p[2] = 0; /* Default media type. */
p[3] = dev_specific_param;
p[6] = p[7] = 0; /* Block descriptor length. */
p += 8;
}
bdrv_get_geometry(s->bs, &nb_sectors);
if (!dbd && nb_sectors) {
if (r->req.cmd.buf[0] == MODE_SENSE) {
outbuf[3] = 8; /* Block descriptor length */
} else { /* MODE_SENSE_10 */
outbuf[7] = 8; /* Block descriptor length */
}
nb_sectors /= s->cluster_size;
if (nb_sectors > 0xffffff)
nb_sectors = 0;
p[0] = 0; /* media density code */
p[1] = (nb_sectors >> 16) & 0xff;
p[2] = (nb_sectors >> 8) & 0xff;
p[3] = nb_sectors & 0xff;
p[4] = 0; /* reserved */
p[5] = 0; /* bytes 5-7 are the sector size in bytes */
p[6] = s->cluster_size * 2;
p[7] = 0;
p += 8;
}
if (page_control == 3) {
/* Saved Values */
scsi_check_condition(r, SENSE_CODE(SAVING_PARAMS_NOT_SUPPORTED));
return -1;
}
if (page == 0x3f) {
for (page = 0; page <= 0x3e; page++) {
mode_sense_page(s, page, &p, page_control);
}
} else {
ret = mode_sense_page(s, page, &p, page_control);
if (ret == -1) {
return -1;
}
}
buflen = p - outbuf;
/*
* The mode data length field specifies the length in bytes of the
* following data that is available to be transferred. The mode data
* length does not include itself.
*/
if (r->req.cmd.buf[0] == MODE_SENSE) {
outbuf[0] = buflen - 1;
} else { /* MODE_SENSE_10 */
outbuf[0] = ((buflen - 2) >> 8) & 0xff;
outbuf[1] = (buflen - 2) & 0xff;
}
if (buflen > r->req.cmd.xfer)
buflen = r->req.cmd.xfer;
return buflen;
}
static int scsi_disk_emulate_read_toc(SCSIRequest *req, uint8_t *outbuf)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
int start_track, format, msf, toclen;
uint64_t nb_sectors;
msf = req->cmd.buf[1] & 2;
format = req->cmd.buf[2] & 0xf;
start_track = req->cmd.buf[6];
bdrv_get_geometry(s->bs, &nb_sectors);
DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);
nb_sectors /= s->cluster_size;
switch (format) {
case 0:
toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);
break;
case 1:
/* multi session : only a single session defined */
toclen = 12;
memset(outbuf, 0, 12);
outbuf[1] = 0x0a;
outbuf[2] = 0x01;
outbuf[3] = 0x01;
break;
case 2:
toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);
break;
default:
return -1;
}
if (toclen > req->cmd.xfer)
toclen = req->cmd.xfer;
return toclen;
}
static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
{
SCSIRequest *req = &r->req;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
bool start = req->cmd.buf[4] & 1;
bool loej = req->cmd.buf[4] & 2; /* load on start, eject on !start */
if (s->qdev.type == TYPE_ROM && loej) {
if (!start && !s->tray_open && s->tray_locked) {
scsi_check_condition(r,
bdrv_is_inserted(s->bs)
? SENSE_CODE(ILLEGAL_REQ_REMOVAL_PREVENTED)
: SENSE_CODE(NOT_READY_REMOVAL_PREVENTED));
return -1;
}
bdrv_eject(s->bs, !start);
s->tray_open = !start;
}
return 0;
}
static int scsi_disk_emulate_command(SCSIDiskReq *r)
{
SCSIRequest *req = &r->req;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
uint64_t nb_sectors;
uint8_t *outbuf;
int buflen = 0;
if (!r->iov.iov_base) {
/*
* FIXME: we shouldn't return anything bigger than 4k, but the code
* requires the buffer to be as big as req->cmd.xfer in several
* places. So, do not allow CDBs with a very large ALLOCATION
* LENGTH. The real fix would be to modify scsi_read_data and
* dma_buf_read, so that they return data beyond the buflen
* as all zeros.
*/
if (req->cmd.xfer > 65536) {
goto illegal_request;
}
r->buflen = MAX(4096, req->cmd.xfer);
r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);
}
outbuf = r->iov.iov_base;
switch (req->cmd.buf[0]) {
case TEST_UNIT_READY:
if (s->tray_open || !bdrv_is_inserted(s->bs))
goto not_ready;
break;
case INQUIRY:
buflen = scsi_disk_emulate_inquiry(req, outbuf);
if (buflen < 0)
goto illegal_request;
break;
case MODE_SENSE:
case MODE_SENSE_10:
buflen = scsi_disk_emulate_mode_sense(r, outbuf);
if (buflen < 0)
goto illegal_request;
break;
case READ_TOC:
buflen = scsi_disk_emulate_read_toc(req, outbuf);
if (buflen < 0)
goto illegal_request;
break;
case RESERVE:
if (req->cmd.buf[1] & 1)
goto illegal_request;
break;
case RESERVE_10:
if (req->cmd.buf[1] & 3)
goto illegal_request;
break;
case RELEASE:
if (req->cmd.buf[1] & 1)
goto illegal_request;
break;
case RELEASE_10:
if (req->cmd.buf[1] & 3)
goto illegal_request;
break;
case START_STOP:
if (scsi_disk_emulate_start_stop(r) < 0) {
return -1;
}
break;
case ALLOW_MEDIUM_REMOVAL:
s->tray_locked = req->cmd.buf[4] & 1;
bdrv_lock_medium(s->bs, req->cmd.buf[4] & 1);
break;
case READ_CAPACITY_10:
/* The normal LEN field for this command is zero. */
memset(outbuf, 0, 8);
bdrv_get_geometry(s->bs, &nb_sectors);
if (!nb_sectors)
goto not_ready;
nb_sectors /= s->cluster_size;
/* Returned value is the address of the last sector. */
nb_sectors--;
/* Remember the new size for read/write sanity checking. */
s->max_lba = nb_sectors;
/* Clip to 2TB, instead of returning capacity modulo 2TB. */
if (nb_sectors > UINT32_MAX)
nb_sectors = UINT32_MAX;
outbuf[0] = (nb_sectors >> 24) & 0xff;
outbuf[1] = (nb_sectors >> 16) & 0xff;
outbuf[2] = (nb_sectors >> 8) & 0xff;
outbuf[3] = nb_sectors & 0xff;
outbuf[4] = 0;
outbuf[5] = 0;
outbuf[6] = s->cluster_size * 2;
outbuf[7] = 0;
buflen = 8;
break;
case GET_CONFIGURATION:
memset(outbuf, 0, 8);
/* ??? This should probably return much more information. For now
just return the basic header indicating the CD-ROM profile. */
outbuf[7] = 8; // CD-ROM
buflen = 8;
break;
case SERVICE_ACTION_IN_16:
/* Service Action In subcommands. */
if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {
DPRINTF("SAI READ CAPACITY(16)\n");
memset(outbuf, 0, req->cmd.xfer);
bdrv_get_geometry(s->bs, &nb_sectors);
if (!nb_sectors)
goto not_ready;
nb_sectors /= s->cluster_size;
/* Returned value is the address of the last sector. */
nb_sectors--;
/* Remember the new size for read/write sanity checking. */
s->max_lba = nb_sectors;
outbuf[0] = (nb_sectors >> 56) & 0xff;
outbuf[1] = (nb_sectors >> 48) & 0xff;
outbuf[2] = (nb_sectors >> 40) & 0xff;
outbuf[3] = (nb_sectors >> 32) & 0xff;
outbuf[4] = (nb_sectors >> 24) & 0xff;
outbuf[5] = (nb_sectors >> 16) & 0xff;
outbuf[6] = (nb_sectors >> 8) & 0xff;
outbuf[7] = nb_sectors & 0xff;
outbuf[8] = 0;
outbuf[9] = 0;
outbuf[10] = s->cluster_size * 2;
outbuf[11] = 0;
outbuf[12] = 0;
outbuf[13] = get_physical_block_exp(&s->qdev.conf);
/* set TPE bit if the format supports discard */
if (s->qdev.conf.discard_granularity) {
outbuf[14] = 0x80;
}
/* Protection, exponent and lowest lba field left blank. */
buflen = req->cmd.xfer;
break;
}
DPRINTF("Unsupported Service Action In\n");
goto illegal_request;
case VERIFY_10:
break;
default:
scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
return -1;
}
return buflen;
not_ready:
if (s->tray_open || !bdrv_is_inserted(s->bs)) {
scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
} else {
scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
}
return -1;
illegal_request:
if (r->req.status == -1) {
scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
}
return -1;
}
/* Execute a scsi command. Returns the length of the data expected by the
command. This will be Positive for data transfers from the device
(eg. disk reads), negative for transfers to the device (eg. disk writes),
and zero if the command does not transfer any data. */
static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
int32_t len;
uint8_t command;
int rc;
command = buf[0];
DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", req->lun, req->tag, buf[0]);
#ifdef DEBUG_SCSI
{
int i;
for (i = 1; i < r->req.cmd.len; i++) {
printf(" 0x%02x", buf[i]);
}
printf("\n");
}
#endif
switch (command) {
case TEST_UNIT_READY:
case INQUIRY:
case MODE_SENSE:
case MODE_SENSE_10:
case RESERVE:
case RESERVE_10:
case RELEASE:
case RELEASE_10:
case START_STOP:
case ALLOW_MEDIUM_REMOVAL:
case READ_CAPACITY_10:
case READ_TOC:
case GET_CONFIGURATION:
case SERVICE_ACTION_IN_16:
case VERIFY_10:
rc = scsi_disk_emulate_command(r);
if (rc < 0) {
return 0;
}
r->iov.iov_len = rc;
break;
case SYNCHRONIZE_CACHE:
bdrv_acct_start(s->bs, &r->acct, 0, BDRV_ACCT_FLUSH);
r->req.aiocb = bdrv_aio_flush(s->bs, scsi_flush_complete, r);
if (r->req.aiocb == NULL) {
scsi_flush_complete(r, -EIO);
}
return 0;
case READ_6:
case READ_10:
case READ_12:
case READ_16:
len = r->req.cmd.xfer / s->qdev.blocksize;
DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len);
if (r->req.cmd.lba > s->max_lba)
goto illegal_lba;
r->sector = r->req.cmd.lba * s->cluster_size;
r->sector_count = len * s->cluster_size;
break;
case WRITE_6:
case WRITE_10:
case WRITE_12:
case WRITE_16:
case WRITE_VERIFY_10:
case WRITE_VERIFY_12:
case WRITE_VERIFY_16:
len = r->req.cmd.xfer / s->qdev.blocksize;
DPRINTF("Write %s(sector %" PRId64 ", count %d)\n",
(command & 0xe) == 0xe ? "And Verify " : "",
r->req.cmd.lba, len);
if (r->req.cmd.lba > s->max_lba)
goto illegal_lba;
r->sector = r->req.cmd.lba * s->cluster_size;
r->sector_count = len * s->cluster_size;
break;
case MODE_SELECT:
DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
/* We don't support mode parameter changes.
Allow the mode parameter header + block descriptors only. */
if (r->req.cmd.xfer > 12) {
goto fail;
}
break;
case MODE_SELECT_10:
DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
/* We don't support mode parameter changes.
Allow the mode parameter header + block descriptors only. */
if (r->req.cmd.xfer > 16) {
goto fail;
}
break;
case SEEK_6:
case SEEK_10:
DPRINTF("Seek(%d) (sector %" PRId64 ")\n", command == SEEK_6 ? 6 : 10,
r->req.cmd.lba);
if (r->req.cmd.lba > s->max_lba) {
goto illegal_lba;
}
break;
case WRITE_SAME_16:
len = r->req.cmd.xfer / s->qdev.blocksize;
DPRINTF("WRITE SAME(16) (sector %" PRId64 ", count %d)\n",
r->req.cmd.lba, len);
if (r->req.cmd.lba > s->max_lba) {
goto illegal_lba;
}
/*
* We only support WRITE SAME with the unmap bit set for now.
*/
if (!(buf[1] & 0x8)) {
goto fail;
}
rc = bdrv_discard(s->bs, r->req.cmd.lba * s->cluster_size,
len * s->cluster_size);
if (rc < 0) {
/* XXX: better error code ?*/
goto fail;
}
break;
case REQUEST_SENSE:
abort();
default:
DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
return 0;
fail:
scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
return 0;
illegal_lba:
scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
return 0;
}
if (r->sector_count == 0 && r->iov.iov_len == 0) {
scsi_req_complete(&r->req, GOOD);
}
len = r->sector_count * 512 + r->iov.iov_len;
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
return -len;
} else {
if (!r->sector_count)
r->sector_count = -1;
return len;
}
}
static void scsi_disk_reset(DeviceState *dev)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev.qdev, dev);
uint64_t nb_sectors;
scsi_device_purge_requests(&s->qdev, SENSE_CODE(RESET));
bdrv_get_geometry(s->bs, &nb_sectors);
nb_sectors /= s->cluster_size;
if (nb_sectors) {
nb_sectors--;
}
s->max_lba = nb_sectors;
}
static void scsi_destroy(SCSIDevice *dev)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
scsi_device_purge_requests(&s->qdev, SENSE_CODE(NO_SENSE));
blockdev_mark_auto_del(s->qdev.conf.bs);
}
static void scsi_cd_change_media_cb(void *opaque, bool load)
{
((SCSIDiskState *)opaque)->tray_open = !load;
}
static bool scsi_cd_is_tray_open(void *opaque)
{
return ((SCSIDiskState *)opaque)->tray_open;
}
static bool scsi_cd_is_medium_locked(void *opaque)
{
return ((SCSIDiskState *)opaque)->tray_locked;
}
static const BlockDevOps scsi_cd_block_ops = {
.change_media_cb = scsi_cd_change_media_cb,
.is_tray_open = scsi_cd_is_tray_open,
.is_medium_locked = scsi_cd_is_medium_locked,
};
static int scsi_initfn(SCSIDevice *dev, uint8_t scsi_type)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
DriveInfo *dinfo;
if (!s->qdev.conf.bs) {
error_report("scsi-disk: drive property not set");
return -1;
}
s->bs = s->qdev.conf.bs;
if (scsi_type == TYPE_DISK && !bdrv_is_inserted(s->bs)) {
error_report("Device needs media, but drive is empty");
return -1;
}
if (!s->serial) {
/* try to fall back to value set with legacy -drive serial=... */
dinfo = drive_get_by_blockdev(s->bs);
if (*dinfo->serial) {
s->serial = g_strdup(dinfo->serial);
}
}
if (!s->version) {
s->version = g_strdup(QEMU_VERSION);
}
if (bdrv_is_sg(s->bs)) {
error_report("scsi-disk: unwanted /dev/sg*");
return -1;
}
if (scsi_type == TYPE_ROM) {
bdrv_set_dev_ops(s->bs, &scsi_cd_block_ops, s);
s->qdev.blocksize = 2048;
} else if (scsi_type == TYPE_DISK) {
s->qdev.blocksize = s->qdev.conf.logical_block_size;
} else {
error_report("scsi-disk: Unhandled SCSI type %02x", scsi_type);
return -1;
}
s->cluster_size = s->qdev.blocksize / 512;
bdrv_set_buffer_alignment(s->bs, s->qdev.blocksize);
s->qdev.type = scsi_type;
qemu_add_vm_change_state_handler(scsi_dma_restart_cb, s);
add_boot_device_path(s->qdev.conf.bootindex, &dev->qdev, ",0");
return 0;
}
static int scsi_hd_initfn(SCSIDevice *dev)
{
return scsi_initfn(dev, TYPE_DISK);
}
static int scsi_cd_initfn(SCSIDevice *dev)
{
return scsi_initfn(dev, TYPE_ROM);
}
static int scsi_disk_initfn(SCSIDevice *dev)
{
DriveInfo *dinfo;
uint8_t scsi_type;
if (!dev->conf.bs) {
scsi_type = TYPE_DISK; /* will die in scsi_initfn() */
} else {
dinfo = drive_get_by_blockdev(dev->conf.bs);
scsi_type = dinfo->media_cd ? TYPE_ROM : TYPE_DISK;
}
return scsi_initfn(dev, scsi_type);
}
static SCSIReqOps scsi_disk_reqops = {
.size = sizeof(SCSIDiskReq),
.free_req = scsi_free_request,
.send_command = scsi_send_command,
.read_data = scsi_read_data,
.write_data = scsi_write_data,
.cancel_io = scsi_cancel_io,
.get_buf = scsi_get_buf,
};
static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,
uint32_t lun, void *hba_private)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
SCSIRequest *req;
req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);
return req;
}
#define DEFINE_SCSI_DISK_PROPERTIES() \
DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf), \
DEFINE_PROP_STRING("ver", SCSIDiskState, version), \
DEFINE_PROP_STRING("serial", SCSIDiskState, serial)
static SCSIDeviceInfo scsi_disk_info[] = {
{
.qdev.name = "scsi-hd",
.qdev.fw_name = "disk",
.qdev.desc = "virtual SCSI disk",
.qdev.size = sizeof(SCSIDiskState),
.qdev.reset = scsi_disk_reset,
.init = scsi_hd_initfn,
.destroy = scsi_destroy,
.alloc_req = scsi_new_request,
.qdev.props = (Property[]) {
DEFINE_SCSI_DISK_PROPERTIES(),
DEFINE_PROP_BIT("removable", SCSIDiskState, removable, 0, false),
DEFINE_PROP_END_OF_LIST(),
}
},{
.qdev.name = "scsi-cd",
.qdev.fw_name = "disk",
.qdev.desc = "virtual SCSI CD-ROM",
.qdev.size = sizeof(SCSIDiskState),
.qdev.reset = scsi_disk_reset,
.init = scsi_cd_initfn,
.destroy = scsi_destroy,
.alloc_req = scsi_new_request,
.qdev.props = (Property[]) {
DEFINE_SCSI_DISK_PROPERTIES(),
DEFINE_PROP_END_OF_LIST(),
},
},{
.qdev.name = "scsi-disk", /* legacy -device scsi-disk */
.qdev.fw_name = "disk",
.qdev.desc = "virtual SCSI disk or CD-ROM (legacy)",
.qdev.size = sizeof(SCSIDiskState),
.qdev.reset = scsi_disk_reset,
.init = scsi_disk_initfn,
.destroy = scsi_destroy,
.alloc_req = scsi_new_request,
.qdev.props = (Property[]) {
DEFINE_SCSI_DISK_PROPERTIES(),
DEFINE_PROP_BIT("removable", SCSIDiskState, removable, 0, false),
DEFINE_PROP_END_OF_LIST(),
}
}
};
static void scsi_disk_register_devices(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(scsi_disk_info); i++) {
scsi_qdev_register(&scsi_disk_info[i]);
}
}
device_init(scsi_disk_register_devices)
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3502_0 |
crossvul-cpp_data_good_4772_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD RRRR AAA W W %
% D D R R A A W W %
% D D RRRR AAAAA W W W %
% D D R RN A A WW WW %
% DDDD R R A A W W %
% %
% %
% MagickCore Image Drawing Methods %
% %
% %
% Software Design %
% Cristy %
% July 1998 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon
% rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion",
% Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent
% (www.appligent.com) contributed the dash pattern, linecap stroking
% algorithm, and minor rendering improvements.
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/annotate.h"
#include "magick/artifact.h"
#include "magick/blob.h"
#include "magick/cache.h"
#include "magick/cache-private.h"
#include "magick/cache-view.h"
#include "magick/channel.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/composite-private.h"
#include "magick/constitute.h"
#include "magick/draw.h"
#include "magick/draw-private.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/paint.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/resample.h"
#include "magick/resample-private.h"
#include "magick/resource_.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread-private.h"
#include "magick/token.h"
#include "magick/transform.h"
#include "magick/utility.h"
/*
Define declarations.
*/
#define BezierQuantum 200
#define DrawEpsilon (1.0e-10)
/*
Typedef declarations.
*/
typedef struct _EdgeInfo
{
SegmentInfo
bounds;
double
scanline;
PointInfo
*points;
size_t
number_points;
ssize_t
direction;
MagickBooleanType
ghostline;
size_t
highwater;
} EdgeInfo;
typedef struct _ElementInfo
{
double
cx,
cy,
major,
minor,
angle;
} ElementInfo;
typedef struct _PolygonInfo
{
EdgeInfo
*edges;
size_t
number_edges;
} PolygonInfo;
typedef enum
{
MoveToCode,
OpenCode,
GhostlineCode,
LineToCode,
EndCode
} PathInfoCode;
typedef struct _PathInfo
{
PointInfo
point;
PathInfoCode
code;
} PathInfo;
/*
Forward declarations.
*/
static MagickBooleanType
DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *);
static PrimitiveInfo
*TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *);
static size_t
TracePath(PrimitiveInfo *,const char *);
static void
TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo),
TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo,
const double,const MagickBooleanType,const MagickBooleanType),
TraceBezier(PrimitiveInfo *,const size_t),
TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo),
TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo,
PointInfo),
TraceSquareLinecap(PrimitiveInfo *,const size_t,const double);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireDrawInfo() returns a DrawInfo structure properly initialized.
%
% The format of the AcquireDrawInfo method is:
%
% DrawInfo *AcquireDrawInfo(void)
%
*/
MagickExport DrawInfo *AcquireDrawInfo(void)
{
DrawInfo
*draw_info;
draw_info=(DrawInfo *) AcquireMagickMemory(sizeof(*draw_info));
if (draw_info == (DrawInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetDrawInfo((ImageInfo *) NULL,draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneDrawInfo() makes a copy of the given draw_info structure. If NULL
% is specified, a new DrawInfo structure is created initialized to default
% values.
%
% The format of the CloneDrawInfo method is:
%
% DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
% const DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
const DrawInfo *draw_info)
{
DrawInfo
*clone_info;
clone_info=(DrawInfo *) AcquireMagickMemory(sizeof(*clone_info));
if (clone_info == (DrawInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetDrawInfo(image_info,clone_info);
if (draw_info == (DrawInfo *) NULL)
return(clone_info);
if (clone_info->primitive != (char *) NULL)
(void) CloneString(&clone_info->primitive,draw_info->primitive);
if (draw_info->geometry != (char *) NULL)
(void) CloneString(&clone_info->geometry,draw_info->geometry);
clone_info->viewbox=draw_info->viewbox;
clone_info->affine=draw_info->affine;
clone_info->gravity=draw_info->gravity;
clone_info->fill=draw_info->fill;
clone_info->stroke=draw_info->stroke;
clone_info->stroke_width=draw_info->stroke_width;
if (draw_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue,
&draw_info->fill_pattern->exception);
else
if (draw_info->tile != (Image *) NULL)
clone_info->fill_pattern=CloneImage(draw_info->tile,0,0,MagickTrue,
&draw_info->tile->exception);
clone_info->tile=NewImageList(); /* tile is deprecated */
if (draw_info->stroke_pattern != (Image *) NULL)
clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0,
MagickTrue,&draw_info->stroke_pattern->exception);
clone_info->stroke_antialias=draw_info->stroke_antialias;
clone_info->text_antialias=draw_info->text_antialias;
clone_info->fill_rule=draw_info->fill_rule;
clone_info->linecap=draw_info->linecap;
clone_info->linejoin=draw_info->linejoin;
clone_info->miterlimit=draw_info->miterlimit;
clone_info->dash_offset=draw_info->dash_offset;
clone_info->decorate=draw_info->decorate;
clone_info->compose=draw_info->compose;
if (draw_info->text != (char *) NULL)
(void) CloneString(&clone_info->text,draw_info->text);
if (draw_info->font != (char *) NULL)
(void) CloneString(&clone_info->font,draw_info->font);
if (draw_info->metrics != (char *) NULL)
(void) CloneString(&clone_info->metrics,draw_info->metrics);
if (draw_info->family != (char *) NULL)
(void) CloneString(&clone_info->family,draw_info->family);
clone_info->style=draw_info->style;
clone_info->stretch=draw_info->stretch;
clone_info->weight=draw_info->weight;
if (draw_info->encoding != (char *) NULL)
(void) CloneString(&clone_info->encoding,draw_info->encoding);
clone_info->pointsize=draw_info->pointsize;
clone_info->kerning=draw_info->kerning;
clone_info->interline_spacing=draw_info->interline_spacing;
clone_info->interword_spacing=draw_info->interword_spacing;
clone_info->direction=draw_info->direction;
if (draw_info->density != (char *) NULL)
(void) CloneString(&clone_info->density,draw_info->density);
clone_info->align=draw_info->align;
clone_info->undercolor=draw_info->undercolor;
clone_info->border_color=draw_info->border_color;
if (draw_info->server_name != (char *) NULL)
(void) CloneString(&clone_info->server_name,draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
{
register ssize_t
x;
for (x=0; fabs(draw_info->dash_pattern[x]) >= DrawEpsilon; x++) ;
clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL,
sizeof(*clone_info->dash_pattern));
if (clone_info->dash_pattern == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) CopyMagickMemory(clone_info->dash_pattern,draw_info->dash_pattern,
(size_t) (x+1)*sizeof(*clone_info->dash_pattern));
}
clone_info->gradient=draw_info->gradient;
if (draw_info->gradient.stops != (StopInfo *) NULL)
{
size_t
number_stops;
number_stops=clone_info->gradient.number_stops;
clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t)
number_stops,sizeof(*clone_info->gradient.stops));
if (clone_info->gradient.stops == (StopInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) CopyMagickMemory(clone_info->gradient.stops,
draw_info->gradient.stops,(size_t) number_stops*
sizeof(*clone_info->gradient.stops));
}
if (draw_info->clip_mask != (char *) NULL)
(void) CloneString(&clone_info->clip_mask,draw_info->clip_mask);
clone_info->bounds=draw_info->bounds;
clone_info->clip_units=draw_info->clip_units;
clone_info->render=draw_info->render;
clone_info->fill_opacity=draw_info->fill_opacity;
clone_info->stroke_opacity=draw_info->stroke_opacity;
clone_info->element_reference=draw_info->element_reference;
clone_info->debug=IsEventLogging();
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P a t h T o P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPathToPolygon() converts a path to the more efficient sorted
% rendering form.
%
% The format of the ConvertPathToPolygon method is:
%
% PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info)
%
% A description of each parameter follows:
%
% o Method ConvertPathToPolygon returns the path in a more efficient sorted
% rendering form of type PolygonInfo.
%
% o draw_info: Specifies a pointer to an DrawInfo structure.
%
% o path_info: Specifies a pointer to an PathInfo structure.
%
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int CompareEdges(const void *x,const void *y)
{
register const EdgeInfo
*p,
*q;
/*
Compare two edges.
*/
p=(const EdgeInfo *) x;
q=(const EdgeInfo *) y;
if ((p->points[0].y-DrawEpsilon) > q->points[0].y)
return(1);
if ((p->points[0].y+DrawEpsilon) < q->points[0].y)
return(-1);
if ((p->points[0].x-DrawEpsilon) > q->points[0].x)
return(1);
if ((p->points[0].x+DrawEpsilon) < q->points[0].x)
return(-1);
if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)-
(p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0)
return(1);
return(-1);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static void LogPolygonInfo(const PolygonInfo *polygon_info)
{
register EdgeInfo
*p;
register ssize_t
i,
j;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge");
p=polygon_info->edges;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:",
(double) i);
(void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s",
p->direction != MagickFalse ? "down" : "up");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s",
p->ghostline != MagickFalse ? "transparent" : "opaque");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" bounds: %g,%g - %g,%g",p->bounds.x1,p->bounds.y1,
p->bounds.x2,p->bounds.y2);
for (j=0; j < (ssize_t) p->number_points; j++)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %g,%g",
p->points[j].x,p->points[j].y);
p++;
}
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge");
}
static void ReversePoints(PointInfo *points,const size_t number_points)
{
PointInfo
point;
register ssize_t
i;
for (i=0; i < (ssize_t) (number_points >> 1); i++)
{
point=points[i];
points[i]=points[number_points-(i+1)];
points[number_points-(i+1)]=point;
}
}
static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info)
{
long
direction,
next_direction;
PointInfo
point,
*points;
PolygonInfo
*polygon_info;
SegmentInfo
bounds;
register ssize_t
i,
n;
MagickBooleanType
ghostline;
size_t
edge,
number_edges,
number_points;
/*
Convert a path to the more efficient sorted rendering form.
*/
polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info));
if (polygon_info == (PolygonInfo *) NULL)
return((PolygonInfo *) NULL);
number_edges=16;
polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory(number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
(void) ResetMagickMemory(polygon_info->edges,0,number_edges*
sizeof(*polygon_info->edges));
direction=0;
edge=0;
ghostline=MagickFalse;
n=0;
number_points=0;
points=(PointInfo *) NULL;
(void) ResetMagickMemory(&point,0,sizeof(point));
(void) ResetMagickMemory(&bounds,0,sizeof(bounds));
for (i=0; path_info[i].code != EndCode; i++)
{
if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) ||
(path_info[i].code == GhostlineCode))
{
/*
Move to.
*/
if ((points != (PointInfo *) NULL) && (n >= 2))
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
points=(PointInfo *) NULL;
ghostline=MagickFalse;
edge++;
}
if (points == (PointInfo *) NULL)
{
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse;
point=path_info[i].point;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
direction=0;
n=1;
continue;
}
/*
Line to.
*/
next_direction=((path_info[i].point.y > point.y) ||
((fabs(path_info[i].point.y-point.y) < DrawEpsilon) &&
(path_info[i].point.x > point.x))) ? 1 : -1;
if ((points != (PointInfo *) NULL) && (direction != 0) &&
(direction != next_direction))
{
/*
New edge.
*/
point=points[n-1];
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
n=1;
ghostline=MagickFalse;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
edge++;
}
direction=next_direction;
if (points == (PointInfo *) NULL)
continue;
if (n == (ssize_t) number_points)
{
number_points<<=1;
points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
point=path_info[i].point;
points[n]=point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.x > bounds.x2)
bounds.x2=point.x;
n++;
}
if (points != (PointInfo *) NULL)
{
if (n < 2)
points=(PointInfo *) RelinquishMagickMemory(points);
else
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
ghostline=MagickFalse;
edge++;
}
}
polygon_info->number_edges=edge;
qsort(polygon_info->edges,(size_t) polygon_info->number_edges,
sizeof(*polygon_info->edges),CompareEdges);
if (IsEventLogging() != MagickFalse)
LogPolygonInfo(polygon_info);
return(polygon_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P r i m i t i v e T o P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector
% path structure.
%
% The format of the ConvertPrimitiveToPath method is:
%
% PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o Method ConvertPrimitiveToPath returns a vector path structure of type
% PathInfo.
%
% o draw_info: a structure of type DrawInfo.
%
% o primitive_info: Specifies a pointer to an PrimitiveInfo structure.
%
%
*/
static void LogPathInfo(const PathInfo *path_info)
{
register const PathInfo
*p;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path");
for (p=path_info; p->code != EndCode; p++)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %g,%g %s",p->point.x,p->point.y,p->code == GhostlineCode ?
"moveto ghostline" : p->code == OpenCode ? "moveto open" :
p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" :
"?");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path");
}
static PathInfo *ConvertPrimitiveToPath(
const DrawInfo *magick_unused(draw_info),const PrimitiveInfo *primitive_info)
{
PathInfo
*path_info;
PathInfoCode
code;
PointInfo
p,
q;
register ssize_t
i,
n;
ssize_t
coordinates,
start;
magick_unreferenced(draw_info);
/*
Converts a PrimitiveInfo structure into a vector path structure.
*/
switch (primitive_info->primitive)
{
case PointPrimitive:
case ColorPrimitive:
case MattePrimitive:
case TextPrimitive:
case ImagePrimitive:
return((PathInfo *) NULL);
default:
break;
}
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
path_info=(PathInfo *) AcquireQuantumMemory((size_t) (2UL*i+3UL),
sizeof(*path_info));
if (path_info == (PathInfo *) NULL)
return((PathInfo *) NULL);
coordinates=0;
n=0;
p.x=(-1.0);
p.y=(-1.0);
q.x=(-1.0);
q.y=(-1.0);
start=0;
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
code=LineToCode;
if (coordinates <= 0)
{
coordinates=(ssize_t) primitive_info[i].coordinates;
p=primitive_info[i].point;
start=n;
code=MoveToCode;
}
coordinates--;
/*
Eliminate duplicate points.
*/
if ((i == 0) || (fabs(q.x-primitive_info[i].point.x) >= DrawEpsilon) ||
(fabs(q.y-primitive_info[i].point.y) >= DrawEpsilon))
{
path_info[n].code=code;
path_info[n].point=primitive_info[i].point;
q=primitive_info[i].point;
n++;
}
if (coordinates > 0)
continue;
if ((fabs(p.x-primitive_info[i].point.x) < DrawEpsilon) &&
(fabs(p.y-primitive_info[i].point.y) < DrawEpsilon))
continue;
/*
Mark the p point as open if it does not match the q.
*/
path_info[start].code=OpenCode;
path_info[n].code=GhostlineCode;
path_info[n].point=primitive_info[i].point;
n++;
path_info[n].code=LineToCode;
path_info[n].point=p;
n++;
}
path_info[n].code=EndCode;
path_info[n].point.x=0.0;
path_info[n].point.y=0.0;
if (IsEventLogging() != MagickFalse)
LogPathInfo(path_info);
return(path_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyDrawInfo() deallocates memory associated with an DrawInfo
% structure.
%
% The format of the DestroyDrawInfo method is:
%
% DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
{
if (draw_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickSignature);
if (draw_info->primitive != (char *) NULL)
draw_info->primitive=DestroyString(draw_info->primitive);
if (draw_info->text != (char *) NULL)
draw_info->text=DestroyString(draw_info->text);
if (draw_info->geometry != (char *) NULL)
draw_info->geometry=DestroyString(draw_info->geometry);
if (draw_info->tile != (Image *) NULL)
draw_info->tile=DestroyImage(draw_info->tile);
if (draw_info->fill_pattern != (Image *) NULL)
draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern);
if (draw_info->stroke_pattern != (Image *) NULL)
draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern);
if (draw_info->font != (char *) NULL)
draw_info->font=DestroyString(draw_info->font);
if (draw_info->metrics != (char *) NULL)
draw_info->metrics=DestroyString(draw_info->metrics);
if (draw_info->family != (char *) NULL)
draw_info->family=DestroyString(draw_info->family);
if (draw_info->encoding != (char *) NULL)
draw_info->encoding=DestroyString(draw_info->encoding);
if (draw_info->density != (char *) NULL)
draw_info->density=DestroyString(draw_info->density);
if (draw_info->server_name != (char *) NULL)
draw_info->server_name=(char *)
RelinquishMagickMemory(draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
draw_info->dash_pattern=(double *) RelinquishMagickMemory(
draw_info->dash_pattern);
if (draw_info->gradient.stops != (StopInfo *) NULL)
draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory(
draw_info->gradient.stops);
if (draw_info->clip_mask != (char *) NULL)
draw_info->clip_mask=DestroyString(draw_info->clip_mask);
draw_info->signature=(~MagickSignature);
draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y E d g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyEdge() destroys the specified polygon edge.
%
% The format of the DestroyEdge method is:
%
% ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
% o edge: the polygon edge number to destroy.
%
*/
static size_t DestroyEdge(PolygonInfo *polygon_info,
const size_t edge)
{
assert(edge < polygon_info->number_edges);
polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory(
polygon_info->edges[edge].points);
polygon_info->number_edges--;
if (edge < polygon_info->number_edges)
(void) CopyMagickMemory(polygon_info->edges+edge,polygon_info->edges+edge+1,
(size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges));
return(polygon_info->number_edges);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y P o l y g o n I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyPolygonInfo() destroys the PolygonInfo data structure.
%
% The format of the DestroyPolygonInfo method is:
%
% PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
*/
static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
{
register ssize_t
i;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
polygon_info->edges[i].points=(PointInfo *)
RelinquishMagickMemory(polygon_info->edges[i].points);
polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges);
return((PolygonInfo *) RelinquishMagickMemory(polygon_info));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w A f f i n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawAffineImage() composites the source over the destination image as
% dictated by the affine transform.
%
% The format of the DrawAffineImage method is:
%
% MagickBooleanType DrawAffineImage(Image *image,const Image *source,
% const AffineMatrix *affine)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o source: the source image.
%
% o affine: the affine transform.
%
*/
static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine,
const double y,const SegmentInfo *edge)
{
double
intercept,
z;
register double
x;
SegmentInfo
inverse_edge;
/*
Determine left and right edges.
*/
inverse_edge.x1=edge->x1;
inverse_edge.y1=edge->y1;
inverse_edge.x2=edge->x2;
inverse_edge.y2=edge->y2;
z=affine->ry*y+affine->tx;
if (affine->sx >= DrawEpsilon)
{
intercept=(-z/affine->sx);
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->sx < -DrawEpsilon)
{
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->sx);
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns))
{
inverse_edge.x2=edge->x1;
return(inverse_edge);
}
/*
Determine top and bottom edges.
*/
z=affine->sy*y+affine->ty;
if (affine->rx >= DrawEpsilon)
{
intercept=(-z/affine->rx);
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->rx < -DrawEpsilon)
{
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->rx);
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows))
{
inverse_edge.x2=edge->x2;
return(inverse_edge);
}
return(inverse_edge);
}
static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine)
{
AffineMatrix
inverse_affine;
double
determinant;
determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx*
affine->ry);
inverse_affine.sx=determinant*affine->sy;
inverse_affine.rx=determinant*(-affine->rx);
inverse_affine.ry=determinant*(-affine->ry);
inverse_affine.sy=determinant*affine->sx;
inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty*
inverse_affine.ry;
inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty*
inverse_affine.sy;
return(inverse_affine);
}
MagickExport MagickBooleanType DrawAffineImage(Image *image,
const Image *source,const AffineMatrix *affine)
{
AffineMatrix
inverse_affine;
CacheView
*image_view,
*source_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickPixelPacket
zero;
PointInfo
extent[4],
min,
max,
point;
register ssize_t
i;
SegmentInfo
edge;
ssize_t
start,
stop,
y;
/*
Determine bounding box.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(source != (const Image *) NULL);
assert(source->signature == MagickSignature);
assert(affine != (AffineMatrix *) NULL);
extent[0].x=0.0;
extent[0].y=0.0;
extent[1].x=(double) source->columns-1.0;
extent[1].y=0.0;
extent[2].x=(double) source->columns-1.0;
extent[2].y=(double) source->rows-1.0;
extent[3].x=0.0;
extent[3].y=(double) source->rows-1.0;
for (i=0; i < 4; i++)
{
point=extent[i];
extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx;
extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty;
}
min=extent[0];
max=extent[0];
for (i=1; i < 4; i++)
{
if (min.x > extent[i].x)
min.x=extent[i].x;
if (min.y > extent[i].y)
min.y=extent[i].y;
if (max.x < extent[i].x)
max.x=extent[i].x;
if (max.y < extent[i].y)
max.y=extent[i].y;
}
/*
Affine transform image.
*/
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
edge.x1=MagickMax(min.x,0.0);
edge.y1=MagickMax(min.y,0.0);
edge.x2=MagickMin(max.x,(double) image->columns-1.0);
edge.y2=MagickMin(max.y,(double) image->rows-1.0);
inverse_affine=InverseAffineMatrix(affine);
GetMagickPixelPacket(image,&zero);
exception=(&image->exception);
start=(ssize_t) ceil(edge.y1-0.5);
stop=(ssize_t) floor(edge.y2+0.5);
source_view=AcquireVirtualCacheView(source,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(source,image,1,1)
#endif
for (y=start; y <= stop; y++)
{
MagickPixelPacket
composite,
pixel;
PointInfo
point;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
SegmentInfo
inverse_edge;
ssize_t
x_offset;
inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge);
if (inverse_edge.x2 < inverse_edge.x1)
continue;
q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1-
0.5),y,(size_t) (floor(inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1),
1,exception);
if (q == (PixelPacket *) NULL)
continue;
indexes=GetCacheViewAuthenticIndexQueue(image_view);
pixel=zero;
composite=zero;
x_offset=0;
for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++)
{
point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+
inverse_affine.tx;
point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+
inverse_affine.ty;
(void) InterpolateMagickPixelPacket(source,source_view,
UndefinedInterpolatePixel,point.x,point.y,&pixel,exception);
SetMagickPixelPacket(image,q,indexes+x_offset,&composite);
MagickPixelCompositeOver(&pixel,pixel.opacity,&composite,
composite.opacity,&composite);
SetPixelPacket(image,&composite,q,indexes+x_offset);
x_offset++;
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w B o u n d i n g R e c t a n g l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawBoundingRectangles() draws the bounding rectangles on the image. This
% is only useful for developers debugging the rendering algorithm.
%
% The format of the DrawBoundingRectangles method is:
%
% void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
% PolygonInfo *polygon_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o polygon_info: Specifies a pointer to a PolygonInfo structure.
%
*/
static void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
const PolygonInfo *polygon_info)
{
double
mid;
DrawInfo
*clone_info;
PointInfo
end,
resolution,
start;
PrimitiveInfo
primitive_info[6];
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
coordinates;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) QueryColorDatabase("#0000",&clone_info->fill,&image->exception);
resolution.x=DefaultResolution;
resolution.y=DefaultResolution;
if (clone_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(clone_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == MagickFalse)
resolution.y=resolution.x;
}
mid=(resolution.x/72.0)*ExpandAffine(&clone_info->affine)*
clone_info->stroke_width/2.0;
bounds.x1=0.0;
bounds.y1=0.0;
bounds.x2=0.0;
bounds.y2=0.0;
if (polygon_info != (PolygonInfo *) NULL)
{
bounds=polygon_info->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1)
bounds.x1=polygon_info->edges[i].bounds.x1;
if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1)
bounds.y1=polygon_info->edges[i].bounds.y1;
if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2)
bounds.x2=polygon_info->edges[i].bounds.x2;
if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2)
bounds.y2=polygon_info->edges[i].bounds.y2;
}
bounds.x1-=mid;
bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double)
image->columns ? (double) image->columns-1 : bounds.x1;
bounds.y1-=mid;
bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double)
image->rows ? (double) image->rows-1 : bounds.y1;
bounds.x2+=mid;
bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double)
image->columns ? (double) image->columns-1 : bounds.x2;
bounds.y2+=mid;
bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double)
image->rows ? (double) image->rows-1 : bounds.y2;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].direction != 0)
(void) QueryColorDatabase("red",&clone_info->stroke,
&image->exception);
else
(void) QueryColorDatabase("green",&clone_info->stroke,
&image->exception);
start.x=(double) (polygon_info->edges[i].bounds.x1-mid);
start.y=(double) (polygon_info->edges[i].bounds.y1-mid);
end.x=(double) (polygon_info->edges[i].bounds.x2+mid);
end.y=(double) (polygon_info->edges[i].bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
(void) DrawPrimitive(image,clone_info,primitive_info);
}
}
(void) QueryColorDatabase("blue",&clone_info->stroke,&image->exception);
start.x=(double) (bounds.x1-mid);
start.y=(double) (bounds.y1-mid);
end.x=(double) (bounds.x2+mid);
end.y=(double) (bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
(void) DrawPrimitive(image,clone_info,primitive_info);
clone_info=DestroyDrawInfo(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w C l i p P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawClipPath() draws the clip path on the image mask.
%
% The format of the DrawClipPath method is:
%
% MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info,
% const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o name: the name of the clip path.
%
*/
MagickExport MagickBooleanType DrawClipPath(Image *image,
const DrawInfo *draw_info,const char *name)
{
char
clip_mask[MaxTextExtent];
const char
*value;
DrawInfo
*clone_info;
MagickStatusType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
(void) FormatLocaleString(clip_mask,MaxTextExtent,"%s",name);
value=GetImageArtifact(image,clip_mask);
if (value == (const char *) NULL)
return(MagickFalse);
if (image->clip_mask == (Image *) NULL)
{
Image
*clip_mask;
clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,
&image->exception);
if (clip_mask == (Image *) NULL)
return(MagickFalse);
(void) SetImageClipMask(image,clip_mask);
clip_mask=DestroyImage(clip_mask);
}
(void) QueryColorDatabase("#00000000",&image->clip_mask->background_color,
&image->exception);
image->clip_mask->background_color.opacity=(Quantum) TransparentOpacity;
(void) SetImageBackgroundColor(image->clip_mask);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s",
draw_info->clip_mask);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->primitive,value);
(void) QueryColorDatabase("#ffffff",&clone_info->fill,&image->exception);
clone_info->clip_mask=(char *) NULL;
status=DrawImage(image->clip_mask,clone_info);
status&=NegateImage(image->clip_mask,MagickFalse);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w D a s h P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the
% image while respecting the dash offset and dash pattern attributes.
%
% The format of the DrawDashPolygon method is:
%
% MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info,Image *image)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o image: the image.
%
%
*/
static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,Image *image)
{
double
length,
maximum_length,
offset,
scale,
total_length;
DrawInfo
*clone_info;
MagickStatusType
status;
PrimitiveInfo
*dash_polygon;
register double
dx,
dy;
register ssize_t
i;
size_t
number_vertices;
ssize_t
j,
n;
assert(draw_info != (const DrawInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash");
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
number_vertices=(size_t) i;
dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(2UL*number_vertices+1UL),sizeof(*dash_polygon));
if (dash_polygon == (PrimitiveInfo *) NULL)
return(MagickFalse);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->miterlimit=0;
dash_polygon[0]=primitive_info[0];
scale=ExpandAffine(&draw_info->affine);
length=scale*(draw_info->dash_pattern[0]-0.5);
offset=fabs(draw_info->dash_offset) >= DrawEpsilon ?
scale*draw_info->dash_offset : 0.0;
j=1;
for (n=0; offset > 0.0; j=0)
{
if (draw_info->dash_pattern[n] <= 0.0)
break;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
if (offset > length)
{
offset-=length;
n++;
length=scale*(draw_info->dash_pattern[n]+0.5);
continue;
}
if (offset < length)
{
length-=offset;
offset=0.0;
break;
}
offset=0.0;
n++;
}
status=MagickTrue;
maximum_length=0.0;
total_length=0.0;
for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++)
{
dx=primitive_info[i].point.x-primitive_info[i-1].point.x;
dy=primitive_info[i].point.y-primitive_info[i-1].point.y;
maximum_length=hypot((double) dx,dy);
if (fabs(length) < DrawEpsilon)
{
n++;
if (fabs(draw_info->dash_pattern[n]) < DrawEpsilon)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); )
{
total_length+=length;
if ((n & 0x01) != 0)
{
dash_polygon[0]=primitive_info[0];
dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
j=1;
}
else
{
if ((j+1) > (ssize_t) (2*number_vertices))
break;
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon);
}
n++;
if (fabs(draw_info->dash_pattern[n]) < DrawEpsilon)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
length-=(maximum_length-total_length);
if ((n & 0x01) != 0)
continue;
dash_polygon[j]=primitive_info[i];
dash_polygon[j].coordinates=1;
j++;
}
if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1))
{
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x+=DrawEpsilon;
dash_polygon[j].point.y+=DrawEpsilon;
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon);
}
dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawImage() draws a graphic primitive on your image. The primitive
% may be represented as a string or filename. Precede the filename with an
% "at" sign (@) and the contents of the file are drawn on the image. You
% can affect how text is drawn by setting one or more members of the draw
% info structure.
%
% The format of the DrawImage method is:
%
% MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
*/
static inline MagickBooleanType IsPoint(const char *point)
{
char
*p;
double
value;
value=StringToDouble(point,&p);
return((fabs(value) < DrawEpsilon) && (p == point) ? MagickFalse : MagickTrue);
}
static inline void TracePoint(PrimitiveInfo *primitive_info,
const PointInfo point)
{
primitive_info->coordinates=1;
primitive_info->point=point;
}
MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info)
{
#define RenderImageTag "Render/Image"
AffineMatrix
affine,
current;
char
key[2*MaxTextExtent],
keyword[MaxTextExtent],
geometry[MaxTextExtent],
name[MaxTextExtent],
*next_token,
pattern[MaxTextExtent],
*primitive,
*token;
const char
*q;
double
angle,
factor,
primitive_extent;
DrawInfo
**graphic_context;
MagickBooleanType
proceed;
MagickSizeType
length,
number_points;
MagickStatusType
status;
PointInfo
point;
PixelPacket
start_color;
PrimitiveInfo
*primitive_info;
PrimitiveType
primitive_type;
register const char
*p;
register ssize_t
i,
x;
SegmentInfo
bounds;
size_t
extent;
ssize_t
j,
k,
n;
/*
Ensure the annotation info is valid.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if ((draw_info->primitive == (char *) NULL) ||
(*draw_info->primitive == '\0'))
return(MagickFalse);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image");
if (*draw_info->primitive != '@')
primitive=AcquireString(draw_info->primitive);
else
primitive=FileToString(draw_info->primitive+1,~0UL,&image->exception);
if (primitive == (char *) NULL)
return(MagickFalse);
primitive_extent=(double) strlen(primitive);
(void) SetImageArtifact(image,"MVG",primitive);
n=0;
/*
Allocate primitive info memory.
*/
graphic_context=(DrawInfo **) AcquireMagickMemory(
sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
primitive=DestroyString(primitive);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
number_points=6553;
primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
primitive=DestroyString(primitive);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info);
graphic_context[n]->viewbox=image->page;
if ((image->page.width == 0) || (image->page.height == 0))
{
graphic_context[n]->viewbox.width=image->columns;
graphic_context[n]->viewbox.height=image->rows;
}
token=AcquireString(primitive);
extent=strlen(token)+MaxTextExtent;
(void) QueryColorDatabase("#000000",&start_color,&image->exception);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
for (q=primitive; *q != '\0'; )
{
/*
Interpret graphic primitive.
*/
GetNextToken(q,&q,MaxTextExtent,keyword);
if (*keyword == '\0')
break;
if (*keyword == '#')
{
/*
Comment.
*/
while ((*q != '\n') && (*q != '\0'))
q++;
continue;
}
p=q-strlen(keyword)-1;
primitive_type=UndefinedPrimitive;
current=graphic_context[n]->affine;
GetAffineMatrix(&affine);
switch (*keyword)
{
case ';':
break;
case 'a':
case 'A':
{
if (LocaleCompare("affine",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.rx=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ry=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("arc",keyword) == 0)
{
primitive_type=ArcPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'b':
case 'B':
{
if (LocaleCompare("bezier",keyword) == 0)
{
primitive_type=BezierPrimitive;
break;
}
if (LocaleCompare("border-color",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) QueryColorDatabase(token,&graphic_context[n]->border_color,
&image->exception);
break;
}
status=MagickFalse;
break;
}
case 'c':
case 'C':
{
if (LocaleCompare("clip-path",keyword) == 0)
{
/*
Create clip mask.
*/
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->clip_mask,token);
(void) DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask);
break;
}
if (LocaleCompare("clip-rule",keyword) == 0)
{
ssize_t
fill_rule;
GetNextToken(q,&q,extent,token);
fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("clip-units",keyword) == 0)
{
ssize_t
clip_units;
GetNextToken(q,&q,extent,token);
clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse,
token);
if (clip_units == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->clip_units=(ClipPathUnits) clip_units;
if (clip_units == ObjectBoundingBox)
{
GetAffineMatrix(¤t);
affine.sx=draw_info->bounds.x2;
affine.sy=draw_info->bounds.y2;
affine.tx=draw_info->bounds.x1;
affine.ty=draw_info->bounds.y1;
break;
}
break;
}
if (LocaleCompare("circle",keyword) == 0)
{
primitive_type=CirclePrimitive;
break;
}
if (LocaleCompare("color",keyword) == 0)
{
primitive_type=ColorPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'd':
case 'D':
{
if (LocaleCompare("decorate",keyword) == 0)
{
ssize_t
decorate;
GetNextToken(q,&q,extent,token);
decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse,
token);
if (decorate == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->decorate=(DecorationType) decorate;
break;
}
if (LocaleCompare("direction",keyword) == 0)
{
ssize_t
direction;
GetNextToken(q,&q,extent,token);
direction=ParseCommandOption(MagickDirectionOptions,MagickFalse,
token);
if (direction == -1)
status=MagickFalse;
else
graphic_context[n]->direction=(DirectionType) direction;
break;
}
status=MagickFalse;
break;
}
case 'e':
case 'E':
{
if (LocaleCompare("ellipse",keyword) == 0)
{
primitive_type=EllipsePrimitive;
break;
}
if (LocaleCompare("encoding",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->encoding,token);
break;
}
status=MagickFalse;
break;
}
case 'f':
case 'F':
{
if (LocaleCompare("fill",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(pattern,MaxTextExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->fill_pattern);
else
{
status&=QueryColorDatabase(token,&graphic_context[n]->fill,
&image->exception);
if (graphic_context[n]->fill_opacity != OpaqueOpacity)
graphic_context[n]->fill.opacity=
graphic_context[n]->fill_opacity;
if (status == MagickFalse)
{
ImageInfo
*pattern_info;
pattern_info=AcquireImageInfo();
(void) CopyMagickString(pattern_info->filename,token,
MaxTextExtent);
graphic_context[n]->fill_pattern=
ReadImage(pattern_info,&image->exception);
CatchException(&image->exception);
pattern_info=DestroyImageInfo(pattern_info);
}
}
break;
}
if (LocaleCompare("fill-opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->fill.opacity=QuantumRange*factor*
StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("fill-rule",keyword) == 0)
{
ssize_t
fill_rule;
GetNextToken(q,&q,extent,token);
fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("font",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->font,token);
if (LocaleCompare("none",token) == 0)
graphic_context[n]->font=(char *)
RelinquishMagickMemory(graphic_context[n]->font);
break;
}
if (LocaleCompare("font-family",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->family,token);
break;
}
if (LocaleCompare("font-size",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->pointsize=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("font-stretch",keyword) == 0)
{
ssize_t
stretch;
GetNextToken(q,&q,extent,token);
stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token);
if (stretch == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->stretch=(StretchType) stretch;
break;
}
if (LocaleCompare("font-style",keyword) == 0)
{
ssize_t
style;
GetNextToken(q,&q,extent,token);
style=ParseCommandOption(MagickStyleOptions,MagickFalse,token);
if (style == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->style=(StyleType) style;
break;
}
if (LocaleCompare("font-weight",keyword) == 0)
{
ssize_t
weight;
GetNextToken(q,&q,extent,token);
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token);
if (weight == -1)
weight=(ssize_t) StringToUnsignedLong(token);
graphic_context[n]->weight=(size_t) weight;
break;
}
status=MagickFalse;
break;
}
case 'g':
case 'G':
{
if (LocaleCompare("gradient-units",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("gravity",keyword) == 0)
{
ssize_t
gravity;
GetNextToken(q,&q,extent,token);
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token);
if (gravity == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->gravity=(GravityType) gravity;
break;
}
status=MagickFalse;
break;
}
case 'i':
case 'I':
{
if (LocaleCompare("image",keyword) == 0)
{
ssize_t
compose;
primitive_type=ImagePrimitive;
GetNextToken(q,&q,extent,token);
compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token);
if (compose == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->compose=(CompositeOperator) compose;
break;
}
if (LocaleCompare("interline-spacing",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->interline_spacing=StringToDouble(token,
&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("interword-spacing",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->interword_spacing=StringToDouble(token,
&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'k':
case 'K':
{
if (LocaleCompare("kerning",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->kerning=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'l':
case 'L':
{
if (LocaleCompare("line",keyword) == 0)
{
primitive_type=LinePrimitive;
break;
}
status=MagickFalse;
break;
}
case 'm':
case 'M':
{
if (LocaleCompare("matte",keyword) == 0)
{
primitive_type=MattePrimitive;
break;
}
status=MagickFalse;
break;
}
case 'o':
case 'O':
{
if (LocaleCompare("offset",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->fill_opacity=QuantumRange-QuantumRange*((1.0-
QuantumScale*graphic_context[n]->fill_opacity)*factor*
StringToDouble(token,&next_token));
graphic_context[n]->stroke_opacity=QuantumRange-QuantumRange*((1.0-
QuantumScale*graphic_context[n]->stroke_opacity)*factor*
StringToDouble(token,&next_token));
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'p':
case 'P':
{
if (LocaleCompare("path",keyword) == 0)
{
primitive_type=PathPrimitive;
break;
}
if (LocaleCompare("point",keyword) == 0)
{
primitive_type=PointPrimitive;
break;
}
if (LocaleCompare("polyline",keyword) == 0)
{
primitive_type=PolylinePrimitive;
break;
}
if (LocaleCompare("polygon",keyword) == 0)
{
primitive_type=PolygonPrimitive;
break;
}
if (LocaleCompare("pop",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare("clip-path",token) == 0)
break;
if (LocaleCompare("defs",token) == 0)
break;
if (LocaleCompare("gradient",token) == 0)
break;
if (LocaleCompare("graphic-context",token) == 0)
{
if (n <= 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),DrawError,
"UnbalancedGraphicContextPushPop","`%s'",token);
status=MagickFalse;
n=0;
break;
}
if (graphic_context[n]->clip_mask != (char *) NULL)
if (LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0)
(void) SetImageClipMask(image,(Image *) NULL);
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
n--;
break;
}
if (LocaleCompare("pattern",token) == 0)
break;
status=MagickFalse;
break;
}
if (LocaleCompare("push",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare("clip-path",token) == 0)
{
char
name[MaxTextExtent];
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(name,MaxTextExtent,"%s",token);
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"clip-path") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
(void) SetImageArtifact(image,name,token);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("gradient",token) == 0)
{
char
key[2*MaxTextExtent],
name[MaxTextExtent],
type[MaxTextExtent];
SegmentInfo
segment;
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MaxTextExtent);
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(type,token,MaxTextExtent);
GetNextToken(q,&q,extent,token);
segment.x1=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.y1=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.x2=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.y2=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
if (LocaleCompare(type,"radial") == 0)
{
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
}
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"gradient") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
bounds.x1=graphic_context[n]->affine.sx*segment.x1+
graphic_context[n]->affine.ry*segment.y1+
graphic_context[n]->affine.tx;
bounds.y1=graphic_context[n]->affine.rx*segment.x1+
graphic_context[n]->affine.sy*segment.y1+
graphic_context[n]->affine.ty;
bounds.x2=graphic_context[n]->affine.sx*segment.x2+
graphic_context[n]->affine.ry*segment.y2+
graphic_context[n]->affine.tx;
bounds.y2=graphic_context[n]->affine.rx*segment.x2+
graphic_context[n]->affine.sy*segment.y2+
graphic_context[n]->affine.ty;
(void) FormatLocaleString(key,MaxTextExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatLocaleString(key,MaxTextExtent,"%s-type",name);
(void) SetImageArtifact(image,key,type);
(void) FormatLocaleString(key,MaxTextExtent,"%s-geometry",name);
(void) FormatLocaleString(geometry,MaxTextExtent,
"%gx%g%+.15g%+.15g",
MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0),
MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0),
bounds.x1,bounds.y1);
(void) SetImageArtifact(image,key,geometry);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("pattern",token) == 0)
{
RectangleInfo
bounds;
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MaxTextExtent);
GetNextToken(q,&q,extent,token);
bounds.x=(ssize_t) ceil(StringToDouble(token,&next_token)-0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
bounds.y=(ssize_t) ceil(StringToDouble(token,&next_token)-0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
bounds.width=(size_t) floor(StringToDouble(token,&next_token)+
0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
bounds.height=(size_t) floor(StringToDouble(token,&next_token)+
0.5);
if (token == next_token)
status=MagickFalse;
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"pattern") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
(void) FormatLocaleString(key,MaxTextExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatLocaleString(key,MaxTextExtent,"%s-geometry",name);
(void) FormatLocaleString(geometry,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) bounds.width,(double)
bounds.height,(double) bounds.x,(double) bounds.y);
(void) SetImageArtifact(image,key,geometry);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("graphic-context",token) == 0)
{
n++;
graphic_context=(DrawInfo **) ResizeQuantumMemory(
graphic_context,(size_t) (n+1),sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),ResourceLimitError,
"MemoryAllocationFailed","`%s'",image->filename);
break;
}
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,
graphic_context[n-1]);
break;
}
if (LocaleCompare("defs",token) == 0)
break;
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'r':
case 'R':
{
if (LocaleCompare("rectangle",keyword) == 0)
{
primitive_type=RectanglePrimitive;
break;
}
if (LocaleCompare("rotate",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0)));
break;
}
if (LocaleCompare("roundRectangle",keyword) == 0)
{
primitive_type=RoundRectanglePrimitive;
break;
}
status=MagickFalse;
break;
}
case 's':
case 'S':
{
if (LocaleCompare("scale",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("skewX",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
affine.ry=sin(DegreesToRadians(angle));
break;
}
if (LocaleCompare("skewY",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
affine.rx=(-tan(DegreesToRadians(angle)/2.0));
break;
}
if (LocaleCompare("stop-color",keyword) == 0)
{
GradientType
type;
PixelPacket
stop_color;
GetNextToken(q,&q,extent,token);
(void) QueryColorDatabase(token,&stop_color,&image->exception);
type=LinearGradient;
if (draw_info->gradient.type == RadialGradient)
type=RadialGradient;
(void) GradientImage(image,type,PadSpread,&start_color,&stop_color);
start_color=stop_color;
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("stroke",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(pattern,MaxTextExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->stroke_pattern);
else
{
status&=QueryColorDatabase(token,&graphic_context[n]->stroke,
&image->exception);
if (graphic_context[n]->stroke_opacity != OpaqueOpacity)
graphic_context[n]->stroke.opacity=
graphic_context[n]->stroke_opacity;
if (status == MagickFalse)
{
ImageInfo
*pattern_info;
pattern_info=AcquireImageInfo();
(void) CopyMagickString(pattern_info->filename,token,
MaxTextExtent);
graphic_context[n]->stroke_pattern=
ReadImage(pattern_info,&image->exception);
CatchException(&image->exception);
pattern_info=DestroyImageInfo(pattern_info);
}
}
break;
}
if (LocaleCompare("stroke-antialias",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->stroke_antialias=
StringToLong(token) != 0 ? MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("stroke-dasharray",keyword) == 0)
{
if (graphic_context[n]->dash_pattern != (double *) NULL)
graphic_context[n]->dash_pattern=(double *)
RelinquishMagickMemory(graphic_context[n]->dash_pattern);
if (IsPoint(q) != MagickFalse)
{
const char
*p;
p=q;
GetNextToken(p,&p,extent,token);
if (*token == ',')
GetNextToken(p,&p,extent,token);
for (x=0; IsPoint(token) != MagickFalse; x++)
{
GetNextToken(p,&p,extent,token);
if (*token == ',')
GetNextToken(p,&p,extent,token);
}
graphic_context[n]->dash_pattern=(double *)
AcquireQuantumMemory((size_t) (2UL*x+1UL),
sizeof(*graphic_context[n]->dash_pattern));
if (graphic_context[n]->dash_pattern == (double *) NULL)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),ResourceLimitError,
"MemoryAllocationFailed","`%s'",image->filename);
status=MagickFalse;
break;
}
for (j=0; j < x; j++)
{
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->dash_pattern[j]=StringToDouble(token,
&next_token);
if (token == next_token)
status=MagickFalse;
if (graphic_context[n]->dash_pattern[j] < 0.0)
status=MagickFalse;
}
if ((x & 0x01) != 0)
for ( ; j < (2*x); j++)
graphic_context[n]->dash_pattern[j]=
graphic_context[n]->dash_pattern[j-x];
graphic_context[n]->dash_pattern[j]=0.0;
break;
}
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("stroke-dashoffset",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->dash_offset=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("stroke-linecap",keyword) == 0)
{
ssize_t
linecap;
GetNextToken(q,&q,extent,token);
linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token);
if (linecap == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->linecap=(LineCap) linecap;
break;
}
if (LocaleCompare("stroke-linejoin",keyword) == 0)
{
ssize_t
linejoin;
GetNextToken(q,&q,extent,token);
linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse,
token);
if (linejoin == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->linejoin=(LineJoin) linejoin;
break;
}
if (LocaleCompare("stroke-miterlimit",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->miterlimit=StringToUnsignedLong(token);
break;
}
if (LocaleCompare("stroke-opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->stroke.opacity=QuantumRange*factor*
StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("stroke-width",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->stroke_width=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 't':
case 'T':
{
if (LocaleCompare("text",keyword) == 0)
{
primitive_type=TextPrimitive;
break;
}
if (LocaleCompare("text-align",keyword) == 0)
{
ssize_t
align;
GetNextToken(q,&q,extent,token);
align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-anchor",keyword) == 0)
{
ssize_t
align;
GetNextToken(q,&q,extent,token);
align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-antialias",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->text_antialias=
StringToLong(token) != 0 ? MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("text-undercolor",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) QueryColorDatabase(token,&graphic_context[n]->undercolor,
&image->exception);
break;
}
if (LocaleCompare("translate",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'v':
case 'V':
{
if (LocaleCompare("viewbox",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token,
&next_token)-0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token,
&next_token)-0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble(
token,&next_token)+0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble(
token,&next_token)+0.5);
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
default:
{
status=MagickFalse;
break;
}
}
if (status == MagickFalse)
break;
if ((fabs(affine.sx-1.0) >= DrawEpsilon) ||
(fabs(affine.rx) >= DrawEpsilon) ||
(fabs(affine.ry) >= DrawEpsilon) ||
(fabs(affine.sy-1.0) >= DrawEpsilon) ||
(fabs(affine.tx) >= DrawEpsilon) ||
(fabs(affine.ty) >= DrawEpsilon))
{
graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx;
graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx;
graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy;
graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy;
graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+
current.tx;
graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+
current.ty;
}
if (primitive_type == UndefinedPrimitive)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",
(int) (q-p),p);
continue;
}
/*
Parse the primitive attributes.
*/
i=0;
j=0;
primitive_info[0].point.x=0.0;
primitive_info[0].point.y=0.0;
for (x=0; *q != '\0'; x++)
{
/*
Define points.
*/
if (IsPoint(q) == MagickFalse)
break;
GetNextToken(q,&q,extent,token);
point.x=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
point.y=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,(const char **) NULL,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
primitive_info[i].primitive=primitive_type;
primitive_info[i].point=point;
primitive_info[i].coordinates=0;
primitive_info[i].method=FloodfillMethod;
i++;
if (i < (ssize_t) number_points)
continue;
number_points<<=1;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
(size_t) number_points,sizeof(*primitive_info));
if ((primitive_info == (PrimitiveInfo *) NULL) ||
(number_points != (MagickSizeType) ((size_t) number_points)))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
break;
}
}
primitive_info[j].primitive=primitive_type;
primitive_info[j].coordinates=(size_t) x;
primitive_info[j].method=FloodfillMethod;
primitive_info[j].text=(char *) NULL;
/*
Circumscribe primitive within a circle.
*/
bounds.x1=primitive_info[j].point.x;
bounds.y1=primitive_info[j].point.y;
bounds.x2=primitive_info[j].point.x;
bounds.y2=primitive_info[j].point.y;
for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++)
{
point=primitive_info[j+k].point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.y < bounds.y1)
bounds.y1=point.y;
if (point.x > bounds.x2)
bounds.x2=point.x;
if (point.y > bounds.y2)
bounds.y2=point.y;
}
/*
Speculate how many points our primitive might consume.
*/
length=primitive_info[j].coordinates;
switch (primitive_type)
{
case RectanglePrimitive:
{
length*=5;
break;
}
case RoundRectanglePrimitive:
{
double
alpha,
beta,
radius;
alpha=bounds.x2-bounds.x1;
beta=bounds.y2-bounds.y1;
radius=hypot((double) alpha,(double) beta);
length*=5;
length+=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates > 107)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
DrawError,"TooManyBezierCoordinates","`%s'",token);
length=BezierQuantum*primitive_info[j].coordinates;
break;
}
case PathPrimitive:
{
char
*s,
*t;
GetNextToken(q,&q,extent,token);
length=1;
t=token;
for (s=token; *s != '\0'; s=t)
{
double
value;
value=StringToDouble(s,&t);
(void) value;
if (s == t)
{
t++;
continue;
}
length++;
}
length=length*BezierQuantum;
break;
}
case CirclePrimitive:
case ArcPrimitive:
case EllipsePrimitive:
{
double
alpha,
beta,
radius;
alpha=bounds.x2-bounds.x1;
beta=bounds.y2-bounds.y1;
radius=hypot((double) alpha,(double) beta);
length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;
break;
}
default:
break;
}
if ((i+length) >= number_points)
{
/*
Resize based on speculative points required by primitive.
*/
number_points+=length+1;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
(size_t) number_points,sizeof(*primitive_info));
if ((primitive_info == (PrimitiveInfo *) NULL) ||
(number_points != (MagickSizeType) ((size_t) number_points)))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
}
switch (primitive_type)
{
case PointPrimitive:
default:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
TracePoint(primitive_info+j,primitive_info[j].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case LinePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceLine(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RectanglePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceRectangle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RoundRectanglePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
TraceRoundRectangle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case ArcPrimitive:
{
if (primitive_info[j].coordinates != 3)
{
primitive_type=UndefinedPrimitive;
break;
}
TraceArc(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case EllipsePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
TraceEllipse(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case CirclePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceCircle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PolylinePrimitive:
break;
case PolygonPrimitive:
{
primitive_info[i]=primitive_info[j];
primitive_info[i].coordinates=0;
primitive_info[j].coordinates++;
i++;
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates < 3)
{
status=MagickFalse;
break;
}
TraceBezier(primitive_info+j,primitive_info[j].coordinates);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PathPrimitive:
{
i=(ssize_t) (j+TracePath(primitive_info+j,token));
break;
}
case ColorPrimitive:
case MattePrimitive:
{
ssize_t
method;
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
GetNextToken(q,&q,extent,token);
method=ParseCommandOption(MagickMethodOptions,MagickFalse,token);
if (method == -1)
{
status=MagickFalse;
break;
}
primitive_info[j].method=(PaintMethod) method;
break;
}
case TextPrimitive:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
if (*token != ',')
GetNextToken(q,&q,extent,token);
primitive_info[j].text=AcquireString(token);
break;
}
case ImagePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
GetNextToken(q,&q,extent,token);
primitive_info[j].text=AcquireString(token);
break;
}
}
if (primitive_info == (PrimitiveInfo *) NULL)
break;
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p);
if (status == MagickFalse)
break;
primitive_info[i].primitive=UndefinedPrimitive;
if (i == 0)
continue;
/*
Transform points.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+
graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx;
primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+
graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty;
point=primitive_info[i].point;
if (point.x < graphic_context[n]->bounds.x1)
graphic_context[n]->bounds.x1=point.x;
if (point.y < graphic_context[n]->bounds.y1)
graphic_context[n]->bounds.y1=point.y;
if (point.x > graphic_context[n]->bounds.x2)
graphic_context[n]->bounds.x2=point.x;
if (point.y > graphic_context[n]->bounds.y2)
graphic_context[n]->bounds.y2=point.y;
if (primitive_info[i].primitive == ImagePrimitive)
break;
if (i >= (ssize_t) number_points)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
}
if (graphic_context[n]->render != MagickFalse)
{
if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) &&
(LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0))
status&=DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask);
status&=DrawPrimitive(image,graphic_context[n],primitive_info);
}
if (primitive_info->text != (char *) NULL)
primitive_info->text=(char *) RelinquishMagickMemory(
primitive_info->text);
proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType)
primitive_extent);
if (proceed == MagickFalse)
break;
if (status == 0)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image");
/*
Relinquish resources.
*/
token=DestroyString(token);
if (primitive_info != (PrimitiveInfo *) NULL)
primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info);
primitive=DestroyString(primitive);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
if (status == MagickFalse)
ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition",
keyword);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w G r a d i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawGradientImage() draws a linear gradient on the image.
%
% The format of the DrawGradientImage method is:
%
% MagickBooleanType DrawGradientImage(Image *image,
% const DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o _info: the draw info.
%
*/
static inline double GetStopColorOffset(const GradientInfo *gradient,
const ssize_t x,const ssize_t y)
{
switch (gradient->type)
{
case UndefinedGradient:
case LinearGradient:
{
double
gamma,
length,
offset,
scale;
PointInfo
p,
q;
const SegmentInfo
*gradient_vector;
gradient_vector=(&gradient->gradient_vector);
p.x=gradient_vector->x2-gradient_vector->x1;
p.y=gradient_vector->y2-gradient_vector->y1;
q.x=(double) x-gradient_vector->x1;
q.y=(double) y-gradient_vector->y1;
length=sqrt(q.x*q.x+q.y*q.y);
gamma=sqrt(p.x*p.x+p.y*p.y)*length;
gamma=PerceptibleReciprocal(gamma);
scale=p.x*q.x+p.y*q.y;
offset=gamma*scale*length;
return(offset);
}
case RadialGradient:
{
PointInfo
v;
if (gradient->spread == RepeatSpread)
{
v.x=(double) x-gradient->center.x;
v.y=(double) y-gradient->center.y;
return(sqrt(v.x*v.x+v.y*v.y));
}
v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians(
gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians(
gradient->angle))))/gradient->radii.x;
v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians(
gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians(
gradient->angle))))/gradient->radii.y;
return(sqrt(v.x*v.x+v.y*v.y));
}
}
return(0.0);
}
MagickExport MagickBooleanType DrawGradientImage(Image *image,
const DrawInfo *draw_info)
{
CacheView
*image_view;
const GradientInfo
*gradient;
const SegmentInfo
*gradient_vector;
double
length;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickPixelPacket
zero;
PointInfo
point;
RectangleInfo
bounding_box;
ssize_t
y;
/*
Draw linear or radial gradient on image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
gradient=(&draw_info->gradient);
gradient_vector=(&gradient->gradient_vector);
point.x=gradient_vector->x2-gradient_vector->x1;
point.y=gradient_vector->y2-gradient_vector->y1;
length=sqrt(point.x*point.x+point.y*point.y);
bounding_box=gradient->bounding_box;
status=MagickTrue;
exception=(&image->exception);
GetMagickPixelPacket(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++)
{
double
alpha,
offset;
MagickPixelPacket
composite,
pixel;
register IndexPacket
*magick_restrict indexes;
register ssize_t
i,
x;
register PixelPacket
*magick_restrict q;
ssize_t
j;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
pixel=zero;
composite=zero;
offset=GetStopColorOffset(gradient,0,y);
if (gradient->type != RadialGradient)
offset/=length;
for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++)
{
SetMagickPixelPacket(image,q,indexes+x,&pixel);
switch (gradient->spread)
{
case UndefinedSpread:
case PadSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset/=length;
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if ((offset < 0.0) || (i == 0))
composite=gradient->stops[0].color;
else
if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops))
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
MagickPixelCompositeBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case ReflectSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset/=length;
}
if (offset < 0.0)
offset=(-offset);
if ((ssize_t) fmod(offset,2.0) == 0)
offset=fmod(offset,1.0);
else
offset=1.0-fmod(offset,1.0);
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
MagickPixelCompositeBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case RepeatSpread:
{
double
repeat;
MagickBooleanType
antialias;
antialias=MagickFalse;
repeat=0.0;
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type == LinearGradient)
{
repeat=fmod(offset,length);
if (repeat < 0.0)
repeat=length-fmod(-repeat,length);
else
repeat=fmod(offset,length);
antialias=(repeat < length) && ((repeat+1.0) > length) ?
MagickTrue : MagickFalse;
offset=repeat/length;
}
else
{
repeat=fmod(offset,(double) gradient->radius);
if (repeat < 0.0)
repeat=gradient->radius-fmod(-repeat,
(double) gradient->radius);
else
repeat=fmod(offset,(double) gradient->radius);
antialias=repeat+1.0 > gradient->radius ? MagickTrue :
MagickFalse;
offset=repeat/gradient->radius;
}
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
if (antialias != MagickFalse)
{
if (gradient->type == LinearGradient)
alpha=length-repeat;
else
alpha=gradient->radius-repeat;
i=0;
j=(ssize_t) gradient->number_stops-1L;
}
MagickPixelCompositeBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
}
MagickPixelCompositeOver(&composite,composite.opacity,&pixel,
pixel.opacity,&pixel);
SetPixelPacket(image,&pixel,q,indexes+x);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P a t t e r n P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPatternPath() draws a pattern.
%
% The format of the DrawPatternPath method is:
%
% MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info,
% const char *name,Image **pattern)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o name: the pattern name.
%
% o image: the image.
%
*/
MagickExport MagickBooleanType DrawPatternPath(Image *image,
const DrawInfo *draw_info,const char *name,Image **pattern)
{
char
property[MaxTextExtent];
const char
*geometry,
*path,
*type;
DrawInfo
*clone_info;
ImageInfo
*image_info;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
assert(name != (const char *) NULL);
(void) FormatLocaleString(property,MaxTextExtent,"%s",name);
path=GetImageArtifact(image,property);
if (path == (const char *) NULL)
return(MagickFalse);
(void) FormatLocaleString(property,MaxTextExtent,"%s-geometry",name);
geometry=GetImageArtifact(image,property);
if (geometry == (const char *) NULL)
return(MagickFalse);
if ((*pattern) != (Image *) NULL)
*pattern=DestroyImage(*pattern);
image_info=AcquireImageInfo();
image_info->size=AcquireString(geometry);
*pattern=AcquireImage(image_info);
image_info=DestroyImageInfo(image_info);
(void) QueryColorDatabase("#00000000",&(*pattern)->background_color,
&image->exception);
(void) SetImageBackgroundColor(*pattern);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"begin pattern-path %s %s",name,geometry);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill_pattern=NewImageList();
clone_info->stroke_pattern=NewImageList();
(void) FormatLocaleString(property,MaxTextExtent,"%s-type",name);
type=GetImageArtifact(image,property);
if (type != (const char *) NULL)
clone_info->gradient.type=(GradientType) ParseCommandOption(
MagickGradientOptions,MagickFalse,type);
(void) CloneString(&clone_info->primitive,path);
status=DrawImage(*pattern,clone_info);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w P o l y g o n P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPolygonPrimitive() draws a polygon on the image.
%
% The format of the DrawPolygonPrimitive method is:
%
% MagickBooleanType DrawPolygonPrimitive(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
*/
static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info)
{
register ssize_t
i;
assert(polygon_info != (PolygonInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (polygon_info[i] != (PolygonInfo *) NULL)
polygon_info[i]=DestroyPolygonInfo(polygon_info[i]);
polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info);
return(polygon_info);
}
static PolygonInfo **AcquirePolygonThreadSet(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info)
{
PathInfo
*magick_restrict path_info;
PolygonInfo
**polygon_info;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads,
sizeof(*polygon_info));
if (polygon_info == (PolygonInfo **) NULL)
return((PolygonInfo **) NULL);
(void) ResetMagickMemory(polygon_info,0,(size_t)
GetMagickResourceLimit(ThreadResource)*sizeof(*polygon_info));
path_info=ConvertPrimitiveToPath(draw_info,primitive_info);
if (path_info == (PathInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
for (i=0; i < (ssize_t) number_threads; i++)
{
polygon_info[i]=ConvertPathToPolygon(path_info);
if (polygon_info[i] == (PolygonInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
}
path_info=(PathInfo *) RelinquishMagickMemory(path_info);
return(polygon_info);
}
static double GetOpacityPixel(PolygonInfo *polygon_info,const double mid,
const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x,
const ssize_t y,double *stroke_opacity)
{
double
alpha,
beta,
distance,
subpath_opacity;
PointInfo
delta;
register EdgeInfo
*p;
register const PointInfo
*q;
register ssize_t
i;
ssize_t
j,
winding_number;
/*
Compute fill & stroke opacity for this (x,y) point.
*/
*stroke_opacity=0.0;
subpath_opacity=0.0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if ((double) y <= (p->bounds.y1-mid-0.5))
break;
if ((double) y > (p->bounds.y2+mid+0.5))
{
(void) DestroyEdge(polygon_info,(size_t) j);
continue;
}
if (((double) x <= (p->bounds.x1-mid-0.5)) ||
((double) x > (p->bounds.x2+mid+0.5)))
continue;
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) p->number_points; i++)
{
if ((double) y <= (p->points[i-1].y-mid-0.5))
break;
if ((double) y > (p->points[i].y+mid+0.5))
continue;
if (p->scanline != (double) y)
{
p->scanline=(double) y;
p->highwater=(size_t) i;
}
/*
Compute distance between a point and an edge.
*/
q=p->points+i-1;
delta.x=(q+1)->x-q->x;
delta.y=(q+1)->y-q->y;
beta=delta.x*(x-q->x)+delta.y*(y-q->y);
if (beta < 0.0)
{
delta.x=(double) x-q->x;
delta.y=(double) y-q->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=delta.x*delta.x+delta.y*delta.y;
if (beta > alpha)
{
delta.x=(double) x-(q+1)->x;
delta.y=(double) y-(q+1)->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=1.0/alpha;
beta=delta.x*(y-q->y)-delta.y*(x-q->x);
distance=alpha*beta*beta;
}
}
/*
Compute stroke & subpath opacity.
*/
beta=0.0;
if (p->ghostline == MagickFalse)
{
alpha=mid+0.5;
if ((*stroke_opacity < 1.0) &&
(distance <= ((alpha+0.25)*(alpha+0.25))))
{
alpha=mid-0.5;
if (distance <= ((alpha+0.25)*(alpha+0.25)))
*stroke_opacity=1.0;
else
{
beta=1.0;
if (fabs(distance-1.0) >= DrawEpsilon)
beta=sqrt((double) distance);
alpha=beta-mid-0.5;
if (*stroke_opacity < ((alpha-0.25)*(alpha-0.25)))
*stroke_opacity=(alpha-0.25)*(alpha-0.25);
}
}
}
if ((fill == MagickFalse) || (distance > 1.0) || (subpath_opacity >= 1.0))
continue;
if (distance <= 0.0)
{
subpath_opacity=1.0;
continue;
}
if (distance > 1.0)
continue;
if (fabs(beta) < DrawEpsilon)
{
beta=1.0;
if (fabs(distance-1.0) >= DrawEpsilon)
beta=sqrt(distance);
}
alpha=beta-1.0;
if (subpath_opacity < (alpha*alpha))
subpath_opacity=alpha*alpha;
}
}
/*
Compute fill opacity.
*/
if (fill == MagickFalse)
return(0.0);
if (subpath_opacity >= 1.0)
return(1.0);
/*
Determine winding number.
*/
winding_number=0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if ((double) y <= p->bounds.y1)
break;
if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1))
continue;
if ((double) x > p->bounds.x2)
{
winding_number+=p->direction ? 1 : -1;
continue;
}
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) p->number_points; i++)
if ((double) y <= p->points[i].y)
break;
q=p->points+i-1;
if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x)))
winding_number+=p->direction ? 1 : -1;
}
if (fill_rule != NonZeroRule)
{
if ((MagickAbsoluteValue(winding_number) & 0x01) != 0)
return(1.0);
}
else
if (MagickAbsoluteValue(winding_number) != 0)
return(1.0);
return(subpath_opacity);
}
static MagickBooleanType DrawPolygonPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
{
CacheView
*image_view;
double
mid;
ExceptionInfo
*exception;
MagickBooleanType
fill,
status;
PolygonInfo
**magick_restrict polygon_info;
register EdgeInfo
*p;
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
start_y,
stop_y,
y;
/*
Compute bounding box.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickSignature);
assert(primitive_info != (PrimitiveInfo *) NULL);
if (primitive_info->coordinates == 0)
return(MagickTrue);
polygon_info=AcquirePolygonThreadSet(draw_info,primitive_info);
if (polygon_info == (PolygonInfo **) NULL)
return(MagickFalse);
DisableMSCWarning(4127)
if (0)
DrawBoundingRectangles(image,draw_info,polygon_info[0]);
RestoreMSCWarning
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon");
fill=(primitive_info->method == FillToBorderMethod) ||
(primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse;
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
bounds=polygon_info[0]->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++)
{
p=polygon_info[0]->edges+i;
if (p->bounds.x1 < bounds.x1)
bounds.x1=p->bounds.x1;
if (p->bounds.y1 < bounds.y1)
bounds.y1=p->bounds.y1;
if (p->bounds.x2 > bounds.x2)
bounds.x2=p->bounds.x2;
if (p->bounds.y2 > bounds.y2)
bounds.y2=p->bounds.y2;
}
bounds.x1-=(mid+1.0);
bounds.x1=bounds.x1 < 0.0 ? 0.0 : (size_t) ceil(bounds.x1-0.5) >=
image->columns ? (double) image->columns-1 : bounds.x1;
bounds.y1-=(mid+1.0);
bounds.y1=bounds.y1 < 0.0 ? 0.0 : (size_t) ceil(bounds.y1-0.5) >=
image->rows ? (double) image->rows-1 : bounds.y1;
bounds.x2+=(mid+1.0);
bounds.x2=bounds.x2 < 0.0 ? 0.0 : (size_t) floor(bounds.x2+0.5) >=
image->columns ? (double) image->columns-1 : bounds.x2;
bounds.y2+=(mid+1.0);
bounds.y2=bounds.y2 < 0.0 ? 0.0 : (size_t) floor(bounds.y2+0.5) >=
image->rows ? (double) image->rows-1 : bounds.y2;
status=MagickTrue;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
if ((primitive_info->coordinates == 1) ||
(polygon_info[0]->number_edges == 0))
{
/*
Draw point.
*/
start_y=(ssize_t) ceil(bounds.y1-0.5);
stop_y=(ssize_t) floor(bounds.y2+0.5);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=start_y; y <= stop_y; y++)
{
MagickBooleanType
sync;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
start_x,
stop_x;
if (status == MagickFalse)
continue;
start_x=(ssize_t) ceil(bounds.x1-0.5);
stop_x=(ssize_t) floor(bounds.x2+0.5);
x=start_x;
q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for ( ; x <= stop_x; x++)
{
if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) &&
(y == (ssize_t) ceil(primitive_info->point.y-0.5)))
(void) GetFillColor(draw_info,x-start_x,y-start_y,q);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-polygon");
return(status);
}
/*
Draw polygon or line.
*/
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
start_y=(ssize_t) ceil(bounds.y1-0.5);
stop_y=(ssize_t) floor(bounds.y2+0.5);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=start_y; y <= stop_y; y++)
{
const int
id = GetOpenMPThreadId();
double
fill_opacity,
stroke_opacity;
PixelPacket
fill_color,
stroke_color;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
start_x,
stop_x;
if (status == MagickFalse)
continue;
start_x=(ssize_t) ceil(bounds.x1-0.5);
stop_x=(ssize_t) floor(bounds.x2+0.5);
q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+1),1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=start_x; x <= stop_x; x++)
{
/*
Fill and/or stroke.
*/
fill_opacity=GetOpacityPixel(polygon_info[id],mid,fill,
draw_info->fill_rule,x,y,&stroke_opacity);
if (draw_info->stroke_antialias == MagickFalse)
{
fill_opacity=fill_opacity > 0.25 ? 1.0 : 0.0;
stroke_opacity=stroke_opacity > 0.25 ? 1.0 : 0.0;
}
(void) GetFillColor(draw_info,x-start_x,y-start_y,&fill_color);
fill_opacity=(double) (QuantumRange-fill_opacity*(QuantumRange-
fill_color.opacity));
MagickCompositeOver(&fill_color,(MagickRealType) fill_opacity,q,
(MagickRealType) q->opacity,q);
(void) GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color);
stroke_opacity=(double) (QuantumRange-stroke_opacity*(QuantumRange-
stroke_color.opacity));
MagickCompositeOver(&stroke_color,(MagickRealType) stroke_opacity,q,
(MagickRealType) q->opacity,q);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image.
%
% The format of the DrawPrimitive method is:
%
% MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info,
% PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
*/
static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info)
{
const char
*methods[] =
{
"point",
"replace",
"floodfill",
"filltoborder",
"reset",
"?"
};
PointInfo
p,
q,
point;
register ssize_t
i,
x;
ssize_t
coordinates,
y;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
switch (primitive_info->primitive)
{
case PointPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"PointPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case ColorPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ColorPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case MattePrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"MattePrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case TextPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"TextPrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
case ImagePrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ImagePrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
default:
break;
}
coordinates=0;
p=primitive_info[0].point;
q.x=(-1.0);
q.y=(-1.0);
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
if (coordinates <= 0)
{
coordinates=(ssize_t) primitive_info[i].coordinates;
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin open (%.20g)",(double) coordinates);
p=point;
}
point=primitive_info[i].point;
if ((fabs(q.x-point.x) >= DrawEpsilon) ||
(fabs(q.y-point.y) >= DrawEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y);
q=point;
coordinates--;
if (coordinates > 0)
continue;
if ((fabs(p.x-point.x) >= DrawEpsilon) ||
(fabs(p.y-point.y) >= DrawEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)",
(double) coordinates);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)",
(double) coordinates);
}
}
MagickExport MagickBooleanType DrawPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
{
CacheView
*image_view;
ExceptionInfo
*exception;
MagickStatusType
status;
register ssize_t
i,
x;
ssize_t
y;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-primitive");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" affine: %g,%g,%g,%g,%g,%g",draw_info->affine.sx,
draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,
draw_info->affine.tx,draw_info->affine.ty);
}
exception=(&image->exception);
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
((IsPixelGray(&draw_info->fill) == MagickFalse) ||
(IsPixelGray(&draw_info->stroke) == MagickFalse)))
(void) SetImageColorspace(image,sRGBColorspace);
status=MagickTrue;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
image_view=AcquireAuthenticCacheView(image,exception);
switch (primitive_info->primitive)
{
case PointPrimitive:
{
PixelPacket
fill_color;
PixelPacket
*q;
if ((y < 0) || (y >= (ssize_t) image->rows))
break;
if ((x < 0) || (x >= (ssize_t) image->columns))
break;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) GetFillColor(draw_info,x,y,&fill_color);
MagickCompositeOver(&fill_color,(MagickRealType) fill_color.opacity,q,
(MagickRealType) q->opacity,q);
status&=SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ColorPrimitive:
{
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelPacket
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) GetFillColor(draw_info,x,y,q);
status&=SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelPacket
target;
status&=GetOneCacheViewVirtualPixel(image_view,x,y,&target,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsColorSimilar(image,q,&target) == MagickFalse)
{
q++;
continue;
}
(void) GetFillColor(draw_info,x,y,q);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
MagickPixelPacket
target;
(void) GetOneVirtualMagickPixel(image,x,y,&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(MagickRealType) draw_info->border_color.red;
target.green=(MagickRealType) draw_info->border_color.green;
target.blue=(MagickRealType) draw_info->border_color.blue;
}
status&=FloodfillPaintImage(image,DefaultChannels,draw_info,&target,x,
y,primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) GetFillColor(draw_info,x,y,q);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case MattePrimitive:
{
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelPacket
pixel;
PixelPacket
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) GetFillColor(draw_info,x,y,&pixel);
SetPixelOpacity(q,pixel.opacity);
status&=SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelPacket
pixel,
target;
status&=GetOneCacheViewVirtualPixel(image_view,x,y,&target,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsColorSimilar(image,q,&target) == MagickFalse)
{
q++;
continue;
}
(void) GetFillColor(draw_info,x,y,&pixel);
SetPixelOpacity(q,pixel.opacity);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
MagickPixelPacket
target;
(void) GetOneVirtualMagickPixel(image,x,y,&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(MagickRealType) draw_info->border_color.red;
target.green=(MagickRealType) draw_info->border_color.green;
target.blue=(MagickRealType) draw_info->border_color.blue;
}
status&=FloodfillPaintImage(image,OpacityChannel,draw_info,&target,x,
y,primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelPacket
pixel;
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) GetFillColor(draw_info,x,y,&pixel);
SetPixelOpacity(q,pixel.opacity);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case TextPrimitive:
{
char
geometry[MaxTextExtent];
DrawInfo
*clone_info;
if (primitive_info->text == (char *) NULL)
break;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->text,primitive_info->text);
(void) FormatLocaleString(geometry,MaxTextExtent,"%+f%+f",
primitive_info->point.x,primitive_info->point.y);
(void) CloneString(&clone_info->geometry,geometry);
status&=AnnotateImage(image,clone_info);
clone_info=DestroyDrawInfo(clone_info);
break;
}
case ImagePrimitive:
{
AffineMatrix
affine;
char
composite_geometry[MaxTextExtent];
Image
*composite_image;
ImageInfo
*clone_info;
RectangleInfo
geometry;
ssize_t
x1,
y1;
if (primitive_info->text == (char *) NULL)
break;
clone_info=AcquireImageInfo();
if (LocaleNCompare(primitive_info->text,"data:",5) == 0)
composite_image=ReadInlineImage(clone_info,primitive_info->text,
&image->exception);
else
{
(void) CopyMagickString(clone_info->filename,primitive_info->text,
MaxTextExtent);
composite_image=ReadImage(clone_info,&image->exception);
}
clone_info=DestroyImageInfo(clone_info);
if (composite_image == (Image *) NULL)
break;
(void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)
NULL,(void *) NULL);
x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);
y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);
if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||
((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))
{
char
geometry[MaxTextExtent];
/*
Resize image.
*/
(void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g!",
primitive_info[1].point.x,primitive_info[1].point.y);
composite_image->filter=image->filter;
(void) TransformImage(&composite_image,(char *) NULL,geometry);
}
if (composite_image->matte == MagickFalse)
(void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel);
if (draw_info->opacity != OpaqueOpacity)
(void) SetImageOpacity(composite_image,draw_info->opacity);
SetGeometry(image,&geometry);
image->gravity=draw_info->gravity;
geometry.x=x;
geometry.y=y;
(void) FormatLocaleString(composite_geometry,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double)
composite_image->rows,(double) geometry.x,(double) geometry.y);
(void) ParseGravityGeometry(image,composite_geometry,&geometry,
&image->exception);
affine=draw_info->affine;
affine.tx=(double) geometry.x;
affine.ty=(double) geometry.y;
composite_image->interpolate=image->interpolate;
if (draw_info->compose == OverCompositeOp)
(void) DrawAffineImage(image,composite_image,&affine);
else
(void) CompositeImage(image,draw_info->compose,composite_image,
geometry.x,geometry.y);
composite_image=DestroyImage(composite_image);
break;
}
default:
{
double
mid,
scale;
DrawInfo
*clone_info;
if (IsEventLogging() != MagickFalse)
LogPrimitiveInfo(primitive_info);
scale=ExpandAffine(&draw_info->affine);
if ((draw_info->dash_pattern != (double *) NULL) &&
(fabs(draw_info->dash_pattern[0]) >= DrawEpsilon) &&
(fabs(scale*draw_info->stroke_width) >= DrawEpsilon) &&
(draw_info->stroke.opacity != (Quantum) TransparentOpacity))
{
/*
Draw dash polygon.
*/
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.opacity=(Quantum) TransparentOpacity;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info);
clone_info=DestroyDrawInfo(clone_info);
(void) DrawDashPolygon(draw_info,primitive_info,image);
break;
}
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
if ((mid > 1.0) &&
((draw_info->stroke.opacity != (Quantum) TransparentOpacity) ||
(draw_info->stroke_pattern != (Image *) NULL)))
{
MagickBooleanType
closed_path;
/*
Draw strokes while respecting line cap/join attributes.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
closed_path=
(primitive_info[i-1].point.x == primitive_info[0].point.x) &&
(primitive_info[i-1].point.y == primitive_info[0].point.y) ?
MagickTrue : MagickFalse;
i=(ssize_t) primitive_info[0].coordinates;
i=(ssize_t) primitive_info[0].coordinates;
if (((closed_path != MagickFalse) &&
(draw_info->linejoin == RoundJoin)) ||
(primitive_info[i].primitive != UndefinedPrimitive))
{
(void) DrawPolygonPrimitive(image,draw_info,primitive_info);
break;
}
if (draw_info->linecap == RoundCap)
{
(void) DrawPolygonPrimitive(image,draw_info,primitive_info);
break;
}
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.opacity=(Quantum) TransparentOpacity;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info);
clone_info=DestroyDrawInfo(clone_info);
status&=DrawStrokePolygon(image,draw_info,primitive_info);
break;
}
status&=DrawPolygonPrimitive(image,draw_info,primitive_info);
break;
}
}
image_view=DestroyCacheView(image_view);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w S t r o k e P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on
% the image while respecting the line cap and join attributes.
%
% The format of the DrawStrokePolygon method is:
%
% MagickBooleanType DrawStrokePolygon(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
%
*/
static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info)
{
PrimitiveInfo
linecap[5];
register ssize_t
i;
for (i=0; i < 4; i++)
linecap[i]=(*primitive_info);
linecap[0].coordinates=4;
linecap[1].point.x+=2.0*DrawEpsilon;
linecap[2].point.x+=2.0*DrawEpsilon;
linecap[2].point.y+=2.0*DrawEpsilon;
linecap[3].point.y+=2.0*DrawEpsilon;
linecap[4].primitive=UndefinedPrimitive;
(void) DrawPolygonPrimitive(image,draw_info,linecap);
}
static MagickBooleanType DrawStrokePolygon(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
{
DrawInfo
*clone_info;
MagickBooleanType
closed_path;
MagickStatusType
status;
PrimitiveInfo
*stroke_polygon;
register const PrimitiveInfo
*p,
*q;
/*
Draw stroked polygon.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-stroke-polygon");
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill=draw_info->stroke;
if (clone_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern);
if (clone_info->stroke_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0,
MagickTrue,&clone_info->stroke_pattern->exception);
clone_info->stroke.opacity=(Quantum) TransparentOpacity;
clone_info->stroke_width=0.0;
clone_info->fill_rule=NonZeroRule;
status=MagickTrue;
for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates)
{
stroke_polygon=TraceStrokePolygon(draw_info,p);
status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon);
if (status == 0)
break;
stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon);
q=p+p->coordinates-1;
closed_path=(fabs(q->point.x-p->point.x) < DrawEpsilon) &&
(fabs(q->point.y-p->point.y) < DrawEpsilon) ? MagickTrue : MagickFalse;
if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse))
{
DrawRoundLinecap(image,draw_info,p);
DrawRoundLinecap(image,draw_info,q);
}
}
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-stroke-polygon");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A f f i n e M a t r i x %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAffineMatrix() returns an AffineMatrix initialized to the identity
% matrix.
%
% The format of the GetAffineMatrix method is:
%
% void GetAffineMatrix(AffineMatrix *affine_matrix)
%
% A description of each parameter follows:
%
% o affine_matrix: the affine matrix.
%
*/
MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(affine_matrix != (AffineMatrix *) NULL);
(void) ResetMagickMemory(affine_matrix,0,sizeof(*affine_matrix));
affine_matrix->sx=1.0;
affine_matrix->sy=1.0;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetDrawInfo() initializes draw_info to default values from image_info.
%
% The format of the GetDrawInfo method is:
%
% void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info..
%
% o draw_info: the draw info.
%
*/
MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
{
char
*next_token;
const char
*option;
ExceptionInfo
*exception;
ImageInfo
*clone_info;
/*
Initialize draw attributes.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
(void) ResetMagickMemory(draw_info,0,sizeof(*draw_info));
clone_info=CloneImageInfo(image_info);
GetAffineMatrix(&draw_info->affine);
exception=AcquireExceptionInfo();
(void) QueryColorDatabase("#000F",&draw_info->fill,exception);
(void) QueryColorDatabase("#FFF0",&draw_info->stroke,exception);
draw_info->stroke_antialias=clone_info->antialias;
draw_info->stroke_width=1.0;
draw_info->fill_rule=EvenOddRule;
draw_info->fill_opacity=OpaqueOpacity;
draw_info->stroke_opacity=OpaqueOpacity;
draw_info->linecap=ButtCap;
draw_info->linejoin=MiterJoin;
draw_info->miterlimit=10;
draw_info->decorate=NoDecoration;
if (clone_info->font != (char *) NULL)
draw_info->font=AcquireString(clone_info->font);
if (clone_info->density != (char *) NULL)
draw_info->density=AcquireString(clone_info->density);
draw_info->text_antialias=clone_info->antialias;
draw_info->pointsize=12.0;
if (fabs(clone_info->pointsize) >= DrawEpsilon)
draw_info->pointsize=clone_info->pointsize;
draw_info->undercolor.opacity=(Quantum) TransparentOpacity;
draw_info->border_color=clone_info->border_color;
draw_info->compose=OverCompositeOp;
if (clone_info->server_name != (char *) NULL)
draw_info->server_name=AcquireString(clone_info->server_name);
draw_info->render=MagickTrue;
draw_info->debug=IsEventLogging();
option=GetImageOption(clone_info,"direction");
if (option != (const char *) NULL)
draw_info->direction=(DirectionType) ParseCommandOption(
MagickDirectionOptions,MagickFalse,option);
else
draw_info->direction=UndefinedDirection;
option=GetImageOption(clone_info,"encoding");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->encoding,option);
option=GetImageOption(clone_info,"family");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->family,option);
option=GetImageOption(clone_info,"fill");
if (option != (const char *) NULL)
(void) QueryColorDatabase(option,&draw_info->fill,exception);
option=GetImageOption(clone_info,"gravity");
if (option != (const char *) NULL)
draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"interline-spacing");
if (option != (const char *) NULL)
draw_info->interline_spacing=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"interword-spacing");
if (option != (const char *) NULL)
draw_info->interword_spacing=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"kerning");
if (option != (const char *) NULL)
draw_info->kerning=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"stroke");
if (option != (const char *) NULL)
(void) QueryColorDatabase(option,&draw_info->stroke,exception);
option=GetImageOption(clone_info,"strokewidth");
if (option != (const char *) NULL)
draw_info->stroke_width=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"style");
if (option != (const char *) NULL)
draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"undercolor");
if (option != (const char *) NULL)
(void) QueryColorDatabase(option,&draw_info->undercolor,exception);
option=GetImageOption(clone_info,"weight");
if (option != (const char *) NULL)
{
ssize_t
weight;
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option);
if (weight == -1)
weight=(ssize_t) StringToUnsignedLong(option);
draw_info->weight=(size_t) weight;
}
exception=DestroyExceptionInfo(exception);
draw_info->signature=MagickSignature;
clone_info=DestroyImageInfo(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P e r m u t a t e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Permutate() returns the permuation of the (n,k).
%
% The format of the Permutate method is:
%
% void Permutate(ssize_t n,ssize_t k)
%
% A description of each parameter follows:
%
% o n:
%
% o k:
%
%
*/
static inline double Permutate(const ssize_t n,const ssize_t k)
{
double
r;
register ssize_t
i;
r=1.0;
for (i=k+1; i <= n; i++)
r*=i;
for (i=1; i <= (n-k); i++)
r/=i;
return(r);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ T r a c e P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TracePrimitive is a collection of methods for generating graphic
% primitives such as arcs, ellipses, paths, etc.
%
*/
static void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end,const PointInfo degrees)
{
PointInfo
center,
radii;
center.x=0.5*(end.x+start.x);
center.y=0.5*(end.y+start.y);
radii.x=fabs(center.x-start.x);
radii.y=fabs(center.y-start.y);
TraceEllipse(primitive_info,center,radii,degrees);
}
static void TraceArcPath(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end,const PointInfo arc,const double angle,
const MagickBooleanType large_arc,const MagickBooleanType sweep)
{
double
alpha,
beta,
delta,
factor,
gamma,
theta;
PointInfo
center,
points[3],
radii;
register double
cosine,
sine;
register PrimitiveInfo
*p;
register ssize_t
i;
size_t
arc_segments;
if ((fabs(start.x-end.x) < DrawEpsilon) &&
(fabs(start.y-end.y) < DrawEpsilon))
{
TracePoint(primitive_info,end);
return;
}
radii.x=fabs(arc.x);
radii.y=fabs(arc.y);
if ((fabs(radii.x) < DrawEpsilon) || (fabs(radii.y) < DrawEpsilon))
{
TraceLine(primitive_info,start,end);
return;
}
cosine=cos(DegreesToRadians(fmod((double) angle,360.0)));
sine=sin(DegreesToRadians(fmod((double) angle,360.0)));
center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2);
center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2);
delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/
(radii.y*radii.y);
if (delta < DrawEpsilon)
{
TraceLine(primitive_info,start,end);
return;
}
if (delta > 1.0)
{
radii.x*=sqrt((double) delta);
radii.y*=sqrt((double) delta);
}
points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x);
points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y);
points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x);
points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y);
alpha=points[1].x-points[0].x;
beta=points[1].y-points[0].y;
factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25;
if (factor <= 0.0)
factor=0.0;
else
{
factor=sqrt((double) factor);
if (sweep == large_arc)
factor=(-factor);
}
center.x=(double) ((points[0].x+points[1].x)/2-factor*beta);
center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha);
alpha=atan2(points[0].y-center.y,points[0].x-center.x);
theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha;
if ((theta < 0.0) && (sweep != MagickFalse))
theta+=2.0*MagickPI;
else
if ((theta > 0.0) && (sweep == MagickFalse))
theta-=2.0*MagickPI;
arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+
DrawEpsilon))));
p=primitive_info;
for (i=0; i < (ssize_t) arc_segments; i++)
{
beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments));
gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))*
sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/
sin(fmod((double) beta,DegreesToRadians(360.0)));
points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x;
p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y;
(p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y*
points[0].y);
(p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y*
points[0].y);
(p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y*
points[1].y);
(p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y*
points[1].y);
(p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y*
points[2].y);
(p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y*
points[2].y);
if (i == (ssize_t) (arc_segments-1))
(p+3)->point=end;
TraceBezier(p,4);
p+=p->coordinates;
}
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceBezier(PrimitiveInfo *primitive_info,
const size_t number_coordinates)
{
double
alpha,
*coefficients,
weight;
PointInfo
end,
point,
*points;
register PrimitiveInfo
*p;
register ssize_t
i,
j;
size_t
control_points,
quantum;
/*
Allocate coeficients.
*/
quantum=number_coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
for (j=i+1; j < (ssize_t) number_coordinates; j++)
{
alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);
if (alpha > (double) quantum)
quantum=(size_t) alpha;
alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);
if (alpha > (double) quantum)
quantum=(size_t) alpha;
}
}
quantum=(size_t) MagickMin((double) quantum/number_coordinates,
(double) BezierQuantum);
control_points=quantum*number_coordinates;
coefficients=(double *) AcquireQuantumMemory((size_t)
number_coordinates,sizeof(*coefficients));
points=(PointInfo *) AcquireQuantumMemory((size_t) control_points,
sizeof(*points));
if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
/*
Compute bezier points.
*/
end=primitive_info[number_coordinates-1].point;
for (i=0; i < (ssize_t) number_coordinates; i++)
coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);
weight=0.0;
for (i=0; i < (ssize_t) control_points; i++)
{
p=primitive_info;
point.x=0.0;
point.y=0.0;
alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);
for (j=0; j < (ssize_t) number_coordinates; j++)
{
point.x+=alpha*coefficients[j]*p->point.x;
point.y+=alpha*coefficients[j]*p->point.y;
alpha*=weight/(1.0-weight);
p++;
}
points[i]=point;
weight+=1.0/control_points;
}
/*
Bezier curves are just short segmented polys.
*/
p=primitive_info;
for (i=0; i < (ssize_t) control_points; i++)
{
TracePoint(p,points[i]);
p+=p->coordinates;
}
TracePoint(p,end);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
}
static void TraceCircle(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
double
alpha,
beta,
radius;
PointInfo
offset,
degrees;
alpha=end.x-start.x;
beta=end.y-start.y;
radius=hypot((double) alpha,(double) beta);
offset.x=(double) radius;
offset.y=(double) radius;
degrees.x=0.0;
degrees.y=360.0;
TraceEllipse(primitive_info,start,offset,degrees);
}
static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo stop,const PointInfo degrees)
{
double
delta,
step,
y;
PointInfo
angle,
point;
register PrimitiveInfo
*p;
register ssize_t
i;
/*
Ellipses are just short segmented polys.
*/
if ((fabs(stop.x) < DrawEpsilon) && (fabs(stop.y) < DrawEpsilon))
{
TracePoint(primitive_info,start);
return;
}
delta=2.0/MagickMax(stop.x,stop.y);
step=MagickPI/8.0;
if ((delta >= 0.0) && (delta < (MagickPI/8.0)))
step=MagickPI/(4*(MagickPI/delta/2+0.5));
angle.x=DegreesToRadians(degrees.x);
y=degrees.y;
while (y < degrees.x)
y+=360.0;
angle.y=(double) (DegreesToRadians(y)-DrawEpsilon);
for (p=primitive_info; angle.x < angle.y; angle.x+=step)
{
point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*stop.x+start.x;
point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*stop.y+start.y;
TracePoint(p,point);
p+=p->coordinates;
}
point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*stop.x+start.x;
point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*stop.y+start.y;
TracePoint(p,point);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
TracePoint(primitive_info,start);
if ((fabs(start.x-end.x) < DrawEpsilon) &&
(fabs(start.y-end.y) < DrawEpsilon))
{
primitive_info->primitive=PointPrimitive;
primitive_info->coordinates=1;
return;
}
TracePoint(primitive_info+1,end);
(primitive_info+1)->primitive=primitive_info->primitive;
primitive_info->coordinates=2;
}
static size_t TracePath(PrimitiveInfo *primitive_info,const char *path)
{
char
*next_token,
token[MaxTextExtent];
const char
*p;
double
x,
y;
int
attribute,
last_attribute;
PointInfo
end = {0.0, 0.0},
points[4] = { {0.0,0.0}, {0.0,0.0}, {0.0,0.0}, {0.0,0.0} },
point = {0.0, 0.0},
start = {0.0, 0.0};
PrimitiveType
primitive_type;
register PrimitiveInfo
*q;
register ssize_t
i;
size_t
number_coordinates,
z_count;
attribute=0;
number_coordinates=0;
z_count=0;
primitive_type=primitive_info->primitive;
q=primitive_info;
for (p=path; *p != '\0'; )
{
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == '\0')
break;
last_attribute=attribute;
attribute=(int) (*p++);
switch (attribute)
{
case 'a':
case 'A':
{
double
angle;
MagickBooleanType
large_arc,
sweep;
PointInfo
arc;
/*
Compute arc points.
*/
do
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
arc.x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
arc.y=StringToDouble(token,&next_token);
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
angle=StringToDouble(token,&next_token);
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
y=StringToDouble(token,&next_token);
end.x=(double) (attribute == (int) 'A' ? x : point.x+x);
end.y=(double) (attribute == (int) 'A' ? y : point.y+y);
TraceArcPath(q,point,end,arc,angle,large_arc,sweep);
q+=q->coordinates;
point=end;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'c':
case 'C':
{
/*
Compute bezier points.
*/
do
{
points[0]=point;
for (i=1; i < 4; i++)
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
y=StringToDouble(token,&next_token);
end.x=(double) (attribute == (int) 'C' ? x : point.x+x);
end.y=(double) (attribute == (int) 'C' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
TraceBezier(q,4);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'H':
case 'h':
{
do
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
x=StringToDouble(token,&next_token);
point.x=(double) (attribute == (int) 'H' ? x: point.x+x);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'l':
case 'L':
{
do
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
y=StringToDouble(token,&next_token);
point.x=(double) (attribute == (int) 'L' ? x : point.x+x);
point.y=(double) (attribute == (int) 'L' ? y : point.y+y);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'M':
case 'm':
{
if (q != primitive_info)
{
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
}
i=0;
do
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
y=StringToDouble(token,&next_token);
point.x=(double) (attribute == (int) 'M' ? x : point.x+x);
point.y=(double) (attribute == (int) 'M' ? y : point.y+y);
if (i == 0)
start=point;
i++;
TracePoint(q,point);
q+=q->coordinates;
if ((i != 0) && (attribute == (int) 'M'))
{
TracePoint(q,point);
q+=q->coordinates;
}
} while (IsPoint(p) != MagickFalse);
break;
}
case 'q':
case 'Q':
{
/*
Compute bezier points.
*/
do
{
points[0]=point;
for (i=1; i < 3; i++)
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
y=StringToDouble(token,&next_token);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'Q' ? x : point.x+x);
end.y=(double) (attribute == (int) 'Q' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
TraceBezier(q,3);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 's':
case 'S':
{
/*
Compute bezier points.
*/
do
{
points[0]=points[3];
points[1].x=2.0*points[3].x-points[2].x;
points[1].y=2.0*points[3].y-points[2].y;
for (i=2; i < 4; i++)
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
y=StringToDouble(token,&next_token);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'S' ? x : point.x+x);
end.y=(double) (attribute == (int) 'S' ? y : point.y+y);
points[i]=end;
}
if (strchr("CcSs",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
TraceBezier(q,4);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 't':
case 'T':
{
/*
Compute bezier points.
*/
do
{
points[0]=points[2];
points[1].x=2.0*points[2].x-points[1].x;
points[1].y=2.0*points[2].y-points[1].y;
for (i=2; i < 3; i++)
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
y=StringToDouble(token,&next_token);
end.x=(double) (attribute == (int) 'T' ? x : point.x+x);
end.y=(double) (attribute == (int) 'T' ? y : point.y+y);
points[i]=end;
}
if (strchr("QqTt",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
TraceBezier(q,3);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'v':
case 'V':
{
do
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
y=StringToDouble(token,&next_token);
point.y=(double) (attribute == (int) 'V' ? y : point.y+y);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'z':
case 'Z':
{
point=start;
TracePoint(q,point);
q+=q->coordinates;
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
z_count++;
break;
}
default:
{
if (isalpha((int) ((unsigned char) attribute)) != 0)
(void) FormatLocaleFile(stderr,"attribute not recognized: %c\n",
attribute);
break;
}
}
}
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
q--;
q->primitive=primitive_type;
if (z_count > 1)
q->method=FillToBorderMethod;
}
q=primitive_info;
return(number_coordinates);
}
static void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
PointInfo
point;
register PrimitiveInfo
*p;
register ssize_t
i;
p=primitive_info;
TracePoint(p,start);
p+=p->coordinates;
point.x=start.x;
point.y=end.y;
TracePoint(p,point);
p+=p->coordinates;
TracePoint(p,end);
p+=p->coordinates;
point.x=end.x;
point.y=start.y;
TracePoint(p,point);
p+=p->coordinates;
TracePoint(p,start);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceRoundRectangle(PrimitiveInfo *primitive_info,
const PointInfo start,const PointInfo end,PointInfo arc)
{
PointInfo
degrees,
offset,
point;
register PrimitiveInfo
*p;
register ssize_t
i;
p=primitive_info;
offset.x=fabs(end.x-start.x);
offset.y=fabs(end.y-start.y);
if (arc.x > (0.5*offset.x))
arc.x=0.5*offset.x;
if (arc.y > (0.5*offset.y))
arc.y=0.5*offset.y;
point.x=start.x+offset.x-arc.x;
point.y=start.y+arc.y;
degrees.x=270.0;
degrees.y=360.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+offset.x-arc.x;
point.y=start.y+offset.y-arc.y;
degrees.x=0.0;
degrees.y=90.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+offset.y-arc.y;
degrees.x=90.0;
degrees.y=180.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+arc.y;
degrees.x=180.0;
degrees.y=270.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
TracePoint(p,primitive_info->point);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceSquareLinecap(PrimitiveInfo *primitive_info,
const size_t number_vertices,const double offset)
{
double
distance;
register double
dx,
dy;
register ssize_t
i;
ssize_t
j;
dx=0.0;
dy=0.0;
for (i=1; i < (ssize_t) number_vertices; i++)
{
dx=primitive_info[0].point.x-primitive_info[i].point.x;
dy=primitive_info[0].point.y-primitive_info[i].point.y;
if ((fabs((double) dx) >= DrawEpsilon) ||
(fabs((double) dy) >= DrawEpsilon))
break;
}
if (i == (ssize_t) number_vertices)
i=(ssize_t) number_vertices-1L;
distance=hypot((double) dx,(double) dy);
primitive_info[0].point.x=(double) (primitive_info[i].point.x+
dx*(distance+offset)/distance);
primitive_info[0].point.y=(double) (primitive_info[i].point.y+
dy*(distance+offset)/distance);
for (j=(ssize_t) number_vertices-2; j >= 0; j--)
{
dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x;
dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y;
if ((fabs((double) dx) >= DrawEpsilon) ||
(fabs((double) dy) >= DrawEpsilon))
break;
}
distance=hypot((double) dx,(double) dy);
primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+
dx*(distance+offset)/distance);
primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+
dy*(distance+offset)/distance);
}
static inline double DrawEpsilonReciprocal(const double x)
{
double sign = x < 0.0 ? -1.0 : 1.0;
return((sign*x) >= DrawEpsilon ? 1.0/x : sign*(1.0/DrawEpsilon));
}
static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info)
{
typedef struct _LineSegment
{
double
p,
q;
} LineSegment;
double
delta_theta,
dot_product,
mid,
miterlimit;
LineSegment
dx,
dy,
inverse_slope,
slope,
theta;
MagickBooleanType
closed_path;
PointInfo
box_p[5],
box_q[5],
center,
offset,
*path_p,
*path_q;
PrimitiveInfo
*polygon_primitive,
*stroke_polygon;
register ssize_t
i;
size_t
arc_segments,
max_strokes,
number_vertices;
ssize_t
j,
n,
p,
q;
/*
Allocate paths.
*/
number_vertices=primitive_info->coordinates;
max_strokes=2*number_vertices+6*BezierQuantum+360;
path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_p));
path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_q));
polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
number_vertices+2UL,sizeof(*polygon_primitive));
if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) ||
(polygon_primitive == (PrimitiveInfo *) NULL))
return((PrimitiveInfo *) NULL);
(void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t)
number_vertices*sizeof(*polygon_primitive));
closed_path=
(fabs(primitive_info[number_vertices-1].point.x-primitive_info[0].point.x) < DrawEpsilon) &&
(fabs(primitive_info[number_vertices-1].point.y-primitive_info[0].point.y) < DrawEpsilon) ?
MagickTrue : MagickFalse;
if ((draw_info->linejoin == RoundJoin) ||
((draw_info->linejoin == MiterJoin) && (closed_path != MagickFalse)))
{
polygon_primitive[number_vertices]=primitive_info[1];
number_vertices++;
}
polygon_primitive[number_vertices].primitive=UndefinedPrimitive;
/*
Compute the slope for the first line segment, p.
*/
dx.p=0.0;
dy.p=0.0;
for (n=1; n < (ssize_t) number_vertices; n++)
{
dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;
dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;
if ((fabs(dx.p) >= DrawEpsilon) || (fabs(dy.p) >= DrawEpsilon))
break;
}
if (n == (ssize_t) number_vertices)
n=(ssize_t) number_vertices-1L;
slope.p=0.0;
inverse_slope.p=0.0;
if (fabs(dx.p) < DrawEpsilon)
{
if (dx.p >= 0.0)
slope.p=dy.p < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon;
else
slope.p=dy.p < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon;
}
else
if (fabs(dy.p) < DrawEpsilon)
{
if (dy.p >= 0.0)
inverse_slope.p=dx.p < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon;
else
inverse_slope.p=dx.p < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon;
}
else
{
slope.p=dy.p/dx.p;
inverse_slope.p=(-1.0/slope.p);
}
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid);
if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))
TraceSquareLinecap(polygon_primitive,number_vertices,mid);
offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));
offset.y=(double) (offset.x*inverse_slope.p);
if ((dy.p*offset.x-dx.p*offset.y) > 0.0)
{
box_p[0].x=polygon_primitive[0].point.x-offset.x;
box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;
box_p[1].x=polygon_primitive[n].point.x-offset.x;
box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;
box_q[0].x=polygon_primitive[0].point.x+offset.x;
box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;
box_q[1].x=polygon_primitive[n].point.x+offset.x;
box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;
}
else
{
box_p[0].x=polygon_primitive[0].point.x+offset.x;
box_p[0].y=polygon_primitive[0].point.y+offset.y;
box_p[1].x=polygon_primitive[n].point.x+offset.x;
box_p[1].y=polygon_primitive[n].point.y+offset.y;
box_q[0].x=polygon_primitive[0].point.x-offset.x;
box_q[0].y=polygon_primitive[0].point.y-offset.y;
box_q[1].x=polygon_primitive[n].point.x-offset.x;
box_q[1].y=polygon_primitive[n].point.y-offset.y;
}
/*
Create strokes for the line join attribute: bevel, miter, round.
*/
p=0;
q=0;
path_q[p++]=box_q[0];
path_p[q++]=box_p[0];
for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)
{
/*
Compute the slope for this line segment, q.
*/
dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;
dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;
dot_product=dx.q*dx.q+dy.q*dy.q;
if (dot_product < 0.25)
continue;
slope.q=0.0;
inverse_slope.q=0.0;
if (fabs(dx.q) < DrawEpsilon)
{
if (dx.q >= 0.0)
slope.q=dy.q < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon;
else
slope.q=dy.q < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon;
}
else
if (fabs(dy.q) < DrawEpsilon)
{
if (dy.q >= 0.0)
inverse_slope.q=dx.q < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon;
else
inverse_slope.q=dx.q < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon;
}
else
{
slope.q=dy.q/dx.q;
inverse_slope.q=(-1.0/slope.q);
}
offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));
offset.y=(double) (offset.x*inverse_slope.q);
dot_product=dy.q*offset.x-dx.q*offset.y;
if (dot_product > 0.0)
{
box_p[2].x=polygon_primitive[n].point.x-offset.x;
box_p[2].y=polygon_primitive[n].point.y-offset.y;
box_p[3].x=polygon_primitive[i].point.x-offset.x;
box_p[3].y=polygon_primitive[i].point.y-offset.y;
box_q[2].x=polygon_primitive[n].point.x+offset.x;
box_q[2].y=polygon_primitive[n].point.y+offset.y;
box_q[3].x=polygon_primitive[i].point.x+offset.x;
box_q[3].y=polygon_primitive[i].point.y+offset.y;
}
else
{
box_p[2].x=polygon_primitive[n].point.x+offset.x;
box_p[2].y=polygon_primitive[n].point.y+offset.y;
box_p[3].x=polygon_primitive[i].point.x+offset.x;
box_p[3].y=polygon_primitive[i].point.y+offset.y;
box_q[2].x=polygon_primitive[n].point.x-offset.x;
box_q[2].y=polygon_primitive[n].point.y-offset.y;
box_q[3].x=polygon_primitive[i].point.x-offset.x;
box_q[3].y=polygon_primitive[i].point.y-offset.y;
}
if (fabs((double) (slope.p-slope.q)) < DrawEpsilon)
{
box_p[4]=box_p[1];
box_q[4]=box_q[1];
}
else
{
box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+
box_p[3].y)/(slope.p-slope.q));
box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);
box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+
box_q[3].y)/(slope.p-slope.q));
box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);
}
if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360))
{
if (~max_strokes < (6*BezierQuantum+360))
{
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
}
else
{
max_strokes+=6*BezierQuantum+360;
path_p=(PointInfo *) ResizeQuantumMemory(path_p,max_strokes,
sizeof(*path_p));
path_q=(PointInfo *) ResizeQuantumMemory(path_q,max_strokes,
sizeof(*path_q));
}
if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL))
{
if (path_p != (PointInfo *) NULL)
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
if (path_q != (PointInfo *) NULL)
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
polygon_primitive=(PrimitiveInfo *)
RelinquishMagickMemory(polygon_primitive);
return((PrimitiveInfo *) NULL);
}
}
dot_product=dx.q*dy.p-dx.p*dy.q;
if (dot_product <= 0.0)
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);
theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);
if (theta.q < theta.p)
theta.q+=2.0*MagickPI;
arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/
(2.0*sqrt((double) (1.0/mid)))));
path_q[q].x=box_q[1].x;
path_q[q].y=box_q[1].y;
q++;
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
path_q[q].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_q[q].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
q++;
}
path_q[q++]=box_q[2];
break;
}
default:
break;
}
else
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);
theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);
if (theta.p < theta.q)
theta.p+=2.0*MagickPI;
arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/
(2.0*sqrt((double) (1.0/mid)))));
path_p[p++]=box_p[1];
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
path_p[p].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_p[p].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
p++;
}
path_p[p++]=box_p[2];
break;
}
default:
break;
}
slope.p=slope.q;
inverse_slope.p=inverse_slope.q;
box_p[0]=box_p[2];
box_p[1]=box_p[3];
box_q[0]=box_q[2];
box_q[1]=box_q[3];
dx.p=dx.q;
dy.p=dy.q;
n=i;
}
path_p[p++]=box_p[1];
path_q[q++]=box_q[1];
/*
Trace stroked polygon.
*/
stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));
if (stroke_polygon != (PrimitiveInfo *) NULL)
{
for (i=0; i < (ssize_t) p; i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_p[i];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
}
for ( ; i < (ssize_t) (p+q+closed_path); i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[p+closed_path].point;
i++;
}
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
stroke_polygon[i].primitive=UndefinedPrimitive;
stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);
}
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);
return(stroke_polygon);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4772_1 |
crossvul-cpp_data_good_4733_0 | /*
* Copyright (c) 2007 Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/errno.h>
#include <linux/if_ether.h>
#include <linux/mlx4/cmd.h>
#include "mlx4.h"
#define MLX4_MAC_VALID (1ull << 63)
#define MLX4_MAC_MASK 0xffffffffffffULL
#define MLX4_VLAN_VALID (1u << 31)
#define MLX4_VLAN_MASK 0xfff
void mlx4_init_mac_table(struct mlx4_dev *dev, struct mlx4_mac_table *table)
{
int i;
mutex_init(&table->mutex);
for (i = 0; i < MLX4_MAX_MAC_NUM; i++) {
table->entries[i] = 0;
table->refs[i] = 0;
}
table->max = 1 << dev->caps.log_num_macs;
table->total = 0;
}
void mlx4_init_vlan_table(struct mlx4_dev *dev, struct mlx4_vlan_table *table)
{
int i;
mutex_init(&table->mutex);
for (i = 0; i < MLX4_MAX_VLAN_NUM; i++) {
table->entries[i] = 0;
table->refs[i] = 0;
}
table->max = 1 << dev->caps.log_num_vlans;
table->total = 0;
}
static int mlx4_set_port_mac_table(struct mlx4_dev *dev, u8 port,
__be64 *entries)
{
struct mlx4_cmd_mailbox *mailbox;
u32 in_mod;
int err;
mailbox = mlx4_alloc_cmd_mailbox(dev);
if (IS_ERR(mailbox))
return PTR_ERR(mailbox);
memcpy(mailbox->buf, entries, MLX4_MAC_TABLE_SIZE);
in_mod = MLX4_SET_PORT_MAC_TABLE << 8 | port;
err = mlx4_cmd(dev, mailbox->dma, in_mod, 1, MLX4_CMD_SET_PORT,
MLX4_CMD_TIME_CLASS_B);
mlx4_free_cmd_mailbox(dev, mailbox);
return err;
}
int mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac, int *index)
{
struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table;
int i, err = 0;
int free = -1;
mlx4_dbg(dev, "Registering MAC: 0x%llx\n", (unsigned long long) mac);
mutex_lock(&table->mutex);
for (i = 0; i < MLX4_MAX_MAC_NUM - 1; i++) {
if (free < 0 && !table->refs[i]) {
free = i;
continue;
}
if (mac == (MLX4_MAC_MASK & be64_to_cpu(table->entries[i]))) {
/* MAC already registered, increase refernce count */
*index = i;
++table->refs[i];
goto out;
}
}
if (free < 0) {
err = -ENOMEM;
goto out;
}
mlx4_dbg(dev, "Free MAC index is %d\n", free);
if (table->total == table->max) {
/* No free mac entries */
err = -ENOSPC;
goto out;
}
/* Register new MAC */
table->refs[free] = 1;
table->entries[free] = cpu_to_be64(mac | MLX4_MAC_VALID);
err = mlx4_set_port_mac_table(dev, port, table->entries);
if (unlikely(err)) {
mlx4_err(dev, "Failed adding MAC: 0x%llx\n", (unsigned long long) mac);
table->refs[free] = 0;
table->entries[free] = 0;
goto out;
}
*index = free;
++table->total;
out:
mutex_unlock(&table->mutex);
return err;
}
EXPORT_SYMBOL_GPL(mlx4_register_mac);
void mlx4_unregister_mac(struct mlx4_dev *dev, u8 port, int index)
{
struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table;
mutex_lock(&table->mutex);
if (!table->refs[index]) {
mlx4_warn(dev, "No MAC entry for index %d\n", index);
goto out;
}
if (--table->refs[index]) {
mlx4_warn(dev, "Have more references for index %d,"
"no need to modify MAC table\n", index);
goto out;
}
table->entries[index] = 0;
mlx4_set_port_mac_table(dev, port, table->entries);
--table->total;
out:
mutex_unlock(&table->mutex);
}
EXPORT_SYMBOL_GPL(mlx4_unregister_mac);
static int mlx4_set_port_vlan_table(struct mlx4_dev *dev, u8 port,
__be32 *entries)
{
struct mlx4_cmd_mailbox *mailbox;
u32 in_mod;
int err;
mailbox = mlx4_alloc_cmd_mailbox(dev);
if (IS_ERR(mailbox))
return PTR_ERR(mailbox);
memcpy(mailbox->buf, entries, MLX4_VLAN_TABLE_SIZE);
in_mod = MLX4_SET_PORT_VLAN_TABLE << 8 | port;
err = mlx4_cmd(dev, mailbox->dma, in_mod, 1, MLX4_CMD_SET_PORT,
MLX4_CMD_TIME_CLASS_B);
mlx4_free_cmd_mailbox(dev, mailbox);
return err;
}
int mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index)
{
struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table;
int i, err = 0;
int free = -1;
mutex_lock(&table->mutex);
for (i = MLX4_VLAN_REGULAR; i < MLX4_MAX_VLAN_NUM; i++) {
if (free < 0 && (table->refs[i] == 0)) {
free = i;
continue;
}
if (table->refs[i] &&
(vlan == (MLX4_VLAN_MASK &
be32_to_cpu(table->entries[i])))) {
/* Vlan already registered, increase refernce count */
*index = i;
++table->refs[i];
goto out;
}
}
if (free < 0) {
err = -ENOMEM;
goto out;
}
if (table->total == table->max) {
/* No free vlan entries */
err = -ENOSPC;
goto out;
}
/* Register new MAC */
table->refs[free] = 1;
table->entries[free] = cpu_to_be32(vlan | MLX4_VLAN_VALID);
err = mlx4_set_port_vlan_table(dev, port, table->entries);
if (unlikely(err)) {
mlx4_warn(dev, "Failed adding vlan: %u\n", vlan);
table->refs[free] = 0;
table->entries[free] = 0;
goto out;
}
*index = free;
++table->total;
out:
mutex_unlock(&table->mutex);
return err;
}
EXPORT_SYMBOL_GPL(mlx4_register_vlan);
void mlx4_unregister_vlan(struct mlx4_dev *dev, u8 port, int index)
{
struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table;
if (index < MLX4_VLAN_REGULAR) {
mlx4_warn(dev, "Trying to free special vlan index %d\n", index);
return;
}
mutex_lock(&table->mutex);
if (!table->refs[index]) {
mlx4_warn(dev, "No vlan entry for index %d\n", index);
goto out;
}
if (--table->refs[index]) {
mlx4_dbg(dev, "Have more references for index %d,"
"no need to modify vlan table\n", index);
goto out;
}
table->entries[index] = 0;
mlx4_set_port_vlan_table(dev, port, table->entries);
--table->total;
out:
mutex_unlock(&table->mutex);
}
EXPORT_SYMBOL_GPL(mlx4_unregister_vlan);
int mlx4_get_port_ib_caps(struct mlx4_dev *dev, u8 port, __be32 *caps)
{
struct mlx4_cmd_mailbox *inmailbox, *outmailbox;
u8 *inbuf, *outbuf;
int err;
inmailbox = mlx4_alloc_cmd_mailbox(dev);
if (IS_ERR(inmailbox))
return PTR_ERR(inmailbox);
outmailbox = mlx4_alloc_cmd_mailbox(dev);
if (IS_ERR(outmailbox)) {
mlx4_free_cmd_mailbox(dev, inmailbox);
return PTR_ERR(outmailbox);
}
inbuf = inmailbox->buf;
outbuf = outmailbox->buf;
memset(inbuf, 0, 256);
memset(outbuf, 0, 256);
inbuf[0] = 1;
inbuf[1] = 1;
inbuf[2] = 1;
inbuf[3] = 1;
*(__be16 *) (&inbuf[16]) = cpu_to_be16(0x0015);
*(__be32 *) (&inbuf[20]) = cpu_to_be32(port);
err = mlx4_cmd_box(dev, inmailbox->dma, outmailbox->dma, port, 3,
MLX4_CMD_MAD_IFC, MLX4_CMD_TIME_CLASS_C);
if (!err)
*caps = *(__be32 *) (outbuf + 84);
mlx4_free_cmd_mailbox(dev, inmailbox);
mlx4_free_cmd_mailbox(dev, outmailbox);
return err;
}
int mlx4_SET_PORT(struct mlx4_dev *dev, u8 port)
{
struct mlx4_cmd_mailbox *mailbox;
int err;
if (dev->caps.port_type[port] == MLX4_PORT_TYPE_ETH)
return 0;
mailbox = mlx4_alloc_cmd_mailbox(dev);
if (IS_ERR(mailbox))
return PTR_ERR(mailbox);
memset(mailbox->buf, 0, 256);
((__be32 *) mailbox->buf)[1] = dev->caps.ib_port_def_cap[port];
err = mlx4_cmd(dev, mailbox->dma, port, 0, MLX4_CMD_SET_PORT,
MLX4_CMD_TIME_CLASS_B);
mlx4_free_cmd_mailbox(dev, mailbox);
return err;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4733_0 |
crossvul-cpp_data_bad_5822_0 | /*
* JPEG 2000 image decoder
* Copyright (c) 2007 Kamil Nowosad
* Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* JPEG 2000 image decoder
*/
#include "libavutil/avassert.h"
#include "libavutil/common.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "avcodec.h"
#include "bytestream.h"
#include "internal.h"
#include "thread.h"
#include "jpeg2000.h"
#define JP2_SIG_TYPE 0x6A502020
#define JP2_SIG_VALUE 0x0D0A870A
#define JP2_CODESTREAM 0x6A703263
#define JP2_HEADER 0x6A703268
#define HAD_COC 0x01
#define HAD_QCC 0x02
typedef struct Jpeg2000TilePart {
uint8_t tile_index; // Tile index who refers the tile-part
const uint8_t *tp_end;
GetByteContext tpg; // bit stream in tile-part
} Jpeg2000TilePart;
/* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile
* one per component, so tile_part elements have a size of 3 */
typedef struct Jpeg2000Tile {
Jpeg2000Component *comp;
uint8_t properties[4];
Jpeg2000CodingStyle codsty[4];
Jpeg2000QuantStyle qntsty[4];
Jpeg2000TilePart tile_part[4];
uint16_t tp_idx; // Tile-part index
} Jpeg2000Tile;
typedef struct Jpeg2000DecoderContext {
AVClass *class;
AVCodecContext *avctx;
GetByteContext g;
int width, height;
int image_offset_x, image_offset_y;
int tile_offset_x, tile_offset_y;
uint8_t cbps[4]; // bits per sample in particular components
uint8_t sgnd[4]; // if a component is signed
uint8_t properties[4];
int cdx[4], cdy[4];
int precision;
int ncomponents;
int colour_space;
uint32_t palette[256];
int8_t pal8;
int cdef[4];
int tile_width, tile_height;
unsigned numXtiles, numYtiles;
int maxtilelen;
Jpeg2000CodingStyle codsty[4];
Jpeg2000QuantStyle qntsty[4];
int bit_index;
int curtileno;
Jpeg2000Tile *tile;
/*options parameters*/
int reduction_factor;
} Jpeg2000DecoderContext;
/* get_bits functions for JPEG2000 packet bitstream
* It is a get_bit function with a bit-stuffing routine. If the value of the
* byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB.
* cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */
static int get_bits(Jpeg2000DecoderContext *s, int n)
{
int res = 0;
while (--n >= 0) {
res <<= 1;
if (s->bit_index == 0) {
s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
}
s->bit_index--;
res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
}
return res;
}
static void jpeg2000_flush(Jpeg2000DecoderContext *s)
{
if (bytestream2_get_byte(&s->g) == 0xff)
bytestream2_skip(&s->g, 1);
s->bit_index = 8;
}
/* decode the value stored in node */
static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
int threshold)
{
Jpeg2000TgtNode *stack[30];
int sp = -1, curval = 0;
if (!node)
return AVERROR_INVALIDDATA;
while (node && !node->vis) {
stack[++sp] = node;
node = node->parent;
}
if (node)
curval = node->val;
else
curval = stack[sp]->val;
while (curval < threshold && sp >= 0) {
if (curval < stack[sp]->val)
curval = stack[sp]->val;
while (curval < threshold) {
int ret;
if ((ret = get_bits(s, 1)) > 0) {
stack[sp]->vis++;
break;
} else if (!ret)
curval++;
else
return ret;
}
stack[sp]->val = curval;
sp--;
}
return curval;
}
static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components,
int bpc, uint32_t log2_chroma_wh, int pal8)
{
int match = 1;
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
if (desc->nb_components != components) {
return 0;
}
switch (components) {
case 4:
match = match && desc->comp[3].depth_minus1 + 1 >= bpc &&
(log2_chroma_wh >> 14 & 3) == 0 &&
(log2_chroma_wh >> 12 & 3) == 0;
case 3:
match = match && desc->comp[2].depth_minus1 + 1 >= bpc &&
(log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w &&
(log2_chroma_wh >> 8 & 3) == desc->log2_chroma_h;
case 2:
match = match && desc->comp[1].depth_minus1 + 1 >= bpc &&
(log2_chroma_wh >> 6 & 3) == desc->log2_chroma_w &&
(log2_chroma_wh >> 4 & 3) == desc->log2_chroma_h;
case 1:
match = match && desc->comp[0].depth_minus1 + 1 >= bpc &&
(log2_chroma_wh >> 2 & 3) == 0 &&
(log2_chroma_wh & 3) == 0 &&
(desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL;
}
return match;
}
// pix_fmts with lower bpp have to be listed before
// similar pix_fmts with higher bpp.
#define RGB_PIXEL_FORMATS AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64
#define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16
#define YUV_PIXEL_FORMATS AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \
AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \
AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \
AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \
AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \
AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \
AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \
AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \
AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \
AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \
AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16
#define XYZ_PIXEL_FORMATS AV_PIX_FMT_XYZ12
static const enum AVPixelFormat rgb_pix_fmts[] = {RGB_PIXEL_FORMATS};
static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS};
static const enum AVPixelFormat yuv_pix_fmts[] = {YUV_PIXEL_FORMATS};
static const enum AVPixelFormat xyz_pix_fmts[] = {XYZ_PIXEL_FORMATS};
static const enum AVPixelFormat all_pix_fmts[] = {RGB_PIXEL_FORMATS,
GRAY_PIXEL_FORMATS,
YUV_PIXEL_FORMATS,
XYZ_PIXEL_FORMATS};
/* marker segments */
/* get sizes and offsets of image, tiles; number of components */
static int get_siz(Jpeg2000DecoderContext *s)
{
int i;
int ncomponents;
uint32_t log2_chroma_wh = 0;
const enum AVPixelFormat *possible_fmts = NULL;
int possible_fmts_nb = 0;
if (bytestream2_get_bytes_left(&s->g) < 36)
return AVERROR_INVALIDDATA;
s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
s->width = bytestream2_get_be32u(&s->g); // Width
s->height = bytestream2_get_be32u(&s->g); // Height
s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz
s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz
s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz
s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz
ncomponents = bytestream2_get_be16u(&s->g); // CSiz
if (ncomponents <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
s->ncomponents);
return AVERROR_INVALIDDATA;
}
if (ncomponents > 4) {
avpriv_request_sample(s->avctx, "Support for %d components",
s->ncomponents);
return AVERROR_PATCHWELCOME;
}
s->ncomponents = ncomponents;
if (s->tile_width <= 0 || s->tile_height <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
s->tile_width, s->tile_height);
return AVERROR_INVALIDDATA;
}
if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
return AVERROR_INVALIDDATA;
for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
uint8_t x = bytestream2_get_byteu(&s->g);
s->cbps[i] = (x & 0x7f) + 1;
s->precision = FFMAX(s->cbps[i], s->precision);
s->sgnd[i] = !!(x & 0x80);
s->cdx[i] = bytestream2_get_byteu(&s->g);
s->cdy[i] = bytestream2_get_byteu(&s->g);
if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
|| !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid sample seperation\n");
return AVERROR_INVALIDDATA;
}
log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
}
s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(EINVAL);
}
s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
if (!s->tile) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(ENOMEM);
}
for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
Jpeg2000Tile *tile = s->tile + i;
tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
if (!tile->comp)
return AVERROR(ENOMEM);
}
/* compute image size with reduction factor */
s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x,
s->reduction_factor);
s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
s->reduction_factor);
if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
possible_fmts = xyz_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
} else {
switch (s->colour_space) {
case 16:
possible_fmts = rgb_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
break;
case 17:
possible_fmts = gray_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
break;
case 18:
possible_fmts = yuv_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
break;
default:
possible_fmts = all_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
break;
}
}
for (i = 0; i < possible_fmts_nb; ++i) {
if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
s->avctx->pix_fmt = possible_fmts[i];
break;
}
}
if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) {
av_log(s->avctx, AV_LOG_ERROR,
"Unknown pix_fmt, profile: %d, colour_space: %d, "
"components: %d, precision: %d, "
"cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n",
s->avctx->profile, s->colour_space, ncomponents, s->precision,
ncomponents > 2 ? s->cdx[1] : 0,
ncomponents > 2 ? s->cdy[1] : 0,
ncomponents > 2 ? s->cdx[2] : 0,
ncomponents > 2 ? s->cdy[2] : 0);
}
return 0;
}
/* get common part for COD and COC segments */
static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
{
uint8_t byte;
if (bytestream2_get_bytes_left(&s->g) < 5)
return AVERROR_INVALIDDATA;
/* nreslevels = number of resolution levels
= number of decomposition level +1 */
c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
return AVERROR_INVALIDDATA;
}
/* compute number of resolution levels to decode */
if (c->nreslevels < s->reduction_factor)
c->nreslevels2decode = 1;
else
c->nreslevels2decode = c->nreslevels - s->reduction_factor;
c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
c->log2_cblk_width + c->log2_cblk_height > 12) {
av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
return AVERROR_INVALIDDATA;
}
c->cblk_style = bytestream2_get_byteu(&s->g);
if (c->cblk_style != 0) { // cblk style
av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
}
c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
/* set integer 9/7 DWT in case of BITEXACT flag */
if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
c->transform = FF_DWT97_INT;
if (c->csty & JPEG2000_CSTY_PREC) {
int i;
for (i = 0; i < c->nreslevels; i++) {
byte = bytestream2_get_byte(&s->g);
c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
}
} else {
memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
}
return 0;
}
/* get coding parameters for a particular tile or whole image*/
static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
uint8_t *properties)
{
Jpeg2000CodingStyle tmp;
int compno, ret;
if (bytestream2_get_bytes_left(&s->g) < 5)
return AVERROR_INVALIDDATA;
tmp.csty = bytestream2_get_byteu(&s->g);
// get progression order
tmp.prog_order = bytestream2_get_byteu(&s->g);
tmp.nlayers = bytestream2_get_be16u(&s->g);
tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation
if (tmp.mct && s->ncomponents < 3) {
av_log(s->avctx, AV_LOG_ERROR,
"MCT %d with too few components (%d)\n",
tmp.mct, s->ncomponents);
return AVERROR_INVALIDDATA;
}
if ((ret = get_cox(s, &tmp)) < 0)
return ret;
for (compno = 0; compno < s->ncomponents; compno++)
if (!(properties[compno] & HAD_COC))
memcpy(c + compno, &tmp, sizeof(tmp));
return 0;
}
/* Get coding parameters for a component in the whole image or a
* particular tile. */
static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
uint8_t *properties)
{
int compno, ret;
if (bytestream2_get_bytes_left(&s->g) < 2)
return AVERROR_INVALIDDATA;
compno = bytestream2_get_byteu(&s->g);
if (compno >= s->ncomponents) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid compno %d. There are %d components in the image.\n",
compno, s->ncomponents);
return AVERROR_INVALIDDATA;
}
c += compno;
c->csty = bytestream2_get_byteu(&s->g);
if ((ret = get_cox(s, c)) < 0)
return ret;
properties[compno] |= HAD_COC;
return 0;
}
/* Get common part for QCD and QCC segments. */
static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
{
int i, x;
if (bytestream2_get_bytes_left(&s->g) < 1)
return AVERROR_INVALIDDATA;
x = bytestream2_get_byteu(&s->g); // Sqcd
q->nguardbits = x >> 5;
q->quantsty = x & 0x1f;
if (q->quantsty == JPEG2000_QSTY_NONE) {
n -= 3;
if (bytestream2_get_bytes_left(&s->g) < n ||
n > JPEG2000_MAX_DECLEVELS*3)
return AVERROR_INVALIDDATA;
for (i = 0; i < n; i++)
q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
} else if (q->quantsty == JPEG2000_QSTY_SI) {
if (bytestream2_get_bytes_left(&s->g) < 2)
return AVERROR_INVALIDDATA;
x = bytestream2_get_be16u(&s->g);
q->expn[0] = x >> 11;
q->mant[0] = x & 0x7ff;
for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
q->expn[i] = curexpn;
q->mant[i] = q->mant[0];
}
} else {
n = (n - 3) >> 1;
if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
n > JPEG2000_MAX_DECLEVELS*3)
return AVERROR_INVALIDDATA;
for (i = 0; i < n; i++) {
x = bytestream2_get_be16u(&s->g);
q->expn[i] = x >> 11;
q->mant[i] = x & 0x7ff;
}
}
return 0;
}
/* Get quantization parameters for a particular tile or a whole image. */
static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
uint8_t *properties)
{
Jpeg2000QuantStyle tmp;
int compno, ret;
if ((ret = get_qcx(s, n, &tmp)) < 0)
return ret;
for (compno = 0; compno < s->ncomponents; compno++)
if (!(properties[compno] & HAD_QCC))
memcpy(q + compno, &tmp, sizeof(tmp));
return 0;
}
/* Get quantization parameters for a component in the whole image
* on in a particular tile. */
static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
uint8_t *properties)
{
int compno;
if (bytestream2_get_bytes_left(&s->g) < 1)
return AVERROR_INVALIDDATA;
compno = bytestream2_get_byteu(&s->g);
if (compno >= s->ncomponents) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid compno %d. There are %d components in the image.\n",
compno, s->ncomponents);
return AVERROR_INVALIDDATA;
}
properties[compno] |= HAD_QCC;
return get_qcx(s, n - 1, q + compno);
}
/* Get start of tile segment. */
static int get_sot(Jpeg2000DecoderContext *s, int n)
{
Jpeg2000TilePart *tp;
uint16_t Isot;
uint32_t Psot;
uint8_t TPsot;
if (bytestream2_get_bytes_left(&s->g) < 8)
return AVERROR_INVALIDDATA;
s->curtileno = 0;
Isot = bytestream2_get_be16u(&s->g); // Isot
if (Isot >= s->numXtiles * s->numYtiles)
return AVERROR_INVALIDDATA;
s->curtileno = Isot;
Psot = bytestream2_get_be32u(&s->g); // Psot
TPsot = bytestream2_get_byteu(&s->g); // TPsot
/* Read TNSot but not used */
bytestream2_get_byteu(&s->g); // TNsot
if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) {
av_log(s->avctx, AV_LOG_ERROR, "Psot %d too big\n", Psot);
return AVERROR_INVALIDDATA;
}
if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) {
avpriv_request_sample(s->avctx, "Support for %d components", TPsot);
return AVERROR_PATCHWELCOME;
}
s->tile[Isot].tp_idx = TPsot;
tp = s->tile[Isot].tile_part + TPsot;
tp->tile_index = Isot;
tp->tp_end = s->g.buffer + Psot - n - 2;
if (!TPsot) {
Jpeg2000Tile *tile = s->tile + s->curtileno;
/* copy defaults */
memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
}
return 0;
}
/* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
* Used to know the number of tile parts and lengths.
* There may be multiple TLMs in the header.
* TODO: The function is not used for tile-parts management, nor anywhere else.
* It can be useful to allocate memory for tile parts, before managing the SOT
* markers. Parsing the TLM header is needed to increment the input header
* buffer.
* This marker is mandatory for DCI. */
static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n)
{
uint8_t Stlm, ST, SP, tile_tlm, i;
bytestream2_get_byte(&s->g); /* Ztlm: skipped */
Stlm = bytestream2_get_byte(&s->g);
// too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
ST = (Stlm >> 4) & 0x03;
// TODO: Manage case of ST = 0b11 --> raise error
SP = (Stlm >> 6) & 0x01;
tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
for (i = 0; i < tile_tlm; i++) {
switch (ST) {
case 0:
break;
case 1:
bytestream2_get_byte(&s->g);
break;
case 2:
bytestream2_get_be16(&s->g);
break;
case 3:
bytestream2_get_be32(&s->g);
break;
}
if (SP == 0) {
bytestream2_get_be16(&s->g);
} else {
bytestream2_get_be32(&s->g);
}
}
return 0;
}
static int init_tile(Jpeg2000DecoderContext *s, int tileno)
{
int compno;
int tilex = tileno % s->numXtiles;
int tiley = tileno / s->numXtiles;
Jpeg2000Tile *tile = s->tile + tileno;
if (!tile->comp)
return AVERROR(ENOMEM);
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = tile->comp + compno;
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
int ret; // global bandno
comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width);
comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height);
comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);
comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);
comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);
comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);
if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
s->cbps[compno], s->cdx[compno],
s->cdy[compno], s->avctx))
return ret;
}
return 0;
}
/* Read the number of coding passes. */
static int getnpasses(Jpeg2000DecoderContext *s)
{
int num;
if (!get_bits(s, 1))
return 1;
if (!get_bits(s, 1))
return 2;
if ((num = get_bits(s, 2)) != 3)
return num < 0 ? num : 3 + num;
if ((num = get_bits(s, 5)) != 31)
return num < 0 ? num : 6 + num;
num = get_bits(s, 7);
return num < 0 ? num : 37 + num;
}
static int getlblockinc(Jpeg2000DecoderContext *s)
{
int res = 0, ret;
while (ret = get_bits(s, 1)) {
if (ret < 0)
return ret;
res++;
}
return res;
}
static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s,
Jpeg2000CodingStyle *codsty,
Jpeg2000ResLevel *rlevel, int precno,
int layno, uint8_t *expn, int numgbits)
{
int bandno, cblkno, ret, nb_code_blocks;
if (!(ret = get_bits(s, 1))) {
jpeg2000_flush(s);
return 0;
} else if (ret < 0)
return ret;
for (bandno = 0; bandno < rlevel->nbands; bandno++) {
Jpeg2000Band *band = rlevel->band + bandno;
Jpeg2000Prec *prec = band->prec + precno;
if (band->coord[0][0] == band->coord[0][1] ||
band->coord[1][0] == band->coord[1][1])
continue;
nb_code_blocks = prec->nb_codeblocks_height *
prec->nb_codeblocks_width;
for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
Jpeg2000Cblk *cblk = prec->cblk + cblkno;
int incl, newpasses, llen;
if (cblk->npasses)
incl = get_bits(s, 1);
else
incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
if (!incl)
continue;
else if (incl < 0)
return incl;
if (!cblk->npasses) {
int v = expn[bandno] + numgbits - 1 -
tag_tree_decode(s, prec->zerobits + cblkno, 100);
if (v < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"nonzerobits %d invalid\n", v);
return AVERROR_INVALIDDATA;
}
cblk->nonzerobits = v;
}
if ((newpasses = getnpasses(s)) < 0)
return newpasses;
if ((llen = getlblockinc(s)) < 0)
return llen;
cblk->lblock += llen;
if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
return ret;
if (ret > sizeof(cblk->data)) {
avpriv_request_sample(s->avctx,
"Block with lengthinc greater than %zu",
sizeof(cblk->data));
return AVERROR_PATCHWELCOME;
}
cblk->lengthinc = ret;
cblk->npasses += newpasses;
}
}
jpeg2000_flush(s);
if (codsty->csty & JPEG2000_CSTY_EPH) {
if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
bytestream2_skip(&s->g, 2);
else
av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
}
for (bandno = 0; bandno < rlevel->nbands; bandno++) {
Jpeg2000Band *band = rlevel->band + bandno;
Jpeg2000Prec *prec = band->prec + precno;
nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
Jpeg2000Cblk *cblk = prec->cblk + cblkno;
if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc
|| sizeof(cblk->data) < cblk->length + cblk->lengthinc + 2
)
return AVERROR_INVALIDDATA;
bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc);
cblk->length += cblk->lengthinc;
cblk->lengthinc = 0;
}
}
return 0;
}
static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
{
int ret = 0;
int layno, reslevelno, compno, precno, ok_reslevel;
int x, y;
s->bit_index = 8;
switch (tile->codsty[0].prog_order) {
case JPEG2000_PGOD_RLCP:
avpriv_request_sample(s->avctx, "Progression order RLCP");
case JPEG2000_PGOD_LRCP:
for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
ok_reslevel = 1;
for (reslevelno = 0; ok_reslevel; reslevelno++) {
ok_reslevel = 0;
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
if (reslevelno < codsty->nreslevels) {
Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
reslevelno;
ok_reslevel = 1;
for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
if ((ret = jpeg2000_decode_packet(s,
codsty, rlevel,
precno, layno,
qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
qntsty->nguardbits)) < 0)
return ret;
}
}
}
}
break;
case JPEG2000_PGOD_CPRL:
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
/* Set bit stream buffer address according to tile-part.
* For DCinema one tile-part per component, so can be
* indexed by component. */
s->g = tile->tile_part[compno].tpg;
/* Position loop (y axis)
* TODO: Automate computing of step 256.
* Fixed here, but to be computed before entering here. */
for (y = 0; y < s->height; y += 256) {
/* Position loop (y axis)
* TODO: automate computing of step 256.
* Fixed here, but to be computed before entering here. */
for (x = 0; x < s->width; x += 256) {
for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
uint16_t prcx, prcy;
uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
(y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
continue;
if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
(x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
continue;
// check if a precinct exists
prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
precno = prcx + rlevel->num_precincts_x * prcy;
for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
if ((ret = jpeg2000_decode_packet(s, codsty, rlevel,
precno, layno,
qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
qntsty->nguardbits)) < 0)
return ret;
}
}
}
}
}
break;
case JPEG2000_PGOD_RPCL:
avpriv_request_sample(s->avctx, "Progression order RPCL");
ret = AVERROR_PATCHWELCOME;
break;
case JPEG2000_PGOD_PCRL:
avpriv_request_sample(s->avctx, "Progression order PCRL");
ret = AVERROR_PATCHWELCOME;
break;
default:
break;
}
/* EOC marker reached */
bytestream2_skip(&s->g, 2);
return ret;
}
/* TIER-1 routines */
static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
int bpno, int bandno, int bpass_csty_symbol,
int vert_causal_ctx_csty_symbol)
{
int mask = 3 << (bpno - 1), y0, x, y;
for (y0 = 0; y0 < height; y0 += 4)
for (x = 0; x < width; x++)
for (y = y0; y < height && y < y0 + 4; y++) {
if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)
&& !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
int flags_mask = -1;
if (vert_causal_ctx_csty_symbol && y == y0 + 3)
flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) {
int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
if (bpass_csty_symbol)
t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
else
t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
-mask : mask;
ff_jpeg2000_set_significance(t1, x, y,
t1->data[y][x] < 0);
}
t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
}
}
}
static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
int bpno)
{
int phalf, nhalf;
int y0, x, y;
phalf = 1 << (bpno - 1);
nhalf = -phalf;
for (y0 = 0; y0 < height; y0 += 4)
for (x = 0; x < width; x++)
for (y = y0; y < height && y < y0 + 4; y++)
if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
int r = ff_mqc_decode(&t1->mqc,
t1->mqc.cx_states + ctxno)
? phalf : nhalf;
t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
}
}
static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
int width, int height, int bpno, int bandno,
int seg_symbols, int vert_causal_ctx_csty_symbol)
{
int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
for (y0 = 0; y0 < height; y0 += 4) {
for (x = 0; x < width; x++) {
if (y0 + 3 < height &&
!((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
(t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
(t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
(t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
continue;
runlen = ff_mqc_decode(&t1->mqc,
t1->mqc.cx_states + MQC_CX_UNI);
runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
t1->mqc.cx_states +
MQC_CX_UNI);
dec = 1;
} else {
runlen = 0;
dec = 0;
}
for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
if (!dec) {
if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
int flags_mask = -1;
if (vert_causal_ctx_csty_symbol && y == y0 + 3)
flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask,
bandno));
}
}
if (dec) {
int xorbit;
int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
&xorbit);
t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
t1->mqc.cx_states + ctxno) ^
xorbit)
? -mask : mask;
ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
}
dec = 0;
t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
}
}
}
if (seg_symbols) {
int val;
val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
if (val != 0xa)
av_log(s->avctx, AV_LOG_ERROR,
"Segmentation symbol value incorrect\n");
}
}
static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
int width, int height, int bandpos)
{
int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
int clnpass_cnt = 0;
int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS;
int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
for (y = 0; y < height; y++)
memset(t1->data[y], 0, width * sizeof(**t1->data));
/* If code-block contains no compressed data: nothing to do. */
if (!cblk->length)
return 0;
for (y = 0; y < height + 2; y++)
memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));
cblk->data[cblk->length] = 0xff;
cblk->data[cblk->length+1] = 0xff;
ff_mqc_initdec(&t1->mqc, cblk->data);
while (passno--) {
switch(pass_t) {
case 0:
decode_sigpass(t1, width, height, bpno + 1, bandpos,
bpass_csty_symbol && (clnpass_cnt >= 4),
vert_causal_ctx_csty_symbol);
break;
case 1:
decode_refpass(t1, width, height, bpno + 1);
if (bpass_csty_symbol && clnpass_cnt >= 4)
ff_mqc_initdec(&t1->mqc, cblk->data);
break;
case 2:
decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
vert_causal_ctx_csty_symbol);
clnpass_cnt = clnpass_cnt + 1;
if (bpass_csty_symbol && clnpass_cnt >= 4)
ff_mqc_initdec(&t1->mqc, cblk->data);
break;
}
pass_t++;
if (pass_t == 3) {
bpno--;
pass_t = 0;
}
}
return 0;
}
/* TODO: Verify dequantization for lossless case
* comp->data can be float or int
* band->stepsize can be float or int
* depending on the type of DWT transformation.
* see ISO/IEC 15444-1:2002 A.6.1 */
/* Float dequantization of a codeblock.*/
static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
Jpeg2000Component *comp,
Jpeg2000T1Context *t1, Jpeg2000Band *band)
{
int i, j;
int w = cblk->coord[0][1] - cblk->coord[0][0];
for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
int *src = t1->data[j];
for (i = 0; i < w; ++i)
datap[i] = src[i] * band->f_stepsize;
}
}
/* Integer dequantization of a codeblock.*/
static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
Jpeg2000Component *comp,
Jpeg2000T1Context *t1, Jpeg2000Band *band)
{
int i, j;
int w = cblk->coord[0][1] - cblk->coord[0][0];
for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
int *src = t1->data[j];
for (i = 0; i < w; ++i)
datap[i] = (src[i] * band->i_stepsize + (1 << 14)) >> 15;
}
}
/* Inverse ICT parameters in float and integer.
* int value = (float value) * (1<<16) */
static const float f_ict_params[4] = {
1.402f,
0.34413f,
0.71414f,
1.772f
};
static const int i_ict_params[4] = {
91881,
22553,
46802,
116130
};
static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
{
int i, csize = 1;
int32_t *src[3], i0, i1, i2;
float *srcf[3], i0f, i1f, i2f;
for (i = 0; i < 3; i++)
if (tile->codsty[0].transform == FF_DWT97)
srcf[i] = tile->comp[i].f_data;
else
src [i] = tile->comp[i].i_data;
for (i = 0; i < 2; i++)
csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
switch (tile->codsty[0].transform) {
case FF_DWT97:
for (i = 0; i < csize; i++) {
i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
- (f_ict_params[2] * *srcf[2]);
i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
*srcf[0]++ = i0f;
*srcf[1]++ = i1f;
*srcf[2]++ = i2f;
}
break;
case FF_DWT97_INT:
for (i = 0; i < csize; i++) {
i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
- (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
*src[0]++ = i0;
*src[1]++ = i1;
*src[2]++ = i2;
}
break;
case FF_DWT53:
for (i = 0; i < csize; i++) {
i1 = *src[0] - (*src[2] + *src[1] >> 2);
i0 = i1 + *src[2];
i2 = i1 + *src[1];
*src[0]++ = i0;
*src[1]++ = i1;
*src[2]++ = i2;
}
break;
}
}
static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
AVFrame *picture)
{
int compno, reslevelno, bandno;
int x, y;
uint8_t *line;
Jpeg2000T1Context t1;
/* Loop on tile components */
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = tile->comp + compno;
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
/* Loop on resolution levels */
for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
/* Loop on bands */
for (bandno = 0; bandno < rlevel->nbands; bandno++) {
int nb_precincts, precno;
Jpeg2000Band *band = rlevel->band + bandno;
int cblkno = 0, bandpos;
bandpos = bandno + (reslevelno > 0);
if (band->coord[0][0] == band->coord[0][1] ||
band->coord[1][0] == band->coord[1][1])
continue;
nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
/* Loop on precincts */
for (precno = 0; precno < nb_precincts; precno++) {
Jpeg2000Prec *prec = band->prec + precno;
/* Loop on codeblocks */
for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
int x, y;
Jpeg2000Cblk *cblk = prec->cblk + cblkno;
decode_cblk(s, codsty, &t1, cblk,
cblk->coord[0][1] - cblk->coord[0][0],
cblk->coord[1][1] - cblk->coord[1][0],
bandpos);
x = cblk->coord[0][0];
y = cblk->coord[1][0];
if (codsty->transform == FF_DWT97)
dequantization_float(x, y, cblk, comp, &t1, band);
else
dequantization_int(x, y, cblk, comp, &t1, band);
} /* end cblk */
} /*end prec */
} /* end band */
} /* end reslevel */
/* inverse DWT */
ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
} /*end comp */
/* inverse MCT transformation */
if (tile->codsty[0].mct)
mct_decode(s, tile);
if (s->cdef[0] < 0) {
for (x = 0; x < s->ncomponents; x++)
s->cdef[x] = x + 1;
if ((s->ncomponents & 1) == 0)
s->cdef[s->ncomponents-1] = 0;
}
if (s->precision <= 8) {
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = tile->comp + compno;
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
float *datap = comp->f_data;
int32_t *i_datap = comp->i_data;
int cbps = s->cbps[compno];
int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
int planar = !!picture->data[2];
int pixelsize = planar ? 1 : s->ncomponents;
int plane = 0;
if (planar)
plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
y = tile->comp[compno].coord[1][0] - s->image_offset_y;
line = picture->data[plane] + y * picture->linesize[plane];
for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
uint8_t *dst;
x = tile->comp[compno].coord[0][0] - s->image_offset_x;
dst = line + x * pixelsize + compno*!planar;
if (codsty->transform == FF_DWT97) {
for (; x < w; x += s->cdx[compno]) {
int val = lrintf(*datap) + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
*dst = val << (8 - cbps);
datap++;
dst += pixelsize;
}
} else {
for (; x < w; x += s->cdx[compno]) {
int val = *i_datap + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
*dst = val << (8 - cbps);
i_datap++;
dst += pixelsize;
}
}
line += picture->linesize[plane];
}
}
} else {
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = tile->comp + compno;
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
float *datap = comp->f_data;
int32_t *i_datap = comp->i_data;
uint16_t *linel;
int cbps = s->cbps[compno];
int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
int planar = !!picture->data[2];
int pixelsize = planar ? 1 : s->ncomponents;
int plane = 0;
if (planar)
plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
y = tile->comp[compno].coord[1][0] - s->image_offset_y;
linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1);
for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
uint16_t *dst;
x = tile->comp[compno].coord[0][0] - s->image_offset_x;
dst = linel + (x * pixelsize + compno*!planar);
if (codsty->transform == FF_DWT97) {
for (; x < w; x += s-> cdx[compno]) {
int val = lrintf(*datap) + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
/* align 12 bit values in little-endian mode */
*dst = val << (16 - cbps);
datap++;
dst += pixelsize;
}
} else {
for (; x < w; x += s-> cdx[compno]) {
int val = *i_datap + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
/* align 12 bit values in little-endian mode */
*dst = val << (16 - cbps);
i_datap++;
dst += pixelsize;
}
}
linel += picture->linesize[plane] >> 1;
}
}
}
return 0;
}
static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
{
int tileno, compno;
for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
if (s->tile[tileno].comp) {
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = s->tile[tileno].comp + compno;
Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
ff_jpeg2000_cleanup(comp, codsty);
}
av_freep(&s->tile[tileno].comp);
}
}
av_freep(&s->tile);
s->numXtiles = s->numYtiles = 0;
}
static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
{
Jpeg2000CodingStyle *codsty = s->codsty;
Jpeg2000QuantStyle *qntsty = s->qntsty;
uint8_t *properties = s->properties;
for (;;) {
int len, ret = 0;
uint16_t marker;
int oldpos;
if (bytestream2_get_bytes_left(&s->g) < 2) {
av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
break;
}
marker = bytestream2_get_be16u(&s->g);
oldpos = bytestream2_tell(&s->g);
if (marker == JPEG2000_SOD) {
Jpeg2000Tile *tile;
Jpeg2000TilePart *tp;
if (s->curtileno < 0) {
av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
return AVERROR_INVALIDDATA;
}
tile = s->tile + s->curtileno;
tp = tile->tile_part + tile->tp_idx;
if (tp->tp_end < s->g.buffer) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n");
return AVERROR_INVALIDDATA;
}
bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
continue;
}
if (marker == JPEG2000_EOC)
break;
len = bytestream2_get_be16(&s->g);
if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2)
return AVERROR_INVALIDDATA;
switch (marker) {
case JPEG2000_SIZ:
ret = get_siz(s);
if (!s->tile)
s->numXtiles = s->numYtiles = 0;
break;
case JPEG2000_COC:
ret = get_coc(s, codsty, properties);
break;
case JPEG2000_COD:
ret = get_cod(s, codsty, properties);
break;
case JPEG2000_QCC:
ret = get_qcc(s, len, qntsty, properties);
break;
case JPEG2000_QCD:
ret = get_qcd(s, len, qntsty, properties);
break;
case JPEG2000_SOT:
if (!(ret = get_sot(s, len))) {
av_assert1(s->curtileno >= 0);
codsty = s->tile[s->curtileno].codsty;
qntsty = s->tile[s->curtileno].qntsty;
properties = s->tile[s->curtileno].properties;
}
break;
case JPEG2000_COM:
// the comment is ignored
bytestream2_skip(&s->g, len - 2);
break;
case JPEG2000_TLM:
// Tile-part lengths
ret = get_tlm(s, len);
break;
default:
av_log(s->avctx, AV_LOG_ERROR,
"unsupported marker 0x%.4X at pos 0x%X\n",
marker, bytestream2_tell(&s->g) - 4);
bytestream2_skip(&s->g, len - 2);
break;
}
if (bytestream2_tell(&s->g) - oldpos != len || ret) {
av_log(s->avctx, AV_LOG_ERROR,
"error during processing marker segment %.4x\n", marker);
return ret ? ret : -1;
}
}
return 0;
}
/* Read bit stream packets --> T2 operation. */
static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
{
int ret = 0;
int tileno;
for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
Jpeg2000Tile *tile = s->tile + tileno;
if (ret = init_tile(s, tileno))
return ret;
s->g = tile->tile_part[0].tpg;
if (ret = jpeg2000_decode_packets(s, tile))
return ret;
}
return 0;
}
static int jp2_find_codestream(Jpeg2000DecoderContext *s)
{
uint32_t atom_size, atom, atom_end;
int search_range = 10;
while (search_range
&&
bytestream2_get_bytes_left(&s->g) >= 8) {
atom_size = bytestream2_get_be32u(&s->g);
atom = bytestream2_get_be32u(&s->g);
atom_end = bytestream2_tell(&s->g) + atom_size - 8;
if (atom == JP2_CODESTREAM)
return 1;
if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size)
return 0;
if (atom == JP2_HEADER &&
atom_size >= 16) {
uint32_t atom2_size, atom2, atom2_end;
do {
atom2_size = bytestream2_get_be32u(&s->g);
atom2 = bytestream2_get_be32u(&s->g);
atom2_end = bytestream2_tell(&s->g) + atom2_size - 8;
if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size)
break;
if (atom2 == JP2_CODESTREAM) {
return 1;
} else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) {
int method = bytestream2_get_byteu(&s->g);
bytestream2_skipu(&s->g, 2);
if (method == 1) {
s->colour_space = bytestream2_get_be32u(&s->g);
}
} else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) {
int i, size, colour_count, colour_channels, colour_depth[3];
uint32_t r, g, b;
colour_count = bytestream2_get_be16u(&s->g);
colour_channels = bytestream2_get_byteu(&s->g);
// FIXME: Do not ignore channel_sign
colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
size = (colour_depth[0] + 7 >> 3) * colour_count +
(colour_depth[1] + 7 >> 3) * colour_count +
(colour_depth[2] + 7 >> 3) * colour_count;
if (colour_count > 256 ||
colour_channels != 3 ||
colour_depth[0] > 16 ||
colour_depth[1] > 16 ||
colour_depth[2] > 16 ||
atom2_size < size) {
avpriv_request_sample(s->avctx, "Unknown palette");
bytestream2_seek(&s->g, atom2_end, SEEK_SET);
continue;
}
s->pal8 = 1;
for (i = 0; i < colour_count; i++) {
if (colour_depth[0] <= 8) {
r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0];
r |= r >> colour_depth[0];
} else {
r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8;
}
if (colour_depth[1] <= 8) {
g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1];
r |= r >> colour_depth[1];
} else {
g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8;
}
if (colour_depth[2] <= 8) {
b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2];
r |= r >> colour_depth[2];
} else {
b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8;
}
s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b;
}
} else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) {
int n = bytestream2_get_be16u(&s->g);
for (; n>0; n--) {
int cn = bytestream2_get_be16(&s->g);
int av_unused typ = bytestream2_get_be16(&s->g);
int asoc = bytestream2_get_be16(&s->g);
if (cn < 4 || asoc < 4)
s->cdef[cn] = asoc;
}
}
bytestream2_seek(&s->g, atom2_end, SEEK_SET);
} while (atom_end - atom2_end >= 8);
} else {
search_range--;
}
bytestream2_seek(&s->g, atom_end, SEEK_SET);
}
return 0;
}
static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
Jpeg2000DecoderContext *s = avctx->priv_data;
ThreadFrame frame = { .f = data };
AVFrame *picture = data;
int tileno, ret;
s->avctx = avctx;
bytestream2_init(&s->g, avpkt->data, avpkt->size);
s->curtileno = -1;
memset(s->cdef, -1, sizeof(s->cdef));
if (bytestream2_get_bytes_left(&s->g) < 2) {
ret = AVERROR_INVALIDDATA;
goto end;
}
// check if the image is in jp2 format
if (bytestream2_get_bytes_left(&s->g) >= 12 &&
(bytestream2_get_be32u(&s->g) == 12) &&
(bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
(bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
if (!jp2_find_codestream(s)) {
av_log(avctx, AV_LOG_ERROR,
"Could not find Jpeg2000 codestream atom.\n");
ret = AVERROR_INVALIDDATA;
goto end;
}
} else {
bytestream2_seek(&s->g, 0, SEEK_SET);
}
if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
ret = AVERROR_INVALIDDATA;
goto end;
}
if (ret = jpeg2000_read_main_headers(s))
goto end;
/* get picture buffer */
if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
goto end;
picture->pict_type = AV_PICTURE_TYPE_I;
picture->key_frame = 1;
if (ret = jpeg2000_read_bitstream_packets(s))
goto end;
for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
goto end;
jpeg2000_dec_cleanup(s);
*got_frame = 1;
if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t));
return bytestream2_tell(&s->g);
end:
jpeg2000_dec_cleanup(s);
return ret;
}
static void jpeg2000_init_static_data(AVCodec *codec)
{
ff_jpeg2000_init_tier1_luts();
ff_mqc_init_context_tables();
}
#define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
static const AVOption options[] = {
{ "lowres", "Lower the decoding resolution by a power of two",
OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
{ NULL },
};
static const AVProfile profiles[] = {
{ FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
{ FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
{ FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
{ FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
{ FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
{ FF_PROFILE_UNKNOWN },
};
static const AVClass jpeg2000_class = {
.class_name = "jpeg2000",
.item_name = av_default_item_name,
.option = options,
.version = LIBAVUTIL_VERSION_INT,
};
AVCodec ff_jpeg2000_decoder = {
.name = "jpeg2000",
.long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_JPEG2000,
.capabilities = CODEC_CAP_FRAME_THREADS,
.priv_data_size = sizeof(Jpeg2000DecoderContext),
.init_static_data = jpeg2000_init_static_data,
.decode = jpeg2000_decode_frame,
.priv_class = &jpeg2000_class,
.max_lowres = 5,
.profiles = NULL_IF_CONFIG_SMALL(profiles)
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5822_0 |
crossvul-cpp_data_good_4787_20 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF PPPP X X %
% F P P X X %
% FFF PPPP X %
% F P X X %
% F P X X %
% %
% %
% Read/Write FlashPIX Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#if defined(MAGICKCORE_FPX_DELEGATE)
#if !defined(vms) && !defined(macintosh) && !defined(MAGICKCORE_WINDOWS_SUPPORT)
#include <fpxlib.h>
#else
#include "Fpxlib.h"
#endif
#endif
#if defined(MAGICKCORE_FPX_DELEGATE)
/*
Forward declarations.
*/
static MagickBooleanType
WriteFPXImage(const ImageInfo *,Image *);
#endif
#if defined(MAGICKCORE_FPX_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d F P X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadFPXImage() reads a FlashPix image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image. This method was contributed by BillR@corbis.com.
%
% The format of the ReadFPXImage method is:
%
% Image *ReadFPXImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadFPXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
FPXColorspace
colorspace;
FPXImageComponentDesc
*alpha_component,
*blue_component,
*green_component,
*red_component;
FPXImageDesc
fpx_info;
FPXImageHandle
*flashpix;
FPXStatus
fpx_status;
FPXSummaryInformation
summary_info;
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*a,
*b,
*g,
*r;
size_t
memory_limit;
ssize_t
y;
unsigned char
*pixels;
unsigned int
height,
tile_width,
tile_height,
width;
size_t
scene;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) CloseBlob(image);
/*
Initialize FPX toolkit.
*/
fpx_status=FPX_InitSystem();
if (fpx_status != FPX_OK)
ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
memory_limit=20000000;
fpx_status=FPX_SetToolkitMemoryLimit(&memory_limit);
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
}
tile_width=64;
tile_height=64;
flashpix=(FPXImageHandle *) NULL;
{
#if defined(macintosh)
FSSpec
fsspec;
FilenameToFSSpec(image->filename,&fsspec);
fpx_status=FPX_OpenImageByFilename((const FSSpec &) fsspec,(char *) NULL,
#else
fpx_status=FPX_OpenImageByFilename(image->filename,(char *) NULL,
#endif
&width,&height,&tile_width,&tile_height,&colorspace,&flashpix);
}
if (fpx_status == FPX_LOW_MEMORY_ERROR)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (colorspace.numberOfComponents == 0)
{
FPX_ClearSystem();
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
}
if (image_info->view == (char *) NULL)
{
float
aspect_ratio;
/*
Get the aspect ratio.
*/
aspect_ratio=(float) width/height;
fpx_status=FPX_GetImageResultAspectRatio(flashpix,&aspect_ratio);
if (fpx_status != FPX_OK)
ThrowReaderException(DelegateError,"UnableToReadAspectRatio");
if (width != (size_t) floor((aspect_ratio*height)+0.5))
Swap(width,height);
}
fpx_status=FPX_GetSummaryInformation(flashpix,&summary_info);
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowReaderException(DelegateError,"UnableToReadSummaryInfo");
}
if (summary_info.title_valid)
if ((summary_info.title.length != 0) &&
(summary_info.title.ptr != (unsigned char *) NULL))
{
char
*label;
/*
Note image label.
*/
label=(char *) NULL;
if (~summary_info.title.length >= (MaxTextExtent-1))
label=(char *) AcquireQuantumMemory(summary_info.title.length+
MaxTextExtent,sizeof(*label));
if (label == (char *) NULL)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickString(label,(char *) summary_info.title.ptr,
summary_info.title.length+1);
(void) SetImageProperty(image,"label",label);
label=DestroyString(label);
}
if (summary_info.comments_valid)
if ((summary_info.comments.length != 0) &&
(summary_info.comments.ptr != (unsigned char *) NULL))
{
char
*comments;
/*
Note image comment.
*/
comments=(char *) NULL;
if (~summary_info.comments.length >= (MaxTextExtent-1))
comments=(char *) AcquireQuantumMemory(summary_info.comments.length+
MaxTextExtent,sizeof(*comments));
if (comments == (char *) NULL)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickString(comments,(char *) summary_info.comments.ptr,
summary_info.comments.length+1);
(void) SetImageProperty(image,"comment",comments);
comments=DestroyString(comments);
}
/*
Determine resolution by scene specification.
*/
for (i=1; ; i++)
if (((width >> i) < tile_width) || ((height >> i) < tile_height))
break;
scene=i;
if (image_info->number_scenes != 0)
while (scene > image_info->scene)
{
width>>=1;
height>>=1;
scene--;
}
if (image_info->size != (char *) NULL)
while ((width > image->columns) || (height > image->rows))
{
width>>=1;
height>>=1;
scene--;
}
image->depth=8;
image->columns=width;
image->rows=height;
if ((colorspace.numberOfComponents % 2) == 0)
image->matte=MagickTrue;
if (colorspace.numberOfComponents == 1)
{
/*
Create linear colormap.
*/
if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (image_info->ping != MagickFalse)
{
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate memory for the image and pixel buffer.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,(tile_height+
1UL)*colorspace.numberOfComponents*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
FPX_ClearSystem();
(void) FPX_CloseImage(flashpix);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Initialize FlashPix image description.
*/
fpx_info.numberOfComponents=colorspace.numberOfComponents;
for (i=0; i < 4; i++)
{
fpx_info.components[i].myColorType.myDataType=DATA_TYPE_UNSIGNED_BYTE;
fpx_info.components[i].horzSubSampFactor=1;
fpx_info.components[i].vertSubSampFactor=1;
fpx_info.components[i].columnStride=fpx_info.numberOfComponents;
fpx_info.components[i].lineStride=image->columns*
fpx_info.components[i].columnStride;
fpx_info.components[i].theData=pixels+i;
}
fpx_info.components[0].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
NIFRGB_R : MONOCHROME;
red_component=(&fpx_info.components[0]);
fpx_info.components[1].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
NIFRGB_G : ALPHA;
green_component=(&fpx_info.components[1]);
fpx_info.components[2].myColorType.myColor=NIFRGB_B;
blue_component=(&fpx_info.components[2]);
fpx_info.components[3].myColorType.myColor=ALPHA;
alpha_component=(&fpx_info.components[fpx_info.numberOfComponents-1]);
FPX_SetResampleMethod(FPX_LINEAR_INTERPOLATION);
/*
Initialize image pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if ((y % tile_height) == 0)
{
/*
Read FPX image tile (with or without viewing affine)..
*/
if (image_info->view != (char *) NULL)
fpx_status=FPX_ReadImageRectangle(flashpix,0,y,image->columns,y+
tile_height-1,scene,&fpx_info);
else
fpx_status=FPX_ReadImageTransformRectangle(flashpix,0.0F,
(float) y/image->rows,(float) image->columns/image->rows,
(float) (y+tile_height-1)/image->rows,(ssize_t) image->columns,
(ssize_t) tile_height,&fpx_info);
if (fpx_status == FPX_LOW_MEMORY_ERROR)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
/*
Transfer a FPX pixels.
*/
r=red_component->theData+(y % tile_height)*red_component->lineStride;
g=green_component->theData+(y % tile_height)*green_component->lineStride;
b=blue_component->theData+(y % tile_height)*blue_component->lineStride;
a=alpha_component->theData+(y % tile_height)*alpha_component->lineStride;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (fpx_info.numberOfComponents > 2)
{
SetPixelRed(q,ScaleCharToQuantum(*r));
SetPixelGreen(q,ScaleCharToQuantum(*g));
SetPixelBlue(q,ScaleCharToQuantum(*b));
}
else
{
index=ScaleCharToQuantum(*r);
SetPixelIndex(indexes+x,index);
SetPixelRed(q,index);
SetPixelGreen(q,index);
SetPixelBlue(q,index);
}
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*a));
q++;
r+=red_component->columnStride;
g+=green_component->columnStride;
b+=blue_component->columnStride;
a+=alpha_component->columnStride;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r F P X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterFPXImage() adds attributes for the FPX image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterFPXImage method is:
%
% size_t RegisterFPXImage(void)
%
*/
ModuleExport size_t RegisterFPXImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("FPX");
#if defined(MAGICKCORE_FPX_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadFPXImage;
entry->encoder=(EncodeImageHandler *) WriteFPXImage;
#endif
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->blob_support=MagickFalse;
entry->description=ConstantString("FlashPix Format");
entry->module=ConstantString("FPX");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r F P X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterFPXImage() removes format registrations made by the
% FPX module from the list of supported formats.
%
% The format of the UnregisterFPXImage method is:
%
% UnregisterFPXImage(void)
%
*/
ModuleExport void UnregisterFPXImage(void)
{
(void) UnregisterMagickInfo("FPX");
}
#if defined(MAGICKCORE_FPX_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e F P X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteFPXImage() writes an image in the FlashPix image format. This
% method was contributed by BillR@corbis.com.
%
% The format of the WriteFPXImage method is:
%
% MagickBooleanType WriteFPXImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static void ColorTwistMultiply(FPXColorTwistMatrix first,
FPXColorTwistMatrix second,FPXColorTwistMatrix *color_twist)
{
/*
Matrix multiply.
*/
assert(color_twist != (FPXColorTwistMatrix *) NULL);
color_twist->byy=(first.byy*second.byy)+(first.byc1*second.bc1y)+
(first.byc2*second.bc2y)+(first.dummy1_zero*second.dummy4_zero);
color_twist->byc1=(first.byy*second.byc1)+(first.byc1*second.bc1c1)+
(first.byc2*second.bc2c1)+(first.dummy1_zero*second.dummy5_zero);
color_twist->byc2=(first.byy*second.byc2)+(first.byc1*second.bc1c2)+
(first.byc2*second.bc2c2)+(first.dummy1_zero*second.dummy6_zero);
color_twist->dummy1_zero=(first.byy*second.dummy1_zero)+
(first.byc1*second.dummy2_zero)+(first.byc2*second.dummy3_zero)+
(first.dummy1_zero*second.dummy7_one);
color_twist->bc1y=(first.bc1y*second.byy)+(first.bc1c1*second.bc1y)+
(first.bc1c2*second.bc2y)+(first.dummy2_zero*second.dummy4_zero);
color_twist->bc1c1=(first.bc1y*second.byc1)+(first.bc1c1*second.bc1c1)+
(first.bc1c2*second.bc2c1)+(first.dummy2_zero*second.dummy5_zero);
color_twist->bc1c2=(first.bc1y*second.byc2)+(first.bc1c1*second.bc1c2)+
(first.bc1c2*second.bc2c2)+(first.dummy2_zero*second.dummy6_zero);
color_twist->dummy2_zero=(first.bc1y*second.dummy1_zero)+
(first.bc1c1*second.dummy2_zero)+(first.bc1c2*second.dummy3_zero)+
(first.dummy2_zero*second.dummy7_one);
color_twist->bc2y=(first.bc2y*second.byy)+(first.bc2c1*second.bc1y)+
(first.bc2c2*second.bc2y)+(first.dummy3_zero*second.dummy4_zero);
color_twist->bc2c1=(first.bc2y*second.byc1)+(first.bc2c1*second.bc1c1)+
(first.bc2c2*second.bc2c1)+(first.dummy3_zero*second.dummy5_zero);
color_twist->bc2c2=(first.bc2y*second.byc2)+(first.bc2c1*second.bc1c2)+
(first.bc2c2*second.bc2c2)+(first.dummy3_zero*second.dummy6_zero);
color_twist->dummy3_zero=(first.bc2y*second.dummy1_zero)+
(first.bc2c1*second.dummy2_zero)+(first.bc2c2*second.dummy3_zero)+
(first.dummy3_zero*second.dummy7_one);
color_twist->dummy4_zero=(first.dummy4_zero*second.byy)+
(first.dummy5_zero*second.bc1y)+(first.dummy6_zero*second.bc2y)+
(first.dummy7_one*second.dummy4_zero);
color_twist->dummy5_zero=(first.dummy4_zero*second.byc1)+
(first.dummy5_zero*second.bc1c1)+(first.dummy6_zero*second.bc2c1)+
(first.dummy7_one*second.dummy5_zero);
color_twist->dummy6_zero=(first.dummy4_zero*second.byc2)+
(first.dummy5_zero*second.bc1c2)+(first.dummy6_zero*second.bc2c2)+
(first.dummy7_one*second.dummy6_zero);
color_twist->dummy7_one=(first.dummy4_zero*second.dummy1_zero)+
(first.dummy5_zero*second.dummy2_zero)+
(first.dummy6_zero*second.dummy3_zero)+(first.dummy7_one*second.dummy7_one);
}
static void SetBrightness(double brightness,FPXColorTwistMatrix *color_twist)
{
FPXColorTwistMatrix
effect,
result;
/*
Set image brightness in color twist matrix.
*/
assert(color_twist != (FPXColorTwistMatrix *) NULL);
brightness=sqrt((double) brightness);
effect.byy=brightness;
effect.byc1=0.0;
effect.byc2=0.0;
effect.dummy1_zero=0.0;
effect.bc1y=0.0;
effect.bc1c1=brightness;
effect.bc1c2=0.0;
effect.dummy2_zero=0.0;
effect.bc2y=0.0;
effect.bc2c1=0.0;
effect.bc2c2=brightness;
effect.dummy3_zero=0.0;
effect.dummy4_zero=0.0;
effect.dummy5_zero=0.0;
effect.dummy6_zero=0.0;
effect.dummy7_one=1.0;
ColorTwistMultiply(*color_twist,effect,&result);
*color_twist=result;
}
static void SetColorBalance(double red,double green,double blue,
FPXColorTwistMatrix *color_twist)
{
FPXColorTwistMatrix
blue_effect,
green_effect,
result,
rgb_effect,
rg_effect,
red_effect;
/*
Set image color balance in color twist matrix.
*/
assert(color_twist != (FPXColorTwistMatrix *) NULL);
red=sqrt((double) red)-1.0;
green=sqrt((double) green)-1.0;
blue=sqrt((double) blue)-1.0;
red_effect.byy=1.0;
red_effect.byc1=0.0;
red_effect.byc2=0.299*red;
red_effect.dummy1_zero=0.0;
red_effect.bc1y=(-0.299)*red;
red_effect.bc1c1=1.0-0.299*red;
red_effect.bc1c2=(-0.299)*red;
red_effect.dummy2_zero=0.0;
red_effect.bc2y=0.701*red;
red_effect.bc2c1=0.0;
red_effect.bc2c2=1.0+0.402*red;
red_effect.dummy3_zero=0.0;
red_effect.dummy4_zero=0.0;
red_effect.dummy5_zero=0.0;
red_effect.dummy6_zero=0.0;
red_effect.dummy7_one=1.0;
green_effect.byy=1.0;
green_effect.byc1=(-0.114)*green;
green_effect.byc2=(-0.299)*green;
green_effect.dummy1_zero=0.0;
green_effect.bc1y=(-0.587)*green;
green_effect.bc1c1=1.0-0.473*green;
green_effect.bc1c2=0.299*green;
green_effect.dummy2_zero=0.0;
green_effect.bc2y=(-0.587)*green;
green_effect.bc2c1=0.114*green;
green_effect.bc2c2=1.0-0.288*green;
green_effect.dummy3_zero=0.0;
green_effect.dummy4_zero=0.0;
green_effect.dummy5_zero=0.0;
green_effect.dummy6_zero=0.0;
green_effect.dummy7_one=1.0;
blue_effect.byy=1.0;
blue_effect.byc1=0.114*blue;
blue_effect.byc2=0.0;
blue_effect.dummy1_zero=0.0;
blue_effect.bc1y=0.886*blue;
blue_effect.bc1c1=1.0+0.772*blue;
blue_effect.bc1c2=0.0;
blue_effect.dummy2_zero=0.0;
blue_effect.bc2y=(-0.114)*blue;
blue_effect.bc2c1=(-0.114)*blue;
blue_effect.bc2c2=1.0-0.114*blue;
blue_effect.dummy3_zero=0.0;
blue_effect.dummy4_zero=0.0;
blue_effect.dummy5_zero=0.0;
blue_effect.dummy6_zero=0.0;
blue_effect.dummy7_one=1.0;
ColorTwistMultiply(red_effect,green_effect,&rg_effect);
ColorTwistMultiply(rg_effect,blue_effect,&rgb_effect);
ColorTwistMultiply(*color_twist,rgb_effect,&result);
*color_twist=result;
}
static void SetSaturation(double saturation,FPXColorTwistMatrix *color_twist)
{
FPXColorTwistMatrix
effect,
result;
/*
Set image saturation in color twist matrix.
*/
assert(color_twist != (FPXColorTwistMatrix *) NULL);
effect.byy=1.0;
effect.byc1=0.0;
effect.byc2=0.0;
effect.dummy1_zero=0.0;
effect.bc1y=0.0;
effect.bc1c1=saturation;
effect.bc1c2=0.0;
effect.dummy2_zero=0.0;
effect.bc2y=0.0;
effect.bc2c1=0.0;
effect.bc2c2=saturation;
effect.dummy3_zero=0.0;
effect.dummy4_zero=0.0;
effect.dummy5_zero=0.0;
effect.dummy6_zero=0.0;
effect.dummy7_one=1.0;
ColorTwistMultiply(*color_twist,effect,&result);
*color_twist=result;
}
static MagickBooleanType WriteFPXImage(const ImageInfo *image_info,Image *image)
{
FPXBackground
background_color;
FPXColorspace
colorspace =
{
TRUE, 4,
{
{ NIFRGB_R, DATA_TYPE_UNSIGNED_BYTE },
{ NIFRGB_G, DATA_TYPE_UNSIGNED_BYTE },
{ NIFRGB_B, DATA_TYPE_UNSIGNED_BYTE },
{ ALPHA, DATA_TYPE_UNSIGNED_BYTE }
}
};
const char
*comment,
*label;
FPXCompressionOption
compression;
FPXImageDesc
fpx_info;
FPXImageHandle
*flashpix;
FPXStatus
fpx_status;
FPXSummaryInformation
summary_info;
MagickBooleanType
status;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register const PixelPacket
*p;
register ssize_t
i;
size_t
memory_limit;
ssize_t
y;
unsigned char
*pixels;
unsigned int
tile_height,
tile_width;
/*
Open input file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
(void) CloseBlob(image);
/*
Initialize FPX toolkit.
*/
image->depth=8;
memory_limit=20000000;
fpx_status=FPX_SetToolkitMemoryLimit(&memory_limit);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToInitializeFPXLibrary");
tile_width=64;
tile_height=64;
colorspace.numberOfComponents=3;
if (image->matte != MagickFalse)
colorspace.numberOfComponents=4;
if ((image_info->type != TrueColorType) &&
IsGrayImage(image,&image->exception))
{
colorspace.numberOfComponents=1;
colorspace.theComponents[0].myColor=MONOCHROME;
}
background_color.color1_value=0;
background_color.color2_value=0;
background_color.color3_value=0;
background_color.color4_value=0;
compression=NONE;
if (image->compression == JPEGCompression)
compression=JPEG_UNSPECIFIED;
if (image_info->compression == JPEGCompression)
compression=JPEG_UNSPECIFIED;
{
#if defined(macintosh)
FSSpec
fsspec;
FilenameToFSSpec(filename,&fsspec);
fpx_status=FPX_CreateImageByFilename((const FSSpec &) fsspec,image->columns,
#else
fpx_status=FPX_CreateImageByFilename(image->filename,image->columns,
#endif
image->rows,tile_width,tile_height,colorspace,background_color,
compression,&flashpix);
}
if (fpx_status != FPX_OK)
return(status);
if (compression == JPEG_UNSPECIFIED)
{
/*
Initialize the compression by quality for the entire image.
*/
fpx_status=FPX_SetJPEGCompression(flashpix,(unsigned short)
image->quality == UndefinedCompressionQuality ? 75 : image->quality);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetJPEGLevel");
}
/*
Set image summary info.
*/
summary_info.title_valid=MagickFalse;
summary_info.subject_valid=MagickFalse;
summary_info.author_valid=MagickFalse;
summary_info.comments_valid=MagickFalse;
summary_info.keywords_valid=MagickFalse;
summary_info.OLEtemplate_valid=MagickFalse;
summary_info.last_author_valid=MagickFalse;
summary_info.rev_number_valid=MagickFalse;
summary_info.edit_time_valid=MagickFalse;
summary_info.last_printed_valid=MagickFalse;
summary_info.create_dtm_valid=MagickFalse;
summary_info.last_save_dtm_valid=MagickFalse;
summary_info.page_count_valid=MagickFalse;
summary_info.word_count_valid=MagickFalse;
summary_info.char_count_valid=MagickFalse;
summary_info.thumbnail_valid=MagickFalse;
summary_info.appname_valid=MagickFalse;
summary_info.security_valid=MagickFalse;
summary_info.title.ptr=(unsigned char *) NULL;
label=GetImageProperty(image,"label");
if (label != (const char *) NULL)
{
size_t
length;
/*
Note image label.
*/
summary_info.title_valid=MagickTrue;
length=strlen(label);
summary_info.title.length=length;
if (~length >= (MaxTextExtent-1))
summary_info.title.ptr=(unsigned char *) AcquireQuantumMemory(
length+MaxTextExtent,sizeof(*summary_info.title.ptr));
if (summary_info.title.ptr == (unsigned char *) NULL)
ThrowWriterException(DelegateError,"UnableToSetImageTitle");
(void) CopyMagickString((char *) summary_info.title.ptr,label,
MaxTextExtent);
}
comment=GetImageProperty(image,"comment");
if (comment != (const char *) NULL)
{
/*
Note image comment.
*/
summary_info.comments_valid=MagickTrue;
summary_info.comments.ptr=(unsigned char *) AcquireString(comment);
summary_info.comments.length=strlen(comment);
}
fpx_status=FPX_SetSummaryInformation(flashpix,&summary_info);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetSummaryInfo");
/*
Initialize FlashPix image description.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
fpx_info.numberOfComponents=colorspace.numberOfComponents;
for (i=0; i < (ssize_t) fpx_info.numberOfComponents; i++)
{
fpx_info.components[i].myColorType.myDataType=DATA_TYPE_UNSIGNED_BYTE;
fpx_info.components[i].horzSubSampFactor=1;
fpx_info.components[i].vertSubSampFactor=1;
fpx_info.components[i].columnStride=fpx_info.numberOfComponents;
fpx_info.components[i].lineStride=
image->columns*fpx_info.components[i].columnStride;
fpx_info.components[i].theData=pixels+i;
}
fpx_info.components[0].myColorType.myColor=fpx_info.numberOfComponents != 1
? NIFRGB_R : MONOCHROME;
fpx_info.components[1].myColorType.myColor=NIFRGB_G;
fpx_info.components[2].myColorType.myColor=NIFRGB_B;
fpx_info.components[3].myColorType.myColor=ALPHA;
/*
Write image pixelss.
*/
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
if (fpx_info.numberOfComponents == 1)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
size_t
length;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
quantum_type,pixels,&image->exception);
(void) length;
fpx_status=FPX_WriteImageLine(flashpix,&fpx_info);
if (fpx_status != FPX_OK)
break;
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image_info->view != (char *) NULL)
{
FPXAffineMatrix
affine;
FPXColorTwistMatrix
color_twist;
FPXContrastAdjustment
contrast;
FPXFilteringValue
sharpen;
FPXResultAspectRatio
aspect_ratio;
FPXROI
view_rect;
MagickBooleanType
affine_valid,
aspect_ratio_valid,
color_twist_valid,
contrast_valid,
sharpen_valid,
view_rect_valid;
/*
Initialize default viewing parameters.
*/
contrast=1.0;
contrast_valid=MagickTrue;
color_twist.byy=1.0;
color_twist.byc1=0.0;
color_twist.byc2=0.0;
color_twist.dummy1_zero=0.0;
color_twist.bc1y=0.0;
color_twist.bc1c1=1.0;
color_twist.bc1c2=0.0;
color_twist.dummy2_zero=0.0;
color_twist.bc2y=0.0;
color_twist.bc2c1=0.0;
color_twist.bc2c2=1.0;
color_twist.dummy3_zero=0.0;
color_twist.dummy4_zero=0.0;
color_twist.dummy5_zero=0.0;
color_twist.dummy6_zero=0.0;
color_twist.dummy7_one=1.0;
color_twist_valid=MagickTrue;
sharpen=0.0;
sharpen_valid=MagickTrue;
aspect_ratio=(double) image->columns/image->rows;
aspect_ratio_valid=MagickTrue;
view_rect.left=(float) 0.1;
view_rect.width=aspect_ratio-0.2;
view_rect.top=(float) 0.1;
view_rect.height=(float) 0.8; /* 1.0-0.2 */
view_rect_valid=MagickTrue;
affine.a11=1.0;
affine.a12=0.0;
affine.a13=0.0;
affine.a14=0.0;
affine.a21=0.0;
affine.a22=1.0;
affine.a23=0.0;
affine.a24=0.0;
affine.a31=0.0;
affine.a32=0.0;
affine.a33=1.0;
affine.a34=0.0;
affine.a41=0.0;
affine.a42=0.0;
affine.a43=0.0;
affine.a44=1.0;
affine_valid=MagickTrue;
if (0)
{
/*
Color color twist.
*/
SetBrightness(0.5,&color_twist);
SetSaturation(0.5,&color_twist);
SetColorBalance(0.5,1.0,1.0,&color_twist);
color_twist_valid=MagickTrue;
}
if (affine_valid != MagickFalse)
{
fpx_status=FPX_SetImageAffineMatrix(flashpix,&affine);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetAffineMatrix");
}
if (aspect_ratio_valid != MagickFalse)
{
fpx_status=FPX_SetImageResultAspectRatio(flashpix,&aspect_ratio);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetAspectRatio");
}
if (color_twist_valid != MagickFalse)
{
fpx_status=FPX_SetImageColorTwistMatrix(flashpix,&color_twist);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetColorTwist");
}
if (contrast_valid != MagickFalse)
{
fpx_status=FPX_SetImageContrastAdjustment(flashpix,&contrast);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetContrast");
}
if (sharpen_valid != MagickFalse)
{
fpx_status=FPX_SetImageFilteringValue(flashpix,&sharpen);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetFilteringValue");
}
if (view_rect_valid != MagickFalse)
{
fpx_status=FPX_SetImageROI(flashpix,&view_rect);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetRegionOfInterest");
}
}
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_20 |
crossvul-cpp_data_bad_4798_1 | /* $Id$ */
/* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of
* the image data through additional options listed below
*
* Original code:
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
* Additions (c) Richard Nolde 2006-2010
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS OR ANY OTHER COPYRIGHT
* HOLDERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL
* DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND
* ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOFTWARE.
*
* Some portions of the current code are derived from tiffcp, primarly in
* the areas of lowlevel reading and writing of TAGS, scanlines and tiles though
* some of the original functions have been extended to support arbitrary bit
* depths. These functions are presented at the top of this file.
*
* Add support for the options below to extract sections of image(s)
* and to modify the whole image or selected portions of each image by
* rotations, mirroring, and colorscale/colormap inversion of selected
* types of TIFF images when appropriate. Some color model dependent
* functions are restricted to bilevel or 8 bit per sample data.
* See the man page for the full explanations.
*
* New Options:
* -h Display the syntax guide.
* -v Report the version and last build date for tiffcrop and libtiff.
* -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1
* Specify a series of coordinates to define rectangular
* regions by the top left and lower right corners.
* -e c|d|i|m|s export mode for images and selections from input images
* combined All images and selections are written to a single file (default)
* with multiple selections from one image combined into a single image
* divided All images and selections are written to a single file
* with each selection from one image written to a new image
* image Each input image is written to a new file (numeric filename sequence)
* with multiple selections from the image combined into one image
* multiple Each input image is written to a new file (numeric filename sequence)
* with each selection from the image written to a new image
* separated Individual selections from each image are written to separate files
* -U units [in, cm, px ] inches, centimeters or pixels
* -H # Set horizontal resolution of output images to #
* -V # Set vertical resolution of output images to #
* -J # Horizontal margin of output page to # expressed in current
* units when sectioning image into columns x rows
* using the -S cols:rows option.
* -K # Vertical margin of output page to # expressed in current
* units when sectioning image into columns x rows
* using the -S cols:rows option.
* -X # Horizontal dimension of region to extract expressed in current
* units
* -Y # Vertical dimension of region to extract expressed in current
* units
* -O orient Orientation for output image, portrait, landscape, auto
* -P page Page size for output image segments, eg letter, legal, tabloid,
* etc.
* -S cols:rows Divide the image into equal sized segments using cols across
* and rows down
* -E t|l|r|b Edge to use as origin
* -m #,#,#,# Margins from edges for selection: top, left, bottom, right
* (commas separated)
* -Z #:#,#:# Zones of the image designated as zone X of Y,
* eg 1:3 would be first of three equal portions measured
* from reference edge
* -N odd|even|#,#-#,#|last
* Select sequences and/or ranges of images within file
* to process. The words odd or even may be used to specify
* all odd or even numbered images the word last may be used
* in place of a number in the sequence to indicate the final
* image in the file without knowing how many images there are.
* -R # Rotate image or crop selection by 90,180,or 270 degrees
* clockwise
* -F h|v Flip (mirror) image or crop selection horizontally
* or vertically
* -I [black|white|data|both]
* Invert color space, eg dark to light for bilevel and grayscale images
* If argument is white or black, set the PHOTOMETRIC_INTERPRETATION
* tag to MinIsBlack or MinIsWhite without altering the image data
* If the argument is data or both, the image data are modified:
* both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,
* data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag
* -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N
* Dump raw data for input and/or output images to individual files
* in raw (binary) format or text (ASCII) representing binary data
* as strings of 1s and 0s. The filename arguments are used as stems
* from which individual files are created for each image. Text format
* includes annotations for image parameters and scanline info. Level
* selects which functions dump data, with higher numbers selecting
* lower level, scanline level routines. Debug reports a limited set
* of messages to monitor progess without enabling dump logs.
*/
static char tiffcrop_version_id[] = "2.4";
static char tiffcrop_rev_date[] = "12-13-2010";
#include "tif_config.h"
#include "tiffiop.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <limits.h>
#include <sys/stat.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_STDINT_H
# include <stdint.h>
#endif
#ifndef HAVE_GETOPT
extern int getopt(int argc, char * const argv[], const char *optstring);
#endif
#ifdef NEED_LIBPORT
# include "libport.h"
#endif
#include "tiffio.h"
#if defined(VMS)
# define unlink delete
#endif
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
#define TIFF_UINT32_MAX 0xFFFFFFFFU
#ifndef streq
#define streq(a,b) (strcmp((a),(b)) == 0)
#endif
#define strneq(a,b,n) (strncmp((a),(b),(n)) == 0)
#define TRUE 1
#define FALSE 0
#ifndef TIFFhowmany
#define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y)))
#define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3)
#endif
/*
* Definitions and data structures required to support cropping and image
* manipulations.
*/
#define EDGE_TOP 1
#define EDGE_LEFT 2
#define EDGE_BOTTOM 3
#define EDGE_RIGHT 4
#define EDGE_CENTER 5
#define MIRROR_HORIZ 1
#define MIRROR_VERT 2
#define MIRROR_BOTH 3
#define ROTATECW_90 8
#define ROTATECW_180 16
#define ROTATECW_270 32
#define ROTATE_ANY (ROTATECW_90 | ROTATECW_180 | ROTATECW_270)
#define CROP_NONE 0
#define CROP_MARGINS 1
#define CROP_WIDTH 2
#define CROP_LENGTH 4
#define CROP_ZONES 8
#define CROP_REGIONS 16
#define CROP_ROTATE 32
#define CROP_MIRROR 64
#define CROP_INVERT 128
/* Modes for writing out images and selections */
#define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */
#define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */
#define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */
#define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */
#define FILE_PER_SELECTION 4 /* One file per selection */
#define COMPOSITE_IMAGES 0 /* Selections combined into one image */
#define SEPARATED_IMAGES 1 /* Selections saved to separate images */
#define STRIP 1
#define TILE 2
#define MAX_REGIONS 8 /* number of regions to extract from a single page */
#define MAX_OUTBUFFS 8 /* must match larger of zones or regions */
#define MAX_SECTIONS 32 /* number of sections per page to write to output */
#define MAX_IMAGES 2048 /* number of images in descrete list, not in the file */
#define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */
#define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */
#define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */
#define DUMP_NONE 0
#define DUMP_TEXT 1
#define DUMP_RAW 2
/* Offsets into buffer for margins and fixed width and length segments */
struct offset {
uint32 tmargin;
uint32 lmargin;
uint32 bmargin;
uint32 rmargin;
uint32 crop_width;
uint32 crop_length;
uint32 startx;
uint32 endx;
uint32 starty;
uint32 endy;
};
/* Description of a zone within the image. Position 1 of 3 zones would be
* the first third of the image. These are computed after margins and
* width/length requests are applied so that you can extract multiple
* zones from within a larger region for OCR or barcode recognition.
*/
struct buffinfo {
uint32 size; /* size of this buffer */
unsigned char *buffer; /* address of the allocated buffer */
};
struct zone {
int position; /* ordinal of segment to be extracted */
int total; /* total equal sized divisions of crop area */
};
struct pageseg {
uint32 x1; /* index of left edge */
uint32 x2; /* index of right edge */
uint32 y1; /* index of top edge */
uint32 y2; /* index of bottom edge */
int position; /* ordinal of segment to be extracted */
int total; /* total equal sized divisions of crop area */
uint32 buffsize; /* size of buffer needed to hold the cropped zone */
};
struct coordpairs {
double X1; /* index of left edge in current units */
double X2; /* index of right edge in current units */
double Y1; /* index of top edge in current units */
double Y2; /* index of bottom edge in current units */
};
struct region {
uint32 x1; /* pixel offset of left edge */
uint32 x2; /* pixel offset of right edge */
uint32 y1; /* pixel offset of top edge */
uint32 y2; /* picel offset of bottom edge */
uint32 width; /* width in pixels */
uint32 length; /* length in pixels */
uint32 buffsize; /* size of buffer needed to hold the cropped region */
unsigned char *buffptr; /* address of start of the region */
};
/* Cropping parameters from command line and image data
* Note: This should be renamed to proc_opts and expanded to include all current globals
* if possible, but each function that accesses global variables will have to be redone.
*/
struct crop_mask {
double width; /* Selection width for master crop region in requested units */
double length; /* Selection length for master crop region in requesed units */
double margins[4]; /* Top, left, bottom, right margins */
float xres; /* Horizontal resolution read from image*/
float yres; /* Vertical resolution read from image */
uint32 combined_width; /* Width of combined cropped zones */
uint32 combined_length; /* Length of combined cropped zones */
uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */
uint16 img_mode; /* Composite or separate images created from zones or regions */
uint16 exp_mode; /* Export input images or selections to one or more files */
uint16 crop_mode; /* Crop options to be applied */
uint16 res_unit; /* Resolution unit for margins and selections */
uint16 edge_ref; /* Reference edge for sections extraction and combination */
uint16 rotation; /* Clockwise rotation of the extracted region or image */
uint16 mirror; /* Mirror extracted region or image horizontally or vertically */
uint16 invert; /* Invert the color map of image or region */
uint16 photometric; /* Status of photometric interpretation for inverted image */
uint16 selections; /* Number of regions or zones selected */
uint16 regions; /* Number of regions delimited by corner coordinates */
struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */
uint16 zones; /* Number of zones delimited by Ordinal:Total requested */
struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */
struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */
};
#define MAX_PAPERNAMES 49
#define MAX_PAPERNAME_LENGTH 15
#define DEFAULT_RESUNIT RESUNIT_INCH
#define DEFAULT_PAGE_HEIGHT 14.0
#define DEFAULT_PAGE_WIDTH 8.5
#define DEFAULT_RESOLUTION 300
#define DEFAULT_PAPER_SIZE "legal"
#define ORIENTATION_NONE 0
#define ORIENTATION_PORTRAIT 1
#define ORIENTATION_LANDSCAPE 2
#define ORIENTATION_SEASCAPE 4
#define ORIENTATION_AUTO 16
#define PAGE_MODE_NONE 0
#define PAGE_MODE_RESOLUTION 1
#define PAGE_MODE_PAPERSIZE 2
#define PAGE_MODE_MARGINS 4
#define PAGE_MODE_ROWSCOLS 8
#define INVERT_DATA_ONLY 10
#define INVERT_DATA_AND_TAG 11
struct paperdef {
char name[MAX_PAPERNAME_LENGTH];
double width;
double length;
double asratio;
};
/* European page sizes corrected from update sent by
* thomas . jarosch @ intra2net . com on 5/7/2010
* Paper Size Width Length Aspect Ratio */
struct paperdef PaperTable[MAX_PAPERNAMES] = {
{"default", 8.500, 14.000, 0.607},
{"pa4", 8.264, 11.000, 0.751},
{"letter", 8.500, 11.000, 0.773},
{"legal", 8.500, 14.000, 0.607},
{"half-letter", 8.500, 5.514, 1.542},
{"executive", 7.264, 10.528, 0.690},
{"tabloid", 11.000, 17.000, 0.647},
{"11x17", 11.000, 17.000, 0.647},
{"ledger", 17.000, 11.000, 1.545},
{"archa", 9.000, 12.000, 0.750},
{"archb", 12.000, 18.000, 0.667},
{"archc", 18.000, 24.000, 0.750},
{"archd", 24.000, 36.000, 0.667},
{"arche", 36.000, 48.000, 0.750},
{"csheet", 17.000, 22.000, 0.773},
{"dsheet", 22.000, 34.000, 0.647},
{"esheet", 34.000, 44.000, 0.773},
{"superb", 11.708, 17.042, 0.687},
{"commercial", 4.139, 9.528, 0.434},
{"monarch", 3.889, 7.528, 0.517},
{"envelope-dl", 4.333, 8.681, 0.499},
{"envelope-c5", 6.389, 9.028, 0.708},
{"europostcard", 4.139, 5.833, 0.710},
{"a0", 33.110, 46.811, 0.707},
{"a1", 23.386, 33.110, 0.706},
{"a2", 16.535, 23.386, 0.707},
{"a3", 11.693, 16.535, 0.707},
{"a4", 8.268, 11.693, 0.707},
{"a5", 5.827, 8.268, 0.705},
{"a6", 4.134, 5.827, 0.709},
{"a7", 2.913, 4.134, 0.705},
{"a8", 2.047, 2.913, 0.703},
{"a9", 1.457, 2.047, 0.712},
{"a10", 1.024, 1.457, 0.703},
{"b0", 39.370, 55.669, 0.707},
{"b1", 27.835, 39.370, 0.707},
{"b2", 19.685, 27.835, 0.707},
{"b3", 13.898, 19.685, 0.706},
{"b4", 9.843, 13.898, 0.708},
{"b5", 6.929, 9.843, 0.704},
{"b6", 4.921, 6.929, 0.710},
{"c0", 36.102, 51.063, 0.707},
{"c1", 25.512, 36.102, 0.707},
{"c2", 18.031, 25.512, 0.707},
{"c3", 12.756, 18.031, 0.707},
{"c4", 9.016, 12.756, 0.707},
{"c5", 6.378, 9.016, 0.707},
{"c6", 4.488, 6.378, 0.704},
{"", 0.000, 0.000, 1.000}
};
/* Structure to define input image parameters */
struct image_data {
float xres;
float yres;
uint32 width;
uint32 length;
uint16 res_unit;
uint16 bps;
uint16 spp;
uint16 planar;
uint16 photometric;
uint16 orientation;
uint16 compression;
uint16 adjustments;
};
/* Structure to define the output image modifiers */
struct pagedef {
char name[16];
double width; /* width in pixels */
double length; /* length in pixels */
double hmargin; /* margins to subtract from width of sections */
double vmargin; /* margins to subtract from height of sections */
double hres; /* horizontal resolution for output */
double vres; /* vertical resolution for output */
uint32 mode; /* bitmask of modifiers to page format */
uint16 res_unit; /* resolution unit for output image */
unsigned int rows; /* number of section rows */
unsigned int cols; /* number of section cols */
unsigned int orient; /* portrait, landscape, seascape, auto */
};
struct dump_opts {
int debug;
int format;
int level;
char mode[4];
char infilename[PATH_MAX + 1];
char outfilename[PATH_MAX + 1];
FILE *infile;
FILE *outfile;
};
/* globals */
static int outtiled = -1;
static uint32 tilewidth = 0;
static uint32 tilelength = 0;
static uint16 config = 0;
static uint16 compression = 0;
static uint16 predictor = 0;
static uint16 fillorder = 0;
static uint32 rowsperstrip = 0;
static uint32 g3opts = 0;
static int ignore = FALSE; /* if true, ignore read errors */
static uint32 defg3opts = (uint32) -1;
static int quality = 100; /* JPEG quality */
/* static int jpegcolormode = -1; was JPEGCOLORMODE_RGB; */
static int jpegcolormode = JPEGCOLORMODE_RGB;
static uint16 defcompression = (uint16) -1;
static uint16 defpredictor = (uint16) -1;
static int pageNum = 0;
static int little_endian = 1;
/* Functions adapted from tiffcp with additions or significant modifications */
static int readContigStripsIntoBuffer (TIFF*, uint8*);
static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16);
static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16);
static int writeBufferToContigStrips (TIFF*, uint8*, uint32);
static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, tsample_t,
uint16, uint16, struct dump_opts *);
static int processCompressOptions(char*);
static void usage(void);
/* All other functions by Richard Nolde, not found in tiffcp */
static void initImageData (struct image_data *);
static void initCropMasks (struct crop_mask *);
static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []);
static void initDumpOptions(struct dump_opts *);
/* Command line and file naming functions */
void process_command_opts (int, char *[], char *, char *, uint32 *,
uint16 *, uint16 *, uint32 *, uint32 *, uint32 *,
struct crop_mask *, struct pagedef *,
struct dump_opts *,
unsigned int *, unsigned int *);
static int update_output_file (TIFF **, char *, int, char *, unsigned int *);
/* * High level functions for whole image manipulation */
static int get_page_geometry (char *, struct pagedef*);
static int computeInputPixelOffsets(struct crop_mask *, struct image_data *,
struct offset *);
static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *,
struct pagedef *, struct pageseg *,
struct dump_opts *);
static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **);
static int correct_orientation(struct image_data *, unsigned char **);
static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *);
static int processCropSelections(struct image_data *, struct crop_mask *,
unsigned char **, struct buffinfo []);
static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *,
struct dump_opts *, struct buffinfo [],
char *, char *, unsigned int*, unsigned int);
/* Section functions */
static int createImageSection(uint32, unsigned char **);
static int extractImageSection(struct image_data *, struct pageseg *,
unsigned char *, unsigned char *);
static int writeSingleSection(TIFF *, TIFF *, struct image_data *,
struct dump_opts *, uint32, uint32,
double, double, unsigned char *);
static int writeImageSections(TIFF *, TIFF *, struct image_data *,
struct pagedef *, struct pageseg *,
struct dump_opts *, unsigned char *,
unsigned char **);
/* Whole image functions */
static int createCroppedImage(struct image_data *, struct crop_mask *,
unsigned char **, unsigned char **);
static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image,
struct dump_opts * dump,
uint32, uint32, unsigned char *, int, int);
/* Image manipulation functions */
static int rotateContigSamples8bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples16bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples24bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples32bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *,
unsigned char **);
static int mirrorImage(uint16, uint16, uint16, uint32, uint32,
unsigned char *);
static int invertImage(uint16, uint16, uint16, uint32, uint32,
unsigned char *);
/* Functions to reverse the sequence of samples in a scanline */
static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *);
/* Functions for manipulating individual samples in an image */
static int extractSeparateRegion(struct image_data *, struct crop_mask *,
unsigned char *, unsigned char *, int);
static int extractCompositeRegions(struct image_data *, struct crop_mask *,
unsigned char *, unsigned char *);
static int extractContigSamples8bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples16bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples24bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples32bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamplesBytes (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesToTileBuffer(uint8 *, uint8 *, uint32, uint32,
uint32, uint32, tsample_t, uint16,
uint16, uint16, struct dump_opts *);
/* Functions to combine separate planes into interleaved planes */
static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *,
uint32, uint32, tsample_t, uint16,
FILE *, int, int);
static int combineSeparateTileSamples8bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples16bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples24bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples32bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamplesBytes (unsigned char *[], unsigned char *,
uint32, uint32, uint32, uint32,
tsample_t, uint16, FILE *, int, int);
/* Dump functions for debugging */
static void dump_info (FILE *, int, char *, char *, ...);
static int dump_data (FILE *, int, char *, unsigned char *, uint32);
static int dump_byte (FILE *, int, char *, unsigned char);
static int dump_short (FILE *, int, char *, uint16);
static int dump_long (FILE *, int, char *, uint32);
static int dump_wide (FILE *, int, char *, uint64);
static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *);
/* End function declarations */
/* Functions derived in whole or in part from tiffcp */
/* The following functions are taken largely intact from tiffcp */
static char* usage_info[] = {
"usage: tiffcrop [options] source1 ... sourceN destination",
"where options are:",
" -h Print this syntax listing",
" -v Print tiffcrop version identifier and last revision date",
" ",
" -a Append to output instead of overwriting",
" -d offset Set initial directory offset, counting first image as one, not zero",
" -p contig Pack samples contiguously (e.g. RGBRGB...)",
" -p separate Store samples separately (e.g. RRR...GGG...BBB...)",
" -s Write output in strips",
" -t Write output in tiles",
" -i Ignore read errors",
" ",
" -r # Make each strip have no more than # rows",
" -w # Set output tile width (pixels)",
" -l # Set output tile length (pixels)",
" ",
" -f lsb2msb Force lsb-to-msb FillOrder for output",
" -f msb2lsb Force msb-to-lsb FillOrder for output",
"",
" -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding",
" -c zip[:opts] Compress output with deflate encoding",
" -c jpeg[:opts] Compress output with JPEG encoding",
" -c packbits Compress output with packbits encoding",
" -c g3[:opts] Compress output with CCITT Group 3 encoding",
" -c g4 Compress output with CCITT Group 4 encoding",
" -c none Use no compression algorithm on output",
" ",
"Group 3 options:",
" 1d Use default CCITT Group 3 1D-encoding",
" 2d Use optional CCITT Group 3 2D-encoding",
" fill Byte-align EOL codes",
"For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs",
" ",
"JPEG options:",
" # Set compression quality level (0-100, default 100)",
" raw Output color image as raw YCbCr",
" rgb Output color image as RGB",
"For example, -c jpeg:rgb:50 to get JPEG-encoded RGB data with 50% comp. quality",
" ",
"LZW and deflate options:",
" # Set predictor value",
"For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
" ",
"Page and selection options:",
" -N odd|even|#,#-#,#|last sequences and ranges of images within file to process",
" The words odd or even may be used to specify all odd or even numbered images.",
" The word last may be used in place of a number in the sequence to indicate.",
" The final image in the file without knowing how many images there are.",
" Numbers are counted from one even though TIFF IFDs are counted from zero.",
" ",
" -E t|l|r|b edge to use as origin for width and length of crop region",
" -U units [in, cm, px ] inches, centimeters or pixels",
" ",
" -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas",
" -X # horizontal dimension of region to extract expressed in current units",
" -Y # vertical dimension of region to extract expressed in current units",
" -Z #:#,#:# zones of the image designated as position X of Y,",
" eg 1:3 would be first of three equal portions measured from reference edge",
" -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1",
" regions of the image designated by upper left and lower right coordinates",
"",
"Export grouping options:",
" -e c|d|i|m|s export mode for images and selections from input images.",
" When exporting a composite image from multiple zones or regions",
" (combined and image modes), the selections must have equal sizes",
" for the axis perpendicular to the edge specified with -E.",
" c|combined All images and selections are written to a single file (default).",
" with multiple selections from one image combined into a single image.",
" d|divided All images and selections are written to a single file",
" with each selection from one image written to a new image.",
" i|image Each input image is written to a new file (numeric filename sequence)",
" with multiple selections from the image combined into one image.",
" m|multiple Each input image is written to a new file (numeric filename sequence)",
" with each selection from the image written to a new image.",
" s|separated Individual selections from each image are written to separate files.",
"",
"Output options:",
" -H # Set horizontal resolution of output images to #",
" -V # Set vertical resolution of output images to #",
" -J # Set horizontal margin of output page to # expressed in current units",
" when sectioning image into columns x rows using the -S cols:rows option",
" -K # Set verticalal margin of output page to # expressed in current units",
" when sectioning image into columns x rows using the -S cols:rows option",
" ",
" -O orient orientation for output image, portrait, landscape, auto",
" -P page page size for output image segments, eg letter, legal, tabloid, etc",
" use #.#x#.# to specify a custom page size in the currently defined units",
" where #.# represents the width and length",
" -S cols:rows Divide the image into equal sized segments using cols across and rows down.",
" ",
" -F hor|vert|both",
" flip (mirror) image or region horizontally, vertically, or both",
" -R # [90,180,or 270] degrees clockwise rotation of image or extracted region",
" -I [black|white|data|both]",
" invert color space, eg dark to light for bilevel and grayscale images",
" If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ",
" tag to MinIsBlack or MinIsWhite without altering the image data",
" If the argument is data or both, the image data are modified:",
" both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,",
" data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag",
" ",
"-D opt1:value1,opt2:value2,opt3:value3:opt4:value4",
" Debug/dump program progress and/or data to non-TIFF files.",
" Options include the following and must be joined as a comma",
" separate list. The use of this option is generally limited to",
" program debugging and development of future options.",
" ",
" debug:N Display limited program progress indicators where larger N",
" increase the level of detail. Note: Tiffcrop may be compiled with",
" -DDEVELMODE to enable additional very low level debug reporting.",
"",
" Format:txt|raw Format any logged data as ASCII text or raw binary ",
" values. ASCII text dumps include strings of ones and zeroes",
" representing the binary values in the image data plus identifying headers.",
" ",
" level:N Specify the level of detail presented in the dump files.",
" This can vary from dumps of the entire input or output image data to dumps",
" of data processed by specific functions. Current range of levels is 1 to 3.",
" ",
" input:full-path-to-directory/input-dumpname",
" ",
" output:full-path-to-directory/output-dumpnaem",
" ",
" When dump files are being written, each image will be written to a separate",
" file with the name built by adding a numeric sequence value to the dumpname",
" and an extension of .txt for ASCII dumps or .bin for binary dumps.",
" ",
" The four debug/dump options are independent, though it makes little sense to",
" specify a dump file without specifying a detail level.",
" ",
NULL
};
/* This function could be modified to pass starting sample offset
* and number of samples as args to select fewer than spp
* from input image. These would then be passed to individual
* extractContigSampleXX routines.
*/
static int readContigTilesIntoBuffer (TIFF* in, uint8* buf,
uint32 imagelength,
uint32 imagewidth,
uint32 tw, uint32 tl,
tsample_t spp, uint16 bps)
{
int status = 1;
tsample_t sample = 0;
tsample_t count = spp;
uint32 row, col, trow;
uint32 nrow, ncol;
uint32 dst_rowsize, shift_width;
uint32 bytes_per_sample, bytes_per_pixel;
uint32 trailing_bits, prev_trailing_bits;
uint32 tile_rowsize = TIFFTileRowSize(in);
uint32 src_offset, dst_offset;
uint32 row_offset, col_offset;
uint8 *bufp = (uint8*) buf;
unsigned char *src = NULL;
unsigned char *dst = NULL;
tsize_t tbytes = 0, tile_buffsize = 0;
tsize_t tilesize = TIFFTileSize(in);
unsigned char *tilebuf = NULL;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
tile_buffsize = tilesize;
if (tilesize == 0 || tile_rowsize == 0)
{
TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero");
exit(-1);
}
if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
TIFFError("readContigTilesIntoBuffer",
"Tilesize %lu is too small, using alternate calculation %u",
tilesize, tl * tile_rowsize);
#endif
tile_buffsize = tl * tile_rowsize;
if (tl != (tile_buffsize / tile_rowsize))
{
TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
exit(-1);
}
}
/* Add 3 padding bytes for extractContigSamplesShifted32bits */
if( (size_t) tile_buffsize > 0xFFFFFFFFU - 3U )
{
TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
exit(-1);
}
tilebuf = _TIFFmalloc(tile_buffsize + 3);
if (tilebuf == 0)
return 0;
tilebuf[tile_buffsize] = 0;
tilebuf[tile_buffsize+1] = 0;
tilebuf[tile_buffsize+2] = 0;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0);
if (tbytes < tilesize && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu",
(unsigned long) col, (unsigned long) row, (unsigned long)tbytes,
(unsigned long)tilesize);
status = 0;
_TIFFfree(tilebuf);
return status;
}
row_offset = row * dst_rowsize;
col_offset = ((col * bps * spp) + 7)/ 8;
bufp = buf + row_offset + col_offset;
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
/* Each tile scanline will start on a byte boundary but it
* has to be merged into the scanline for the entire
* image buffer and the previous segment may not have
* ended on a byte boundary
*/
/* Optimization for common bit depths, all samples */
if (((bps % 8) == 0) && (count == spp))
{
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
_TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8);
bufp += (imagewidth * bps * spp) / 8;
}
}
else
{
/* Bit depths not a multiple of 8 and/or extract fewer than spp samples */
prev_trailing_bits = trailing_bits = 0;
trailing_bits = (ncol * bps * spp) % 8;
/* for (trow = 0; tl < nrow; trow++) */
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
src = tilebuf + src_offset;
dst_offset = (row + trow) * dst_rowsize;
dst = buf + dst_offset + col_offset;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, ncol, sample,
spp, bps, count, 0, ncol))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps);
return 1;
}
}
prev_trailing_bits += trailing_bits;
/* if (prev_trailing_bits > 7) */
/* prev_trailing_bits-= 8; */
}
}
}
_TIFFfree(tilebuf);
return status;
}
static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *obuf,
uint32 imagelength, uint32 imagewidth,
uint32 tw, uint32 tl,
uint16 spp, uint16 bps)
{
int i, status = 1, sample;
int shift_width, bytes_per_pixel;
uint16 bytes_per_sample;
uint32 row, col; /* Current row and col of image */
uint32 nrow, ncol; /* Number of rows and cols in current tile */
uint32 row_offset, col_offset; /* Output buffer offsets */
tsize_t tbytes = 0, tilesize = TIFFTileSize(in);
tsample_t s;
uint8* bufp = (uint8*)obuf;
unsigned char *srcbuffs[MAX_SAMPLES];
unsigned char *tbuff = NULL;
bytes_per_sample = (bps + 7) / 8;
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
srcbuffs[sample] = NULL;
tbuff = (unsigned char *)_TIFFmalloc(tilesize + 8);
if (!tbuff)
{
TIFFError ("readSeparateTilesIntoBuffer",
"Unable to allocate tile read buffer for sample %d", sample);
for (i = 0; i < sample; i++)
_TIFFfree (srcbuffs[i]);
return 0;
}
srcbuffs[sample] = tbuff;
}
/* Each tile contains only the data for a single plane
* arranged in scanlines of tw * bytes_per_sample bytes.
*/
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
for (s = 0; s < spp && s < MAX_SAMPLES; s++)
{ /* Read each plane of a tile set into srcbuffs[s] */
tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s);
if (tbytes < 0 && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read tile for row %lu col %lu, "
"sample %lu",
(unsigned long) col, (unsigned long) row,
(unsigned long) s);
status = 0;
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
tbuff = srcbuffs[sample];
if (tbuff != NULL)
_TIFFfree(tbuff);
}
return status;
}
}
/* Tiles on the right edge may be padded out to tw
* which must be a multiple of 16.
* Ncol represents the visible (non padding) portion.
*/
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
row_offset = row * (((imagewidth * spp * bps) + 7) / 8);
col_offset = ((col * spp * bps) + 7) / 8;
bufp = obuf + row_offset + col_offset;
if ((bps % 8) == 0)
{
if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow, imagewidth,
tw, spp, bps, NULL, 0, 0))
{
status = 0;
break;
}
}
else
{
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
switch (shift_width)
{
case 1: if (combineSeparateTileSamples8bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 2: if (combineSeparateTileSamples16bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 3: if (combineSeparateTileSamples24bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 4:
case 5:
case 6:
case 7:
case 8: if (combineSeparateTileSamples32bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
default: TIFFError ("readSeparateTilesIntoBuffer", "Unsupported bit depth: %d", bps);
status = 0;
break;
}
}
}
}
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
tbuff = srcbuffs[sample];
if (tbuff != NULL)
_TIFFfree(tbuff);
}
return status;
}
static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength)
{
uint32 row, nrows, rowsperstrip;
tstrip_t strip = 0;
tsize_t stripsize;
TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
for (row = 0; row < imagelength; row += rowsperstrip)
{
nrows = (row + rowsperstrip > imagelength) ?
imagelength - row : rowsperstrip;
stripsize = TIFFVStripSize(out, nrows);
if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0)
{
TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1);
return 1;
}
buf += stripsize;
}
return 0;
}
/* Abandon plans to modify code so that plannar orientation separate images
* do not have all samples for each channel written before all samples
* for the next channel have been abandoned.
* Libtiff internals seem to depend on all data for a given sample
* being contiguous within a strip or tile when PLANAR_CONFIG is
* separate. All strips or tiles of a given plane are written
* before any strips or tiles of a different plane are stored.
*/
static int
writeBufferToSeparateStrips (TIFF* out, uint8* buf,
uint32 length, uint32 width, uint16 spp,
struct dump_opts *dump)
{
uint8 *src;
uint16 bps;
uint32 row, nrows, rowsize, rowsperstrip;
uint32 bytes_per_sample;
tsample_t s;
tstrip_t strip = 0;
tsize_t stripsize = TIFFStripSize(out);
tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out);
tsize_t total_bytes = 0;
tdata_t obuf;
(void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
(void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
bytes_per_sample = (bps + 7) / 8;
if( width == 0 ||
(uint32)bps * (uint32)spp > TIFF_UINT32_MAX / width ||
bps * spp * width > TIFF_UINT32_MAX - 7U )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing (bps * spp * width) + 7");
return 1;
}
rowsize = ((bps * spp * width) + 7U) / 8; /* source has interleaved samples */
if( bytes_per_sample == 0 ||
rowsperstrip > TIFF_UINT32_MAX / bytes_per_sample ||
rowsperstrip * bytes_per_sample > TIFF_UINT32_MAX / (width + 1) )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing rowsperstrip * "
"bytes_per_sample * (width + 1)");
return 1;
}
rowstripsize = rowsperstrip * bytes_per_sample * (width + 1);
obuf = _TIFFmalloc (rowstripsize);
if (obuf == NULL)
return 1;
for (s = 0; s < spp; s++)
{
for (row = 0; row < length; row += rowsperstrip)
{
nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip;
stripsize = TIFFVStripSize(out, nrows);
src = buf + (row * rowsize);
total_bytes += stripsize;
memset (obuf, '\0', rowstripsize);
if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp, bps, dump))
{
_TIFFfree(obuf);
return 1;
}
if ((dump->outfile != NULL) && (dump->level == 1))
{
dump_info(dump->outfile, dump->format,"",
"Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d",
s + 1, strip + 1, stripsize, row + 1, scanlinesize, src - buf);
dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf);
}
if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0)
{
TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1);
_TIFFfree(obuf);
return 1;
}
}
}
_TIFFfree(obuf);
return 0;
}
/* Extract all planes from contiguous buffer into a single tile buffer
* to be written out as a tile.
*/
static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength,
uint32 imagewidth, tsample_t spp,
struct dump_opts* dump)
{
uint16 bps;
uint32 tl, tw;
uint32 row, col, nrow, ncol;
uint32 src_rowsize, col_offset;
uint32 tile_rowsize = TIFFTileRowSize(out);
uint8* bufp = (uint8*) buf;
tsize_t tile_buffsize = 0;
tsize_t tilesize = TIFFTileSize(out);
unsigned char *tilebuf = NULL;
if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) ||
!TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) ||
!TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) )
return 1;
if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0)
{
TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero");
exit(-1);
}
tile_buffsize = tilesize;
if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
TIFFError("writeBufferToContigTiles",
"Tilesize %lu is too small, using alternate calculation %u",
tilesize, tl * tile_rowsize);
#endif
tile_buffsize = tl * tile_rowsize;
if (tl != tile_buffsize / tile_rowsize)
{
TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size");
exit(-1);
}
}
if( imagewidth == 0 ||
(uint32)bps * (uint32)spp > TIFF_UINT32_MAX / imagewidth ||
bps * spp * imagewidth > TIFF_UINT32_MAX - 7U )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing (imagewidth * bps * spp) + 7");
return 1;
}
src_rowsize = ((imagewidth * spp * bps) + 7U) / 8;
tilebuf = _TIFFmalloc(tile_buffsize);
if (tilebuf == 0)
return 1;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
/* Calculate visible portion of tile. */
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
col_offset = (((col * bps * spp) + 7) / 8);
bufp = buf + (row * src_rowsize) + col_offset;
if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth,
tw, 0, spp, spp, bps, dump) > 0)
{
TIFFError("writeBufferToContigTiles",
"Unable to extract data to tile for row %lu, col %lu",
(unsigned long) row, (unsigned long)col);
_TIFFfree(tilebuf);
return 1;
}
if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0)
{
TIFFError("writeBufferToContigTiles",
"Cannot write tile at %lu %lu",
(unsigned long) col, (unsigned long) row);
_TIFFfree(tilebuf);
return 1;
}
}
}
_TIFFfree(tilebuf);
return 0;
} /* end writeBufferToContigTiles */
/* Extract each plane from contiguous buffer into a single tile buffer
* to be written out as a tile.
*/
static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength,
uint32 imagewidth, tsample_t spp,
struct dump_opts * dump)
{
tdata_t obuf = _TIFFmalloc(TIFFTileSize(out));
uint32 tl, tw;
uint32 row, col, nrow, ncol;
uint32 src_rowsize, col_offset;
uint16 bps;
tsample_t s;
uint8* bufp = (uint8*) buf;
if (obuf == NULL)
return 1;
TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
if( imagewidth == 0 ||
(uint32)bps * (uint32)spp > TIFF_UINT32_MAX / imagewidth ||
bps * spp * imagewidth > TIFF_UINT32_MAX - 7 )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing (imagewidth * bps * spp) + 7");
_TIFFfree(obuf);
return 1;
}
src_rowsize = ((imagewidth * spp * bps) + 7U) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
/* Calculate visible portion of tile. */
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
col_offset = (((col * bps * spp) + 7) / 8);
bufp = buf + (row * src_rowsize) + col_offset;
for (s = 0; s < spp; s++)
{
if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth,
tw, s, 1, spp, bps, dump) > 0)
{
TIFFError("writeBufferToSeparateTiles",
"Unable to extract data to tile for row %lu, col %lu sample %d",
(unsigned long) row, (unsigned long)col, (int)s);
_TIFFfree(obuf);
return 1;
}
if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0)
{
TIFFError("writeBufferToseparateTiles",
"Cannot write tile at %lu %lu sample %lu",
(unsigned long) col, (unsigned long) row,
(unsigned long) s);
_TIFFfree(obuf);
return 1;
}
}
}
}
_TIFFfree(obuf);
return 0;
} /* end writeBufferToSeparateTiles */
static void
processG3Options(char* cp)
{
if( (cp = strchr(cp, ':')) ) {
if (defg3opts == (uint32) -1)
defg3opts = 0;
do {
cp++;
if (strneq(cp, "1d", 2))
defg3opts &= ~GROUP3OPT_2DENCODING;
else if (strneq(cp, "2d", 2))
defg3opts |= GROUP3OPT_2DENCODING;
else if (strneq(cp, "fill", 4))
defg3opts |= GROUP3OPT_FILLBITS;
else
usage();
} while( (cp = strchr(cp, ':')) );
}
}
static int
processCompressOptions(char* opt)
{
char* cp = NULL;
if (strneq(opt, "none",4))
{
defcompression = COMPRESSION_NONE;
}
else if (streq(opt, "packbits"))
{
defcompression = COMPRESSION_PACKBITS;
}
else if (strneq(opt, "jpeg", 4))
{
cp = strchr(opt, ':');
defcompression = COMPRESSION_JPEG;
while (cp)
{
if (isdigit((int)cp[1]))
quality = atoi(cp + 1);
else if (strneq(cp + 1, "raw", 3 ))
jpegcolormode = JPEGCOLORMODE_RAW;
else if (strneq(cp + 1, "rgb", 3 ))
jpegcolormode = JPEGCOLORMODE_RGB;
else
usage();
cp = strchr(cp + 1, ':');
}
}
else if (strneq(opt, "g3", 2))
{
processG3Options(opt);
defcompression = COMPRESSION_CCITTFAX3;
}
else if (streq(opt, "g4"))
{
defcompression = COMPRESSION_CCITTFAX4;
}
else if (strneq(opt, "lzw", 3))
{
cp = strchr(opt, ':');
if (cp)
defpredictor = atoi(cp+1);
defcompression = COMPRESSION_LZW;
}
else if (strneq(opt, "zip", 3))
{
cp = strchr(opt, ':');
if (cp)
defpredictor = atoi(cp+1);
defcompression = COMPRESSION_ADOBE_DEFLATE;
}
else
return (0);
return (1);
}
static void
usage(void)
{
int i;
fprintf(stderr, "\n%s\n", TIFFGetVersion());
for (i = 0; usage_info[i] != NULL; i++)
fprintf(stderr, "%s\n", usage_info[i]);
exit(-1);
}
#define CopyField(tag, v) \
if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
#define CopyField2(tag, v1, v2) \
if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
#define CopyField3(tag, v1, v2, v3) \
if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
#define CopyField4(tag, v1, v2, v3, v4) \
if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
static void
cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type)
{
switch (type) {
case TIFF_SHORT:
if (count == 1) {
uint16 shortv;
CopyField(tag, shortv);
} else if (count == 2) {
uint16 shortv1, shortv2;
CopyField2(tag, shortv1, shortv2);
} else if (count == 4) {
uint16 *tr, *tg, *tb, *ta;
CopyField4(tag, tr, tg, tb, ta);
} else if (count == (uint16) -1) {
uint16 shortv1;
uint16* shortav;
CopyField2(tag, shortv1, shortav);
}
break;
case TIFF_LONG:
{ uint32 longv;
CopyField(tag, longv);
}
break;
case TIFF_RATIONAL:
if (count == 1) {
float floatv;
CopyField(tag, floatv);
} else if (count == (uint16) -1) {
float* floatav;
CopyField(tag, floatav);
}
break;
case TIFF_ASCII:
{ char* stringv;
CopyField(tag, stringv);
}
break;
case TIFF_DOUBLE:
if (count == 1) {
double doublev;
CopyField(tag, doublev);
} else if (count == (uint16) -1) {
double* doubleav;
CopyField(tag, doubleav);
}
break;
default:
TIFFError(TIFFFileName(in),
"Data type %d is not supported, tag %d skipped",
tag, type);
}
}
static struct cpTag {
uint16 tag;
uint16 count;
TIFFDataType type;
} tags[] = {
{ TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
{ TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
{ TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
{ TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
{ TIFFTAG_MAKE, 1, TIFF_ASCII },
{ TIFFTAG_MODEL, 1, TIFF_ASCII },
{ TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
{ TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
{ TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
{ TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
{ TIFFTAG_PAGENAME, 1, TIFF_ASCII },
{ TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
{ TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
{ TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
{ TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
{ TIFFTAG_DATETIME, 1, TIFF_ASCII },
{ TIFFTAG_ARTIST, 1, TIFF_ASCII },
{ TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
{ TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL },
{ TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
{ TIFFTAG_INKSET, 1, TIFF_SHORT },
{ TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
{ TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
{ TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
{ TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
{ TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
{ TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT },
{ TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE },
{ TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE },
{ TIFFTAG_STONITS, 1, TIFF_DOUBLE },
};
#define NTAGS (sizeof (tags) / sizeof (tags[0]))
#define CopyTag(tag, count, type) cpTag(in, out, tag, count, type)
/* Functions written by Richard Nolde, with exceptions noted. */
void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum,
uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth,
uint32 *deftilelength, uint32 *defrowsperstrip,
struct crop_mask *crop_data, struct pagedef *page,
struct dump_opts *dump,
unsigned int *imagelist, unsigned int *image_count )
{
int c, good_args = 0;
char *opt_offset = NULL; /* Position in string of value sought */
char *opt_ptr = NULL; /* Pointer to next token in option set */
char *sep = NULL; /* Pointer to a token separator */
unsigned int i, j, start, end;
#if !HAVE_DECL_OPTARG
extern int optind;
extern char* optarg;
#endif
*mp++ = 'w';
*mp = '\0';
while ((c = getopt(argc, argv,
"ac:d:e:f:hil:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1)
{
good_args++;
switch (c) {
case 'a': mode[0] = 'a'; /* append to output */
break;
case 'c': if (!processCompressOptions(optarg)) /* compression scheme */
{
TIFFError ("Unknown compression option", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */
if (start == 0)
{
TIFFError ("","Directory offset must be greater than zero");
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
*dirnum = start - 1;
break;
case 'e': switch (tolower((int) optarg[0])) /* image export modes*/
{
case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE;
crop_data->img_mode = COMPOSITE_IMAGES;
break; /* Composite */
case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Divided */
case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE;
crop_data->img_mode = COMPOSITE_IMAGES;
break; /* Image */
case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Multiple */
case 's': crop_data->exp_mode = FILE_PER_SELECTION;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Sections */
default: TIFFError ("Unknown export mode","%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'f': if (streq(optarg, "lsb2msb")) /* fill order */
*deffillorder = FILLORDER_LSB2MSB;
else if (streq(optarg, "msb2lsb"))
*deffillorder = FILLORDER_MSB2LSB;
else
{
TIFFError ("Unknown fill order", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'h': usage();
break;
case 'i': ignore = TRUE; /* ignore errors */
break;
case 'l': outtiled = TRUE; /* tile length */
*deftilelength = atoi(optarg);
break;
case 'p': /* planar configuration */
if (streq(optarg, "separate"))
*defconfig = PLANARCONFIG_SEPARATE;
else if (streq(optarg, "contig"))
*defconfig = PLANARCONFIG_CONTIG;
else
{
TIFFError ("Unkown planar configuration", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'r': /* rows/strip */
*defrowsperstrip = atol(optarg);
break;
case 's': /* generate stripped output */
outtiled = FALSE;
break;
case 't': /* generate tiled output */
outtiled = TRUE;
break;
case 'v': TIFFError("Library Release", "%s", TIFFGetVersion());
TIFFError ("Tiffcrop version", "%s, last updated: %s",
tiffcrop_version_id, tiffcrop_rev_date);
TIFFError ("Tiffcp code", "Copyright (c) 1988-1997 Sam Leffler");
TIFFError (" ", "Copyright (c) 1991-1997 Silicon Graphics, Inc");
TIFFError ("Tiffcrop additions", "Copyright (c) 2007-2010 Richard Nolde");
exit (0);
break;
case 'w': /* tile width */
outtiled = TRUE;
*deftilewidth = atoi(optarg);
break;
case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */
crop_data->crop_mode |= CROP_REGIONS;
for (i = 0, opt_ptr = strtok (optarg, ":");
((opt_ptr != NULL) && (i < MAX_REGIONS));
(opt_ptr = strtok (NULL, ":")), i++)
{
crop_data->regions++;
if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf",
&crop_data->corners[i].X1, &crop_data->corners[i].Y1,
&crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4)
{
TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
}
/* check for remaining elements over MAX_REGIONS */
if ((opt_ptr != NULL) && (i >= MAX_REGIONS))
{
TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);;
}
break;
/* options for file open modes */
case 'B': *mp++ = 'b'; *mp = '\0';
break;
case 'L': *mp++ = 'l'; *mp = '\0';
break;
case 'M': *mp++ = 'm'; *mp = '\0';
break;
case 'C': *mp++ = 'c'; *mp = '\0';
break;
/* options for Debugging / data dump */
case 'D': for (i = 0, opt_ptr = strtok (optarg, ",");
(opt_ptr != NULL);
(opt_ptr = strtok (NULL, ",")), i++)
{
opt_offset = strpbrk(opt_ptr, ":=");
if (opt_offset == NULL)
{
TIFFError("Invalid dump option", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
*opt_offset = '\0';
/* convert option to lowercase */
end = strlen (opt_ptr);
for (i = 0; i < end; i++)
*(opt_ptr + i) = tolower((int) *(opt_ptr + i));
/* Look for dump format specification */
if (strncmp(opt_ptr, "for", 3) == 0)
{
/* convert value to lowercase */
end = strlen (opt_offset + 1);
for (i = 1; i <= end; i++)
*(opt_offset + i) = tolower((int) *(opt_offset + i));
/* check dump format value */
if (strncmp (opt_offset + 1, "txt", 3) == 0)
{
dump->format = DUMP_TEXT;
strcpy (dump->mode, "w");
}
else
{
if (strncmp(opt_offset + 1, "raw", 3) == 0)
{
dump->format = DUMP_RAW;
strcpy (dump->mode, "wb");
}
else
{
TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
}
}
else
{ /* Look for dump level specification */
if (strncmp (opt_ptr, "lev", 3) == 0)
dump->level = atoi(opt_offset + 1);
/* Look for input data dump file name */
if (strncmp (opt_ptr, "in", 2) == 0)
{
strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20);
dump->infilename[PATH_MAX - 20] = '\0';
}
/* Look for output data dump file name */
if (strncmp (opt_ptr, "out", 3) == 0)
{
strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20);
dump->outfilename[PATH_MAX - 20] = '\0';
}
if (strncmp (opt_ptr, "deb", 3) == 0)
dump->debug = atoi(opt_offset + 1);
}
}
if ((strlen(dump->infilename)) || (strlen(dump->outfilename)))
{
if (dump->level == 1)
TIFFError("","Defaulting to dump level 1, no data.");
if (dump->format == DUMP_NONE)
{
TIFFError("", "You must specify a dump format for dump files");
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
}
break;
/* image manipulation routine options */
case 'm': /* margins to exclude from selection, uppercase M was already used */
/* order of values must be TOP, LEFT, BOTTOM, RIGHT */
crop_data->crop_mode |= CROP_MARGINS;
for (i = 0, opt_ptr = strtok (optarg, ",:");
((opt_ptr != NULL) && (i < 4));
(opt_ptr = strtok (NULL, ",:")), i++)
{
crop_data->margins[i] = atof(opt_ptr);
}
break;
case 'E': /* edge reference */
switch (tolower((int) optarg[0]))
{
case 't': crop_data->edge_ref = EDGE_TOP;
break;
case 'b': crop_data->edge_ref = EDGE_BOTTOM;
break;
case 'l': crop_data->edge_ref = EDGE_LEFT;
break;
case 'r': crop_data->edge_ref = EDGE_RIGHT;
break;
default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'F': /* flip eg mirror image or cropped segment, M was already used */
crop_data->crop_mode |= CROP_MIRROR;
switch (tolower((int) optarg[0]))
{
case 'h': crop_data->mirror = MIRROR_HORIZ;
break;
case 'v': crop_data->mirror = MIRROR_VERT;
break;
case 'b': crop_data->mirror = MIRROR_BOTH;
break;
default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'H': /* set horizontal resolution to new value */
page->hres = atof (optarg);
page->mode |= PAGE_MODE_RESOLUTION;
break;
case 'I': /* invert the color space, eg black to white */
crop_data->crop_mode |= CROP_INVERT;
/* The PHOTOMETIC_INTERPRETATION tag may be updated */
if (streq(optarg, "black"))
{
crop_data->photometric = PHOTOMETRIC_MINISBLACK;
continue;
}
if (streq(optarg, "white"))
{
crop_data->photometric = PHOTOMETRIC_MINISWHITE;
continue;
}
if (streq(optarg, "data"))
{
crop_data->photometric = INVERT_DATA_ONLY;
continue;
}
if (streq(optarg, "both"))
{
crop_data->photometric = INVERT_DATA_AND_TAG;
continue;
}
TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
break;
case 'J': /* horizontal margin for sectioned ouput pages */
page->hmargin = atof(optarg);
page->mode |= PAGE_MODE_MARGINS;
break;
case 'K': /* vertical margin for sectioned ouput pages*/
page->vmargin = atof(optarg);
page->mode |= PAGE_MODE_MARGINS;
break;
case 'N': /* list of images to process */
for (i = 0, opt_ptr = strtok (optarg, ",");
((opt_ptr != NULL) && (i < MAX_IMAGES));
(opt_ptr = strtok (NULL, ",")))
{ /* We do not know how many images are in file yet
* so we build a list to include the maximum allowed
* and follow it until we hit the end of the file.
* Image count is not accurate for odd, even, last
* so page numbers won't be valid either.
*/
if (streq(opt_ptr, "odd"))
{
for (j = 1; j <= MAX_IMAGES; j += 2)
imagelist[i++] = j;
*image_count = (MAX_IMAGES - 1) / 2;
break;
}
else
{
if (streq(opt_ptr, "even"))
{
for (j = 2; j <= MAX_IMAGES; j += 2)
imagelist[i++] = j;
*image_count = MAX_IMAGES / 2;
break;
}
else
{
if (streq(opt_ptr, "last"))
imagelist[i++] = MAX_IMAGES;
else /* single value between commas */
{
sep = strpbrk(opt_ptr, ":-");
if (!sep)
imagelist[i++] = atoi(opt_ptr);
else
{
*sep = '\0';
start = atoi (opt_ptr);
if (!strcmp((sep + 1), "last"))
end = MAX_IMAGES;
else
end = atoi (sep + 1);
for (j = start; j <= end && j - start + i < MAX_IMAGES; j++)
imagelist[i++] = j;
}
}
}
}
}
*image_count = i;
break;
case 'O': /* page orientation */
switch (tolower((int) optarg[0]))
{
case 'a': page->orient = ORIENTATION_AUTO;
break;
case 'p': page->orient = ORIENTATION_PORTRAIT;
break;
case 'l': page->orient = ORIENTATION_LANDSCAPE;
break;
default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'P': /* page size selection */
if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2)
{
strcpy (page->name, "Custom");
page->mode |= PAGE_MODE_PAPERSIZE;
break;
}
if (get_page_geometry (optarg, page))
{
if (!strcmp(optarg, "list"))
{
TIFFError("", "Name Width Length (in inches)");
for (i = 0; i < MAX_PAPERNAMES - 1; i++)
TIFFError ("", "%-15.15s %5.2f %5.2f",
PaperTable[i].name, PaperTable[i].width,
PaperTable[i].length);
exit (-1);
}
TIFFError ("Invalid paper size", "%s", optarg);
TIFFError ("", "Select one of:");
TIFFError("", "Name Width Length (in inches)");
for (i = 0; i < MAX_PAPERNAMES - 1; i++)
TIFFError ("", "%-15.15s %5.2f %5.2f",
PaperTable[i].name, PaperTable[i].width,
PaperTable[i].length);
exit (-1);
}
else
{
page->mode |= PAGE_MODE_PAPERSIZE;
}
break;
case 'R': /* rotate image or cropped segment */
crop_data->crop_mode |= CROP_ROTATE;
switch (strtoul(optarg, NULL, 0))
{
case 90: crop_data->rotation = (uint16)90;
break;
case 180: crop_data->rotation = (uint16)180;
break;
case 270: crop_data->rotation = (uint16)270;
break;
default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */
sep = strpbrk(optarg, ",:");
if (sep)
{
*sep = '\0';
page->cols = atoi(optarg);
page->rows = atoi(sep +1);
}
else
{
page->cols = atoi(optarg);
page->rows = atoi(optarg);
}
if ((page->cols * page->rows) > MAX_SECTIONS)
{
TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS);
exit (-1);
}
page->mode |= PAGE_MODE_ROWSCOLS;
break;
case 'U': /* units for measurements and offsets */
if (streq(optarg, "in"))
{
crop_data->res_unit = RESUNIT_INCH;
page->res_unit = RESUNIT_INCH;
}
else if (streq(optarg, "cm"))
{
crop_data->res_unit = RESUNIT_CENTIMETER;
page->res_unit = RESUNIT_CENTIMETER;
}
else if (streq(optarg, "px"))
{
crop_data->res_unit = RESUNIT_NONE;
page->res_unit = RESUNIT_NONE;
}
else
{
TIFFError ("Illegal unit of measure","%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'V': /* set vertical resolution to new value */
page->vres = atof (optarg);
page->mode |= PAGE_MODE_RESOLUTION;
break;
case 'X': /* selection width */
crop_data->crop_mode |= CROP_WIDTH;
crop_data->width = atof(optarg);
break;
case 'Y': /* selection length */
crop_data->crop_mode |= CROP_LENGTH;
crop_data->length = atof(optarg);
break;
case 'Z': /* zones of an image X:Y read as zone X of Y */
crop_data->crop_mode |= CROP_ZONES;
for (i = 0, opt_ptr = strtok (optarg, ",");
((opt_ptr != NULL) && (i < MAX_REGIONS));
(opt_ptr = strtok (NULL, ",")), i++)
{
crop_data->zones++;
opt_offset = strchr(opt_ptr, ':');
if (!opt_offset) {
TIFFError("Wrong parameter syntax for -Z", "tiffcrop -h");
exit(-1);
}
*opt_offset = '\0';
crop_data->zonelist[i].position = atoi(opt_ptr);
crop_data->zonelist[i].total = atoi(opt_offset + 1);
}
/* check for remaining elements over MAX_REGIONS */
if ((opt_ptr != NULL) && (i >= MAX_REGIONS))
{
TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS);
exit (-1);
}
break;
case '?': TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
/*NOTREACHED*/
}
}
} /* end process_command_opts */
/* Start a new output file if one has not been previously opened or
* autoindex is set to non-zero. Update page and file counters
* so TIFFTAG PAGENUM will be correct in image.
*/
static int
update_output_file (TIFF **tiffout, char *mode, int autoindex,
char *outname, unsigned int *page)
{
static int findex = 0; /* file sequence indicator */
char *sep;
char filenum[16];
char export_ext[16];
char exportname[PATH_MAX];
if (autoindex && (*tiffout != NULL))
{
/* Close any export file that was previously opened */
TIFFClose (*tiffout);
*tiffout = NULL;
}
strcpy (export_ext, ".tiff");
memset (exportname, '\0', PATH_MAX);
/* Leave room for page number portion of the new filename */
strncpy (exportname, outname, PATH_MAX - 16);
if (*tiffout == NULL) /* This is a new export file */
{
if (autoindex)
{ /* create a new filename for each export */
findex++;
if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF")))
{
strncpy (export_ext, sep, 5);
*sep = '\0';
}
else
strncpy (export_ext, ".tiff", 5);
export_ext[5] = '\0';
/* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow of pathname */
if (findex > MAX_EXPORT_PAGES)
{
TIFFError("update_output_file", "Maximum of %d pages per file exceeded", MAX_EXPORT_PAGES);
return 1;
}
snprintf(filenum, sizeof(filenum), "-%03d%s", findex, export_ext);
filenum[14] = '\0';
strncat (exportname, filenum, 15);
}
exportname[PATH_MAX - 1] = '\0';
*tiffout = TIFFOpen(exportname, mode);
if (*tiffout == NULL)
{
TIFFError("update_output_file", "Unable to open output file %s", exportname);
return 1;
}
*page = 0;
return 0;
}
else
(*page)++;
return 0;
} /* end update_output_file */
int
main(int argc, char* argv[])
{
#if !HAVE_DECL_OPTARG
extern int optind;
#endif
uint16 defconfig = (uint16) -1;
uint16 deffillorder = 0;
uint32 deftilewidth = (uint32) 0;
uint32 deftilelength = (uint32) 0;
uint32 defrowsperstrip = (uint32) 0;
uint32 dirnum = 0;
TIFF *in = NULL;
TIFF *out = NULL;
char mode[10];
char *mp = mode;
/** RJN additions **/
struct image_data image; /* Image parameters for one image */
struct crop_mask crop; /* Cropping parameters for all images */
struct pagedef page; /* Page definition for output pages */
struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */
struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */
struct dump_opts dump; /* Data dump options */
unsigned char *read_buff = NULL; /* Input image data buffer */
unsigned char *crop_buff = NULL; /* Crop area buffer */
unsigned char *sect_buff = NULL; /* Image section buffer */
unsigned char *sect_src = NULL; /* Image section buffer pointer */
unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */
unsigned int image_count = 0;
unsigned int dump_images = 0;
unsigned int next_image = 0;
unsigned int next_page = 0;
unsigned int total_pages = 0;
unsigned int total_images = 0;
unsigned int end_of_input = FALSE;
int seg, length;
char temp_filename[PATH_MAX + 1];
little_endian = *((unsigned char *)&little_endian) & '1';
initImageData(&image);
initCropMasks(&crop);
initPageSetup(&page, sections, seg_buffs);
initDumpOptions(&dump);
process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig,
&deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip,
&crop, &page, &dump, imagelist, &image_count);
if (argc - optind < 2)
usage();
if ((argc - optind) == 2)
pageNum = -1;
else
total_images = 0;
/* read multiple input files and write to output file(s) */
while (optind < argc - 1)
{
in = TIFFOpen (argv[optind], "r");
if (in == NULL)
return (-3);
/* If only one input file is specified, we can use directory count */
total_images = TIFFNumberOfDirectories(in);
if (image_count == 0)
{
dirnum = 0;
total_pages = total_images; /* Only valid with single input file */
}
else
{
dirnum = (tdir_t)(imagelist[next_image] - 1);
next_image++;
/* Total pages only valid for enumerated list of pages not derived
* using odd, even, or last keywords.
*/
if (image_count > total_images)
image_count = total_images;
total_pages = image_count;
}
/* MAX_IMAGES is used for special case "last" in selection list */
if (dirnum == (MAX_IMAGES - 1))
dirnum = total_images - 1;
if (dirnum > (total_images))
{
TIFFError (TIFFFileName(in),
"Invalid image number %d, File contains only %d images",
(int)dirnum + 1, total_images);
if (out != NULL)
(void) TIFFClose(out);
return (1);
}
if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum))
{
TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum);
if (out != NULL)
(void) TIFFClose(out);
return (1);
}
end_of_input = FALSE;
while (end_of_input == FALSE)
{
config = defconfig;
compression = defcompression;
predictor = defpredictor;
fillorder = deffillorder;
rowsperstrip = defrowsperstrip;
tilewidth = deftilewidth;
tilelength = deftilelength;
g3opts = defg3opts;
if (dump.format != DUMP_NONE)
{
/* manage input and/or output dump files here */
dump_images++;
length = strlen(dump.infilename);
if (length > 0)
{
if (dump.infile != NULL)
fclose (dump.infile);
/* dump.infilename is guaranteed to be NUL termimated and have 20 bytes
fewer than PATH_MAX */
snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s",
dump.infilename, dump_images,
(dump.format == DUMP_TEXT) ? "txt" : "raw");
if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL)
{
TIFFError ("Unable to open dump file for writing", "%s", temp_filename);
exit (-1);
}
dump_info(dump.infile, dump.format, "Reading image","%d from %s",
dump_images, TIFFFileName(in));
}
length = strlen(dump.outfilename);
if (length > 0)
{
if (dump.outfile != NULL)
fclose (dump.outfile);
/* dump.outfilename is guaranteed to be NUL termimated and have 20 bytes
fewer than PATH_MAX */
snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s",
dump.outfilename, dump_images,
(dump.format == DUMP_TEXT) ? "txt" : "raw");
if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL)
{
TIFFError ("Unable to open dump file for writing", "%s", temp_filename);
exit (-1);
}
dump_info(dump.outfile, dump.format, "Writing image","%d from %s",
dump_images, TIFFFileName(in));
}
}
if (dump.debug)
TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages);
if (loadImage(in, &image, &dump, &read_buff))
{
TIFFError("main", "Unable to load source image");
exit (-1);
}
/* Correct the image orientation if it was not ORIENTATION_TOPLEFT.
*/
if (image.adjustments != 0)
{
if (correct_orientation(&image, &read_buff))
TIFFError("main", "Unable to correct image orientation");
}
if (getCropOffsets(&image, &crop, &dump))
{
TIFFError("main", "Unable to define crop regions");
exit (-1);
}
if (crop.selections > 0)
{
if (processCropSelections(&image, &crop, &read_buff, seg_buffs))
{
TIFFError("main", "Unable to process image selections");
exit (-1);
}
}
else /* Single image segment without zones or regions */
{
if (createCroppedImage(&image, &crop, &read_buff, &crop_buff))
{
TIFFError("main", "Unable to create output image");
exit (-1);
}
}
if (page.mode == PAGE_MODE_NONE)
{ /* Whole image or sections not based on output page size */
if (crop.selections > 0)
{
writeSelections(in, &out, &crop, &image, &dump, seg_buffs,
mp, argv[argc - 1], &next_page, total_pages);
}
else /* One file all images and sections */
{
if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1],
&next_page))
exit (1);
if (writeCroppedImage(in, out, &image, &dump,crop.combined_width,
crop.combined_length, crop_buff, next_page, total_pages))
{
TIFFError("main", "Unable to write new image");
exit (-1);
}
}
}
else
{
/* If we used a crop buffer, our data is there, otherwise it is
* in the read_buffer
*/
if (crop_buff != NULL)
sect_src = crop_buff;
else
sect_src = read_buff;
/* Break input image into pages or rows and columns */
if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump))
{
TIFFError("main", "Unable to compute output section data");
exit (-1);
}
/* If there are multiple files on the command line, the final one is assumed
* to be the output filename into which the images are written.
*/
if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page))
exit (1);
if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, §_buff))
{
TIFFError("main", "Unable to write image sections");
exit (-1);
}
}
/* No image list specified, just read the next image */
if (image_count == 0)
dirnum++;
else
{
dirnum = (tdir_t)(imagelist[next_image] - 1);
next_image++;
}
if (dirnum == MAX_IMAGES - 1)
dirnum = TIFFNumberOfDirectories(in) - 1;
if (!TIFFSetDirectory(in, (tdir_t)dirnum))
end_of_input = TRUE;
}
TIFFClose(in);
optind++;
}
/* If we did not use the read buffer as the crop buffer */
if (read_buff)
_TIFFfree(read_buff);
if (crop_buff)
_TIFFfree(crop_buff);
if (sect_buff)
_TIFFfree(sect_buff);
/* Clean up any segment buffers used for zones or regions */
for (seg = 0; seg < crop.selections; seg++)
_TIFFfree (seg_buffs[seg].buffer);
if (dump.format != DUMP_NONE)
{
if (dump.infile != NULL)
fclose (dump.infile);
if (dump.outfile != NULL)
{
dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out));
fclose (dump.outfile);
}
}
TIFFClose(out);
return (0);
} /* end main */
/* Debugging functions */
static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count)
{
int j, k;
uint32 i;
char dump_array[10];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (i = 0; i < count; i++)
{
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
}
dump_array[8] = '\0';
fprintf (dumpfile," %s", dump_array);
}
fprintf (dumpfile,"\n");
}
else
{
if ((fwrite (data, 1, count, dumpfile)) != count)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data)
{
int j, k;
char dump_array[10];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
}
dump_array[8] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 1, 1, dumpfile)) != 1)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data)
{
int j, k;
char dump_array[20];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 15; k >= 0; j++, k--)
{
bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[17] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 2, 1, dumpfile)) != 2)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data)
{
int j, k;
char dump_array[40];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 31; k >= 0; j++, k--)
{
bitset = data & (((uint32)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[35] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 4, 1, dumpfile)) != 4)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data)
{
int j, k;
char dump_array[80];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 63; k >= 0; j++, k--)
{
bitset = data & (((uint64)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[71] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 8, 1, dumpfile)) != 8)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...)
{
if (format == DUMP_TEXT)
{
va_list ap;
va_start(ap, msg);
fprintf(dumpfile, "%s ", prefix);
vfprintf(dumpfile, msg, ap);
fprintf(dumpfile, "\n");
va_end(ap);
}
}
static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width,
uint32 row, unsigned char *buff)
{
int j, k;
uint32 i;
unsigned char * dump_ptr;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
for (i = 0; i < rows; i++)
{
dump_ptr = buff + (i * width);
if (format == DUMP_TEXT)
dump_info (dumpfile, format, "",
"Row %4d, %d bytes at offset %d",
row + i + 1, width, row * width);
for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10)
dump_data (dumpfile, format, "", dump_ptr, 10);
if (k > 0)
dump_data (dumpfile, format, "", dump_ptr, k);
}
return (0);
}
/* Extract one or more samples from an interleaved buffer. If count == 1,
* only the sample plane indicated by sample will be extracted. If count > 1,
* count samples beginning at sample will be extracted. Portions of a
* scanline can be extracted by specifying a start and end value.
*/
static int
extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int i, bytes_per_sample, sindex;
uint32 col, dst_rowsize, bit_offset;
uint32 src_byte /*, src_bit */;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesBytes","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesBytes",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesBytes",
"Invalid end column value %d ignored", end);
end = cols;
}
dst_rowsize = (bps * (end - start) * count) / 8;
bytes_per_sample = (bps + 7) / 8;
/* Optimize case for copying all samples */
if (count == spp)
{
src = in + (start * spp * bytes_per_sample);
_TIFFmemcpy (dst, src, dst_rowsize);
}
else
{
for (col = start; col < end; col++)
{
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
bit_offset = col * bps * spp;
if (sindex == 0)
{
src_byte = bit_offset / 8;
/* src_bit = bit_offset % 8; */
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
/* src_bit = (bit_offset + (sindex * bps)) % 8; */
}
src = in + src_byte;
for (i = 0; i < bytes_per_sample; i++)
*dst++ = *src++;
}
}
}
return (0);
} /* end extractContigSamplesBytes */
static int
extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamples8bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples8bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples8bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
buff2 = (buff2 | (buff1 >> ready_bits));
ready_bits += bps;
}
}
while (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples8bits */
static int
extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamples16bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples16bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples16bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint16)-1 >> (16 - bps);
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 8) /* add another bps bits to the buffer */
{
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples16bits */
static int
extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamples24bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples24bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples24bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint32)-1 >> ( 32 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 16) /* add another bps bits to the buffer */
{
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples24bits */
static int
extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
uint32 col, src_byte, src_bit, bit_offset;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamples32bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples32bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples32bits",
"Invalid end column value %d ignored", end);
end = cols;
}
/* shift_width = ((bps + 7) / 8) + 1; */
ready_bits = 0;
maskbits = (uint64)-1 >> ( 64 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples32bits */
static int
extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted8bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted8bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*src) & matchbits) << (src_bit);
if ((col == start) && (sindex == sample))
buff2 = *src & ((uint8)-1) << (shift);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ |= buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
buff2 = buff2 | (buff1 >> ready_bits);
ready_bits += bps;
}
}
while (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted8bits */
static int
extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted16bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted16bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint16)-1 >> (16 - bps);
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
if ((col == start) && (sindex == sample))
buff2 = buff1 & ((uint16)-1) << (8 - shift);
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 8) /* add another bps bits to the buffer */
buff2 = buff2 | (buff1 >> ready_bits);
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted16bits */
static int
extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted24bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted24bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint32)-1 >> ( 32 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
if ((col == start) && (sindex == sample))
buff2 = buff1 & ((uint32)-1) << (16 - shift);
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 16) /* add another bps bits to the buffer */
{
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted24bits */
static int
extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
uint32 col, src_byte, src_bit, bit_offset;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted32bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted32bits",
"Invalid end column value %d ignored", end);
end = cols;
}
/* shift_width = ((bps + 7) / 8) + 1; */
ready_bits = shift;
maskbits = (uint64)-1 >> ( 64 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
if ((col == start) && (sindex == sample))
buff2 = buff3 & ((uint64)-1) << (32 - shift);
buff1 = (buff3 & matchbits) << (src_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted32bits */
static int
extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
struct dump_opts *dump)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, src_offset, row, first_col = 0;
uint32 dst_rowsize, dst_offset;
tsample_t count = 1;
uint8 *src, *dst;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
src_rowsize = ((bps * spp * cols) + 7) / 8;
dst_rowsize = ((bps * cols) + 7) / 8;
if ((dump->outfile != NULL) && (dump->level == 4))
{
dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer",
"Sample %d, %d rows", sample + 1, rows + 1);
}
for (row = 0; row < rows; row++)
{
src_offset = row * src_rowsize;
dst_offset = row * dst_rowsize;
src = in + src_offset;
dst = out + dst_offset;
/* pack the data into the scanline */
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 1: if (bps == 1)
{
if (extractContigSamples8bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
}
else
if (extractContigSamples16bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 2: if (extractContigSamples24bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 3:
case 4:
case 5: if (extractContigSamples32bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps);
return (1);
}
if ((dump->outfile != NULL) && (dump->level == 4))
dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
}
return (0);
} /* end extractContigSamplesToBuffer */
static int
extractContigSamplesToTileBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols,
uint32 imagewidth, uint32 tilewidth, tsample_t sample,
uint16 count, uint16 spp, uint16 bps, struct dump_opts *dump)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, src_offset, row;
uint32 dst_rowsize, dst_offset;
uint8 *src, *dst;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
if ((dump->outfile != NULL) && (dump->level == 4))
{
dump_info (dump->outfile, dump->format, "extractContigSamplesToTileBuffer",
"Sample %d, %d rows", sample + 1, rows + 1);
}
src_rowsize = ((bps * spp * imagewidth) + 7) / 8;
dst_rowsize = ((bps * tilewidth * count) + 7) / 8;
for (row = 0; row < rows; row++)
{
src_offset = row * src_rowsize;
dst_offset = row * dst_rowsize;
src = in + src_offset;
dst = out + dst_offset;
/* pack the data into the scanline */
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 1: if (bps == 1)
{
if (extractContigSamples8bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
}
else
if (extractContigSamples16bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 2: if (extractContigSamples24bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 3:
case 4:
case 5: if (extractContigSamples32bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
default: TIFFError ("extractContigSamplesToTileBuffer", "Unsupported bit depth: %d", bps);
return (1);
}
if ((dump->outfile != NULL) && (dump->level == 4))
dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
}
return (0);
} /* end extractContigSamplesToTileBuffer */
static int readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
int32 bytes_read = 0;
uint32 strip, nstrips = TIFFNumberOfStrips(in);
uint32 stripsize = TIFFStripSize(in);
uint32 rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %d: read %lu bytes, strip size %lu",
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %lu after %lu rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += bytes_read;
}
return 1;
} /* end readContigStripsIntoBuffer */
static int
combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out,
uint32 cols, uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int i, bytes_per_sample;
uint32 row, col, col_offset, src_rowsize, dst_rowsize, row_offset;
unsigned char *src;
unsigned char *dst;
tsample_t s;
src = srcbuffs[0];
dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamplesBytes","Invalid buffer address");
return (1);
}
bytes_per_sample = (bps + 7) / 8;
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * spp * cols) + 7) / 8;
for (row = 0; row < rows; row++)
{
if ((dumpfile != NULL) && (level == 2))
{
for (s = 0; s < spp; s++)
{
dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s);
dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize));
}
}
dst = out + (row * dst_rowsize);
row_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
col_offset = row_offset + (col * (bps / 8));
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = srcbuffs[s] + col_offset;
for (i = 0; i < bytes_per_sample; i++)
*(dst + i) = *(src + i);
src += bytes_per_sample;
dst += bytes_per_sample;
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamplesBytes */
static int
combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
/* int bytes_per_sample = 0; */
uint32 src_rowsize, dst_rowsize, src_offset;
uint32 bit_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples8bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint8)-1 >> ( 8 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (8 - src_bit - bps);
/* load up next sample from each plane */
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
strcpy (action, "Flush");
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Match bits", matchbits);
dump_byte (dumpfile, format, "Src bits", *src);
dump_byte (dumpfile, format, "Buff1 bits", buff1);
dump_byte (dumpfile, format, "Buff2 bits", buff2);
dump_info (dumpfile, format, "","%s", action);
}
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", buff1);
}
}
if ((dumpfile != NULL) && (level >= 2))
{
dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples8bits */
static int
combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0 */;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples16bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint16)-1 >> (16 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (16 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_short (dumpfile, format, "Match bits", matchbits);
dump_data (dumpfile, format, "Src bits", src, 2);
dump_short (dumpfile, format, "Buff1 bits", buff1);
dump_short (dumpfile, format, "Buff2 bits", buff2);
dump_byte (dumpfile, format, "Write byte", bytebuff);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", bytebuff);
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples16bits */
static int
combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0 */;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples24bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint32)-1 >> ( 32 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (32 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples24bits */
static int
combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */;
uint32 src_rowsize, dst_rowsize, bit_offset, src_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 row, col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples32bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint64)-1 >> ( 64 - bps);
/* shift_width = ((bps + 7) / 8) + 1; */
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (64 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_wide (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 8);
dump_wide (dumpfile, format, "Buff1 bits ", buff1);
dump_wide (dumpfile, format, "Buff2 bits ", buff2);
dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action);
}
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
}
}
return (0);
} /* end combineSeparateSamples32bits */
static int
combineSeparateTileSamplesBytes (unsigned char *srcbuffs[], unsigned char *out,
uint32 cols, uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int i, bytes_per_sample;
uint32 row, col, col_offset, src_rowsize, dst_rowsize, src_offset;
unsigned char *src;
unsigned char *dst;
tsample_t s;
src = srcbuffs[0];
dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamplesBytes","Invalid buffer address");
return (1);
}
bytes_per_sample = (bps + 7) / 8;
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = imagewidth * bytes_per_sample * spp;
for (row = 0; row < rows; row++)
{
if ((dumpfile != NULL) && (level == 2))
{
for (s = 0; s < spp; s++)
{
dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Input data, Sample %d", s);
dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize));
}
}
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
#ifdef DEVELMODE
TIFFError("","Tile row %4d, Src offset %6d Dst offset %6d",
row, src_offset, dst - out);
#endif
for (col = 0; col < cols; col++)
{
col_offset = src_offset + (col * (bps / 8));
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = srcbuffs[s] + col_offset;
for (i = 0; i < bytes_per_sample; i++)
*(dst + i) = *(src + i);
dst += bytes_per_sample;
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Output data, combined samples");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamplesBytes */
static int
combineSeparateTileSamples8bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize, src_offset;
uint32 bit_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples8bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint8)-1 >> ( 8 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (8 - src_bit - bps);
/* load up next sample from each plane */
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
strcpy (action, "Flush");
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Match bits", matchbits);
dump_byte (dumpfile, format, "Src bits", *src);
dump_byte (dumpfile, format, "Buff1 bits", buff1);
dump_byte (dumpfile, format, "Buff2 bits", buff2);
dump_info (dumpfile, format, "","%s", action);
}
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", buff1);
}
}
if ((dumpfile != NULL) && (level >= 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples8bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples8bits */
static int
combineSeparateTileSamples16bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples16bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint16)-1 >> (16 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (16 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_short (dumpfile, format, "Match bits", matchbits);
dump_data (dumpfile, format, "Src bits", src, 2);
dump_short (dumpfile, format, "Buff1 bits", buff1);
dump_short (dumpfile, format, "Buff2 bits", buff2);
dump_byte (dumpfile, format, "Write byte", bytebuff);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", bytebuff);
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples16bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples16bits */
static int
combineSeparateTileSamples24bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples24bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint32)-1 >> ( 32 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (32 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples24bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples24bits */
static int
combineSeparateTileSamples32bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, shift_width = 0 */;
uint32 src_rowsize, dst_rowsize, bit_offset, src_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 row, col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples32bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint64)-1 >> ( 64 - bps);
/* shift_width = ((bps + 7) / 8) + 1; */
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (64 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_wide (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 8);
dump_wide (dumpfile, format, "Buff1 bits ", buff1);
dump_wide (dumpfile, format, "Buff2 bits ", buff2);
dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action);
}
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples32bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
}
}
return (0);
} /* end combineSeparateTileSamples32bits */
static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length,
uint32 width, uint16 spp,
struct dump_opts *dump)
{
int i, bytes_per_sample, bytes_per_pixel, shift_width, result = 1;
uint32 j;
int32 bytes_read = 0;
uint16 bps, planar;
uint32 nstrips;
uint32 strips_per_sample;
uint32 src_rowsize, dst_rowsize, rows_processed, rps;
uint32 rows_this_strip = 0;
tsample_t s;
tstrip_t strip;
tsize_t scanlinesize = TIFFScanlineSize(in);
tsize_t stripsize = TIFFStripSize(in);
unsigned char *srcbuffs[MAX_SAMPLES];
unsigned char *buff = NULL;
unsigned char *dst = NULL;
if (obuf == NULL)
{
TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument");
return (0);
}
memset (srcbuffs, '\0', sizeof(srcbuffs));
TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
if (rps > length)
rps = length;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
src_rowsize = ((bps * width) + 7) / 8;
dst_rowsize = ((bps * width * spp) + 7) / 8;
dst = obuf;
if ((dump->infile != NULL) && (dump->level == 3))
{
dump_info (dump->infile, dump->format, "",
"Image width %d, length %d, Scanline size, %4d bytes",
width, length, scanlinesize);
dump_info (dump->infile, dump->format, "",
"Bits per sample %d, Samples per pixel %d, Shift width %d",
bps, spp, shift_width);
}
/* Libtiff seems to assume/require that data for separate planes are
* written one complete plane after another and not interleaved in any way.
* Multiple scanlines and possibly strips of the same plane must be
* written before data for any other plane.
*/
nstrips = TIFFNumberOfStrips(in);
strips_per_sample = nstrips /spp;
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
srcbuffs[s] = NULL;
buff = _TIFFmalloc(stripsize);
if (!buff)
{
TIFFError ("readSeparateStripsIntoBuffer",
"Unable to allocate strip read buffer for sample %d", s);
for (i = 0; i < s; i++)
_TIFFfree (srcbuffs[i]);
return 0;
}
srcbuffs[s] = buff;
}
rows_processed = 0;
for (j = 0; (j < strips_per_sample) && (result == 1); j++)
{
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
buff = srcbuffs[s];
strip = (s * strips_per_sample) + j;
bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize);
rows_this_strip = bytes_read / src_rowsize;
if (bytes_read < 0 && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read strip %lu for sample %d",
(unsigned long) strip, s + 1);
result = 0;
break;
}
#ifdef DEVELMODE
TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d",
strip, bytes_read, rows_this_strip, shift_width);
#endif
}
if (rps > rows_this_strip)
rps = rows_this_strip;
dst = obuf + (dst_rowsize * rows_processed);
if ((bps % 8) == 0)
{
if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
}
else
{
switch (shift_width)
{
case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 4:
case 5:
case 6:
case 7:
case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps);
result = 0;
break;
}
}
if ((rows_processed + rps) > length)
{
rows_processed = length;
rps = length - rows_processed;
}
else
rows_processed += rps;
}
/* free any buffers allocated for each plane or scanline and
* any temporary buffers
*/
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
buff = srcbuffs[s];
if (buff != NULL)
_TIFFfree(buff);
}
return (result);
} /* end readSeparateStripsIntoBuffer */
static int
get_page_geometry (char *name, struct pagedef *page)
{
char *ptr;
int n;
for (ptr = name; *ptr; ptr++)
*ptr = (char)tolower((int)*ptr);
for (n = 0; n < MAX_PAPERNAMES; n++)
{
if (strcmp(name, PaperTable[n].name) == 0)
{
page->width = PaperTable[n].width;
page->length = PaperTable[n].length;
strncpy (page->name, PaperTable[n].name, 15);
page->name[15] = '\0';
return (0);
}
}
return (1);
}
static void
initPageSetup (struct pagedef *page, struct pageseg *pagelist,
struct buffinfo seg_buffs[])
{
int i;
strcpy (page->name, "");
page->mode = PAGE_MODE_NONE;
page->res_unit = RESUNIT_NONE;
page->hres = 0.0;
page->vres = 0.0;
page->width = 0.0;
page->length = 0.0;
page->hmargin = 0.0;
page->vmargin = 0.0;
page->rows = 0;
page->cols = 0;
page->orient = ORIENTATION_NONE;
for (i = 0; i < MAX_SECTIONS; i++)
{
pagelist[i].x1 = (uint32)0;
pagelist[i].x2 = (uint32)0;
pagelist[i].y1 = (uint32)0;
pagelist[i].y2 = (uint32)0;
pagelist[i].buffsize = (uint32)0;
pagelist[i].position = 0;
pagelist[i].total = 0;
}
for (i = 0; i < MAX_OUTBUFFS; i++)
{
seg_buffs[i].size = 0;
seg_buffs[i].buffer = NULL;
}
}
static void
initImageData (struct image_data *image)
{
image->xres = 0.0;
image->yres = 0.0;
image->width = 0;
image->length = 0;
image->res_unit = RESUNIT_NONE;
image->bps = 0;
image->spp = 0;
image->planar = 0;
image->photometric = 0;
image->orientation = 0;
image->compression = COMPRESSION_NONE;
image->adjustments = 0;
}
static void
initCropMasks (struct crop_mask *cps)
{
int i;
cps->crop_mode = CROP_NONE;
cps->res_unit = RESUNIT_NONE;
cps->edge_ref = EDGE_TOP;
cps->width = 0;
cps->length = 0;
for (i = 0; i < 4; i++)
cps->margins[i] = 0.0;
cps->bufftotal = (uint32)0;
cps->combined_width = (uint32)0;
cps->combined_length = (uint32)0;
cps->rotation = (uint16)0;
cps->photometric = INVERT_DATA_AND_TAG;
cps->mirror = (uint16)0;
cps->invert = (uint16)0;
cps->zones = (uint32)0;
cps->regions = (uint32)0;
for (i = 0; i < MAX_REGIONS; i++)
{
cps->corners[i].X1 = 0.0;
cps->corners[i].X2 = 0.0;
cps->corners[i].Y1 = 0.0;
cps->corners[i].Y2 = 0.0;
cps->regionlist[i].x1 = 0;
cps->regionlist[i].x2 = 0;
cps->regionlist[i].y1 = 0;
cps->regionlist[i].y2 = 0;
cps->regionlist[i].width = 0;
cps->regionlist[i].length = 0;
cps->regionlist[i].buffsize = 0;
cps->regionlist[i].buffptr = NULL;
cps->zonelist[i].position = 0;
cps->zonelist[i].total = 0;
}
cps->exp_mode = ONE_FILE_COMPOSITE;
cps->img_mode = COMPOSITE_IMAGES;
}
static void initDumpOptions(struct dump_opts *dump)
{
dump->debug = 0;
dump->format = DUMP_NONE;
dump->level = 1;
sprintf (dump->mode, "w");
memset (dump->infilename, '\0', PATH_MAX + 1);
memset (dump->outfilename, '\0',PATH_MAX + 1);
dump->infile = NULL;
dump->outfile = NULL;
}
/* Compute pixel offsets into the image for margins and fixed regions */
static int
computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image,
struct offset *off)
{
double scale;
float xres, yres;
/* Values for these offsets are in pixels from start of image, not bytes,
* and are indexed from zero to width - 1 or length - 1 */
uint32 tmargin, bmargin, lmargin, rmargin;
uint32 startx, endx; /* offsets of first and last columns to extract */
uint32 starty, endy; /* offsets of first and last row to extract */
uint32 width, length, crop_width, crop_length;
uint32 i, max_width, max_length, zwidth, zlength, buffsize;
uint32 x1, x2, y1, y2;
if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER)
{
xres = 1.0;
yres = 1.0;
}
else
{
if (((image->xres == 0) || (image->yres == 0)) &&
(crop->res_unit != RESUNIT_NONE) &&
((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) ||
(crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)))
{
TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution");
TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again");
return (-1);
}
xres = image->xres;
yres = image->yres;
}
/* Translate user units to image units */
scale = 1.0;
switch (crop->res_unit) {
case RESUNIT_CENTIMETER:
if (image->res_unit == RESUNIT_INCH)
scale = 1.0/2.54;
break;
case RESUNIT_INCH:
if (image->res_unit == RESUNIT_CENTIMETER)
scale = 2.54;
break;
case RESUNIT_NONE: /* Dimensions in pixels */
default:
break;
}
if (crop->crop_mode & CROP_REGIONS)
{
max_width = max_length = 0;
for (i = 0; i < crop->regions; i++)
{
if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER))
{
x1 = (uint32) (crop->corners[i].X1 * scale * xres);
x2 = (uint32) (crop->corners[i].X2 * scale * xres);
y1 = (uint32) (crop->corners[i].Y1 * scale * yres);
y2 = (uint32) (crop->corners[i].Y2 * scale * yres);
}
else
{
x1 = (uint32) (crop->corners[i].X1);
x2 = (uint32) (crop->corners[i].X2);
y1 = (uint32) (crop->corners[i].Y1);
y2 = (uint32) (crop->corners[i].Y2);
}
if (x1 < 1)
crop->regionlist[i].x1 = 0;
else
crop->regionlist[i].x1 = (uint32) (x1 - 1);
if (x2 > image->width - 1)
crop->regionlist[i].x2 = image->width - 1;
else
crop->regionlist[i].x2 = (uint32) (x2 - 1);
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
if (y1 < 1)
crop->regionlist[i].y1 = 0;
else
crop->regionlist[i].y1 = (uint32) (y1 - 1);
if (y2 > image->length - 1)
crop->regionlist[i].y2 = image->length - 1;
else
crop->regionlist[i].y2 = (uint32) (y2 - 1);
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
if (zwidth > max_width)
max_width = zwidth;
if (zlength > max_length)
max_length = zlength;
buffsize = (uint32)
(((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1));
crop->regionlist[i].buffsize = buffsize;
crop->bufftotal += buffsize;
if (crop->img_mode == COMPOSITE_IMAGES)
{
switch (crop->edge_ref)
{
case EDGE_LEFT:
case EDGE_RIGHT:
crop->combined_length = zlength;
crop->combined_width += zwidth;
break;
case EDGE_BOTTOM:
case EDGE_TOP: /* width from left, length from top */
default:
crop->combined_width = zwidth;
crop->combined_length += zlength;
break;
}
}
}
return (0);
}
/* Convert crop margins into offsets into image
* Margins are expressed as pixel rows and columns, not bytes
*/
if (crop->crop_mode & CROP_MARGINS)
{
if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)
{ /* User has specified pixels as reference unit */
tmargin = (uint32)(crop->margins[0]);
lmargin = (uint32)(crop->margins[1]);
bmargin = (uint32)(crop->margins[2]);
rmargin = (uint32)(crop->margins[3]);
}
else
{ /* inches or centimeters specified */
tmargin = (uint32)(crop->margins[0] * scale * yres);
lmargin = (uint32)(crop->margins[1] * scale * xres);
bmargin = (uint32)(crop->margins[2] * scale * yres);
rmargin = (uint32)(crop->margins[3] * scale * xres);
}
if ((lmargin + rmargin) > image->width)
{
TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width");
lmargin = (uint32) 0;
rmargin = (uint32) 0;
return (-1);
}
if ((tmargin + bmargin) > image->length)
{
TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length");
tmargin = (uint32) 0;
bmargin = (uint32) 0;
return (-1);
}
}
else
{ /* no margins requested */
tmargin = (uint32) 0;
lmargin = (uint32) 0;
bmargin = (uint32) 0;
rmargin = (uint32) 0;
}
/* Width, height, and margins are expressed as pixel offsets into image */
if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)
{
if (crop->crop_mode & CROP_WIDTH)
width = (uint32)crop->width;
else
width = image->width - lmargin - rmargin;
if (crop->crop_mode & CROP_LENGTH)
length = (uint32)crop->length;
else
length = image->length - tmargin - bmargin;
}
else
{
if (crop->crop_mode & CROP_WIDTH)
width = (uint32)(crop->width * scale * image->xres);
else
width = image->width - lmargin - rmargin;
if (crop->crop_mode & CROP_LENGTH)
length = (uint32)(crop->length * scale * image->yres);
else
length = image->length - tmargin - bmargin;
}
off->tmargin = tmargin;
off->bmargin = bmargin;
off->lmargin = lmargin;
off->rmargin = rmargin;
/* Calculate regions defined by margins, width, and length.
* Coordinates expressed as 0 to imagewidth - 1, imagelength - 1,
* since they are used to compute offsets into buffers */
switch (crop->edge_ref) {
case EDGE_BOTTOM:
startx = lmargin;
if ((startx + width) >= (image->width - rmargin))
endx = image->width - rmargin - 1;
else
endx = startx + width - 1;
endy = image->length - bmargin - 1;
if ((endy - length) <= tmargin)
starty = tmargin;
else
starty = endy - length + 1;
break;
case EDGE_RIGHT:
endx = image->width - rmargin - 1;
if ((endx - width) <= lmargin)
startx = lmargin;
else
startx = endx - width + 1;
starty = tmargin;
if ((starty + length) >= (image->length - bmargin))
endy = image->length - bmargin - 1;
else
endy = starty + length - 1;
break;
case EDGE_TOP: /* width from left, length from top */
case EDGE_LEFT:
default:
startx = lmargin;
if ((startx + width) >= (image->width - rmargin))
endx = image->width - rmargin - 1;
else
endx = startx + width - 1;
starty = tmargin;
if ((starty + length) >= (image->length - bmargin))
endy = image->length - bmargin - 1;
else
endy = starty + length - 1;
break;
}
off->startx = startx;
off->starty = starty;
off->endx = endx;
off->endy = endy;
crop_width = endx - startx + 1;
crop_length = endy - starty + 1;
if (crop_width <= 0)
{
TIFFError("computeInputPixelOffsets",
"Invalid left/right margins and /or image crop width requested");
return (-1);
}
if (crop_width > image->width)
crop_width = image->width;
if (crop_length <= 0)
{
TIFFError("computeInputPixelOffsets",
"Invalid top/bottom margins and /or image crop length requested");
return (-1);
}
if (crop_length > image->length)
crop_length = image->length;
off->crop_width = crop_width;
off->crop_length = crop_length;
return (0);
} /* end computeInputPixelOffsets */
/*
* Translate crop options into pixel offsets for one or more regions of the image.
* Options are applied in this order: margins, specific width and length, zones,
* but all are optional. Margins are relative to each edge. Width, length and
* zones are relative to the specified reference edge. Zones are expressed as
* X:Y where X is the ordinal value in a set of Y equal sized portions. eg.
* 2:3 would indicate the middle third of the region qualified by margins and
* any explicit width and length specified. Regions are specified by coordinates
* of the top left and lower right corners with range 1 to width or height.
*/
static int
getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump)
{
struct offset offsets;
int i;
int32 test;
uint32 seg, total, need_buff = 0;
uint32 buffsize;
uint32 zwidth, zlength;
memset(&offsets, '\0', sizeof(struct offset));
crop->bufftotal = 0;
crop->combined_width = (uint32)0;
crop->combined_length = (uint32)0;
crop->selections = 0;
/* Compute pixel offsets if margins or fixed width or length specified */
if ((crop->crop_mode & CROP_MARGINS) ||
(crop->crop_mode & CROP_REGIONS) ||
(crop->crop_mode & CROP_LENGTH) ||
(crop->crop_mode & CROP_WIDTH))
{
if (computeInputPixelOffsets(crop, image, &offsets))
{
TIFFError ("getCropOffsets", "Unable to compute crop margins");
return (-1);
}
need_buff = TRUE;
crop->selections = crop->regions;
/* Regions are only calculated from top and left edges with no margins */
if (crop->crop_mode & CROP_REGIONS)
return (0);
}
else
{ /* cropped area is the full image */
offsets.tmargin = 0;
offsets.lmargin = 0;
offsets.bmargin = 0;
offsets.rmargin = 0;
offsets.crop_width = image->width;
offsets.crop_length = image->length;
offsets.startx = 0;
offsets.endx = image->width - 1;
offsets.starty = 0;
offsets.endy = image->length - 1;
need_buff = FALSE;
}
if (dump->outfile != NULL)
{
dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d",
offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin);
dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d",
offsets.crop_width, offsets.crop_length);
}
if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */
{
if (need_buff == FALSE) /* No margins or fixed width or length areas */
{
crop->selections = 0;
crop->combined_width = image->width;
crop->combined_length = image->length;
return (0);
}
else
{
/* Use one region for margins and fixed width or length areas
* even though it was not formally declared as a region.
*/
crop->selections = 1;
crop->zones = 1;
crop->zonelist[0].total = 1;
crop->zonelist[0].position = 1;
}
}
else
crop->selections = crop->zones;
for (i = 0; i < crop->zones; i++)
{
seg = crop->zonelist[i].position;
total = crop->zonelist[i].total;
switch (crop->edge_ref)
{
case EDGE_LEFT: /* zones from left to right, length from top */
zlength = offsets.crop_length;
crop->regionlist[i].y1 = offsets.starty;
crop->regionlist[i].y2 = offsets.endy;
crop->regionlist[i].x1 = offsets.startx +
(uint32)(offsets.crop_width * 1.0 * (seg - 1) / total);
test = (int32)offsets.startx +
(int32)(offsets.crop_width * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].x2 = 0;
else
{
if (test > (int32)(image->width - 1))
crop->regionlist[i].x2 = image->width - 1;
else
crop->regionlist[i].x2 = test - 1;
}
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
crop->combined_length = (uint32)zlength;
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_width += (uint32)zwidth;
else
crop->combined_width = (uint32)zwidth;
break;
case EDGE_BOTTOM: /* width from left, zones from bottom to top */
zwidth = offsets.crop_width;
crop->regionlist[i].x1 = offsets.startx;
crop->regionlist[i].x2 = offsets.endx;
test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].y1 = 0;
else
crop->regionlist[i].y1 = test + 1;
test = offsets.endy - (offsets.crop_length * 1.0 * (seg - 1) / total);
if (test < 1 )
crop->regionlist[i].y2 = 0;
else
{
if (test > (int32)(image->length - 1))
crop->regionlist[i].y2 = image->length - 1;
else
crop->regionlist[i].y2 = test;
}
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_length += (uint32)zlength;
else
crop->combined_length = (uint32)zlength;
crop->combined_width = (uint32)zwidth;
break;
case EDGE_RIGHT: /* zones from right to left, length from top */
zlength = offsets.crop_length;
crop->regionlist[i].y1 = offsets.starty;
crop->regionlist[i].y2 = offsets.endy;
crop->regionlist[i].x1 = offsets.startx +
(uint32)(offsets.crop_width * (total - seg) * 1.0 / total);
test = offsets.startx +
(offsets.crop_width * (total - seg + 1) * 1.0 / total);
if (test < 1 )
crop->regionlist[i].x2 = 0;
else
{
if (test > (int32)(image->width - 1))
crop->regionlist[i].x2 = image->width - 1;
else
crop->regionlist[i].x2 = test - 1;
}
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
crop->combined_length = (uint32)zlength;
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_width += (uint32)zwidth;
else
crop->combined_width = (uint32)zwidth;
break;
case EDGE_TOP: /* width from left, zones from top to bottom */
default:
zwidth = offsets.crop_width;
crop->regionlist[i].x1 = offsets.startx;
crop->regionlist[i].x2 = offsets.endx;
crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total);
test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].y2 = 0;
else
{
if (test > (int32)(image->length - 1))
crop->regionlist[i].y2 = image->length - 1;
else
crop->regionlist[i].y2 = test - 1;
}
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_length += (uint32)zlength;
else
crop->combined_length = (uint32)zlength;
crop->combined_width = (uint32)zwidth;
break;
} /* end switch statement */
buffsize = (uint32)
((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1));
crop->regionlist[i].width = (uint32) zwidth;
crop->regionlist[i].length = (uint32) zlength;
crop->regionlist[i].buffsize = buffsize;
crop->bufftotal += buffsize;
if (dump->outfile != NULL)
dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d",
i + 1, (uint32)zwidth, (uint32)zlength,
crop->regionlist[i].x1, crop->regionlist[i].x2,
crop->regionlist[i].y1, crop->regionlist[i].y2);
}
return (0);
} /* end getCropOffsets */
static int
computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image,
struct pagedef *page, struct pageseg *sections,
struct dump_opts* dump)
{
double scale;
double pwidth, plength; /* Output page width and length in user units*/
uint32 iwidth, ilength; /* Input image width and length in pixels*/
uint32 owidth, olength; /* Output image width and length in pixels*/
uint32 orows, ocols; /* rows and cols for output */
uint32 hmargin, vmargin; /* Horizontal and vertical margins */
uint32 x1, x2, y1, y2, line_bytes;
/* unsigned int orientation; */
uint32 i, j, k;
scale = 1.0;
if (page->res_unit == RESUNIT_NONE)
page->res_unit = image->res_unit;
switch (image->res_unit) {
case RESUNIT_CENTIMETER:
if (page->res_unit == RESUNIT_INCH)
scale = 1.0/2.54;
break;
case RESUNIT_INCH:
if (page->res_unit == RESUNIT_CENTIMETER)
scale = 2.54;
break;
case RESUNIT_NONE: /* Dimensions in pixels */
default:
break;
}
/* get width, height, resolutions of input image selection */
if (crop->combined_width > 0)
iwidth = crop->combined_width;
else
iwidth = image->width;
if (crop->combined_length > 0)
ilength = crop->combined_length;
else
ilength = image->length;
if (page->hres <= 1.0)
page->hres = image->xres;
if (page->vres <= 1.0)
page->vres = image->yres;
if ((page->hres < 1.0) || (page->vres < 1.0))
{
TIFFError("computeOutputPixelOffsets",
"Invalid horizontal or vertical resolution specified or read from input image");
return (1);
}
/* If no page sizes are being specified, we just use the input image size to
* calculate maximum margins that can be taken from image.
*/
if (page->width <= 0)
pwidth = iwidth;
else
pwidth = page->width;
if (page->length <= 0)
plength = ilength;
else
plength = page->length;
if (dump->debug)
{
TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, "
"Hmargin: %3.2f, Vmargin: %3.2f",
page->name, page->vres, page->hres,
page->hmargin, page->vmargin);
TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %3.2f, length: %3.2f",
page->res_unit, scale, pwidth, plength);
}
/* compute margins at specified unit and resolution */
if (page->mode & PAGE_MODE_MARGINS)
{
if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER)
{ /* inches or centimeters specified */
hmargin = (uint32)(page->hmargin * scale * page->hres * ((image->bps + 7)/ 8));
vmargin = (uint32)(page->vmargin * scale * page->vres * ((image->bps + 7)/ 8));
}
else
{ /* Otherwise user has specified pixels as reference unit */
hmargin = (uint32)(page->hmargin * scale * ((image->bps + 7)/ 8));
vmargin = (uint32)(page->vmargin * scale * ((image->bps + 7)/ 8));
}
if ((hmargin * 2.0) > (pwidth * page->hres))
{
TIFFError("computeOutputPixelOffsets",
"Combined left and right margins exceed page width");
hmargin = (uint32) 0;
return (-1);
}
if ((vmargin * 2.0) > (plength * page->vres))
{
TIFFError("computeOutputPixelOffsets",
"Combined top and bottom margins exceed page length");
vmargin = (uint32) 0;
return (-1);
}
}
else
{
hmargin = 0;
vmargin = 0;
}
if (page->mode & PAGE_MODE_ROWSCOLS )
{
/* Maybe someday but not for now */
if (page->mode & PAGE_MODE_MARGINS)
TIFFError("computeOutputPixelOffsets",
"Output margins cannot be specified with rows and columns");
owidth = TIFFhowmany(iwidth, page->cols);
olength = TIFFhowmany(ilength, page->rows);
}
else
{
if (page->mode & PAGE_MODE_PAPERSIZE )
{
owidth = (uint32)((pwidth * page->hres) - (hmargin * 2));
olength = (uint32)((plength * page->vres) - (vmargin * 2));
}
else
{
owidth = (uint32)(iwidth - (hmargin * 2 * page->hres));
olength = (uint32)(ilength - (vmargin * 2 * page->vres));
}
}
if (owidth > iwidth)
owidth = iwidth;
if (olength > ilength)
olength = ilength;
/* Compute the number of pages required for Portrait or Landscape */
switch (page->orient)
{
case ORIENTATION_NONE:
case ORIENTATION_PORTRAIT:
ocols = TIFFhowmany(iwidth, owidth);
orows = TIFFhowmany(ilength, olength);
/* orientation = ORIENTATION_PORTRAIT; */
break;
case ORIENTATION_LANDSCAPE:
ocols = TIFFhowmany(iwidth, olength);
orows = TIFFhowmany(ilength, owidth);
x1 = olength;
olength = owidth;
owidth = x1;
/* orientation = ORIENTATION_LANDSCAPE; */
break;
case ORIENTATION_AUTO:
default:
x1 = TIFFhowmany(iwidth, owidth);
x2 = TIFFhowmany(ilength, olength);
y1 = TIFFhowmany(iwidth, olength);
y2 = TIFFhowmany(ilength, owidth);
if ( (x1 * x2) < (y1 * y2))
{ /* Portrait */
ocols = x1;
orows = x2;
/* orientation = ORIENTATION_PORTRAIT; */
}
else
{ /* Landscape */
ocols = y1;
orows = y2;
x1 = olength;
olength = owidth;
owidth = x1;
/* orientation = ORIENTATION_LANDSCAPE; */
}
}
if (ocols < 1)
ocols = 1;
if (orows < 1)
orows = 1;
/* If user did not specify rows and cols, set them from calcuation */
if (page->rows < 1)
page->rows = orows;
if (page->cols < 1)
page->cols = ocols;
line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp;
if ((page->rows * page->cols) > MAX_SECTIONS)
{
TIFFError("computeOutputPixelOffsets",
"Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections");
return (-1);
}
/* build the list of offsets for each output section */
for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++)
{
y1 = (uint32)(olength * i);
y2 = (uint32)(olength * (i + 1) - 1);
if (y2 >= ilength)
y2 = ilength - 1;
for (j = 0; j < ocols; j++, k++)
{
x1 = (uint32)(owidth * j);
x2 = (uint32)(owidth * (j + 1) - 1);
if (x2 >= iwidth)
x2 = iwidth - 1;
sections[k].x1 = x1;
sections[k].x2 = x2;
sections[k].y1 = y1;
sections[k].y2 = y2;
sections[k].buffsize = line_bytes * olength;
sections[k].position = k + 1;
sections[k].total = orows * ocols;
}
}
return (0);
} /* end computeOutputPixelOffsets */
static int
loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr)
{
uint32 i;
float xres = 0.0, yres = 0.0;
uint32 nstrips = 0, ntiles = 0;
uint16 planar = 0;
uint16 bps = 0, spp = 0, res_unit = 0;
uint16 orientation = 0;
uint16 input_compression = 0, input_photometric = 0;
uint16 subsampling_horiz, subsampling_vert;
uint32 width = 0, length = 0;
uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0;
uint32 tw = 0, tl = 0; /* Tile width and length */
uint32 tile_rowsize = 0;
unsigned char *read_buff = NULL;
unsigned char *new_buff = NULL;
int readunit = 0;
static uint32 prev_readsize = 0;
TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp);
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric))
TIFFError("loadImage","Image lacks Photometric interpreation tag");
if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width))
TIFFError("loadimage","Image lacks image width tag");
if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length))
TIFFError("loadimage","Image lacks image length tag");
TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres);
TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres);
if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit))
res_unit = RESUNIT_INCH;
if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression))
input_compression = COMPRESSION_NONE;
#ifdef DEBUG2
char compressionid[16];
switch (input_compression)
{
case COMPRESSION_NONE: /* 1 dump mode */
strcpy (compressionid, "None/dump");
break;
case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */
strcpy (compressionid, "Huffman RLE");
break;
case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */
strcpy (compressionid, "Group3 Fax");
break;
case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */
strcpy (compressionid, "Group4 Fax");
break;
case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */
strcpy (compressionid, "LZW");
break;
case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */
strcpy (compressionid, "Old Jpeg");
break;
case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */
strcpy (compressionid, "New Jpeg");
break;
case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */
strcpy (compressionid, "Next RLE");
break;
case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */
strcpy (compressionid, "CITTRLEW");
break;
case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */
strcpy (compressionid, "Mac Packbits");
break;
case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */
strcpy (compressionid, "Thunderscan");
break;
case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */
strcpy (compressionid, "IT8 padded");
break;
case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */
strcpy (compressionid, "IT8 RLE");
break;
case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */
strcpy (compressionid, "IT8 mono");
break;
case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */
strcpy (compressionid, "IT8 lineart");
break;
case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */
strcpy (compressionid, "Pixar 10 bit");
break;
case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */
strcpy (compressionid, "Pixar 11bit");
break;
case COMPRESSION_DEFLATE: /* 32946 Deflate compression */
strcpy (compressionid, "Deflate");
break;
case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */
strcpy (compressionid, "Adobe deflate");
break;
default:
strcpy (compressionid, "None/unknown");
break;
}
TIFFError("loadImage", "Input compression %s", compressionid);
#endif
scanlinesize = TIFFScanlineSize(in);
image->bps = bps;
image->spp = spp;
image->planar = planar;
image->width = width;
image->length = length;
image->xres = xres;
image->yres = yres;
image->res_unit = res_unit;
image->compression = input_compression;
image->photometric = input_photometric;
#ifdef DEBUG2
char photometricid[12];
switch (input_photometric)
{
case PHOTOMETRIC_MINISWHITE:
strcpy (photometricid, "MinIsWhite");
break;
case PHOTOMETRIC_MINISBLACK:
strcpy (photometricid, "MinIsBlack");
break;
case PHOTOMETRIC_RGB:
strcpy (photometricid, "RGB");
break;
case PHOTOMETRIC_PALETTE:
strcpy (photometricid, "Palette");
break;
case PHOTOMETRIC_MASK:
strcpy (photometricid, "Mask");
break;
case PHOTOMETRIC_SEPARATED:
strcpy (photometricid, "Separated");
break;
case PHOTOMETRIC_YCBCR:
strcpy (photometricid, "YCBCR");
break;
case PHOTOMETRIC_CIELAB:
strcpy (photometricid, "CIELab");
break;
case PHOTOMETRIC_ICCLAB:
strcpy (photometricid, "ICCLab");
break;
case PHOTOMETRIC_ITULAB:
strcpy (photometricid, "ITULab");
break;
case PHOTOMETRIC_LOGL:
strcpy (photometricid, "LogL");
break;
case PHOTOMETRIC_LOGLUV:
strcpy (photometricid, "LOGLuv");
break;
default:
strcpy (photometricid, "Unknown");
break;
}
TIFFError("loadImage", "Input photometric interpretation %s", photometricid);
#endif
image->orientation = orientation;
switch (orientation)
{
case 0:
case ORIENTATION_TOPLEFT:
image->adjustments = 0;
break;
case ORIENTATION_TOPRIGHT:
image->adjustments = MIRROR_HORIZ;
break;
case ORIENTATION_BOTRIGHT:
image->adjustments = ROTATECW_180;
break;
case ORIENTATION_BOTLEFT:
image->adjustments = MIRROR_VERT;
break;
case ORIENTATION_LEFTTOP:
image->adjustments = MIRROR_VERT | ROTATECW_90;
break;
case ORIENTATION_RIGHTTOP:
image->adjustments = ROTATECW_90;
break;
case ORIENTATION_RIGHTBOT:
image->adjustments = MIRROR_VERT | ROTATECW_270;
break;
case ORIENTATION_LEFTBOT:
image->adjustments = ROTATECW_270;
break;
default:
image->adjustments = 0;
image->orientation = ORIENTATION_TOPLEFT;
}
if ((bps == 0) || (spp == 0))
{
TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)",
spp, bps);
return (-1);
}
if (TIFFIsTiled(in))
{
readunit = TILE;
tlsize = TIFFTileSize(in);
ntiles = TIFFNumberOfTiles(in);
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
tile_rowsize = TIFFTileRowSize(in);
if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0)
{
TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero.");
exit(-1);
}
buffsize = tlsize * ntiles;
if (tlsize != (buffsize / ntiles))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
if (buffsize < (uint32)(ntiles * tl * tile_rowsize))
{
buffsize = ntiles * tl * tile_rowsize;
if (ntiles != (buffsize / tl / tile_rowsize))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
#ifdef DEBUG2
TIFFError("loadImage",
"Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu",
tlsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Tilesize: %u, Number of Tiles: %u, Tile row size: %u",
tlsize, ntiles, tile_rowsize);
}
else
{
uint32 buffsize_check;
readunit = STRIP;
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
stsize = TIFFStripSize(in);
nstrips = TIFFNumberOfStrips(in);
if (nstrips == 0 || stsize == 0)
{
TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero.");
exit(-1);
}
buffsize = stsize * nstrips;
if (stsize != (buffsize / nstrips))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
buffsize_check = ((length * width * spp * bps) + 7);
if (length != ((buffsize_check - 7) / width / spp / bps))
{
TIFFError("loadImage", "Integer overflow detected.");
exit(-1);
}
if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8))
{
buffsize = ((length * width * spp * bps) + 7) / 8;
#ifdef DEBUG2
TIFFError("loadImage",
"Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu",
stsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u",
stsize, nstrips, rowsperstrip, scanlinesize);
}
if (input_compression == COMPRESSION_JPEG)
{ /* Force conversion to RGB */
jpegcolormode = JPEGCOLORMODE_RGB;
TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
/* The clause up to the read statement is taken from Tom Lane's tiffcp patch */
else
{ /* Otherwise, can't handle subsampled input */
if (input_photometric == PHOTOMETRIC_YCBCR)
{
TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
&subsampling_horiz, &subsampling_vert);
if (subsampling_horiz != 1 || subsampling_vert != 1)
{
TIFFError("loadImage",
"Can't copy/convert subsampled image with subsampling %d horiz %d vert",
subsampling_horiz, subsampling_vert);
return (-1);
}
}
}
read_buff = *read_ptr;
/* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */
/* outside buffer */
if (!read_buff)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff = (unsigned char *)_TIFFmalloc(buffsize+3);
}
else
{
if (prev_readsize < buffsize)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
new_buff = _TIFFrealloc(read_buff, buffsize+3);
if (!new_buff)
{
free (read_buff);
read_buff = (unsigned char *)_TIFFmalloc(buffsize+3);
}
else
read_buff = new_buff;
}
}
if (!read_buff)
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff[buffsize] = 0;
read_buff[buffsize+1] = 0;
read_buff[buffsize+2] = 0;
prev_readsize = buffsize;
*read_ptr = read_buff;
/* N.B. The read functions used copy separate plane data into a buffer as interleaved
* samples rather than separate planes so the same logic works to extract regions
* regardless of the way the data are organized in the input file.
*/
switch (readunit) {
case STRIP:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigStripsIntoBuffer(in, read_buff)))
{
TIFFError("loadImage", "Unable to read contiguous strips into buffer");
return (-1);
}
}
else
{
if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump)))
{
TIFFError("loadImage", "Unable to read separate strips into buffer");
return (-1);
}
}
break;
case TILE:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read contiguous tiles into buffer");
return (-1);
}
}
else
{
if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read separate tiles into buffer");
return (-1);
}
}
break;
default: TIFFError("loadImage", "Unsupported image file format");
return (-1);
break;
}
if ((dump->infile != NULL) && (dump->level == 2))
{
dump_info (dump->infile, dump->format, "loadImage",
"Image width %d, length %d, Raw image data, %4d bytes",
width, length, buffsize);
dump_info (dump->infile, dump->format, "",
"Bits per sample %d, Samples per pixel %d", bps, spp);
for (i = 0; i < length; i++)
dump_buffer(dump->infile, dump->format, 1, scanlinesize,
i, read_buff + (i * scanlinesize));
}
return (0);
} /* end loadImage */
static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr)
{
uint16 mirror, rotation;
unsigned char *work_buff;
work_buff = *work_buff_ptr;
if ((image == NULL) || (work_buff == NULL))
{
TIFFError ("correct_orientatin", "Invalid image or buffer pointer");
return (-1);
}
if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT))
{
mirror = (uint16)(image->adjustments & MIRROR_BOTH);
if (mirrorImage(image->spp, image->bps, mirror,
image->width, image->length, work_buff))
{
TIFFError ("correct_orientation", "Unable to mirror image");
return (-1);
}
}
if (image->adjustments & ROTATE_ANY)
{
if (image->adjustments & ROTATECW_90)
rotation = (uint16) 90;
else
if (image->adjustments & ROTATECW_180)
rotation = (uint16) 180;
else
if (image->adjustments & ROTATECW_270)
rotation = (uint16) 270;
else
{
TIFFError ("correct_orientation", "Invalid rotation value: %d",
image->adjustments & ROTATE_ANY);
return (-1);
}
if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr))
{
TIFFError ("correct_orientation", "Unable to rotate image");
return (-1);
}
image->orientation = ORIENTATION_TOPLEFT;
}
return (0);
} /* end correct_orientation */
/* Extract multiple zones from an image and combine into a single composite image */
static int
extractCompositeRegions(struct image_data *image, struct crop_mask *crop,
unsigned char *read_buff, unsigned char *crop_buff)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 i, trailing_bits, prev_trailing_bits;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_rowsize, dst_rowsize, src_offset, dst_offset;
uint32 crop_width, crop_length, img_width /*, img_length */;
uint32 prev_length, prev_width, composite_width;
uint16 bps, spp;
uint8 *src, *dst;
tsample_t count, sample = 0; /* Update to extract one or more samples */
img_width = image->width;
/* img_length = image->length; */
bps = image->bps;
spp = image->spp;
count = spp;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
src = read_buff;
dst = crop_buff;
/* These are setup for adding additional sections */
prev_width = prev_length = 0;
prev_trailing_bits = trailing_bits = 0;
composite_width = crop->combined_width;
crop->combined_width = 0;
crop->combined_length = 0;
for (i = 0; i < crop->selections; i++)
{
/* rows, columns, width, length are expressed in pixels */
first_row = crop->regionlist[i].y1;
last_row = crop->regionlist[i].y2;
first_col = crop->regionlist[i].x1;
last_col = crop->regionlist[i].x2;
crop_width = last_col - first_col + 1;
crop_length = last_row - first_row + 1;
/* These should not be needed for composite images */
crop->regionlist[i].width = crop_width;
crop->regionlist[i].length = crop_length;
crop->regionlist[i].buffptr = crop_buff;
src_rowsize = ((img_width * bps * spp) + 7) / 8;
dst_rowsize = (((crop_width * bps * count) + 7) / 8);
switch (crop->edge_ref)
{
default:
case EDGE_TOP:
case EDGE_BOTTOM:
if ((i > 0) && (crop_width != crop->regionlist[i - 1].width))
{
TIFFError ("extractCompositeRegions",
"Only equal width regions can be combined for -E top or bottom");
return (1);
}
crop->combined_width = crop_width;
crop->combined_length += crop_length;
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset + (prev_length * dst_rowsize);
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width, sample,
spp, bps, count, first_col,
last_col + 1))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps);
return (1);
}
}
prev_length += crop_length;
break;
case EDGE_LEFT: /* splice the pieces of each row together, side by side */
case EDGE_RIGHT:
if ((i > 0) && (crop_length != crop->regionlist[i - 1].length))
{
TIFFError ("extractCompositeRegions",
"Only equal length regions can be combined for -E left or right");
return (1);
}
crop->combined_width += crop_width;
crop->combined_length = crop_length;
dst_rowsize = (((composite_width * bps * count) + 7) / 8);
trailing_bits = (crop_width * bps * count) % 8;
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset + prev_width;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps);
return (1);
}
}
prev_width += (crop_width * bps * count) / 8;
prev_trailing_bits += trailing_bits;
if (prev_trailing_bits > 7)
prev_trailing_bits-= 8;
break;
}
}
if (crop->combined_width != composite_width)
TIFFError("combineSeparateRegions","Combined width does not match composite width");
return (0);
} /* end extractCompositeRegions */
/* Copy a single region of input buffer to an output buffer.
* The read functions used copy separate plane data into a buffer
* as interleaved samples rather than separate planes so the same
* logic works to extract regions regardless of the way the data
* are organized in the input file. This function can be used to
* extract one or more samples from the input image by updating the
* parameters for starting sample and number of samples to copy in the
* fifth and eighth arguments of the call to extractContigSamples.
* They would be passed as new elements of the crop_mask struct.
*/
static int
extractSeparateRegion(struct image_data *image, struct crop_mask *crop,
unsigned char *read_buff, unsigned char *crop_buff,
int region)
{
int shift_width, prev_trailing_bits = 0;
uint32 bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, dst_rowsize;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_offset, dst_offset;
uint32 crop_width, crop_length, img_width /*, img_length */;
uint16 bps, spp;
uint8 *src, *dst;
tsample_t count, sample = 0; /* Update to extract more or more samples */
img_width = image->width;
/* img_length = image->length; */
bps = image->bps;
spp = image->spp;
count = spp;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0; /* Byte aligned data only */
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
/* rows, columns, width, length are expressed in pixels */
first_row = crop->regionlist[region].y1;
last_row = crop->regionlist[region].y2;
first_col = crop->regionlist[region].x1;
last_col = crop->regionlist[region].x2;
crop_width = last_col - first_col + 1;
crop_length = last_row - first_row + 1;
crop->regionlist[region].width = crop_width;
crop->regionlist[region].length = crop_length;
crop->regionlist[region].buffptr = crop_buff;
src = read_buff;
dst = crop_buff;
src_rowsize = ((img_width * bps * spp) + 7) / 8;
dst_rowsize = (((crop_width * bps * spp) + 7) / 8);
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width, sample,
spp, bps, count, first_col,
last_col + 1))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps);
return (1);
}
}
return (0);
} /* end extractSeparateRegion */
static int
extractImageSection(struct image_data *image, struct pageseg *section,
unsigned char *src_buff, unsigned char *sect_buff)
{
unsigned char bytebuff1, bytebuff2;
#ifdef DEVELMODE
/* unsigned char *src, *dst; */
#endif
uint32 img_width, img_rowsize;
#ifdef DEVELMODE
uint32 img_length;
#endif
uint32 j, shift1, shift2, trailing_bits;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_offset, dst_offset, row_offset, col_offset;
uint32 offset1, offset2, full_bytes;
uint32 sect_width;
#ifdef DEVELMODE
uint32 sect_length;
#endif
uint16 bps, spp;
#ifdef DEVELMODE
int k;
unsigned char bitset;
static char *bitarray = NULL;
#endif
img_width = image->width;
#ifdef DEVELMODE
img_length = image->length;
#endif
bps = image->bps;
spp = image->spp;
#ifdef DEVELMODE
/* src = src_buff; */
/* dst = sect_buff; */
#endif
src_offset = 0;
dst_offset = 0;
#ifdef DEVELMODE
if (bitarray == NULL)
{
if ((bitarray = (char *)malloc(img_width)) == NULL)
{
TIFFError ("", "DEBUG: Unable to allocate debugging bitarray");
return (-1);
}
}
#endif
/* rows, columns, width, length are expressed in pixels */
first_row = section->y1;
last_row = section->y2;
first_col = section->x1;
last_col = section->x2;
sect_width = last_col - first_col + 1;
#ifdef DEVELMODE
sect_length = last_row - first_row + 1;
#endif
img_rowsize = ((img_width * bps + 7) / 8) * spp;
full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */
trailing_bits = (sect_width * bps) % 8;
#ifdef DEVELMODE
TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n",
first_row, last_row, first_col, last_col);
TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n",
img_width, img_length, bps, spp);
TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n",
sect_width, sect_length, full_bytes, trailing_bits);
#endif
if ((bps % 8) == 0)
{
col_offset = first_col * spp * bps / 8;
for (row = first_row; row <= last_row; row++)
{
/* row_offset = row * img_width * spp * bps / 8; */
row_offset = row * img_rowsize;
src_offset = row_offset + col_offset;
#ifdef DEVELMODE
TIFFError ("", "Src offset: %8d, Dst offset: %8d", src_offset, dst_offset);
#endif
_TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes);
dst_offset += full_bytes;
}
}
else
{ /* bps != 8 */
shift1 = spp * ((first_col * bps) % 8);
shift2 = spp * ((last_col * bps) % 8);
for (row = first_row; row <= last_row; row++)
{
/* pull out the first byte */
row_offset = row * img_rowsize;
offset1 = row_offset + (first_col * bps / 8);
offset2 = row_offset + (last_col * bps / 8);
#ifdef DEVELMODE
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
sprintf(&bitarray[8], " ");
sprintf(&bitarray[9], " ");
for (j = 10, k = 7; j < 18; j++, k--)
{
bitset = *(src_buff + offset2) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[18] = '\0';
TIFFError ("", "Row: %3d Offset1: %d, Shift1: %d, Offset2: %d, Shift2: %d\n",
row, offset1, shift1, offset2, shift2);
#endif
bytebuff1 = bytebuff2 = 0;
if (shift1 == 0) /* the region is byte and sample alligned */
{
_TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes);
#ifdef DEVELMODE
TIFFError ("", " Alligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset);
sprintf(&bitarray[18], "\n");
sprintf(&bitarray[19], "\t");
for (j = 20, k = 7; j < 28; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[28] = ' ';
bitarray[29] = ' ';
#endif
dst_offset += full_bytes;
if (trailing_bits != 0)
{
bytebuff2 = src_buff[offset2] & ((unsigned char)255 << (7 - shift2));
sect_buff[dst_offset] = bytebuff2;
#ifdef DEVELMODE
TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n",
offset2, dst_offset);
for (j = 30, k = 7; j < 38; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[38] = '\0';
TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray);
#endif
dst_offset++;
}
}
else /* each destination byte will have to be built from two source bytes*/
{
#ifdef DEVELMODE
TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset);
#endif
for (j = 0; j <= full_bytes; j++)
{
bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1);
bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (7 - shift1));
sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1));
}
#ifdef DEVELMODE
sprintf(&bitarray[18], "\n");
sprintf(&bitarray[19], "\t");
for (j = 20, k = 7; j < 28; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[28] = ' ';
bitarray[29] = ' ';
#endif
dst_offset += full_bytes;
if (trailing_bits != 0)
{
#ifdef DEVELMODE
TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset1 + full_bytes, dst_offset);
#endif
if (shift2 > shift1)
{
bytebuff1 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (7 - shift2));
bytebuff2 = bytebuff1 & ((unsigned char)255 << shift1);
sect_buff[dst_offset] = bytebuff2;
#ifdef DEVELMODE
TIFFError ("", " Shift2 > Shift1\n");
#endif
}
else
{
if (shift2 < shift1)
{
bytebuff2 = ((unsigned char)255 << (shift1 - shift2 - 1));
sect_buff[dst_offset] &= bytebuff2;
#ifdef DEVELMODE
TIFFError ("", " Shift2 < Shift1\n");
#endif
}
#ifdef DEVELMODE
else
TIFFError ("", " Shift2 == Shift1\n");
#endif
}
}
#ifdef DEVELMODE
sprintf(&bitarray[28], " ");
sprintf(&bitarray[29], " ");
for (j = 30, k = 7; j < 38; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[38] = '\0';
TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray);
#endif
dst_offset++;
}
}
}
return (0);
} /* end extractImageSection */
static int
writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop,
struct image_data *image, struct dump_opts *dump,
struct buffinfo seg_buffs[], char *mp, char *filename,
unsigned int *page, unsigned int total_pages)
{
int i, page_count;
int autoindex = 0;
unsigned char *crop_buff = NULL;
/* Where we open a new file depends on the export mode */
switch (crop->exp_mode)
{
case ONE_FILE_COMPOSITE: /* Regions combined into single image */
autoindex = 0;
crop_buff = seg_buffs[0].buffer;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
page_count = total_pages;
if (writeCroppedImage(in, *out, image, dump,
crop->combined_width,
crop->combined_length,
crop_buff, *page, total_pages))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
break;
case ONE_FILE_SEPARATED: /* Regions as separated images */
autoindex = 0;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
page_count = crop->selections * total_pages;
for (i = 0; i < crop->selections; i++)
{
crop_buff = seg_buffs[i].buffer;
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */
autoindex = 1;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
crop_buff = seg_buffs[0].buffer;
if (writeCroppedImage(in, *out, image, dump,
crop->combined_width,
crop->combined_length,
crop_buff, *page, total_pages))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
break;
case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */
autoindex = 1;
page_count = crop->selections;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
for (i = 0; i < crop->selections; i++)
{
crop_buff = seg_buffs[i].buffer;
/* Write the current region to the current file */
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
case FILE_PER_SELECTION:
autoindex = 1;
page_count = 1;
for (i = 0; i < crop->selections; i++)
{
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
crop_buff = seg_buffs[i].buffer;
/* Write the current region to the current file */
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
default: return (1);
}
return (0);
} /* end writeRegions */
static int
writeImageSections(TIFF *in, TIFF *out, struct image_data *image,
struct pagedef *page, struct pageseg *sections,
struct dump_opts * dump, unsigned char *src_buff,
unsigned char **sect_buff_ptr)
{
double hres, vres;
uint32 i, k, width, length, sectsize;
unsigned char *sect_buff = *sect_buff_ptr;
hres = page->hres;
vres = page->vres;
k = page->cols * page->rows;
if ((k < 1) || (k > MAX_SECTIONS))
{
TIFFError("writeImageSections",
"%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k);
return (-1);
}
for (i = 0; i < k; i++)
{
width = sections[i].x2 - sections[i].x1 + 1;
length = sections[i].y2 - sections[i].y1 + 1;
sectsize = (uint32)
ceil((width * image->bps + 7) / (double)8) * image->spp * length;
/* allocate a buffer if we don't have one already */
if (createImageSection(sectsize, sect_buff_ptr))
{
TIFFError("writeImageSections", "Unable to allocate section buffer");
exit (-1);
}
sect_buff = *sect_buff_ptr;
if (extractImageSection (image, §ions[i], src_buff, sect_buff))
{
TIFFError("writeImageSections", "Unable to extract image sections");
exit (-1);
}
/* call the write routine here instead of outside the loop */
if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff))
{
TIFFError("writeImageSections", "Unable to write image section");
exit (-1);
}
}
return (0);
} /* end writeImageSections */
/* Code in this function is heavily indebted to code in tiffcp
* with modifications by Richard Nolde to handle orientation correctly.
* It will have to be updated significantly if support is added to
* extract one or more samples from original image since the
* original code assumes we are always copying all samples.
*/
static int
writeSingleSection(TIFF *in, TIFF *out, struct image_data *image,
struct dump_opts *dump, uint32 width, uint32 length,
double hres, double vres,
unsigned char *sect_buff)
{
uint16 bps, spp;
uint16 input_compression, input_photometric;
uint16 input_planar;
struct cpTag* p;
/* Calling this seems to reset the compression mode on the TIFF *in file.
TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode);
*/
input_compression = image->compression;
input_photometric = image->photometric;
spp = image->spp;
bps = image->bps;
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
#ifdef DEBUG2
TIFFError("writeSingleSection", "Input compression: %s",
(input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" :
((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg"));
#endif
/* This is the global variable compression which is set
* if the user has specified a command line option for
* a compression option. Should be passed around in one
* of the parameters instead of as a global. If no user
* option specified it will still be (uint16) -1. */
if (compression != (uint16)-1)
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
{ /* OJPEG is no longer supported for writing so upgrade to JPEG */
if (input_compression == COMPRESSION_OJPEG)
{
compression = COMPRESSION_JPEG;
jpegcolormode = JPEGCOLORMODE_RAW;
TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
}
else /* Use the compression from the input file */
CopyField(TIFFTAG_COMPRESSION, compression);
}
if (compression == COMPRESSION_JPEG)
{
if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */
(input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */
{
TIFFError ("writeSingleSection",
"JPEG compression cannot be used with %s image data",
(input_photometric == PHOTOMETRIC_PALETTE) ?
"palette" : "mask");
return (-1);
}
if ((input_photometric == PHOTOMETRIC_RGB) &&
(jpegcolormode == JPEGCOLORMODE_RGB))
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
}
else
{
if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24)
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
}
#ifdef DEBUG2
TIFFError("writeSingleSection", "Input photometric: %s",
(input_photometric == PHOTOMETRIC_RGB) ? "RGB" :
((input_photometric == PHOTOMETRIC_YCBCR) ? "YCbCr" : "Not RGB or YCbCr"));
#endif
if (((input_photometric == PHOTOMETRIC_LOGL) ||
(input_photometric == PHOTOMETRIC_LOGLUV)) &&
((compression != COMPRESSION_SGILOG) &&
(compression != COMPRESSION_SGILOG24)))
{
TIFFError("writeSingleSection",
"LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression");
return (-1);
}
if (fillorder != 0)
TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
else
CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
/* The loadimage function reads input orientation and sets
* image->orientation. The correct_image_orientation function
* applies the required rotation and mirror operations to
* present the data in TOPLEFT orientation and updates
* image->orientation if any transforms are performed,
* as per EXIF standard.
*/
TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
/*
* Choose tiles/strip for the output image according to
* the command line arguments (-tiles, -strips) and the
* structure of the input image.
*/
if (outtiled == -1)
outtiled = TIFFIsTiled(in);
if (outtiled) {
/*
* Setup output file's tile width&height. If either
* is not specified, use either the value from the
* input image or, if nothing is defined, use the
* library default.
*/
if (tilewidth == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
if (tilelength == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
if (tilewidth == 0 || tilelength == 0)
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
} else {
/*
* RowsPerStrip is left unspecified: use either the
* value from the input image or, if nothing is defined,
* use the library default.
*/
if (rowsperstrip == (uint32) 0)
{
if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
if (compression != COMPRESSION_JPEG)
{
if (rowsperstrip > length)
rowsperstrip = length;
}
}
else
if (rowsperstrip == (uint32) -1)
rowsperstrip = length;
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
}
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
if (config != (uint16) -1)
TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
else
CopyField(TIFFTAG_PLANARCONFIG, config);
if (spp <= 4)
CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
/* SMinSampleValue & SMaxSampleValue */
switch (compression) {
/* These are references to GLOBAL variables set by defaults
* and /or the compression flag
*/
case COMPRESSION_JPEG:
if (((bps % 8) == 0) || ((bps % 12) == 0))
{
TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
else
{
TIFFError("writeSingleSection",
"JPEG compression requires 8 or 12 bits per sample");
return (-1);
}
break;
case COMPRESSION_LZW:
case COMPRESSION_ADOBE_DEFLATE:
case COMPRESSION_DEFLATE:
if (predictor != (uint16)-1)
TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
else
CopyField(TIFFTAG_PREDICTOR, predictor);
break;
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
if (compression == COMPRESSION_CCITTFAX3) {
if (g3opts != (uint32) -1)
TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
else
CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
} else {
CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
}
CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
break;
}
{ uint32 len32;
void** data;
if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
}
{ uint16 ninks;
const char* inknames;
if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
int inknameslen = strlen(inknames) + 1;
const char* cp = inknames;
while (ninks > 1) {
cp = strchr(cp, '\0');
if (cp) {
cp++;
inknameslen += (strlen(cp) + 1);
}
ninks--;
}
TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
}
}
}
{
unsigned short pg0, pg1;
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
if (pageNum < 0) /* only one input file */
TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
else
TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
}
}
for (p = tags; p < &tags[NTAGS]; p++)
CopyTag(p->tag, p->count, p->type);
/* Update these since they are overwritten from input res by loop above */
TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres);
TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres);
/* Compute the tile or strip dimensions and write to disk */
if (outtiled)
{
if (config == PLANARCONFIG_CONTIG)
writeBufferToContigTiles (out, sect_buff, length, width, spp, dump);
else
writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump);
}
else
{
if (config == PLANARCONFIG_CONTIG)
writeBufferToContigStrips (out, sect_buff, length);
else
writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump);
}
if (!TIFFWriteDirectory(out))
{
TIFFClose(out);
return (-1);
}
return (0);
} /* end writeSingleSection */
/* Create a buffer to write one section at a time */
static int
createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr)
{
unsigned char *sect_buff = NULL;
unsigned char *new_buff = NULL;
static uint32 prev_sectsize = 0;
sect_buff = *sect_buff_ptr;
if (!sect_buff)
{
sect_buff = (unsigned char *)_TIFFmalloc(sectsize);
*sect_buff_ptr = sect_buff;
_TIFFmemset(sect_buff, 0, sectsize);
}
else
{
if (prev_sectsize < sectsize)
{
new_buff = _TIFFrealloc(sect_buff, sectsize);
if (!new_buff)
{
free (sect_buff);
sect_buff = (unsigned char *)_TIFFmalloc(sectsize);
}
else
sect_buff = new_buff;
_TIFFmemset(sect_buff, 0, sectsize);
}
}
if (!sect_buff)
{
TIFFError("createImageSection", "Unable to allocate/reallocate section buffer");
return (-1);
}
prev_sectsize = sectsize;
*sect_buff_ptr = sect_buff;
return (0);
} /* end createImageSection */
/* Process selections defined by regions, zones, margins, or fixed sized areas */
static int
processCropSelections(struct image_data *image, struct crop_mask *crop,
unsigned char **read_buff_ptr, struct buffinfo seg_buffs[])
{
int i;
uint32 width, length, total_width, total_length;
tsize_t cropsize;
unsigned char *crop_buff = NULL;
unsigned char *read_buff = NULL;
unsigned char *next_buff = NULL;
tsize_t prev_cropsize = 0;
read_buff = *read_buff_ptr;
if (crop->img_mode == COMPOSITE_IMAGES)
{
cropsize = crop->bufftotal;
crop_buff = seg_buffs[0].buffer;
if (!crop_buff)
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
else
{
prev_cropsize = seg_buffs[0].size;
if (prev_cropsize < cropsize)
{
next_buff = _TIFFrealloc(crop_buff, cropsize);
if (! next_buff)
{
_TIFFfree (crop_buff);
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
}
else
crop_buff = next_buff;
}
}
if (!crop_buff)
{
TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer");
return (-1);
}
_TIFFmemset(crop_buff, 0, cropsize);
seg_buffs[0].buffer = crop_buff;
seg_buffs[0].size = cropsize;
/* Checks for matching width or length as required */
if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0)
return (1);
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("processCropSelections",
"Failed to invert colorspace for composite regions");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
/* Mirror and Rotate will not work with multiple regions unless they are the same width */
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("processCropSelections", "Failed to mirror composite regions %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->combined_width,
&crop->combined_length, &crop_buff))
{
TIFFError("processCropSelections",
"Failed to rotate composite regions by %d degrees", crop->rotation);
return (-1);
}
seg_buffs[0].buffer = crop_buff;
seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8)
* image->spp) * crop->combined_length;
}
}
else /* Separated Images */
{
total_width = total_length = 0;
for (i = 0; i < crop->selections; i++)
{
cropsize = crop->bufftotal;
crop_buff = seg_buffs[i].buffer;
if (!crop_buff)
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
else
{
prev_cropsize = seg_buffs[0].size;
if (prev_cropsize < cropsize)
{
next_buff = _TIFFrealloc(crop_buff, cropsize);
if (! next_buff)
{
_TIFFfree (crop_buff);
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
}
else
crop_buff = next_buff;
}
}
if (!crop_buff)
{
TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer");
return (-1);
}
_TIFFmemset(crop_buff, 0, cropsize);
seg_buffs[i].buffer = crop_buff;
seg_buffs[i].size = cropsize;
if (extractSeparateRegion(image, crop, read_buff, crop_buff, i))
{
TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i);
return (-1);
}
width = crop->regionlist[i].width;
length = crop->regionlist[i].length;
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
width, length, crop_buff))
{
TIFFError("processCropSelections",
"Failed to invert colorspace for region");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
width, length, crop_buff))
{
TIFFError("processCropSelections", "Failed to mirror crop region %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->regionlist[i].width,
&crop->regionlist[i].length, &crop_buff))
{
TIFFError("processCropSelections",
"Failed to rotate crop region by %d degrees", crop->rotation);
return (-1);
}
total_width += crop->regionlist[i].width;
total_length += crop->regionlist[i].length;
crop->combined_width = total_width;
crop->combined_length = total_length;
seg_buffs[i].buffer = crop_buff;
seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8)
* image->spp) * crop->regionlist[i].length;
}
}
}
return (0);
} /* end processCropSelections */
/* Copy the crop section of the data from the current image into a buffer
* and adjust the IFD values to reflect the new size. If no cropping is
* required, use the origial read buffer as the crop buffer.
*
* There is quite a bit of redundancy between this routine and the more
* specialized processCropSelections, but this provides
* the most optimized path when no Zones or Regions are required.
*/
static int
createCroppedImage(struct image_data *image, struct crop_mask *crop,
unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr)
{
tsize_t cropsize;
unsigned char *read_buff = NULL;
unsigned char *crop_buff = NULL;
unsigned char *new_buff = NULL;
static tsize_t prev_cropsize = 0;
read_buff = *read_buff_ptr;
/* process full image, no crop buffer needed */
crop_buff = read_buff;
*crop_buff_ptr = read_buff;
crop->combined_width = image->width;
crop->combined_length = image->length;
cropsize = crop->bufftotal;
crop_buff = *crop_buff_ptr;
if (!crop_buff)
{
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
*crop_buff_ptr = crop_buff;
_TIFFmemset(crop_buff, 0, cropsize);
prev_cropsize = cropsize;
}
else
{
if (prev_cropsize < cropsize)
{
new_buff = _TIFFrealloc(crop_buff, cropsize);
if (!new_buff)
{
free (crop_buff);
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
}
else
crop_buff = new_buff;
_TIFFmemset(crop_buff, 0, cropsize);
}
}
if (!crop_buff)
{
TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer");
return (-1);
}
*crop_buff_ptr = crop_buff;
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("createCroppedImage",
"Failed to invert colorspace for image or cropped selection");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->combined_width,
&crop->combined_length, crop_buff_ptr))
{
TIFFError("createCroppedImage",
"Failed to rotate image or cropped selection by %d degrees", crop->rotation);
return (-1);
}
}
if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */
*read_buff_ptr = NULL; /* so we don't try to free it later */
return (0);
} /* end createCroppedImage */
/* Code in this function is heavily indebted to code in tiffcp
* with modifications by Richard Nolde to handle orientation correctly.
* It will have to be updated significantly if support is added to
* extract one or more samples from original image since the
* original code assumes we are always copying all samples.
* Use of global variables for config, compression and others
* should be replaced by addition to the crop_mask struct (which
* will be renamed to proc_opts indicating that is controlls
* user supplied processing options, not just cropping) and
* then passed in as an argument.
*/
static int
writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image,
struct dump_opts *dump, uint32 width, uint32 length,
unsigned char *crop_buff, int pagenum, int total_pages)
{
uint16 bps, spp;
uint16 input_compression, input_photometric;
uint16 input_planar;
struct cpTag* p;
input_compression = image->compression;
input_photometric = image->photometric;
spp = image->spp;
bps = image->bps;
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
#ifdef DEBUG2
TIFFError("writeCroppedImage", "Input compression: %s",
(input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" :
((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg"));
#endif
if (compression != (uint16)-1)
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
{
if (input_compression == COMPRESSION_OJPEG)
{
compression = COMPRESSION_JPEG;
jpegcolormode = JPEGCOLORMODE_RAW;
TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
}
else
CopyField(TIFFTAG_COMPRESSION, compression);
}
if (compression == COMPRESSION_JPEG)
{
if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */
(input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */
{
TIFFError ("writeCroppedImage",
"JPEG compression cannot be used with %s image data",
(input_photometric == PHOTOMETRIC_PALETTE) ?
"palette" : "mask");
return (-1);
}
if ((input_photometric == PHOTOMETRIC_RGB) &&
(jpegcolormode == JPEGCOLORMODE_RGB))
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
}
else
{
if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24)
{
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
}
else
{
if (input_compression == COMPRESSION_SGILOG ||
input_compression == COMPRESSION_SGILOG24)
{
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
}
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
}
}
if (((input_photometric == PHOTOMETRIC_LOGL) ||
(input_photometric == PHOTOMETRIC_LOGLUV)) &&
((compression != COMPRESSION_SGILOG) &&
(compression != COMPRESSION_SGILOG24)))
{
TIFFError("writeCroppedImage",
"LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression");
return (-1);
}
if (fillorder != 0)
TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
else
CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
/* The loadimage function reads input orientation and sets
* image->orientation. The correct_image_orientation function
* applies the required rotation and mirror operations to
* present the data in TOPLEFT orientation and updates
* image->orientation if any transforms are performed,
* as per EXIF standard.
*/
TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
/*
* Choose tiles/strip for the output image according to
* the command line arguments (-tiles, -strips) and the
* structure of the input image.
*/
if (outtiled == -1)
outtiled = TIFFIsTiled(in);
if (outtiled) {
/*
* Setup output file's tile width&height. If either
* is not specified, use either the value from the
* input image or, if nothing is defined, use the
* library default.
*/
if (tilewidth == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
if (tilelength == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
if (tilewidth == 0 || tilelength == 0)
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
} else {
/*
* RowsPerStrip is left unspecified: use either the
* value from the input image or, if nothing is defined,
* use the library default.
*/
if (rowsperstrip == (uint32) 0)
{
if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
if (compression != COMPRESSION_JPEG)
{
if (rowsperstrip > length)
rowsperstrip = length;
}
}
else
if (rowsperstrip == (uint32) -1)
rowsperstrip = length;
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
}
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
if (config != (uint16) -1)
TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
else
CopyField(TIFFTAG_PLANARCONFIG, config);
if (spp <= 4)
CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
/* SMinSampleValue & SMaxSampleValue */
switch (compression) {
case COMPRESSION_JPEG:
if (((bps % 8) == 0) || ((bps % 12) == 0))
{
TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
else
{
TIFFError("writeCroppedImage",
"JPEG compression requires 8 or 12 bits per sample");
return (-1);
}
break;
case COMPRESSION_LZW:
case COMPRESSION_ADOBE_DEFLATE:
case COMPRESSION_DEFLATE:
if (predictor != (uint16)-1)
TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
else
CopyField(TIFFTAG_PREDICTOR, predictor);
break;
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
if (bps != 1)
{
TIFFError("writeCroppedImage",
"Group 3/4 compression is not usable with bps > 1");
return (-1);
}
if (compression == COMPRESSION_CCITTFAX3) {
if (g3opts != (uint32) -1)
TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
else
CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
} else {
CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
}
CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
break;
case COMPRESSION_NONE:
break;
default: break;
}
{ uint32 len32;
void** data;
if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
}
{ uint16 ninks;
const char* inknames;
if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
int inknameslen = strlen(inknames) + 1;
const char* cp = inknames;
while (ninks > 1) {
cp = strchr(cp, '\0');
if (cp) {
cp++;
inknameslen += (strlen(cp) + 1);
}
ninks--;
}
TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
}
}
}
{
unsigned short pg0, pg1;
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages);
}
}
for (p = tags; p < &tags[NTAGS]; p++)
CopyTag(p->tag, p->count, p->type);
/* Compute the tile or strip dimensions and write to disk */
if (outtiled)
{
if (config == PLANARCONFIG_CONTIG)
{
if (writeBufferToContigTiles (out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write contiguous tile data for page %d", pagenum);
}
else
{
if (writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write separate tile data for page %d", pagenum);
}
}
else
{
if (config == PLANARCONFIG_CONTIG)
{
if (writeBufferToContigStrips (out, crop_buff, length))
TIFFError("","Unable to write contiguous strip data for page %d", pagenum);
}
else
{
if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write separate strip data for page %d", pagenum);
}
}
if (!TIFFWriteDirectory(out))
{
TIFFError("","Failed to write IFD for page number %d", pagenum);
TIFFClose(out);
return (-1);
}
return (0);
} /* end writeCroppedImage */
static int
rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 src_byte = 0, src_bit = 0;
uint32 row, rowsize = 0, bit_offset = 0;
uint8 matchbits = 0, maskbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples8bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length ; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*next) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
}
return (0);
} /* end rotateContigSamples8bits */
static int
rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 row, rowsize, bit_offset;
uint32 src_byte = 0, src_bit = 0;
uint16 matchbits = 0, maskbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples16bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint16)-1 >> (16 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (next[0] << 8) | next[1];
else
buff1 = (next[1] << 8) | next[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
}
return (0);
} /* end rotateContigSamples16bits */
static int
rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 row, rowsize, bit_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 matchbits = 0, maskbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples24bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint32)-1 >> (32 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3];
else
buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end rotateContigSamples24bits */
static int
rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0 /*, shift_width = 0 */;
/* int bytes_per_sample, bytes_per_pixel; */
uint32 row, rowsize, bit_offset;
uint32 src_byte, src_bit;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples24bits","Invalid src or destination buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
/* bytes_per_pixel = ((bps * spp) + 7) / 8; */
/* if (bytes_per_pixel < (bytes_per_sample + 1)) */
/* shift_width = bytes_per_pixel; */
/* else */
/* shift_width = bytes_per_sample + 1; */
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint64)-1 >> (64 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end rotateContigSamples32bits */
/* Rotate an image by a multiple of 90 degrees clockwise */
static int
rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width,
uint32 *img_length, unsigned char **ibuff_ptr)
{
int shift_width;
uint32 bytes_per_pixel, bytes_per_sample;
uint32 row, rowsize, src_offset, dst_offset;
uint32 i, col, width, length;
uint32 colsize, buffsize, col_offset, pix_offset;
unsigned char *ibuff;
unsigned char *src;
unsigned char *dst;
uint16 spp, bps;
float res_temp;
unsigned char *rbuff = NULL;
width = *img_width;
length = *img_length;
spp = image->spp;
bps = image->bps;
rowsize = ((bps * spp * width) + 7) / 8;
colsize = ((bps * spp * length) + 7) / 8;
if ((colsize * width) > (rowsize * length))
buffsize = (colsize + 1) * width;
else
buffsize = (rowsize + 1) * length;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
switch (rotation)
{
case 0:
case 360: return (0);
case 90:
case 180:
case 270: break;
default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation);
return (-1);
}
if (!(rbuff = (unsigned char *)_TIFFmalloc(buffsize)))
{
TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize);
return (-1);
}
_TIFFmemset(rbuff, '\0', buffsize);
ibuff = *ibuff_ptr;
switch (rotation)
{
case 180: if ((bps % 8) == 0) /* byte alligned data */
{
src = ibuff;
pix_offset = (spp * bps) / 8;
for (row = 0; row < length; row++)
{
dst_offset = (length - row - 1) * rowsize;
for (col = 0; col < width; col++)
{
col_offset = (width - col - 1) * pix_offset;
dst = rbuff + dst_offset + col_offset;
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *src++;
}
}
}
else
{ /* non 8 bit per sample data */
for (row = 0; row < length; row++)
{
src_offset = row * rowsize;
dst_offset = (length - row - 1) * rowsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (reverseSamples8bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (reverseSamples16bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (reverseSamples24bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (reverseSamples32bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
break;
case 90: if ((bps % 8) == 0) /* byte aligned data */
{
for (col = 0; col < width; col++)
{
src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel);
dst_offset = col * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
for (row = length; row > 0; row--)
{
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *(src + i);
src -= rowsize;
}
}
}
else
{ /* non 8 bit per sample data */
for (col = 0; col < width; col++)
{
src_offset = (length - 1) * rowsize;
dst_offset = col * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (rotateContigSamples8bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (rotateContigSamples16bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (rotateContigSamples24bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (rotateContigSamples32bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
*img_width = length;
*img_length = width;
image->width = length;
image->length = width;
res_temp = image->xres;
image->xres = image->yres;
image->yres = res_temp;
break;
case 270: if ((bps % 8) == 0) /* byte aligned data */
{
for (col = 0; col < width; col++)
{
src_offset = col * bytes_per_pixel;
dst_offset = (width - col - 1) * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
for (row = length; row > 0; row--)
{
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *(src + i);
src += rowsize;
}
}
}
else
{ /* non 8 bit per sample data */
for (col = 0; col < width; col++)
{
src_offset = 0;
dst_offset = (width - col - 1) * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (rotateContigSamples8bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (rotateContigSamples16bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (rotateContigSamples24bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (rotateContigSamples32bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
*img_width = length;
*img_length = width;
image->width = length;
image->length = width;
res_temp = image->xres;
image->xres = image->yres;
image->yres = res_temp;
break;
default:
break;
}
return (0);
} /* end rotateImage */
static int
reverseSamples8bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte, src_bit;
uint32 bit_offset = 0;
uint8 match_bits = 0, mask_bits = 0;
uint8 buff1 = 0, buff2 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples8bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint8)-1 >> ( 8 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (8 - src_bit - bps);
buff1 = ((*src) & match_bits) << (src_bit);
if (ready_bits < 8)
buff2 = (buff2 | (buff1 >> ready_bits));
else /* If we have a full buffer's worth, write it out */
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
}
return (0);
} /* end reverseSamples8bits */
static int
reverseSamples16bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte = 0, high_bit = 0;
uint32 bit_offset = 0;
uint16 match_bits = 0, mask_bits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSample16bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint16)-1 >> (16 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (16 - high_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & match_bits) << (high_bit);
if (ready_bits < 8)
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
}
return (0);
} /* end reverseSamples16bits */
static int
reverseSamples24bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte = 0, high_bit = 0;
uint32 bit_offset = 0;
uint32 match_bits = 0, mask_bits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples24bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint32)-1 >> (32 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (32 - high_bit - bps);
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & match_bits) << (high_bit);
if (ready_bits < 16)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end reverseSamples24bits */
static int
reverseSamples32bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0 /*, shift_width = 0 */;
/* int bytes_per_sample, bytes_per_pixel; */
uint32 bit_offset;
uint32 src_byte = 0, high_bit = 0;
uint32 col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 mask_bits = 0, match_bits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples32bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint64)-1 >> (64 - bps);
dst = obuff;
/* bytes_per_sample = (bps + 7) / 8; */
/* bytes_per_pixel = ((bps * spp) + 7) / 8; */
/* if (bytes_per_pixel < (bytes_per_sample + 1)) */
/* shift_width = bytes_per_pixel; */
/* else */
/* shift_width = bytes_per_sample + 1; */
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (64 - high_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & match_bits) << (high_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end reverseSamples32bits */
static int
reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width,
uint8 *src, uint8 *dst)
{
int i;
uint32 col, bytes_per_pixel, col_offset;
uint8 bytebuff1;
unsigned char swapbuff[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("reverseSamplesBytes","Invalid input or output buffer");
return (1);
}
bytes_per_pixel = ((bps * spp) + 7) / 8;
if( bytes_per_pixel > sizeof(swapbuff) )
{
TIFFError("reverseSamplesBytes","bytes_per_pixel too large");
return (1);
}
switch (bps / 8)
{
case 8: /* Use memcpy for multiple bytes per sample data */
case 4:
case 3:
case 2: for (col = 0; col < (width / 2); col++)
{
col_offset = col * bytes_per_pixel;
_TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel);
_TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel);
_TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel);
}
break;
case 1: /* Use byte copy only for single byte per sample data */
for (col = 0; col < (width / 2); col++)
{
for (i = 0; i < spp; i++)
{
bytebuff1 = *src;
*src++ = *(dst - spp + i);
*(dst - spp + i) = bytebuff1;
}
dst -= spp;
}
break;
default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps);
return (1);
}
return (0);
} /* end reverseSamplesBytes */
/* Mirror an image horizontally or vertically */
static int
mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff)
{
int shift_width;
uint32 bytes_per_pixel, bytes_per_sample;
uint32 row, rowsize, row_offset;
unsigned char *line_buff = NULL;
unsigned char *src;
unsigned char *dst;
src = ibuff;
rowsize = ((width * bps * spp) + 7) / 8;
switch (mirror)
{
case MIRROR_BOTH:
case MIRROR_VERT:
line_buff = (unsigned char *)_TIFFmalloc(rowsize);
if (line_buff == NULL)
{
TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize);
return (-1);
}
dst = ibuff + (rowsize * (length - 1));
for (row = 0; row < length / 2; row++)
{
_TIFFmemcpy(line_buff, src, rowsize);
_TIFFmemcpy(src, dst, rowsize);
_TIFFmemcpy(dst, line_buff, rowsize);
src += (rowsize);
dst -= (rowsize);
}
if (line_buff)
_TIFFfree(line_buff);
if (mirror == MIRROR_VERT)
break;
case MIRROR_HORIZ :
if ((bps % 8) == 0) /* byte alligned data */
{
for (row = 0; row < length; row++)
{
row_offset = row * rowsize;
src = ibuff + row_offset;
dst = ibuff + row_offset + rowsize;
if (reverseSamplesBytes(spp, bps, width, src, dst))
{
return (-1);
}
}
}
else
{ /* non 8 bit per sample data */
if (!(line_buff = (unsigned char *)_TIFFmalloc(rowsize + 1)))
{
TIFFError("mirrorImage", "Unable to allocate mirror line buffer");
return (-1);
}
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
for (row = 0; row < length; row++)
{
row_offset = row * rowsize;
src = ibuff + row_offset;
_TIFFmemset (line_buff, '\0', rowsize);
switch (shift_width)
{
case 1: if (reverseSamples16bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
case 2: if (reverseSamples24bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
case 3:
case 4:
case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
default: TIFFError("mirrorImage","Unsupported bit depth %d", bps);
_TIFFfree(line_buff);
return (-1);
}
}
if (line_buff)
_TIFFfree(line_buff);
}
break;
default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror);
return (-1);
break;
}
return (0);
}
/* Invert the light and dark values for a bilevel or grayscale image */
static int
invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff)
{
uint32 row, col;
unsigned char bytebuff1, bytebuff2, bytebuff3, bytebuff4;
unsigned char *src;
uint16 *src_uint16;
uint32 *src_uint32;
if (spp != 1)
{
TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel");
return (-1);
}
if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK)
{
TIFFError("invertImage", "Only black and white and grayscale images can be inverted");
return (-1);
}
src = work_buff;
if (src == NULL)
{
TIFFError ("invertImage", "Invalid crop buffer passed to invertImage");
return (-1);
}
switch (bps)
{
case 32: src_uint32 = (uint32 *)src;
for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
*src_uint32 = (uint32)0xFFFFFFFF - *src_uint32;
src_uint32++;
}
break;
case 16: src_uint16 = (uint16 *)src;
for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
*src_uint16 = (uint16)0xFFFF - *src_uint16;
src_uint16++;
}
break;
case 8: for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
*src = (uint8)255 - *src;
src++;
}
break;
case 4: for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
bytebuff1 = 16 - (uint8)(*src & 240 >> 4);
bytebuff2 = 16 - (*src & 15);
*src = bytebuff1 << 4 & bytebuff2;
src++;
}
break;
case 2: for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
bytebuff1 = 4 - (uint8)(*src & 192 >> 6);
bytebuff2 = 4 - (uint8)(*src & 48 >> 4);
bytebuff3 = 4 - (uint8)(*src & 12 >> 2);
bytebuff4 = 4 - (uint8)(*src & 3);
*src = (bytebuff1 << 6) || (bytebuff2 << 4) || (bytebuff3 << 2) || bytebuff4;
src++;
}
break;
case 1: for (row = 0; row < length; row++)
for (col = 0; col < width; col += 8 /(spp * bps))
{
*src = ~(*src);
src++;
}
break;
default: TIFFError("invertImage", "Unsupported bit depth %d", bps);
return (-1);
}
return (0);
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4798_1 |
crossvul-cpp_data_good_3305_1 | /*
* XDR support for nfsd
*
* Copyright (C) 1995, 1996 Olaf Kirch <okir@monad.swb.de>
*/
#include "vfs.h"
#include "xdr.h"
#include "auth.h"
#define NFSDDBG_FACILITY NFSDDBG_XDR
/*
* Mapping of S_IF* types to NFS file types
*/
static u32 nfs_ftypes[] = {
NFNON, NFCHR, NFCHR, NFBAD,
NFDIR, NFBAD, NFBLK, NFBAD,
NFREG, NFBAD, NFLNK, NFBAD,
NFSOCK, NFBAD, NFLNK, NFBAD,
};
/*
* XDR functions for basic NFS types
*/
static __be32 *
decode_fh(__be32 *p, struct svc_fh *fhp)
{
fh_init(fhp, NFS_FHSIZE);
memcpy(&fhp->fh_handle.fh_base, p, NFS_FHSIZE);
fhp->fh_handle.fh_size = NFS_FHSIZE;
/* FIXME: Look up export pointer here and verify
* Sun Secure RPC if requested */
return p + (NFS_FHSIZE >> 2);
}
/* Helper function for NFSv2 ACL code */
__be32 *nfs2svc_decode_fh(__be32 *p, struct svc_fh *fhp)
{
return decode_fh(p, fhp);
}
static __be32 *
encode_fh(__be32 *p, struct svc_fh *fhp)
{
memcpy(p, &fhp->fh_handle.fh_base, NFS_FHSIZE);
return p + (NFS_FHSIZE>> 2);
}
/*
* Decode a file name and make sure that the path contains
* no slashes or null bytes.
*/
static __be32 *
decode_filename(__be32 *p, char **namp, unsigned int *lenp)
{
char *name;
unsigned int i;
if ((p = xdr_decode_string_inplace(p, namp, lenp, NFS_MAXNAMLEN)) != NULL) {
for (i = 0, name = *namp; i < *lenp; i++, name++) {
if (*name == '\0' || *name == '/')
return NULL;
}
}
return p;
}
static __be32 *
decode_pathname(__be32 *p, char **namp, unsigned int *lenp)
{
char *name;
unsigned int i;
if ((p = xdr_decode_string_inplace(p, namp, lenp, NFS_MAXPATHLEN)) != NULL) {
for (i = 0, name = *namp; i < *lenp; i++, name++) {
if (*name == '\0')
return NULL;
}
}
return p;
}
static __be32 *
decode_sattr(__be32 *p, struct iattr *iap)
{
u32 tmp, tmp1;
iap->ia_valid = 0;
/* Sun client bug compatibility check: some sun clients seem to
* put 0xffff in the mode field when they mean 0xffffffff.
* Quoting the 4.4BSD nfs server code: Nah nah nah nah na nah.
*/
if ((tmp = ntohl(*p++)) != (u32)-1 && tmp != 0xffff) {
iap->ia_valid |= ATTR_MODE;
iap->ia_mode = tmp;
}
if ((tmp = ntohl(*p++)) != (u32)-1) {
iap->ia_uid = make_kuid(&init_user_ns, tmp);
if (uid_valid(iap->ia_uid))
iap->ia_valid |= ATTR_UID;
}
if ((tmp = ntohl(*p++)) != (u32)-1) {
iap->ia_gid = make_kgid(&init_user_ns, tmp);
if (gid_valid(iap->ia_gid))
iap->ia_valid |= ATTR_GID;
}
if ((tmp = ntohl(*p++)) != (u32)-1) {
iap->ia_valid |= ATTR_SIZE;
iap->ia_size = tmp;
}
tmp = ntohl(*p++); tmp1 = ntohl(*p++);
if (tmp != (u32)-1 && tmp1 != (u32)-1) {
iap->ia_valid |= ATTR_ATIME | ATTR_ATIME_SET;
iap->ia_atime.tv_sec = tmp;
iap->ia_atime.tv_nsec = tmp1 * 1000;
}
tmp = ntohl(*p++); tmp1 = ntohl(*p++);
if (tmp != (u32)-1 && tmp1 != (u32)-1) {
iap->ia_valid |= ATTR_MTIME | ATTR_MTIME_SET;
iap->ia_mtime.tv_sec = tmp;
iap->ia_mtime.tv_nsec = tmp1 * 1000;
/*
* Passing the invalid value useconds=1000000 for mtime
* is a Sun convention for "set both mtime and atime to
* current server time". It's needed to make permissions
* checks for the "touch" program across v2 mounts to
* Solaris and Irix boxes work correctly. See description of
* sattr in section 6.1 of "NFS Illustrated" by
* Brent Callaghan, Addison-Wesley, ISBN 0-201-32750-5
*/
if (tmp1 == 1000000)
iap->ia_valid &= ~(ATTR_ATIME_SET|ATTR_MTIME_SET);
}
return p;
}
static __be32 *
encode_fattr(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp,
struct kstat *stat)
{
struct dentry *dentry = fhp->fh_dentry;
int type;
struct timespec time;
u32 f;
type = (stat->mode & S_IFMT);
*p++ = htonl(nfs_ftypes[type >> 12]);
*p++ = htonl((u32) stat->mode);
*p++ = htonl((u32) stat->nlink);
*p++ = htonl((u32) from_kuid(&init_user_ns, stat->uid));
*p++ = htonl((u32) from_kgid(&init_user_ns, stat->gid));
if (S_ISLNK(type) && stat->size > NFS_MAXPATHLEN) {
*p++ = htonl(NFS_MAXPATHLEN);
} else {
*p++ = htonl((u32) stat->size);
}
*p++ = htonl((u32) stat->blksize);
if (S_ISCHR(type) || S_ISBLK(type))
*p++ = htonl(new_encode_dev(stat->rdev));
else
*p++ = htonl(0xffffffff);
*p++ = htonl((u32) stat->blocks);
switch (fsid_source(fhp)) {
default:
case FSIDSOURCE_DEV:
*p++ = htonl(new_encode_dev(stat->dev));
break;
case FSIDSOURCE_FSID:
*p++ = htonl((u32) fhp->fh_export->ex_fsid);
break;
case FSIDSOURCE_UUID:
f = ((u32*)fhp->fh_export->ex_uuid)[0];
f ^= ((u32*)fhp->fh_export->ex_uuid)[1];
f ^= ((u32*)fhp->fh_export->ex_uuid)[2];
f ^= ((u32*)fhp->fh_export->ex_uuid)[3];
*p++ = htonl(f);
break;
}
*p++ = htonl((u32) stat->ino);
*p++ = htonl((u32) stat->atime.tv_sec);
*p++ = htonl(stat->atime.tv_nsec ? stat->atime.tv_nsec / 1000 : 0);
lease_get_mtime(d_inode(dentry), &time);
*p++ = htonl((u32) time.tv_sec);
*p++ = htonl(time.tv_nsec ? time.tv_nsec / 1000 : 0);
*p++ = htonl((u32) stat->ctime.tv_sec);
*p++ = htonl(stat->ctime.tv_nsec ? stat->ctime.tv_nsec / 1000 : 0);
return p;
}
/* Helper function for NFSv2 ACL code */
__be32 *nfs2svc_encode_fattr(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp, struct kstat *stat)
{
return encode_fattr(rqstp, p, fhp, stat);
}
/*
* XDR decode functions
*/
int
nfssvc_decode_void(struct svc_rqst *rqstp, __be32 *p, void *dummy)
{
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_fhandle(struct svc_rqst *rqstp, __be32 *p, struct nfsd_fhandle *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_sattrargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_sattrargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = decode_sattr(p, &args->attrs);
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_diropargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_diropargs *args)
{
if (!(p = decode_fh(p, &args->fh))
|| !(p = decode_filename(p, &args->name, &args->len)))
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_readargs *args)
{
unsigned int len;
int v;
p = decode_fh(p, &args->fh);
if (!p)
return 0;
args->offset = ntohl(*p++);
len = args->count = ntohl(*p++);
p++; /* totalcount - unused */
len = min_t(unsigned int, len, NFSSVC_MAXBLKSIZE_V2);
/* set up somewhere to store response.
* We take pages, put them on reslist and include in iovec
*/
v=0;
while (len > 0) {
struct page *p = *(rqstp->rq_next_page++);
rqstp->rq_vec[v].iov_base = page_address(p);
rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE);
len -= rqstp->rq_vec[v].iov_len;
v++;
}
args->vlen = v;
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_writeargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_writeargs *args)
{
unsigned int len, hdr, dlen;
struct kvec *head = rqstp->rq_arg.head;
int v;
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p++; /* beginoffset */
args->offset = ntohl(*p++); /* offset */
p++; /* totalcount */
len = args->len = ntohl(*p++);
/*
* The protocol specifies a maximum of 8192 bytes.
*/
if (len > NFSSVC_MAXBLKSIZE_V2)
return 0;
/*
* Check to make sure that we got the right number of
* bytes.
*/
hdr = (void*)p - head->iov_base;
if (hdr > head->iov_len)
return 0;
dlen = head->iov_len + rqstp->rq_arg.page_len - hdr;
/*
* Round the length of the data which was specified up to
* the next multiple of XDR units and then compare that
* against the length which was actually received.
* Note that when RPCSEC/GSS (for example) is used, the
* data buffer can be padded so dlen might be larger
* than required. It must never be smaller.
*/
if (dlen < XDR_QUADLEN(len)*4)
return 0;
rqstp->rq_vec[0].iov_base = (void*)p;
rqstp->rq_vec[0].iov_len = head->iov_len - hdr;
v = 0;
while (len > rqstp->rq_vec[v].iov_len) {
len -= rqstp->rq_vec[v].iov_len;
v++;
rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_pages[v]);
rqstp->rq_vec[v].iov_len = PAGE_SIZE;
}
rqstp->rq_vec[v].iov_len = len;
args->vlen = v + 1;
return 1;
}
int
nfssvc_decode_createargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_createargs *args)
{
if ( !(p = decode_fh(p, &args->fh))
|| !(p = decode_filename(p, &args->name, &args->len)))
return 0;
p = decode_sattr(p, &args->attrs);
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_renameargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_renameargs *args)
{
if (!(p = decode_fh(p, &args->ffh))
|| !(p = decode_filename(p, &args->fname, &args->flen))
|| !(p = decode_fh(p, &args->tfh))
|| !(p = decode_filename(p, &args->tname, &args->tlen)))
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readlinkargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
args->buffer = page_address(*(rqstp->rq_next_page++));
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_linkargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_linkargs *args)
{
if (!(p = decode_fh(p, &args->ffh))
|| !(p = decode_fh(p, &args->tfh))
|| !(p = decode_filename(p, &args->tname, &args->tlen)))
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_symlinkargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_symlinkargs *args)
{
if ( !(p = decode_fh(p, &args->ffh))
|| !(p = decode_filename(p, &args->fname, &args->flen))
|| !(p = decode_pathname(p, &args->tname, &args->tlen)))
return 0;
p = decode_sattr(p, &args->attrs);
return xdr_argsize_check(rqstp, p);
}
int
nfssvc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_readdirargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
args->cookie = ntohl(*p++);
args->count = ntohl(*p++);
args->count = min_t(u32, args->count, PAGE_SIZE);
args->buffer = page_address(*(rqstp->rq_next_page++));
return xdr_argsize_check(rqstp, p);
}
/*
* XDR encode functions
*/
int
nfssvc_encode_void(struct svc_rqst *rqstp, __be32 *p, void *dummy)
{
return xdr_ressize_check(rqstp, p);
}
int
nfssvc_encode_attrstat(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_attrstat *resp)
{
p = encode_fattr(rqstp, p, &resp->fh, &resp->stat);
return xdr_ressize_check(rqstp, p);
}
int
nfssvc_encode_diropres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_diropres *resp)
{
p = encode_fh(p, &resp->fh);
p = encode_fattr(rqstp, p, &resp->fh, &resp->stat);
return xdr_ressize_check(rqstp, p);
}
int
nfssvc_encode_readlinkres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_readlinkres *resp)
{
*p++ = htonl(resp->len);
xdr_ressize_check(rqstp, p);
rqstp->rq_res.page_len = resp->len;
if (resp->len & 3) {
/* need to pad the tail */
rqstp->rq_res.tail[0].iov_base = p;
*p = 0;
rqstp->rq_res.tail[0].iov_len = 4 - (resp->len&3);
}
return 1;
}
int
nfssvc_encode_readres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_readres *resp)
{
p = encode_fattr(rqstp, p, &resp->fh, &resp->stat);
*p++ = htonl(resp->count);
xdr_ressize_check(rqstp, p);
/* now update rqstp->rq_res to reflect data as well */
rqstp->rq_res.page_len = resp->count;
if (resp->count & 3) {
/* need to pad the tail */
rqstp->rq_res.tail[0].iov_base = p;
*p = 0;
rqstp->rq_res.tail[0].iov_len = 4 - (resp->count&3);
}
return 1;
}
int
nfssvc_encode_readdirres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_readdirres *resp)
{
xdr_ressize_check(rqstp, p);
p = resp->buffer;
*p++ = 0; /* no more entries */
*p++ = htonl((resp->common.err == nfserr_eof));
rqstp->rq_res.page_len = (((unsigned long)p-1) & ~PAGE_MASK)+1;
return 1;
}
int
nfssvc_encode_statfsres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_statfsres *resp)
{
struct kstatfs *stat = &resp->stats;
*p++ = htonl(NFSSVC_MAXBLKSIZE_V2); /* max transfer size */
*p++ = htonl(stat->f_bsize);
*p++ = htonl(stat->f_blocks);
*p++ = htonl(stat->f_bfree);
*p++ = htonl(stat->f_bavail);
return xdr_ressize_check(rqstp, p);
}
int
nfssvc_encode_entry(void *ccdv, const char *name,
int namlen, loff_t offset, u64 ino, unsigned int d_type)
{
struct readdir_cd *ccd = ccdv;
struct nfsd_readdirres *cd = container_of(ccd, struct nfsd_readdirres, common);
__be32 *p = cd->buffer;
int buflen, slen;
/*
dprintk("nfsd: entry(%.*s off %ld ino %ld)\n",
namlen, name, offset, ino);
*/
if (offset > ~((u32) 0)) {
cd->common.err = nfserr_fbig;
return -EINVAL;
}
if (cd->offset)
*cd->offset = htonl(offset);
/* truncate filename */
namlen = min(namlen, NFS2_MAXNAMLEN);
slen = XDR_QUADLEN(namlen);
if ((buflen = cd->buflen - slen - 4) < 0) {
cd->common.err = nfserr_toosmall;
return -EINVAL;
}
if (ino > ~((u32) 0)) {
cd->common.err = nfserr_fbig;
return -EINVAL;
}
*p++ = xdr_one; /* mark entry present */
*p++ = htonl((u32) ino); /* file id */
p = xdr_encode_array(p, name, namlen);/* name length & name */
cd->offset = p; /* remember pointer */
*p++ = htonl(~0U); /* offset of next entry */
cd->buflen = buflen;
cd->buffer = p;
cd->common.err = nfs_ok;
return 0;
}
/*
* XDR release functions
*/
int
nfssvc_release_fhandle(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_fhandle *resp)
{
fh_put(&resp->fh);
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3305_1 |
crossvul-cpp_data_good_2686_3 | /*
* Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/*
* txtproto_print() derived from original code by Hannes Gredler
* (hannes@gredler.at):
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <sys/stat.h>
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include "netdissect.h"
#include "ascii_strcasecmp.h"
#include "timeval-operations.h"
int32_t thiszone; /* seconds offset from gmt to local time */
/* invalid string to print '(invalid)' for malformed or corrupted packets */
const char istr[] = " (invalid)";
/*
* timestamp display buffer size, the biggest size of both formats is needed
* sizeof("0000000000.000000000") > sizeof("00:00:00.000000000")
*/
#define TS_BUF_SIZE sizeof("0000000000.000000000")
#define TOKBUFSIZE 128
/*
* Print out a character, filtering out the non-printable ones
*/
void
fn_print_char(netdissect_options *ndo, u_char c)
{
if (!ND_ISASCII(c)) {
c = ND_TOASCII(c);
ND_PRINT((ndo, "M-"));
}
if (!ND_ISPRINT(c)) {
c ^= 0x40; /* DEL to ?, others to alpha */
ND_PRINT((ndo, "^"));
}
ND_PRINT((ndo, "%c", c));
}
/*
* Print out a null-terminated filename (or other ASCII string).
* If ep is NULL, assume no truncation check is needed.
* Return true if truncated.
* Stop at ep (if given) or before the null char, whichever is first.
*/
int
fn_print(netdissect_options *ndo,
register const u_char *s, register const u_char *ep)
{
register int ret;
register u_char c;
ret = 1; /* assume truncated */
while (ep == NULL || s < ep) {
c = *s++;
if (c == '\0') {
ret = 0;
break;
}
if (!ND_ISASCII(c)) {
c = ND_TOASCII(c);
ND_PRINT((ndo, "M-"));
}
if (!ND_ISPRINT(c)) {
c ^= 0x40; /* DEL to ?, others to alpha */
ND_PRINT((ndo, "^"));
}
ND_PRINT((ndo, "%c", c));
}
return(ret);
}
/*
* Print out a null-terminated filename (or other ASCII string) from
* a fixed-length buffer.
* If ep is NULL, assume no truncation check is needed.
* Return the number of bytes of string processed, including the
* terminating null, if not truncated. Return 0 if truncated.
*/
u_int
fn_printztn(netdissect_options *ndo,
register const u_char *s, register u_int n, register const u_char *ep)
{
register u_int bytes;
register u_char c;
bytes = 0;
for (;;) {
if (n == 0 || (ep != NULL && s >= ep)) {
/*
* Truncated. This includes "no null before we
* got to the end of the fixed-length buffer".
*
* XXX - BOOTP says "null-terminated", which
* means the maximum length of the string, in
* bytes, is 1 less than the size of the buffer,
* as there must always be a terminating null.
*/
bytes = 0;
break;
}
c = *s++;
bytes++;
n--;
if (c == '\0') {
/* End of string */
break;
}
if (!ND_ISASCII(c)) {
c = ND_TOASCII(c);
ND_PRINT((ndo, "M-"));
}
if (!ND_ISPRINT(c)) {
c ^= 0x40; /* DEL to ?, others to alpha */
ND_PRINT((ndo, "^"));
}
ND_PRINT((ndo, "%c", c));
}
return(bytes);
}
/*
* Print out a counted filename (or other ASCII string).
* If ep is NULL, assume no truncation check is needed.
* Return true if truncated.
* Stop at ep (if given) or after n bytes, whichever is first.
*/
int
fn_printn(netdissect_options *ndo,
register const u_char *s, register u_int n, register const u_char *ep)
{
register u_char c;
while (n > 0 && (ep == NULL || s < ep)) {
n--;
c = *s++;
if (!ND_ISASCII(c)) {
c = ND_TOASCII(c);
ND_PRINT((ndo, "M-"));
}
if (!ND_ISPRINT(c)) {
c ^= 0x40; /* DEL to ?, others to alpha */
ND_PRINT((ndo, "^"));
}
ND_PRINT((ndo, "%c", c));
}
return (n == 0) ? 0 : 1;
}
/*
* Print out a null-padded filename (or other ASCII string).
* If ep is NULL, assume no truncation check is needed.
* Return true if truncated.
* Stop at ep (if given) or after n bytes or before the null char,
* whichever is first.
*/
int
fn_printzp(netdissect_options *ndo,
register const u_char *s, register u_int n,
register const u_char *ep)
{
register int ret;
register u_char c;
ret = 1; /* assume truncated */
while (n > 0 && (ep == NULL || s < ep)) {
n--;
c = *s++;
if (c == '\0') {
ret = 0;
break;
}
if (!ND_ISASCII(c)) {
c = ND_TOASCII(c);
ND_PRINT((ndo, "M-"));
}
if (!ND_ISPRINT(c)) {
c ^= 0x40; /* DEL to ?, others to alpha */
ND_PRINT((ndo, "^"));
}
ND_PRINT((ndo, "%c", c));
}
return (n == 0) ? 0 : ret;
}
/*
* Format the timestamp
*/
static char *
ts_format(netdissect_options *ndo
#ifndef HAVE_PCAP_SET_TSTAMP_PRECISION
_U_
#endif
, int sec, int usec, char *buf)
{
const char *format;
#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
switch (ndo->ndo_tstamp_precision) {
case PCAP_TSTAMP_PRECISION_MICRO:
format = "%02d:%02d:%02d.%06u";
break;
case PCAP_TSTAMP_PRECISION_NANO:
format = "%02d:%02d:%02d.%09u";
break;
default:
format = "%02d:%02d:%02d.{unknown}";
break;
}
#else
format = "%02d:%02d:%02d.%06u";
#endif
snprintf(buf, TS_BUF_SIZE, format,
sec / 3600, (sec % 3600) / 60, sec % 60, usec);
return buf;
}
/*
* Format the timestamp - Unix timeval style
*/
static char *
ts_unix_format(netdissect_options *ndo
#ifndef HAVE_PCAP_SET_TSTAMP_PRECISION
_U_
#endif
, int sec, int usec, char *buf)
{
const char *format;
#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
switch (ndo->ndo_tstamp_precision) {
case PCAP_TSTAMP_PRECISION_MICRO:
format = "%u.%06u";
break;
case PCAP_TSTAMP_PRECISION_NANO:
format = "%u.%09u";
break;
default:
format = "%u.{unknown}";
break;
}
#else
format = "%u.%06u";
#endif
snprintf(buf, TS_BUF_SIZE, format,
(unsigned)sec, (unsigned)usec);
return buf;
}
/*
* Print the timestamp
*/
void
ts_print(netdissect_options *ndo,
register const struct timeval *tvp)
{
register int s;
struct tm *tm;
time_t Time;
char buf[TS_BUF_SIZE];
static struct timeval tv_ref;
struct timeval tv_result;
int negative_offset;
int nano_prec;
switch (ndo->ndo_tflag) {
case 0: /* Default */
s = (tvp->tv_sec + thiszone) % 86400;
ND_PRINT((ndo, "%s ", ts_format(ndo, s, tvp->tv_usec, buf)));
break;
case 1: /* No time stamp */
break;
case 2: /* Unix timeval style */
ND_PRINT((ndo, "%s ", ts_unix_format(ndo,
tvp->tv_sec, tvp->tv_usec, buf)));
break;
case 3: /* Microseconds/nanoseconds since previous packet */
case 5: /* Microseconds/nanoseconds since first packet */
#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
switch (ndo->ndo_tstamp_precision) {
case PCAP_TSTAMP_PRECISION_MICRO:
nano_prec = 0;
break;
case PCAP_TSTAMP_PRECISION_NANO:
nano_prec = 1;
break;
default:
nano_prec = 0;
break;
}
#else
nano_prec = 0;
#endif
if (!(netdissect_timevalisset(&tv_ref)))
tv_ref = *tvp; /* set timestamp for first packet */
negative_offset = netdissect_timevalcmp(tvp, &tv_ref, <);
if (negative_offset)
netdissect_timevalsub(&tv_ref, tvp, &tv_result, nano_prec);
else
netdissect_timevalsub(tvp, &tv_ref, &tv_result, nano_prec);
ND_PRINT((ndo, (negative_offset ? "-" : " ")));
ND_PRINT((ndo, "%s ", ts_format(ndo,
tv_result.tv_sec, tv_result.tv_usec, buf)));
if (ndo->ndo_tflag == 3)
tv_ref = *tvp; /* set timestamp for previous packet */
break;
case 4: /* Default + Date */
s = (tvp->tv_sec + thiszone) % 86400;
Time = (tvp->tv_sec + thiszone) - s;
tm = gmtime (&Time);
if (!tm)
ND_PRINT((ndo, "Date fail "));
else
ND_PRINT((ndo, "%04d-%02d-%02d %s ",
tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
ts_format(ndo, s, tvp->tv_usec, buf)));
break;
}
}
/*
* Print an unsigned relative number of seconds (e.g. hold time, prune timer)
* in the form 5m1s. This does no truncation, so 32230861 seconds
* is represented as 1y1w1d1h1m1s.
*/
void
unsigned_relts_print(netdissect_options *ndo,
uint32_t secs)
{
static const char *lengths[] = {"y", "w", "d", "h", "m", "s"};
static const u_int seconds[] = {31536000, 604800, 86400, 3600, 60, 1};
const char **l = lengths;
const u_int *s = seconds;
if (secs == 0) {
ND_PRINT((ndo, "0s"));
return;
}
while (secs > 0) {
if (secs >= *s) {
ND_PRINT((ndo, "%d%s", secs / *s, *l));
secs -= (secs / *s) * *s;
}
s++;
l++;
}
}
/*
* Print a signed relative number of seconds (e.g. hold time, prune timer)
* in the form 5m1s. This does no truncation, so 32230861 seconds
* is represented as 1y1w1d1h1m1s.
*/
void
signed_relts_print(netdissect_options *ndo,
int32_t secs)
{
if (secs < 0) {
ND_PRINT((ndo, "-"));
if (secs == INT32_MIN) {
/*
* -2^31; you can't fit its absolute value into
* a 32-bit signed integer.
*
* Just directly pass said absolute value to
* unsigned_relts_print() directly.
*
* (XXX - does ISO C guarantee that -(-2^n),
* when calculated and cast to an n-bit unsigned
* integer type, will have the value 2^n?)
*/
unsigned_relts_print(ndo, 2147483648U);
} else {
/*
* We now know -secs will fit into an int32_t;
* negate it and pass that to unsigned_relts_print().
*/
unsigned_relts_print(ndo, -secs);
}
return;
}
unsigned_relts_print(ndo, secs);
}
/*
* this is a generic routine for printing unknown data;
* we pass on the linefeed plus indentation string to
* get a proper output - returns 0 on error
*/
int
print_unknown_data(netdissect_options *ndo, const u_char *cp,const char *ident,int len)
{
if (len < 0) {
ND_PRINT((ndo,"%sDissector error: print_unknown_data called with negative length",
ident));
return(0);
}
if (ndo->ndo_snapend - cp < len)
len = ndo->ndo_snapend - cp;
if (len < 0) {
ND_PRINT((ndo,"%sDissector error: print_unknown_data called with pointer past end of packet",
ident));
return(0);
}
hex_print(ndo, ident,cp,len);
return(1); /* everything is ok */
}
/*
* Convert a token value to a string; use "fmt" if not found.
*/
const char *
tok2strbuf(register const struct tok *lp, register const char *fmt,
register u_int v, char *buf, size_t bufsize)
{
if (lp != NULL) {
while (lp->s != NULL) {
if (lp->v == v)
return (lp->s);
++lp;
}
}
if (fmt == NULL)
fmt = "#%d";
(void)snprintf(buf, bufsize, fmt, v);
return (const char *)buf;
}
/*
* Convert a token value to a string; use "fmt" if not found.
* Uses tok2strbuf() on one of four local static buffers of size TOKBUFSIZE
* in round-robin fashion.
*/
const char *
tok2str(register const struct tok *lp, register const char *fmt,
register u_int v)
{
static char buf[4][TOKBUFSIZE];
static int idx = 0;
char *ret;
ret = buf[idx];
idx = (idx+1) & 3;
return tok2strbuf(lp, fmt, v, ret, sizeof(buf[0]));
}
/*
* Convert a bit token value to a string; use "fmt" if not found.
* this is useful for parsing bitfields, the output strings are seperated
* if the s field is positive.
*/
static char *
bittok2str_internal(register const struct tok *lp, register const char *fmt,
register u_int v, const char *sep)
{
static char buf[1024+1]; /* our string buffer */
char *bufp = buf;
size_t space_left = sizeof(buf), string_size;
register u_int rotbit; /* this is the bit we rotate through all bitpositions */
register u_int tokval;
const char * sepstr = "";
while (lp != NULL && lp->s != NULL) {
tokval=lp->v; /* load our first value */
rotbit=1;
while (rotbit != 0) {
/*
* lets AND the rotating bit with our token value
* and see if we have got a match
*/
if (tokval == (v&rotbit)) {
/* ok we have found something */
if (space_left <= 1)
return (buf); /* only enough room left for NUL, if that */
string_size = strlcpy(bufp, sepstr, space_left);
if (string_size >= space_left)
return (buf); /* we ran out of room */
bufp += string_size;
space_left -= string_size;
if (space_left <= 1)
return (buf); /* only enough room left for NUL, if that */
string_size = strlcpy(bufp, lp->s, space_left);
if (string_size >= space_left)
return (buf); /* we ran out of room */
bufp += string_size;
space_left -= string_size;
sepstr = sep;
break;
}
rotbit=rotbit<<1; /* no match - lets shift and try again */
}
lp++;
}
if (bufp == buf)
/* bummer - lets print the "unknown" message as advised in the fmt string if we got one */
(void)snprintf(buf, sizeof(buf), fmt == NULL ? "#%08x" : fmt, v);
return (buf);
}
/*
* Convert a bit token value to a string; use "fmt" if not found.
* this is useful for parsing bitfields, the output strings are not seperated.
*/
char *
bittok2str_nosep(register const struct tok *lp, register const char *fmt,
register u_int v)
{
return (bittok2str_internal(lp, fmt, v, ""));
}
/*
* Convert a bit token value to a string; use "fmt" if not found.
* this is useful for parsing bitfields, the output strings are comma seperated.
*/
char *
bittok2str(register const struct tok *lp, register const char *fmt,
register u_int v)
{
return (bittok2str_internal(lp, fmt, v, ", "));
}
/*
* Convert a value to a string using an array; the macro
* tok2strary() in <netdissect.h> is the public interface to
* this function and ensures that the second argument is
* correct for bounds-checking.
*/
const char *
tok2strary_internal(register const char **lp, int n, register const char *fmt,
register int v)
{
static char buf[TOKBUFSIZE];
if (v >= 0 && v < n && lp[v] != NULL)
return lp[v];
if (fmt == NULL)
fmt = "#%d";
(void)snprintf(buf, sizeof(buf), fmt, v);
return (buf);
}
/*
* Convert a 32-bit netmask to prefixlen if possible
* the function returns the prefix-len; if plen == -1
* then conversion was not possible;
*/
int
mask2plen(uint32_t mask)
{
uint32_t bitmasks[33] = {
0x00000000,
0x80000000, 0xc0000000, 0xe0000000, 0xf0000000,
0xf8000000, 0xfc000000, 0xfe000000, 0xff000000,
0xff800000, 0xffc00000, 0xffe00000, 0xfff00000,
0xfff80000, 0xfffc0000, 0xfffe0000, 0xffff0000,
0xffff8000, 0xffffc000, 0xffffe000, 0xfffff000,
0xfffff800, 0xfffffc00, 0xfffffe00, 0xffffff00,
0xffffff80, 0xffffffc0, 0xffffffe0, 0xfffffff0,
0xfffffff8, 0xfffffffc, 0xfffffffe, 0xffffffff
};
int prefix_len = 32;
/* let's see if we can transform the mask into a prefixlen */
while (prefix_len >= 0) {
if (bitmasks[prefix_len] == mask)
break;
prefix_len--;
}
return (prefix_len);
}
int
mask62plen(const u_char *mask)
{
u_char bitmasks[9] = {
0x00,
0x80, 0xc0, 0xe0, 0xf0,
0xf8, 0xfc, 0xfe, 0xff
};
int byte;
int cidr_len = 0;
for (byte = 0; byte < 16; byte++) {
u_int bits;
for (bits = 0; bits < (sizeof (bitmasks) / sizeof (bitmasks[0])); bits++) {
if (mask[byte] == bitmasks[bits]) {
cidr_len += bits;
break;
}
}
if (mask[byte] != 0xff)
break;
}
return (cidr_len);
}
/*
* Routine to print out information for text-based protocols such as FTP,
* HTTP, SMTP, RTSP, SIP, ....
*/
#define MAX_TOKEN 128
/*
* Fetch a token from a packet, starting at the specified index,
* and return the length of the token.
*
* Returns 0 on error; yes, this is indistinguishable from an empty
* token, but an "empty token" isn't a valid token - it just means
* either a space character at the beginning of the line (this
* includes a blank line) or no more tokens remaining on the line.
*/
static int
fetch_token(netdissect_options *ndo, const u_char *pptr, u_int idx, u_int len,
u_char *tbuf, size_t tbuflen)
{
size_t toklen = 0;
for (; idx < len; idx++) {
if (!ND_TTEST(*(pptr + idx))) {
/* ran past end of captured data */
return (0);
}
if (!isascii(*(pptr + idx))) {
/* not an ASCII character */
return (0);
}
if (isspace(*(pptr + idx))) {
/* end of token */
break;
}
if (!isprint(*(pptr + idx))) {
/* not part of a command token or response code */
return (0);
}
if (toklen + 2 > tbuflen) {
/* no room for this character and terminating '\0' */
return (0);
}
tbuf[toklen] = *(pptr + idx);
toklen++;
}
if (toklen == 0) {
/* no token */
return (0);
}
tbuf[toklen] = '\0';
/*
* Skip past any white space after the token, until we see
* an end-of-line (CR or LF).
*/
for (; idx < len; idx++) {
if (!ND_TTEST(*(pptr + idx))) {
/* ran past end of captured data */
break;
}
if (*(pptr + idx) == '\r' || *(pptr + idx) == '\n') {
/* end of line */
break;
}
if (!isascii(*(pptr + idx)) || !isprint(*(pptr + idx))) {
/* not a printable ASCII character */
break;
}
if (!isspace(*(pptr + idx))) {
/* beginning of next token */
break;
}
}
return (idx);
}
/*
* Scan a buffer looking for a line ending - LF or CR-LF.
* Return the index of the character after the line ending or 0 if
* we encounter a non-ASCII or non-printable character or don't find
* the line ending.
*/
static u_int
print_txt_line(netdissect_options *ndo, const char *protoname,
const char *prefix, const u_char *pptr, u_int idx, u_int len)
{
u_int startidx;
u_int linelen;
startidx = idx;
while (idx < len) {
ND_TCHECK(*(pptr+idx));
if (*(pptr+idx) == '\n') {
/*
* LF without CR; end of line.
* Skip the LF and print the line, with the
* exception of the LF.
*/
linelen = idx - startidx;
idx++;
goto print;
} else if (*(pptr+idx) == '\r') {
/* CR - any LF? */
if ((idx+1) >= len) {
/* not in this packet */
return (0);
}
ND_TCHECK(*(pptr+idx+1));
if (*(pptr+idx+1) == '\n') {
/*
* CR-LF; end of line.
* Skip the CR-LF and print the line, with
* the exception of the CR-LF.
*/
linelen = idx - startidx;
idx += 2;
goto print;
}
/*
* CR followed by something else; treat this
* as if it were binary data, and don't print
* it.
*/
return (0);
} else if (!isascii(*(pptr+idx)) ||
(!isprint(*(pptr+idx)) && *(pptr+idx) != '\t')) {
/*
* Not a printable ASCII character and not a tab;
* treat this as if it were binary data, and
* don't print it.
*/
return (0);
}
idx++;
}
/*
* All printable ASCII, but no line ending after that point
* in the buffer; treat this as if it were truncated.
*/
trunc:
linelen = idx - startidx;
ND_PRINT((ndo, "%s%.*s[!%s]", prefix, (int)linelen, pptr + startidx,
protoname));
return (0);
print:
ND_PRINT((ndo, "%s%.*s", prefix, (int)linelen, pptr + startidx));
return (idx);
}
void
txtproto_print(netdissect_options *ndo, const u_char *pptr, u_int len,
const char *protoname, const char **cmds, u_int flags)
{
u_int idx, eol;
u_char token[MAX_TOKEN+1];
const char *cmd;
int is_reqresp = 0;
const char *pnp;
if (cmds != NULL) {
/*
* This protocol has more than just request and
* response lines; see whether this looks like a
* request or response.
*/
idx = fetch_token(ndo, pptr, 0, len, token, sizeof(token));
if (idx != 0) {
/* Is this a valid request name? */
while ((cmd = *cmds++) != NULL) {
if (ascii_strcasecmp((const char *)token, cmd) == 0) {
/* Yes. */
is_reqresp = 1;
break;
}
}
/*
* No - is this a valid response code (3 digits)?
*
* Is this token the response code, or is the next
* token the response code?
*/
if (flags & RESP_CODE_SECOND_TOKEN) {
/*
* Next token - get it.
*/
idx = fetch_token(ndo, pptr, idx, len, token,
sizeof(token));
}
if (idx != 0) {
if (isdigit(token[0]) && isdigit(token[1]) &&
isdigit(token[2]) && token[3] == '\0') {
/* Yes. */
is_reqresp = 1;
}
}
}
} else {
/*
* This protocol has only request and response lines
* (e.g., FTP, where all the data goes over a
* different connection); assume the payload is
* a request or response.
*/
is_reqresp = 1;
}
/* Capitalize the protocol name */
for (pnp = protoname; *pnp != '\0'; pnp++)
ND_PRINT((ndo, "%c", toupper((u_char)*pnp)));
if (is_reqresp) {
/*
* In non-verbose mode, just print the protocol, followed
* by the first line as the request or response info.
*
* In verbose mode, print lines as text until we run out
* of characters or see something that's not a
* printable-ASCII line.
*/
if (ndo->ndo_vflag) {
/*
* We're going to print all the text lines in the
* request or response; just print the length
* on the first line of the output.
*/
ND_PRINT((ndo, ", length: %u", len));
for (idx = 0;
idx < len && (eol = print_txt_line(ndo, protoname, "\n\t", pptr, idx, len)) != 0;
idx = eol)
;
} else {
/*
* Just print the first text line.
*/
print_txt_line(ndo, protoname, ": ", pptr, 0, len);
}
}
}
void
safeputs(netdissect_options *ndo,
const u_char *s, const u_int maxlen)
{
u_int idx = 0;
while (idx < maxlen && *s) {
safeputchar(ndo, *s);
idx++;
s++;
}
}
void
safeputchar(netdissect_options *ndo,
const u_char c)
{
ND_PRINT((ndo, (c < 0x80 && ND_ISPRINT(c)) ? "%c" : "\\0x%02x", c));
}
#ifdef LBL_ALIGN
/*
* Some compilers try to optimize memcpy(), using the alignment constraint
* on the argument pointer type. by using this function, we try to avoid the
* optimization.
*/
void
unaligned_memcpy(void *p, const void *q, size_t l)
{
memcpy(p, q, l);
}
/* As with memcpy(), so with memcmp(). */
int
unaligned_memcmp(const void *p, const void *q, size_t l)
{
return (memcmp(p, q, l));
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2686_3 |
crossvul-cpp_data_good_4787_16 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% EEEEE M M FFFFF %
% E MM MM F %
% EEE M M M FFF %
% E M M F %
% EEEEE M M F %
% %
% %
% Read Windows Enahanced Metafile Format %
% %
% Software Design %
% Bill Radcliffe %
% 2001 %
% Dirk Lemstra %
% January 2014 %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
/*
* Include declarations.
*/
#include "magick/studio.h"
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
# if !defined(_MSC_VER)
# if defined(__CYGWIN__)
# include <windows.h>
# else
# include <wingdi.h>
# endif
# else
# include <gdiplus.h>
# pragma comment(lib, "gdiplus.lib")
# endif
#endif
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s E F M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsEMF() returns MagickTrue if the image format type, identified by the
% magick string, is a Microsoft Windows Enhanced MetaFile (EMF) file.
%
% The format of the ReadEMFImage method is:
%
% MagickBooleanType IsEMF(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsEMF(const unsigned char *magick,const size_t length)
{
if (length < 48)
return(MagickFalse);
if (memcmp(magick+40,"\040\105\115\106\000\000\001\000",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s W M F %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsWMF() returns MagickTrue if the image format type, identified by the
% magick string, is a Windows MetaFile (WMF) file.
%
% The format of the ReadEMFImage method is:
%
% MagickBooleanType IsEMF(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsWMF(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\327\315\306\232",4) == 0)
return(MagickTrue);
if (memcmp(magick,"\001\000\011\000",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d E M F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadEMFImage() reads an Microsoft Windows Enhanced MetaFile (EMF) or
% Windows MetaFile (WMF) file using the Windows API and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadEMFImage method is:
%
% Image *ReadEMFImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info..
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
# if !defined(_MSC_VER)
# if defined(MAGICKCORE_HAVE__WFOPEN)
static size_t UTF8ToUTF16(const unsigned char *utf8,wchar_t *utf16)
{
register const unsigned char
*p;
if (utf16 != (wchar_t *) NULL)
{
register wchar_t
*q;
wchar_t
c;
/*
Convert UTF-8 to UTF-16.
*/
q=utf16;
for (p=utf8; *p != '\0'; p++)
{
if ((*p & 0x80) == 0)
*q=(*p);
else
if ((*p & 0xE0) == 0xC0)
{
c=(*p);
*q=(c & 0x1F) << 6;
p++;
if ((*p & 0xC0) != 0x80)
return(0);
*q|=(*p & 0x3F);
}
else
if ((*p & 0xF0) == 0xE0)
{
c=(*p);
*q=c << 12;
p++;
if ((*p & 0xC0) != 0x80)
return(0);
c=(*p);
*q|=(c & 0x3F) << 6;
p++;
if ((*p & 0xC0) != 0x80)
return(0);
*q|=(*p & 0x3F);
}
else
return(0);
q++;
}
*q++='\0';
return(q-utf16);
}
/*
Compute UTF-16 string length.
*/
for (p=utf8; *p != '\0'; p++)
{
if ((*p & 0x80) == 0)
;
else
if ((*p & 0xE0) == 0xC0)
{
p++;
if ((*p & 0xC0) != 0x80)
return(0);
}
else
if ((*p & 0xF0) == 0xE0)
{
p++;
if ((*p & 0xC0) != 0x80)
return(0);
p++;
if ((*p & 0xC0) != 0x80)
return(0);
}
else
return(0);
}
return(p-utf8);
}
static wchar_t *ConvertUTF8ToUTF16(const unsigned char *source)
{
size_t
length;
wchar_t
*utf16;
length=UTF8ToUTF16(source,(wchar_t *) NULL);
if (length == 0)
{
register ssize_t
i;
/*
Not UTF-8, just copy.
*/
length=strlen((char *) source);
utf16=(wchar_t *) AcquireQuantumMemory(length+1,sizeof(*utf16));
if (utf16 == (wchar_t *) NULL)
return((wchar_t *) NULL);
for (i=0; i <= (ssize_t) length; i++)
utf16[i]=source[i];
return(utf16);
}
utf16=(wchar_t *) AcquireQuantumMemory(length+1,sizeof(*utf16));
if (utf16 == (wchar_t *) NULL)
return((wchar_t *) NULL);
length=UTF8ToUTF16(source,utf16);
return(utf16);
}
# endif /* MAGICKCORE_HAVE__WFOPEN */
static HENHMETAFILE ReadEnhMetaFile(const char *path,ssize_t *width,
ssize_t *height)
{
#pragma pack( push, 2 )
typedef struct
{
DWORD dwKey;
WORD hmf;
SMALL_RECT bbox;
WORD wInch;
DWORD dwReserved;
WORD wCheckSum;
} APMHEADER, *PAPMHEADER;
#pragma pack( pop )
DWORD
dwSize;
ENHMETAHEADER
emfh;
HANDLE
hFile;
HDC
hDC;
HENHMETAFILE
hTemp;
LPBYTE
pBits;
METAFILEPICT
mp;
HMETAFILE
hOld;
*width=512;
*height=512;
hTemp=GetEnhMetaFile(path);
#if defined(MAGICKCORE_HAVE__WFOPEN)
if (hTemp == (HENHMETAFILE) NULL)
{
wchar_t
*unicode_path;
unicode_path=ConvertUTF8ToUTF16((const unsigned char *) path);
if (unicode_path != (wchar_t *) NULL)
{
hTemp=GetEnhMetaFileW(unicode_path);
unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path);
}
}
#endif
if (hTemp != (HENHMETAFILE) NULL)
{
/*
Enhanced metafile.
*/
GetEnhMetaFileHeader(hTemp,sizeof(ENHMETAHEADER),&emfh);
*width=emfh.rclFrame.right-emfh.rclFrame.left;
*height=emfh.rclFrame.bottom-emfh.rclFrame.top;
return(hTemp);
}
hOld=GetMetaFile(path);
if (hOld != (HMETAFILE) NULL)
{
/*
16bit windows metafile.
*/
dwSize=GetMetaFileBitsEx(hOld,0,NULL);
if (dwSize == 0)
{
DeleteMetaFile(hOld);
return((HENHMETAFILE) NULL);
}
pBits=(LPBYTE) AcquireQuantumMemory(dwSize,sizeof(*pBits));
if (pBits == (LPBYTE) NULL)
{
DeleteMetaFile(hOld);
return((HENHMETAFILE) NULL);
}
if (GetMetaFileBitsEx(hOld,dwSize,pBits) == 0)
{
pBits=(BYTE *) DestroyString((char *) pBits);
DeleteMetaFile(hOld);
return((HENHMETAFILE) NULL);
}
/*
Make an enhanced metafile from the windows metafile.
*/
mp.mm=MM_ANISOTROPIC;
mp.xExt=1000;
mp.yExt=1000;
mp.hMF=NULL;
hDC=GetDC(NULL);
hTemp=SetWinMetaFileBits(dwSize,pBits,hDC,&mp);
ReleaseDC(NULL,hDC);
DeleteMetaFile(hOld);
pBits=(BYTE *) DestroyString((char *) pBits);
GetEnhMetaFileHeader(hTemp,sizeof(ENHMETAHEADER),&emfh);
*width=emfh.rclFrame.right-emfh.rclFrame.left;
*height=emfh.rclFrame.bottom-emfh.rclFrame.top;
return(hTemp);
}
/*
Aldus Placeable metafile.
*/
hFile=CreateFile(path,GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
return(NULL);
dwSize=GetFileSize(hFile,NULL);
pBits=(LPBYTE) AcquireQuantumMemory(dwSize,sizeof(*pBits));
ReadFile(hFile,pBits,dwSize,&dwSize,NULL);
CloseHandle(hFile);
if (((PAPMHEADER) pBits)->dwKey != 0x9ac6cdd7l)
{
pBits=(BYTE *) DestroyString((char *) pBits);
return((HENHMETAFILE) NULL);
}
/*
Make an enhanced metafile from the placable metafile.
*/
mp.mm=MM_ANISOTROPIC;
mp.xExt=((PAPMHEADER) pBits)->bbox.Right-((PAPMHEADER) pBits)->bbox.Left;
*width=mp.xExt;
mp.xExt=(mp.xExt*2540l)/(DWORD) (((PAPMHEADER) pBits)->wInch);
mp.yExt=((PAPMHEADER)pBits)->bbox.Bottom-((PAPMHEADER) pBits)->bbox.Top;
*height=mp.yExt;
mp.yExt=(mp.yExt*2540l)/(DWORD) (((PAPMHEADER) pBits)->wInch);
mp.hMF=NULL;
hDC=GetDC(NULL);
hTemp=SetWinMetaFileBits(dwSize,&(pBits[sizeof(APMHEADER)]),hDC,&mp);
ReleaseDC(NULL,hDC);
pBits=(BYTE *) DestroyString((char *) pBits);
return(hTemp);
}
#define CENTIMETERS_INCH 2.54
static Image *ReadEMFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
BITMAPINFO
DIBinfo;
HBITMAP
hBitmap,
hOldBitmap;
HDC
hDC;
HENHMETAFILE
hemf;
Image
*image;
RECT
rect;
register ssize_t
x;
register PixelPacket
*q;
RGBQUAD
*pBits,
*ppBits;
ssize_t
height,
width,
y;
image=AcquireImage(image_info);
hemf=ReadEnhMetaFile(image_info->filename,&width,&height);
if (hemf == (HENHMETAFILE) NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image->columns == 0) || (image->rows == 0))
{
double
y_resolution,
x_resolution;
y_resolution=DefaultResolution;
x_resolution=DefaultResolution;
if (image->y_resolution > 0)
{
y_resolution=image->y_resolution;
if (image->units == PixelsPerCentimeterResolution)
y_resolution*=CENTIMETERS_INCH;
}
if (image->x_resolution > 0)
{
x_resolution=image->x_resolution;
if (image->units == PixelsPerCentimeterResolution)
x_resolution*=CENTIMETERS_INCH;
}
image->rows=(size_t) ((height/1000.0/CENTIMETERS_INCH)*y_resolution+0.5);
image->columns=(size_t) ((width/1000.0/CENTIMETERS_INCH)*
x_resolution+0.5);
}
if (image_info->size != (char *) NULL)
{
ssize_t
x;
image->columns=width;
image->rows=height;
x=0;
y=0;
(void) GetGeometry(image_info->size,&x,&y,&image->columns,&image->rows);
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (image_info->page != (char *) NULL)
{
char
*geometry;
register char
*p;
MagickStatusType
flags;
ssize_t
sans;
geometry=GetPageGeometry(image_info->page);
p=strchr(geometry,'>');
if (p == (char *) NULL)
{
flags=ParseMetaGeometry(geometry,&sans,&sans,&image->columns,
&image->rows);
if (image->x_resolution != 0.0)
image->columns=(size_t) floor((image->columns*image->x_resolution)+
0.5);
if (image->y_resolution != 0.0)
image->rows=(size_t) floor((image->rows*image->y_resolution)+0.5);
}
else
{
*p='\0';
flags=ParseMetaGeometry(geometry,&sans,&sans,&image->columns,
&image->rows);
if (image->x_resolution != 0.0)
image->columns=(size_t) floor(((image->columns*image->x_resolution)/
DefaultResolution)+0.5);
if (image->y_resolution != 0.0)
image->rows=(size_t) floor(((image->rows*image->y_resolution)/
DefaultResolution)+0.5);
}
(void) flags;
geometry=DestroyString(geometry);
}
hDC=GetDC(NULL);
if (hDC == (HDC) NULL)
{
DeleteEnhMetaFile(hemf);
ThrowReaderException(ResourceLimitError,"UnableToCreateADC");
}
/*
Initialize the bitmap header info.
*/
(void) ResetMagickMemory(&DIBinfo,0,sizeof(BITMAPINFO));
DIBinfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
DIBinfo.bmiHeader.biWidth=(LONG) image->columns;
DIBinfo.bmiHeader.biHeight=(-1)*(LONG) image->rows;
DIBinfo.bmiHeader.biPlanes=1;
DIBinfo.bmiHeader.biBitCount=32;
DIBinfo.bmiHeader.biCompression=BI_RGB;
hBitmap=CreateDIBSection(hDC,&DIBinfo,DIB_RGB_COLORS,(void **) &ppBits,NULL,
0);
ReleaseDC(NULL,hDC);
if (hBitmap == (HBITMAP) NULL)
{
DeleteEnhMetaFile(hemf);
ThrowReaderException(ResourceLimitError,"UnableToCreateBitmap");
}
hDC=CreateCompatibleDC(NULL);
if (hDC == (HDC) NULL)
{
DeleteEnhMetaFile(hemf);
DeleteObject(hBitmap);
ThrowReaderException(ResourceLimitError,"UnableToCreateADC");
}
hOldBitmap=(HBITMAP) SelectObject(hDC,hBitmap);
if (hOldBitmap == (HBITMAP) NULL)
{
DeleteEnhMetaFile(hemf);
DeleteDC(hDC);
DeleteObject(hBitmap);
ThrowReaderException(ResourceLimitError,"UnableToCreateBitmap");
}
/*
Initialize the bitmap to the image background color.
*/
pBits=ppBits;
for (y=0; y < (ssize_t) image->rows; y++)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pBits->rgbRed=ScaleQuantumToChar(image->background_color.red);
pBits->rgbGreen=ScaleQuantumToChar(image->background_color.green);
pBits->rgbBlue=ScaleQuantumToChar(image->background_color.blue);
pBits++;
}
}
rect.top=0;
rect.left=0;
rect.right=(LONG) image->columns;
rect.bottom=(LONG) image->rows;
/*
Convert metafile pixels.
*/
PlayEnhMetaFile(hDC,hemf,&rect);
pBits=ppBits;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(pBits->rgbRed));
SetPixelGreen(q,ScaleCharToQuantum(pBits->rgbGreen));
SetPixelBlue(q,ScaleCharToQuantum(pBits->rgbBlue));
SetPixelOpacity(q,OpaqueOpacity);
pBits++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
DeleteEnhMetaFile(hemf);
SelectObject(hDC,hOldBitmap);
DeleteDC(hDC);
DeleteObject(hBitmap);
return(GetFirstImageInList(image));
}
# else
static Image *ReadEMFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Gdiplus::Bitmap
*bitmap;
Gdiplus::BitmapData
bitmap_data;
Gdiplus::GdiplusStartupInput
startup_input;
Gdiplus::Graphics
*graphics;
Gdiplus::Image
*source;
Gdiplus::Rect
rect;
GeometryInfo
geometry_info;
Image
*image;
MagickStatusType
flags;
register PixelPacket
*q;
register ssize_t
x;
ssize_t
y;
ULONG_PTR
token;
unsigned char
*p;
wchar_t
fileName[MaxTextExtent];
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
image=AcquireImage(image_info);
if (Gdiplus::GdiplusStartup(&token,&startup_input,NULL) !=
Gdiplus::Status::Ok)
ThrowReaderException(CoderError, "GdiplusStartupFailed");
MultiByteToWideChar(CP_UTF8,0,image->filename,-1,fileName,MaxTextExtent);
source=Gdiplus::Image::FromFile(fileName);
if (source == (Gdiplus::Image *) NULL)
{
Gdiplus::GdiplusShutdown(token);
ThrowReaderException(FileOpenError,"UnableToOpenFile");
}
image->x_resolution=source->GetHorizontalResolution();
image->y_resolution=source->GetVerticalResolution();
image->columns=(size_t) source->GetWidth();
image->rows=(size_t) source->GetHeight();
if (image_info->density != (char *) NULL)
{
flags=ParseGeometry(image_info->density,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
if ((image->x_resolution > 0.0) && (image->y_resolution > 0.0))
{
image->columns=(size_t) floor((Gdiplus::REAL) source->GetWidth() /
source->GetHorizontalResolution() * image->x_resolution + 0.5);
image->rows=(size_t)floor((Gdiplus::REAL) source->GetHeight() /
source->GetVerticalResolution() * image->y_resolution + 0.5);
}
}
bitmap=new Gdiplus::Bitmap((INT) image->columns,(INT) image->rows,
PixelFormat32bppARGB);
graphics=Gdiplus::Graphics::FromImage(bitmap);
graphics->SetInterpolationMode(Gdiplus::InterpolationModeHighQualityBicubic);
graphics->SetSmoothingMode(Gdiplus::SmoothingModeHighQuality);
graphics->SetTextRenderingHint(Gdiplus::TextRenderingHintClearTypeGridFit);
graphics->Clear(Gdiplus::Color((BYTE) ScaleQuantumToChar(QuantumRange-
image->background_color.opacity),(BYTE) ScaleQuantumToChar(
image->background_color.red),(BYTE) ScaleQuantumToChar(
image->background_color.green),(BYTE) ScaleQuantumToChar(
image->background_color.blue)));
graphics->DrawImage(source,0,0,(INT) image->columns,(INT) image->rows);
delete graphics;
delete source;
rect=Gdiplus::Rect(0,0,(INT) image->columns,(INT) image->rows);
if (bitmap->LockBits(&rect,Gdiplus::ImageLockModeRead,PixelFormat32bppARGB,
&bitmap_data) != Gdiplus::Ok)
{
delete bitmap;
Gdiplus::GdiplusShutdown(token);
ThrowReaderException(FileOpenError,"UnableToReadImageData");
}
image->matte=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=(unsigned char *) bitmap_data.Scan0+(y*abs(bitmap_data.Stride));
if (bitmap_data.Stride < 0)
q=GetAuthenticPixels(image,0,image->rows-y-1,image->columns,1,exception);
else
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
bitmap->UnlockBits(&bitmap_data);
delete bitmap;
Gdiplus::GdiplusShutdown(token);
return(image);
}
# endif /* _MSC_VER */
#endif /* MAGICKCORE_WINGDI32_DELEGATE */
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r E M F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterEMFImage() adds attributes for the EMF image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterEMFImage method is:
%
% size_t RegisterEMFImage(void)
%
*/
ModuleExport size_t RegisterEMFImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("EMF");
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
entry->decoder=ReadEMFImage;
#endif
entry->description=ConstantString(
"Windows Enhanced Meta File");
entry->magick=(IsImageFormatHandler *) IsEMF;
entry->blob_support=MagickFalse;
entry->module=ConstantString("WMF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("WMF");
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
entry->decoder=ReadEMFImage;
#endif
entry->description=ConstantString("Windows Meta File");
entry->magick=(IsImageFormatHandler *) IsWMF;
entry->blob_support=MagickFalse;
entry->module=ConstantString("WMF");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r E M F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterEMFImage() removes format registrations made by the
% EMF module from the list of supported formats.
%
% The format of the UnregisterEMFImage method is:
%
% UnregisterEMFImage(void)
%
*/
ModuleExport void UnregisterEMFImage(void)
{
(void) UnregisterMagickInfo("EMF");
(void) UnregisterMagickInfo("WMF");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_16 |
crossvul-cpp_data_bad_3503_0 | /*
FUSE: Filesystem in Userspace
Copyright (C) 2001-2008 Miklos Szeredi <miklos@szeredi.hu>
This program can be distributed under the terms of the GNU GPL.
See the file COPYING.
*/
#include "fuse_i.h"
#include <linux/init.h>
#include <linux/module.h>
#include <linux/poll.h>
#include <linux/uio.h>
#include <linux/miscdevice.h>
#include <linux/pagemap.h>
#include <linux/file.h>
#include <linux/slab.h>
#include <linux/pipe_fs_i.h>
#include <linux/swap.h>
#include <linux/splice.h>
MODULE_ALIAS_MISCDEV(FUSE_MINOR);
MODULE_ALIAS("devname:fuse");
static struct kmem_cache *fuse_req_cachep;
static struct fuse_conn *fuse_get_conn(struct file *file)
{
/*
* Lockless access is OK, because file->private data is set
* once during mount and is valid until the file is released.
*/
return file->private_data;
}
static void fuse_request_init(struct fuse_req *req)
{
memset(req, 0, sizeof(*req));
INIT_LIST_HEAD(&req->list);
INIT_LIST_HEAD(&req->intr_entry);
init_waitqueue_head(&req->waitq);
atomic_set(&req->count, 1);
}
struct fuse_req *fuse_request_alloc(void)
{
struct fuse_req *req = kmem_cache_alloc(fuse_req_cachep, GFP_KERNEL);
if (req)
fuse_request_init(req);
return req;
}
EXPORT_SYMBOL_GPL(fuse_request_alloc);
struct fuse_req *fuse_request_alloc_nofs(void)
{
struct fuse_req *req = kmem_cache_alloc(fuse_req_cachep, GFP_NOFS);
if (req)
fuse_request_init(req);
return req;
}
void fuse_request_free(struct fuse_req *req)
{
kmem_cache_free(fuse_req_cachep, req);
}
static void block_sigs(sigset_t *oldset)
{
sigset_t mask;
siginitsetinv(&mask, sigmask(SIGKILL));
sigprocmask(SIG_BLOCK, &mask, oldset);
}
static void restore_sigs(sigset_t *oldset)
{
sigprocmask(SIG_SETMASK, oldset, NULL);
}
static void __fuse_get_request(struct fuse_req *req)
{
atomic_inc(&req->count);
}
/* Must be called with > 1 refcount */
static void __fuse_put_request(struct fuse_req *req)
{
BUG_ON(atomic_read(&req->count) < 2);
atomic_dec(&req->count);
}
static void fuse_req_init_context(struct fuse_req *req)
{
req->in.h.uid = current_fsuid();
req->in.h.gid = current_fsgid();
req->in.h.pid = current->pid;
}
struct fuse_req *fuse_get_req(struct fuse_conn *fc)
{
struct fuse_req *req;
sigset_t oldset;
int intr;
int err;
atomic_inc(&fc->num_waiting);
block_sigs(&oldset);
intr = wait_event_interruptible(fc->blocked_waitq, !fc->blocked);
restore_sigs(&oldset);
err = -EINTR;
if (intr)
goto out;
err = -ENOTCONN;
if (!fc->connected)
goto out;
req = fuse_request_alloc();
err = -ENOMEM;
if (!req)
goto out;
fuse_req_init_context(req);
req->waiting = 1;
return req;
out:
atomic_dec(&fc->num_waiting);
return ERR_PTR(err);
}
EXPORT_SYMBOL_GPL(fuse_get_req);
/*
* Return request in fuse_file->reserved_req. However that may
* currently be in use. If that is the case, wait for it to become
* available.
*/
static struct fuse_req *get_reserved_req(struct fuse_conn *fc,
struct file *file)
{
struct fuse_req *req = NULL;
struct fuse_file *ff = file->private_data;
do {
wait_event(fc->reserved_req_waitq, ff->reserved_req);
spin_lock(&fc->lock);
if (ff->reserved_req) {
req = ff->reserved_req;
ff->reserved_req = NULL;
get_file(file);
req->stolen_file = file;
}
spin_unlock(&fc->lock);
} while (!req);
return req;
}
/*
* Put stolen request back into fuse_file->reserved_req
*/
static void put_reserved_req(struct fuse_conn *fc, struct fuse_req *req)
{
struct file *file = req->stolen_file;
struct fuse_file *ff = file->private_data;
spin_lock(&fc->lock);
fuse_request_init(req);
BUG_ON(ff->reserved_req);
ff->reserved_req = req;
wake_up_all(&fc->reserved_req_waitq);
spin_unlock(&fc->lock);
fput(file);
}
/*
* Gets a requests for a file operation, always succeeds
*
* This is used for sending the FLUSH request, which must get to
* userspace, due to POSIX locks which may need to be unlocked.
*
* If allocation fails due to OOM, use the reserved request in
* fuse_file.
*
* This is very unlikely to deadlock accidentally, since the
* filesystem should not have it's own file open. If deadlock is
* intentional, it can still be broken by "aborting" the filesystem.
*/
struct fuse_req *fuse_get_req_nofail(struct fuse_conn *fc, struct file *file)
{
struct fuse_req *req;
atomic_inc(&fc->num_waiting);
wait_event(fc->blocked_waitq, !fc->blocked);
req = fuse_request_alloc();
if (!req)
req = get_reserved_req(fc, file);
fuse_req_init_context(req);
req->waiting = 1;
return req;
}
void fuse_put_request(struct fuse_conn *fc, struct fuse_req *req)
{
if (atomic_dec_and_test(&req->count)) {
if (req->waiting)
atomic_dec(&fc->num_waiting);
if (req->stolen_file)
put_reserved_req(fc, req);
else
fuse_request_free(req);
}
}
EXPORT_SYMBOL_GPL(fuse_put_request);
static unsigned len_args(unsigned numargs, struct fuse_arg *args)
{
unsigned nbytes = 0;
unsigned i;
for (i = 0; i < numargs; i++)
nbytes += args[i].size;
return nbytes;
}
static u64 fuse_get_unique(struct fuse_conn *fc)
{
fc->reqctr++;
/* zero is special */
if (fc->reqctr == 0)
fc->reqctr = 1;
return fc->reqctr;
}
static void queue_request(struct fuse_conn *fc, struct fuse_req *req)
{
req->in.h.len = sizeof(struct fuse_in_header) +
len_args(req->in.numargs, (struct fuse_arg *) req->in.args);
list_add_tail(&req->list, &fc->pending);
req->state = FUSE_REQ_PENDING;
if (!req->waiting) {
req->waiting = 1;
atomic_inc(&fc->num_waiting);
}
wake_up(&fc->waitq);
kill_fasync(&fc->fasync, SIGIO, POLL_IN);
}
void fuse_queue_forget(struct fuse_conn *fc, struct fuse_forget_link *forget,
u64 nodeid, u64 nlookup)
{
forget->forget_one.nodeid = nodeid;
forget->forget_one.nlookup = nlookup;
spin_lock(&fc->lock);
fc->forget_list_tail->next = forget;
fc->forget_list_tail = forget;
wake_up(&fc->waitq);
kill_fasync(&fc->fasync, SIGIO, POLL_IN);
spin_unlock(&fc->lock);
}
static void flush_bg_queue(struct fuse_conn *fc)
{
while (fc->active_background < fc->max_background &&
!list_empty(&fc->bg_queue)) {
struct fuse_req *req;
req = list_entry(fc->bg_queue.next, struct fuse_req, list);
list_del(&req->list);
fc->active_background++;
req->in.h.unique = fuse_get_unique(fc);
queue_request(fc, req);
}
}
/*
* This function is called when a request is finished. Either a reply
* has arrived or it was aborted (and not yet sent) or some error
* occurred during communication with userspace, or the device file
* was closed. The requester thread is woken up (if still waiting),
* the 'end' callback is called if given, else the reference to the
* request is released
*
* Called with fc->lock, unlocks it
*/
static void request_end(struct fuse_conn *fc, struct fuse_req *req)
__releases(fc->lock)
{
void (*end) (struct fuse_conn *, struct fuse_req *) = req->end;
req->end = NULL;
list_del(&req->list);
list_del(&req->intr_entry);
req->state = FUSE_REQ_FINISHED;
if (req->background) {
if (fc->num_background == fc->max_background) {
fc->blocked = 0;
wake_up_all(&fc->blocked_waitq);
}
if (fc->num_background == fc->congestion_threshold &&
fc->connected && fc->bdi_initialized) {
clear_bdi_congested(&fc->bdi, BLK_RW_SYNC);
clear_bdi_congested(&fc->bdi, BLK_RW_ASYNC);
}
fc->num_background--;
fc->active_background--;
flush_bg_queue(fc);
}
spin_unlock(&fc->lock);
wake_up(&req->waitq);
if (end)
end(fc, req);
fuse_put_request(fc, req);
}
static void wait_answer_interruptible(struct fuse_conn *fc,
struct fuse_req *req)
__releases(fc->lock)
__acquires(fc->lock)
{
if (signal_pending(current))
return;
spin_unlock(&fc->lock);
wait_event_interruptible(req->waitq, req->state == FUSE_REQ_FINISHED);
spin_lock(&fc->lock);
}
static void queue_interrupt(struct fuse_conn *fc, struct fuse_req *req)
{
list_add_tail(&req->intr_entry, &fc->interrupts);
wake_up(&fc->waitq);
kill_fasync(&fc->fasync, SIGIO, POLL_IN);
}
static void request_wait_answer(struct fuse_conn *fc, struct fuse_req *req)
__releases(fc->lock)
__acquires(fc->lock)
{
if (!fc->no_interrupt) {
/* Any signal may interrupt this */
wait_answer_interruptible(fc, req);
if (req->aborted)
goto aborted;
if (req->state == FUSE_REQ_FINISHED)
return;
req->interrupted = 1;
if (req->state == FUSE_REQ_SENT)
queue_interrupt(fc, req);
}
if (!req->force) {
sigset_t oldset;
/* Only fatal signals may interrupt this */
block_sigs(&oldset);
wait_answer_interruptible(fc, req);
restore_sigs(&oldset);
if (req->aborted)
goto aborted;
if (req->state == FUSE_REQ_FINISHED)
return;
/* Request is not yet in userspace, bail out */
if (req->state == FUSE_REQ_PENDING) {
list_del(&req->list);
__fuse_put_request(req);
req->out.h.error = -EINTR;
return;
}
}
/*
* Either request is already in userspace, or it was forced.
* Wait it out.
*/
spin_unlock(&fc->lock);
wait_event(req->waitq, req->state == FUSE_REQ_FINISHED);
spin_lock(&fc->lock);
if (!req->aborted)
return;
aborted:
BUG_ON(req->state != FUSE_REQ_FINISHED);
if (req->locked) {
/* This is uninterruptible sleep, because data is
being copied to/from the buffers of req. During
locked state, there mustn't be any filesystem
operation (e.g. page fault), since that could lead
to deadlock */
spin_unlock(&fc->lock);
wait_event(req->waitq, !req->locked);
spin_lock(&fc->lock);
}
}
void fuse_request_send(struct fuse_conn *fc, struct fuse_req *req)
{
req->isreply = 1;
spin_lock(&fc->lock);
if (!fc->connected)
req->out.h.error = -ENOTCONN;
else if (fc->conn_error)
req->out.h.error = -ECONNREFUSED;
else {
req->in.h.unique = fuse_get_unique(fc);
queue_request(fc, req);
/* acquire extra reference, since request is still needed
after request_end() */
__fuse_get_request(req);
request_wait_answer(fc, req);
}
spin_unlock(&fc->lock);
}
EXPORT_SYMBOL_GPL(fuse_request_send);
static void fuse_request_send_nowait_locked(struct fuse_conn *fc,
struct fuse_req *req)
{
req->background = 1;
fc->num_background++;
if (fc->num_background == fc->max_background)
fc->blocked = 1;
if (fc->num_background == fc->congestion_threshold &&
fc->bdi_initialized) {
set_bdi_congested(&fc->bdi, BLK_RW_SYNC);
set_bdi_congested(&fc->bdi, BLK_RW_ASYNC);
}
list_add_tail(&req->list, &fc->bg_queue);
flush_bg_queue(fc);
}
static void fuse_request_send_nowait(struct fuse_conn *fc, struct fuse_req *req)
{
spin_lock(&fc->lock);
if (fc->connected) {
fuse_request_send_nowait_locked(fc, req);
spin_unlock(&fc->lock);
} else {
req->out.h.error = -ENOTCONN;
request_end(fc, req);
}
}
void fuse_request_send_background(struct fuse_conn *fc, struct fuse_req *req)
{
req->isreply = 1;
fuse_request_send_nowait(fc, req);
}
EXPORT_SYMBOL_GPL(fuse_request_send_background);
static int fuse_request_send_notify_reply(struct fuse_conn *fc,
struct fuse_req *req, u64 unique)
{
int err = -ENODEV;
req->isreply = 0;
req->in.h.unique = unique;
spin_lock(&fc->lock);
if (fc->connected) {
queue_request(fc, req);
err = 0;
}
spin_unlock(&fc->lock);
return err;
}
/*
* Called under fc->lock
*
* fc->connected must have been checked previously
*/
void fuse_request_send_background_locked(struct fuse_conn *fc,
struct fuse_req *req)
{
req->isreply = 1;
fuse_request_send_nowait_locked(fc, req);
}
/*
* Lock the request. Up to the next unlock_request() there mustn't be
* anything that could cause a page-fault. If the request was already
* aborted bail out.
*/
static int lock_request(struct fuse_conn *fc, struct fuse_req *req)
{
int err = 0;
if (req) {
spin_lock(&fc->lock);
if (req->aborted)
err = -ENOENT;
else
req->locked = 1;
spin_unlock(&fc->lock);
}
return err;
}
/*
* Unlock request. If it was aborted during being locked, the
* requester thread is currently waiting for it to be unlocked, so
* wake it up.
*/
static void unlock_request(struct fuse_conn *fc, struct fuse_req *req)
{
if (req) {
spin_lock(&fc->lock);
req->locked = 0;
if (req->aborted)
wake_up(&req->waitq);
spin_unlock(&fc->lock);
}
}
struct fuse_copy_state {
struct fuse_conn *fc;
int write;
struct fuse_req *req;
const struct iovec *iov;
struct pipe_buffer *pipebufs;
struct pipe_buffer *currbuf;
struct pipe_inode_info *pipe;
unsigned long nr_segs;
unsigned long seglen;
unsigned long addr;
struct page *pg;
void *mapaddr;
void *buf;
unsigned len;
unsigned move_pages:1;
};
static void fuse_copy_init(struct fuse_copy_state *cs, struct fuse_conn *fc,
int write,
const struct iovec *iov, unsigned long nr_segs)
{
memset(cs, 0, sizeof(*cs));
cs->fc = fc;
cs->write = write;
cs->iov = iov;
cs->nr_segs = nr_segs;
}
/* Unmap and put previous page of userspace buffer */
static void fuse_copy_finish(struct fuse_copy_state *cs)
{
if (cs->currbuf) {
struct pipe_buffer *buf = cs->currbuf;
if (!cs->write) {
buf->ops->unmap(cs->pipe, buf, cs->mapaddr);
} else {
kunmap(buf->page);
buf->len = PAGE_SIZE - cs->len;
}
cs->currbuf = NULL;
cs->mapaddr = NULL;
} else if (cs->mapaddr) {
kunmap(cs->pg);
if (cs->write) {
flush_dcache_page(cs->pg);
set_page_dirty_lock(cs->pg);
}
put_page(cs->pg);
cs->mapaddr = NULL;
}
}
/*
* Get another pagefull of userspace buffer, and map it to kernel
* address space, and lock request
*/
static int fuse_copy_fill(struct fuse_copy_state *cs)
{
unsigned long offset;
int err;
unlock_request(cs->fc, cs->req);
fuse_copy_finish(cs);
if (cs->pipebufs) {
struct pipe_buffer *buf = cs->pipebufs;
if (!cs->write) {
err = buf->ops->confirm(cs->pipe, buf);
if (err)
return err;
BUG_ON(!cs->nr_segs);
cs->currbuf = buf;
cs->mapaddr = buf->ops->map(cs->pipe, buf, 0);
cs->len = buf->len;
cs->buf = cs->mapaddr + buf->offset;
cs->pipebufs++;
cs->nr_segs--;
} else {
struct page *page;
if (cs->nr_segs == cs->pipe->buffers)
return -EIO;
page = alloc_page(GFP_HIGHUSER);
if (!page)
return -ENOMEM;
buf->page = page;
buf->offset = 0;
buf->len = 0;
cs->currbuf = buf;
cs->mapaddr = kmap(page);
cs->buf = cs->mapaddr;
cs->len = PAGE_SIZE;
cs->pipebufs++;
cs->nr_segs++;
}
} else {
if (!cs->seglen) {
BUG_ON(!cs->nr_segs);
cs->seglen = cs->iov[0].iov_len;
cs->addr = (unsigned long) cs->iov[0].iov_base;
cs->iov++;
cs->nr_segs--;
}
err = get_user_pages_fast(cs->addr, 1, cs->write, &cs->pg);
if (err < 0)
return err;
BUG_ON(err != 1);
offset = cs->addr % PAGE_SIZE;
cs->mapaddr = kmap(cs->pg);
cs->buf = cs->mapaddr + offset;
cs->len = min(PAGE_SIZE - offset, cs->seglen);
cs->seglen -= cs->len;
cs->addr += cs->len;
}
return lock_request(cs->fc, cs->req);
}
/* Do as much copy to/from userspace buffer as we can */
static int fuse_copy_do(struct fuse_copy_state *cs, void **val, unsigned *size)
{
unsigned ncpy = min(*size, cs->len);
if (val) {
if (cs->write)
memcpy(cs->buf, *val, ncpy);
else
memcpy(*val, cs->buf, ncpy);
*val += ncpy;
}
*size -= ncpy;
cs->len -= ncpy;
cs->buf += ncpy;
return ncpy;
}
static int fuse_check_page(struct page *page)
{
if (page_mapcount(page) ||
page->mapping != NULL ||
page_count(page) != 1 ||
(page->flags & PAGE_FLAGS_CHECK_AT_PREP &
~(1 << PG_locked |
1 << PG_referenced |
1 << PG_uptodate |
1 << PG_lru |
1 << PG_active |
1 << PG_reclaim))) {
printk(KERN_WARNING "fuse: trying to steal weird page\n");
printk(KERN_WARNING " page=%p index=%li flags=%08lx, count=%i, mapcount=%i, mapping=%p\n", page, page->index, page->flags, page_count(page), page_mapcount(page), page->mapping);
return 1;
}
return 0;
}
static int fuse_try_move_page(struct fuse_copy_state *cs, struct page **pagep)
{
int err;
struct page *oldpage = *pagep;
struct page *newpage;
struct pipe_buffer *buf = cs->pipebufs;
struct address_space *mapping;
pgoff_t index;
unlock_request(cs->fc, cs->req);
fuse_copy_finish(cs);
err = buf->ops->confirm(cs->pipe, buf);
if (err)
return err;
BUG_ON(!cs->nr_segs);
cs->currbuf = buf;
cs->len = buf->len;
cs->pipebufs++;
cs->nr_segs--;
if (cs->len != PAGE_SIZE)
goto out_fallback;
if (buf->ops->steal(cs->pipe, buf) != 0)
goto out_fallback;
newpage = buf->page;
if (WARN_ON(!PageUptodate(newpage)))
return -EIO;
ClearPageMappedToDisk(newpage);
if (fuse_check_page(newpage) != 0)
goto out_fallback_unlock;
mapping = oldpage->mapping;
index = oldpage->index;
/*
* This is a new and locked page, it shouldn't be mapped or
* have any special flags on it
*/
if (WARN_ON(page_mapped(oldpage)))
goto out_fallback_unlock;
if (WARN_ON(page_has_private(oldpage)))
goto out_fallback_unlock;
if (WARN_ON(PageDirty(oldpage) || PageWriteback(oldpage)))
goto out_fallback_unlock;
if (WARN_ON(PageMlocked(oldpage)))
goto out_fallback_unlock;
err = replace_page_cache_page(oldpage, newpage, GFP_KERNEL);
if (err) {
unlock_page(newpage);
return err;
}
page_cache_get(newpage);
if (!(buf->flags & PIPE_BUF_FLAG_LRU))
lru_cache_add_file(newpage);
err = 0;
spin_lock(&cs->fc->lock);
if (cs->req->aborted)
err = -ENOENT;
else
*pagep = newpage;
spin_unlock(&cs->fc->lock);
if (err) {
unlock_page(newpage);
page_cache_release(newpage);
return err;
}
unlock_page(oldpage);
page_cache_release(oldpage);
cs->len = 0;
return 0;
out_fallback_unlock:
unlock_page(newpage);
out_fallback:
cs->mapaddr = buf->ops->map(cs->pipe, buf, 1);
cs->buf = cs->mapaddr + buf->offset;
err = lock_request(cs->fc, cs->req);
if (err)
return err;
return 1;
}
static int fuse_ref_page(struct fuse_copy_state *cs, struct page *page,
unsigned offset, unsigned count)
{
struct pipe_buffer *buf;
if (cs->nr_segs == cs->pipe->buffers)
return -EIO;
unlock_request(cs->fc, cs->req);
fuse_copy_finish(cs);
buf = cs->pipebufs;
page_cache_get(page);
buf->page = page;
buf->offset = offset;
buf->len = count;
cs->pipebufs++;
cs->nr_segs++;
cs->len = 0;
return 0;
}
/*
* Copy a page in the request to/from the userspace buffer. Must be
* done atomically
*/
static int fuse_copy_page(struct fuse_copy_state *cs, struct page **pagep,
unsigned offset, unsigned count, int zeroing)
{
int err;
struct page *page = *pagep;
if (page && zeroing && count < PAGE_SIZE)
clear_highpage(page);
while (count) {
if (cs->write && cs->pipebufs && page) {
return fuse_ref_page(cs, page, offset, count);
} else if (!cs->len) {
if (cs->move_pages && page &&
offset == 0 && count == PAGE_SIZE) {
err = fuse_try_move_page(cs, pagep);
if (err <= 0)
return err;
} else {
err = fuse_copy_fill(cs);
if (err)
return err;
}
}
if (page) {
void *mapaddr = kmap_atomic(page, KM_USER0);
void *buf = mapaddr + offset;
offset += fuse_copy_do(cs, &buf, &count);
kunmap_atomic(mapaddr, KM_USER0);
} else
offset += fuse_copy_do(cs, NULL, &count);
}
if (page && !cs->write)
flush_dcache_page(page);
return 0;
}
/* Copy pages in the request to/from userspace buffer */
static int fuse_copy_pages(struct fuse_copy_state *cs, unsigned nbytes,
int zeroing)
{
unsigned i;
struct fuse_req *req = cs->req;
unsigned offset = req->page_offset;
unsigned count = min(nbytes, (unsigned) PAGE_SIZE - offset);
for (i = 0; i < req->num_pages && (nbytes || zeroing); i++) {
int err;
err = fuse_copy_page(cs, &req->pages[i], offset, count,
zeroing);
if (err)
return err;
nbytes -= count;
count = min(nbytes, (unsigned) PAGE_SIZE);
offset = 0;
}
return 0;
}
/* Copy a single argument in the request to/from userspace buffer */
static int fuse_copy_one(struct fuse_copy_state *cs, void *val, unsigned size)
{
while (size) {
if (!cs->len) {
int err = fuse_copy_fill(cs);
if (err)
return err;
}
fuse_copy_do(cs, &val, &size);
}
return 0;
}
/* Copy request arguments to/from userspace buffer */
static int fuse_copy_args(struct fuse_copy_state *cs, unsigned numargs,
unsigned argpages, struct fuse_arg *args,
int zeroing)
{
int err = 0;
unsigned i;
for (i = 0; !err && i < numargs; i++) {
struct fuse_arg *arg = &args[i];
if (i == numargs - 1 && argpages)
err = fuse_copy_pages(cs, arg->size, zeroing);
else
err = fuse_copy_one(cs, arg->value, arg->size);
}
return err;
}
static int forget_pending(struct fuse_conn *fc)
{
return fc->forget_list_head.next != NULL;
}
static int request_pending(struct fuse_conn *fc)
{
return !list_empty(&fc->pending) || !list_empty(&fc->interrupts) ||
forget_pending(fc);
}
/* Wait until a request is available on the pending list */
static void request_wait(struct fuse_conn *fc)
__releases(fc->lock)
__acquires(fc->lock)
{
DECLARE_WAITQUEUE(wait, current);
add_wait_queue_exclusive(&fc->waitq, &wait);
while (fc->connected && !request_pending(fc)) {
set_current_state(TASK_INTERRUPTIBLE);
if (signal_pending(current))
break;
spin_unlock(&fc->lock);
schedule();
spin_lock(&fc->lock);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&fc->waitq, &wait);
}
/*
* Transfer an interrupt request to userspace
*
* Unlike other requests this is assembled on demand, without a need
* to allocate a separate fuse_req structure.
*
* Called with fc->lock held, releases it
*/
static int fuse_read_interrupt(struct fuse_conn *fc, struct fuse_copy_state *cs,
size_t nbytes, struct fuse_req *req)
__releases(fc->lock)
{
struct fuse_in_header ih;
struct fuse_interrupt_in arg;
unsigned reqsize = sizeof(ih) + sizeof(arg);
int err;
list_del_init(&req->intr_entry);
req->intr_unique = fuse_get_unique(fc);
memset(&ih, 0, sizeof(ih));
memset(&arg, 0, sizeof(arg));
ih.len = reqsize;
ih.opcode = FUSE_INTERRUPT;
ih.unique = req->intr_unique;
arg.unique = req->in.h.unique;
spin_unlock(&fc->lock);
if (nbytes < reqsize)
return -EINVAL;
err = fuse_copy_one(cs, &ih, sizeof(ih));
if (!err)
err = fuse_copy_one(cs, &arg, sizeof(arg));
fuse_copy_finish(cs);
return err ? err : reqsize;
}
static struct fuse_forget_link *dequeue_forget(struct fuse_conn *fc,
unsigned max,
unsigned *countp)
{
struct fuse_forget_link *head = fc->forget_list_head.next;
struct fuse_forget_link **newhead = &head;
unsigned count;
for (count = 0; *newhead != NULL && count < max; count++)
newhead = &(*newhead)->next;
fc->forget_list_head.next = *newhead;
*newhead = NULL;
if (fc->forget_list_head.next == NULL)
fc->forget_list_tail = &fc->forget_list_head;
if (countp != NULL)
*countp = count;
return head;
}
static int fuse_read_single_forget(struct fuse_conn *fc,
struct fuse_copy_state *cs,
size_t nbytes)
__releases(fc->lock)
{
int err;
struct fuse_forget_link *forget = dequeue_forget(fc, 1, NULL);
struct fuse_forget_in arg = {
.nlookup = forget->forget_one.nlookup,
};
struct fuse_in_header ih = {
.opcode = FUSE_FORGET,
.nodeid = forget->forget_one.nodeid,
.unique = fuse_get_unique(fc),
.len = sizeof(ih) + sizeof(arg),
};
spin_unlock(&fc->lock);
kfree(forget);
if (nbytes < ih.len)
return -EINVAL;
err = fuse_copy_one(cs, &ih, sizeof(ih));
if (!err)
err = fuse_copy_one(cs, &arg, sizeof(arg));
fuse_copy_finish(cs);
if (err)
return err;
return ih.len;
}
static int fuse_read_batch_forget(struct fuse_conn *fc,
struct fuse_copy_state *cs, size_t nbytes)
__releases(fc->lock)
{
int err;
unsigned max_forgets;
unsigned count;
struct fuse_forget_link *head;
struct fuse_batch_forget_in arg = { .count = 0 };
struct fuse_in_header ih = {
.opcode = FUSE_BATCH_FORGET,
.unique = fuse_get_unique(fc),
.len = sizeof(ih) + sizeof(arg),
};
if (nbytes < ih.len) {
spin_unlock(&fc->lock);
return -EINVAL;
}
max_forgets = (nbytes - ih.len) / sizeof(struct fuse_forget_one);
head = dequeue_forget(fc, max_forgets, &count);
spin_unlock(&fc->lock);
arg.count = count;
ih.len += count * sizeof(struct fuse_forget_one);
err = fuse_copy_one(cs, &ih, sizeof(ih));
if (!err)
err = fuse_copy_one(cs, &arg, sizeof(arg));
while (head) {
struct fuse_forget_link *forget = head;
if (!err) {
err = fuse_copy_one(cs, &forget->forget_one,
sizeof(forget->forget_one));
}
head = forget->next;
kfree(forget);
}
fuse_copy_finish(cs);
if (err)
return err;
return ih.len;
}
static int fuse_read_forget(struct fuse_conn *fc, struct fuse_copy_state *cs,
size_t nbytes)
__releases(fc->lock)
{
if (fc->minor < 16 || fc->forget_list_head.next->next == NULL)
return fuse_read_single_forget(fc, cs, nbytes);
else
return fuse_read_batch_forget(fc, cs, nbytes);
}
/*
* Read a single request into the userspace filesystem's buffer. This
* function waits until a request is available, then removes it from
* the pending list and copies request data to userspace buffer. If
* no reply is needed (FORGET) or request has been aborted or there
* was an error during the copying then it's finished by calling
* request_end(). Otherwise add it to the processing list, and set
* the 'sent' flag.
*/
static ssize_t fuse_dev_do_read(struct fuse_conn *fc, struct file *file,
struct fuse_copy_state *cs, size_t nbytes)
{
int err;
struct fuse_req *req;
struct fuse_in *in;
unsigned reqsize;
restart:
spin_lock(&fc->lock);
err = -EAGAIN;
if ((file->f_flags & O_NONBLOCK) && fc->connected &&
!request_pending(fc))
goto err_unlock;
request_wait(fc);
err = -ENODEV;
if (!fc->connected)
goto err_unlock;
err = -ERESTARTSYS;
if (!request_pending(fc))
goto err_unlock;
if (!list_empty(&fc->interrupts)) {
req = list_entry(fc->interrupts.next, struct fuse_req,
intr_entry);
return fuse_read_interrupt(fc, cs, nbytes, req);
}
if (forget_pending(fc)) {
if (list_empty(&fc->pending) || fc->forget_batch-- > 0)
return fuse_read_forget(fc, cs, nbytes);
if (fc->forget_batch <= -8)
fc->forget_batch = 16;
}
req = list_entry(fc->pending.next, struct fuse_req, list);
req->state = FUSE_REQ_READING;
list_move(&req->list, &fc->io);
in = &req->in;
reqsize = in->h.len;
/* If request is too large, reply with an error and restart the read */
if (nbytes < reqsize) {
req->out.h.error = -EIO;
/* SETXATTR is special, since it may contain too large data */
if (in->h.opcode == FUSE_SETXATTR)
req->out.h.error = -E2BIG;
request_end(fc, req);
goto restart;
}
spin_unlock(&fc->lock);
cs->req = req;
err = fuse_copy_one(cs, &in->h, sizeof(in->h));
if (!err)
err = fuse_copy_args(cs, in->numargs, in->argpages,
(struct fuse_arg *) in->args, 0);
fuse_copy_finish(cs);
spin_lock(&fc->lock);
req->locked = 0;
if (req->aborted) {
request_end(fc, req);
return -ENODEV;
}
if (err) {
req->out.h.error = -EIO;
request_end(fc, req);
return err;
}
if (!req->isreply)
request_end(fc, req);
else {
req->state = FUSE_REQ_SENT;
list_move_tail(&req->list, &fc->processing);
if (req->interrupted)
queue_interrupt(fc, req);
spin_unlock(&fc->lock);
}
return reqsize;
err_unlock:
spin_unlock(&fc->lock);
return err;
}
static ssize_t fuse_dev_read(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct fuse_copy_state cs;
struct file *file = iocb->ki_filp;
struct fuse_conn *fc = fuse_get_conn(file);
if (!fc)
return -EPERM;
fuse_copy_init(&cs, fc, 1, iov, nr_segs);
return fuse_dev_do_read(fc, file, &cs, iov_length(iov, nr_segs));
}
static int fuse_dev_pipe_buf_steal(struct pipe_inode_info *pipe,
struct pipe_buffer *buf)
{
return 1;
}
static const struct pipe_buf_operations fuse_dev_pipe_buf_ops = {
.can_merge = 0,
.map = generic_pipe_buf_map,
.unmap = generic_pipe_buf_unmap,
.confirm = generic_pipe_buf_confirm,
.release = generic_pipe_buf_release,
.steal = fuse_dev_pipe_buf_steal,
.get = generic_pipe_buf_get,
};
static ssize_t fuse_dev_splice_read(struct file *in, loff_t *ppos,
struct pipe_inode_info *pipe,
size_t len, unsigned int flags)
{
int ret;
int page_nr = 0;
int do_wakeup = 0;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_conn *fc = fuse_get_conn(in);
if (!fc)
return -EPERM;
bufs = kmalloc(pipe->buffers * sizeof(struct pipe_buffer), GFP_KERNEL);
if (!bufs)
return -ENOMEM;
fuse_copy_init(&cs, fc, 1, NULL, 0);
cs.pipebufs = bufs;
cs.pipe = pipe;
ret = fuse_dev_do_read(fc, in, &cs, len);
if (ret < 0)
goto out;
ret = 0;
pipe_lock(pipe);
if (!pipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
goto out_unlock;
}
if (pipe->nrbufs + cs.nr_segs > pipe->buffers) {
ret = -EIO;
goto out_unlock;
}
while (page_nr < cs.nr_segs) {
int newbuf = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
struct pipe_buffer *buf = pipe->bufs + newbuf;
buf->page = bufs[page_nr].page;
buf->offset = bufs[page_nr].offset;
buf->len = bufs[page_nr].len;
buf->ops = &fuse_dev_pipe_buf_ops;
pipe->nrbufs++;
page_nr++;
ret += buf->len;
if (pipe->inode)
do_wakeup = 1;
}
out_unlock:
pipe_unlock(pipe);
if (do_wakeup) {
smp_mb();
if (waitqueue_active(&pipe->wait))
wake_up_interruptible(&pipe->wait);
kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
}
out:
for (; page_nr < cs.nr_segs; page_nr++)
page_cache_release(bufs[page_nr].page);
kfree(bufs);
return ret;
}
static int fuse_notify_poll(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_poll_wakeup_out outarg;
int err = -EINVAL;
if (size != sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
fuse_copy_finish(cs);
return fuse_notify_poll_wakeup(fc, &outarg);
err:
fuse_copy_finish(cs);
return err;
}
static int fuse_notify_inval_inode(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_inval_inode_out outarg;
int err = -EINVAL;
if (size != sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
fuse_copy_finish(cs);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb) {
err = fuse_reverse_inval_inode(fc->sb, outarg.ino,
outarg.off, outarg.len);
}
up_read(&fc->killsb);
return err;
err:
fuse_copy_finish(cs);
return err;
}
static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_inval_entry_out outarg;
int err = -ENOMEM;
char *buf;
struct qstr name;
buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
if (!buf)
goto err;
err = -EINVAL;
if (size < sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
err = -ENAMETOOLONG;
if (outarg.namelen > FUSE_NAME_MAX)
goto err;
name.name = buf;
name.len = outarg.namelen;
err = fuse_copy_one(cs, buf, outarg.namelen + 1);
if (err)
goto err;
fuse_copy_finish(cs);
buf[outarg.namelen] = 0;
name.hash = full_name_hash(name.name, name.len);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb)
err = fuse_reverse_inval_entry(fc->sb, outarg.parent, &name);
up_read(&fc->killsb);
kfree(buf);
return err;
err:
kfree(buf);
fuse_copy_finish(cs);
return err;
}
static int fuse_notify_store(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_store_out outarg;
struct inode *inode;
struct address_space *mapping;
u64 nodeid;
int err;
pgoff_t index;
unsigned int offset;
unsigned int num;
loff_t file_size;
loff_t end;
err = -EINVAL;
if (size < sizeof(outarg))
goto out_finish;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto out_finish;
err = -EINVAL;
if (size - sizeof(outarg) != outarg.size)
goto out_finish;
nodeid = outarg.nodeid;
down_read(&fc->killsb);
err = -ENOENT;
if (!fc->sb)
goto out_up_killsb;
inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid);
if (!inode)
goto out_up_killsb;
mapping = inode->i_mapping;
index = outarg.offset >> PAGE_CACHE_SHIFT;
offset = outarg.offset & ~PAGE_CACHE_MASK;
file_size = i_size_read(inode);
end = outarg.offset + outarg.size;
if (end > file_size) {
file_size = end;
fuse_write_update_size(inode, file_size);
}
num = outarg.size;
while (num) {
struct page *page;
unsigned int this_num;
err = -ENOMEM;
page = find_or_create_page(mapping, index,
mapping_gfp_mask(mapping));
if (!page)
goto out_iput;
this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset);
err = fuse_copy_page(cs, &page, offset, this_num, 0);
if (!err && offset == 0 && (num != 0 || file_size == end))
SetPageUptodate(page);
unlock_page(page);
page_cache_release(page);
if (err)
goto out_iput;
num -= this_num;
offset = 0;
index++;
}
err = 0;
out_iput:
iput(inode);
out_up_killsb:
up_read(&fc->killsb);
out_finish:
fuse_copy_finish(cs);
return err;
}
static void fuse_retrieve_end(struct fuse_conn *fc, struct fuse_req *req)
{
release_pages(req->pages, req->num_pages, 0);
}
static int fuse_retrieve(struct fuse_conn *fc, struct inode *inode,
struct fuse_notify_retrieve_out *outarg)
{
int err;
struct address_space *mapping = inode->i_mapping;
struct fuse_req *req;
pgoff_t index;
loff_t file_size;
unsigned int num;
unsigned int offset;
size_t total_len = 0;
req = fuse_get_req(fc);
if (IS_ERR(req))
return PTR_ERR(req);
offset = outarg->offset & ~PAGE_CACHE_MASK;
req->in.h.opcode = FUSE_NOTIFY_REPLY;
req->in.h.nodeid = outarg->nodeid;
req->in.numargs = 2;
req->in.argpages = 1;
req->page_offset = offset;
req->end = fuse_retrieve_end;
index = outarg->offset >> PAGE_CACHE_SHIFT;
file_size = i_size_read(inode);
num = outarg->size;
if (outarg->offset > file_size)
num = 0;
else if (outarg->offset + num > file_size)
num = file_size - outarg->offset;
while (num) {
struct page *page;
unsigned int this_num;
page = find_get_page(mapping, index);
if (!page)
break;
this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset);
req->pages[req->num_pages] = page;
req->num_pages++;
num -= this_num;
total_len += this_num;
}
req->misc.retrieve_in.offset = outarg->offset;
req->misc.retrieve_in.size = total_len;
req->in.args[0].size = sizeof(req->misc.retrieve_in);
req->in.args[0].value = &req->misc.retrieve_in;
req->in.args[1].size = total_len;
err = fuse_request_send_notify_reply(fc, req, outarg->notify_unique);
if (err)
fuse_retrieve_end(fc, req);
return err;
}
static int fuse_notify_retrieve(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_retrieve_out outarg;
struct inode *inode;
int err;
err = -EINVAL;
if (size != sizeof(outarg))
goto copy_finish;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto copy_finish;
fuse_copy_finish(cs);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb) {
u64 nodeid = outarg.nodeid;
inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid);
if (inode) {
err = fuse_retrieve(fc, inode, &outarg);
iput(inode);
}
}
up_read(&fc->killsb);
return err;
copy_finish:
fuse_copy_finish(cs);
return err;
}
static int fuse_notify(struct fuse_conn *fc, enum fuse_notify_code code,
unsigned int size, struct fuse_copy_state *cs)
{
switch (code) {
case FUSE_NOTIFY_POLL:
return fuse_notify_poll(fc, size, cs);
case FUSE_NOTIFY_INVAL_INODE:
return fuse_notify_inval_inode(fc, size, cs);
case FUSE_NOTIFY_INVAL_ENTRY:
return fuse_notify_inval_entry(fc, size, cs);
case FUSE_NOTIFY_STORE:
return fuse_notify_store(fc, size, cs);
case FUSE_NOTIFY_RETRIEVE:
return fuse_notify_retrieve(fc, size, cs);
default:
fuse_copy_finish(cs);
return -EINVAL;
}
}
/* Look up request on processing list by unique ID */
static struct fuse_req *request_find(struct fuse_conn *fc, u64 unique)
{
struct list_head *entry;
list_for_each(entry, &fc->processing) {
struct fuse_req *req;
req = list_entry(entry, struct fuse_req, list);
if (req->in.h.unique == unique || req->intr_unique == unique)
return req;
}
return NULL;
}
static int copy_out_args(struct fuse_copy_state *cs, struct fuse_out *out,
unsigned nbytes)
{
unsigned reqsize = sizeof(struct fuse_out_header);
if (out->h.error)
return nbytes != reqsize ? -EINVAL : 0;
reqsize += len_args(out->numargs, out->args);
if (reqsize < nbytes || (reqsize > nbytes && !out->argvar))
return -EINVAL;
else if (reqsize > nbytes) {
struct fuse_arg *lastarg = &out->args[out->numargs-1];
unsigned diffsize = reqsize - nbytes;
if (diffsize > lastarg->size)
return -EINVAL;
lastarg->size -= diffsize;
}
return fuse_copy_args(cs, out->numargs, out->argpages, out->args,
out->page_zeroing);
}
/*
* Write a single reply to a request. First the header is copied from
* the write buffer. The request is then searched on the processing
* list by the unique ID found in the header. If found, then remove
* it from the list and copy the rest of the buffer to the request.
* The request is finished by calling request_end()
*/
static ssize_t fuse_dev_do_write(struct fuse_conn *fc,
struct fuse_copy_state *cs, size_t nbytes)
{
int err;
struct fuse_req *req;
struct fuse_out_header oh;
if (nbytes < sizeof(struct fuse_out_header))
return -EINVAL;
err = fuse_copy_one(cs, &oh, sizeof(oh));
if (err)
goto err_finish;
err = -EINVAL;
if (oh.len != nbytes)
goto err_finish;
/*
* Zero oh.unique indicates unsolicited notification message
* and error contains notification code.
*/
if (!oh.unique) {
err = fuse_notify(fc, oh.error, nbytes - sizeof(oh), cs);
return err ? err : nbytes;
}
err = -EINVAL;
if (oh.error <= -1000 || oh.error > 0)
goto err_finish;
spin_lock(&fc->lock);
err = -ENOENT;
if (!fc->connected)
goto err_unlock;
req = request_find(fc, oh.unique);
if (!req)
goto err_unlock;
if (req->aborted) {
spin_unlock(&fc->lock);
fuse_copy_finish(cs);
spin_lock(&fc->lock);
request_end(fc, req);
return -ENOENT;
}
/* Is it an interrupt reply? */
if (req->intr_unique == oh.unique) {
err = -EINVAL;
if (nbytes != sizeof(struct fuse_out_header))
goto err_unlock;
if (oh.error == -ENOSYS)
fc->no_interrupt = 1;
else if (oh.error == -EAGAIN)
queue_interrupt(fc, req);
spin_unlock(&fc->lock);
fuse_copy_finish(cs);
return nbytes;
}
req->state = FUSE_REQ_WRITING;
list_move(&req->list, &fc->io);
req->out.h = oh;
req->locked = 1;
cs->req = req;
if (!req->out.page_replace)
cs->move_pages = 0;
spin_unlock(&fc->lock);
err = copy_out_args(cs, &req->out, nbytes);
fuse_copy_finish(cs);
spin_lock(&fc->lock);
req->locked = 0;
if (!err) {
if (req->aborted)
err = -ENOENT;
} else if (!req->aborted)
req->out.h.error = -EIO;
request_end(fc, req);
return err ? err : nbytes;
err_unlock:
spin_unlock(&fc->lock);
err_finish:
fuse_copy_finish(cs);
return err;
}
static ssize_t fuse_dev_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct fuse_copy_state cs;
struct fuse_conn *fc = fuse_get_conn(iocb->ki_filp);
if (!fc)
return -EPERM;
fuse_copy_init(&cs, fc, 0, iov, nr_segs);
return fuse_dev_do_write(fc, &cs, iov_length(iov, nr_segs));
}
static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
struct file *out, loff_t *ppos,
size_t len, unsigned int flags)
{
unsigned nbuf;
unsigned idx;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_conn *fc;
size_t rem;
ssize_t ret;
fc = fuse_get_conn(out);
if (!fc)
return -EPERM;
bufs = kmalloc(pipe->buffers * sizeof(struct pipe_buffer), GFP_KERNEL);
if (!bufs)
return -ENOMEM;
pipe_lock(pipe);
nbuf = 0;
rem = 0;
for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
ret = -EINVAL;
if (rem < len) {
pipe_unlock(pipe);
goto out;
}
rem = len;
while (rem) {
struct pipe_buffer *ibuf;
struct pipe_buffer *obuf;
BUG_ON(nbuf >= pipe->buffers);
BUG_ON(!pipe->nrbufs);
ibuf = &pipe->bufs[pipe->curbuf];
obuf = &bufs[nbuf];
if (rem >= ibuf->len) {
*obuf = *ibuf;
ibuf->ops = NULL;
pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
pipe->nrbufs--;
} else {
ibuf->ops->get(pipe, ibuf);
*obuf = *ibuf;
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = rem;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
nbuf++;
rem -= obuf->len;
}
pipe_unlock(pipe);
fuse_copy_init(&cs, fc, 0, NULL, nbuf);
cs.pipebufs = bufs;
cs.pipe = pipe;
if (flags & SPLICE_F_MOVE)
cs.move_pages = 1;
ret = fuse_dev_do_write(fc, &cs, len);
for (idx = 0; idx < nbuf; idx++) {
struct pipe_buffer *buf = &bufs[idx];
buf->ops->release(pipe, buf);
}
out:
kfree(bufs);
return ret;
}
static unsigned fuse_dev_poll(struct file *file, poll_table *wait)
{
unsigned mask = POLLOUT | POLLWRNORM;
struct fuse_conn *fc = fuse_get_conn(file);
if (!fc)
return POLLERR;
poll_wait(file, &fc->waitq, wait);
spin_lock(&fc->lock);
if (!fc->connected)
mask = POLLERR;
else if (request_pending(fc))
mask |= POLLIN | POLLRDNORM;
spin_unlock(&fc->lock);
return mask;
}
/*
* Abort all requests on the given list (pending or processing)
*
* This function releases and reacquires fc->lock
*/
static void end_requests(struct fuse_conn *fc, struct list_head *head)
__releases(fc->lock)
__acquires(fc->lock)
{
while (!list_empty(head)) {
struct fuse_req *req;
req = list_entry(head->next, struct fuse_req, list);
req->out.h.error = -ECONNABORTED;
request_end(fc, req);
spin_lock(&fc->lock);
}
}
/*
* Abort requests under I/O
*
* The requests are set to aborted and finished, and the request
* waiter is woken up. This will make request_wait_answer() wait
* until the request is unlocked and then return.
*
* If the request is asynchronous, then the end function needs to be
* called after waiting for the request to be unlocked (if it was
* locked).
*/
static void end_io_requests(struct fuse_conn *fc)
__releases(fc->lock)
__acquires(fc->lock)
{
while (!list_empty(&fc->io)) {
struct fuse_req *req =
list_entry(fc->io.next, struct fuse_req, list);
void (*end) (struct fuse_conn *, struct fuse_req *) = req->end;
req->aborted = 1;
req->out.h.error = -ECONNABORTED;
req->state = FUSE_REQ_FINISHED;
list_del_init(&req->list);
wake_up(&req->waitq);
if (end) {
req->end = NULL;
__fuse_get_request(req);
spin_unlock(&fc->lock);
wait_event(req->waitq, !req->locked);
end(fc, req);
fuse_put_request(fc, req);
spin_lock(&fc->lock);
}
}
}
static void end_queued_requests(struct fuse_conn *fc)
__releases(fc->lock)
__acquires(fc->lock)
{
fc->max_background = UINT_MAX;
flush_bg_queue(fc);
end_requests(fc, &fc->pending);
end_requests(fc, &fc->processing);
while (forget_pending(fc))
kfree(dequeue_forget(fc, 1, NULL));
}
static void end_polls(struct fuse_conn *fc)
{
struct rb_node *p;
p = rb_first(&fc->polled_files);
while (p) {
struct fuse_file *ff;
ff = rb_entry(p, struct fuse_file, polled_node);
wake_up_interruptible_all(&ff->poll_wait);
p = rb_next(p);
}
}
/*
* Abort all requests.
*
* Emergency exit in case of a malicious or accidental deadlock, or
* just a hung filesystem.
*
* The same effect is usually achievable through killing the
* filesystem daemon and all users of the filesystem. The exception
* is the combination of an asynchronous request and the tricky
* deadlock (see Documentation/filesystems/fuse.txt).
*
* During the aborting, progression of requests from the pending and
* processing lists onto the io list, and progression of new requests
* onto the pending list is prevented by req->connected being false.
*
* Progression of requests under I/O to the processing list is
* prevented by the req->aborted flag being true for these requests.
* For this reason requests on the io list must be aborted first.
*/
void fuse_abort_conn(struct fuse_conn *fc)
{
spin_lock(&fc->lock);
if (fc->connected) {
fc->connected = 0;
fc->blocked = 0;
end_io_requests(fc);
end_queued_requests(fc);
end_polls(fc);
wake_up_all(&fc->waitq);
wake_up_all(&fc->blocked_waitq);
kill_fasync(&fc->fasync, SIGIO, POLL_IN);
}
spin_unlock(&fc->lock);
}
EXPORT_SYMBOL_GPL(fuse_abort_conn);
int fuse_dev_release(struct inode *inode, struct file *file)
{
struct fuse_conn *fc = fuse_get_conn(file);
if (fc) {
spin_lock(&fc->lock);
fc->connected = 0;
fc->blocked = 0;
end_queued_requests(fc);
end_polls(fc);
wake_up_all(&fc->blocked_waitq);
spin_unlock(&fc->lock);
fuse_conn_put(fc);
}
return 0;
}
EXPORT_SYMBOL_GPL(fuse_dev_release);
static int fuse_dev_fasync(int fd, struct file *file, int on)
{
struct fuse_conn *fc = fuse_get_conn(file);
if (!fc)
return -EPERM;
/* No locking - fasync_helper does its own locking */
return fasync_helper(fd, file, on, &fc->fasync);
}
const struct file_operations fuse_dev_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = do_sync_read,
.aio_read = fuse_dev_read,
.splice_read = fuse_dev_splice_read,
.write = do_sync_write,
.aio_write = fuse_dev_write,
.splice_write = fuse_dev_splice_write,
.poll = fuse_dev_poll,
.release = fuse_dev_release,
.fasync = fuse_dev_fasync,
};
EXPORT_SYMBOL_GPL(fuse_dev_operations);
static struct miscdevice fuse_miscdevice = {
.minor = FUSE_MINOR,
.name = "fuse",
.fops = &fuse_dev_operations,
};
int __init fuse_dev_init(void)
{
int err = -ENOMEM;
fuse_req_cachep = kmem_cache_create("fuse_request",
sizeof(struct fuse_req),
0, 0, NULL);
if (!fuse_req_cachep)
goto out;
err = misc_register(&fuse_miscdevice);
if (err)
goto out_cache_clean;
return 0;
out_cache_clean:
kmem_cache_destroy(fuse_req_cachep);
out:
return err;
}
void fuse_dev_cleanup(void)
{
misc_deregister(&fuse_miscdevice);
kmem_cache_destroy(fuse_req_cachep);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3503_0 |
crossvul-cpp_data_bad_5493_0 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1999 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
*
* Purpose:
* A merge of Bjorn Reese's format() function and Daniel's dsprintf()
* 1.0. A full blooded printf() clone with full support for <num>$
* everywhere (parameters, widths and precisions) including variabled
* sized parameters (like doubles, long longs, long doubles and even
* void * in 64-bit architectures).
*
* Current restrictions:
* - Max 128 parameters
* - No 'long double' support.
*
* If you ever want truly portable and good *printf() clones, the project that
* took on from here is named 'Trio' and you find more details on the trio web
* page at https://daniel.haxx.se/projects/trio/
*/
#include "curl_setup.h"
#include <curl/mprintf.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
#ifndef SIZEOF_LONG_DOUBLE
#define SIZEOF_LONG_DOUBLE 0
#endif
/*
* If SIZEOF_SIZE_T has not been defined, default to the size of long.
*/
#ifndef SIZEOF_SIZE_T
# define SIZEOF_SIZE_T CURL_SIZEOF_LONG
#endif
#ifdef HAVE_LONGLONG
# define LONG_LONG_TYPE long long
# define HAVE_LONG_LONG_TYPE
#else
# if defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
# define LONG_LONG_TYPE __int64
# define HAVE_LONG_LONG_TYPE
# else
# undef LONG_LONG_TYPE
# undef HAVE_LONG_LONG_TYPE
# endif
#endif
/*
* Non-ANSI integer extensions
*/
#if (defined(__BORLANDC__) && (__BORLANDC__ >= 0x520)) || \
(defined(__WATCOMC__) && defined(__386__)) || \
(defined(__POCC__) && defined(_MSC_VER)) || \
(defined(_WIN32_WCE)) || \
(defined(__MINGW32__)) || \
(defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64))
# define MP_HAVE_INT_EXTENSIONS
#endif
/*
* Max integer data types that mprintf.c is capable
*/
#ifdef HAVE_LONG_LONG_TYPE
# define mp_intmax_t LONG_LONG_TYPE
# define mp_uintmax_t unsigned LONG_LONG_TYPE
#else
# define mp_intmax_t long
# define mp_uintmax_t unsigned long
#endif
#define BUFFSIZE 256 /* buffer for long-to-str and float-to-str calcs */
#define MAX_PARAMETERS 128 /* lame static limit */
#ifdef __AMIGA__
# undef FORMAT_INT
#endif
/* Lower-case digits. */
static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
/* Upper-case digits. */
static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#define OUTCHAR(x) \
do{ \
if(stream((unsigned char)(x), (FILE *)data) != -1) \
done++; \
else \
return done; /* return immediately on failure */ \
} WHILE_FALSE
/* Data type to read from the arglist */
typedef enum {
FORMAT_UNKNOWN = 0,
FORMAT_STRING,
FORMAT_PTR,
FORMAT_INT,
FORMAT_INTPTR,
FORMAT_LONG,
FORMAT_LONGLONG,
FORMAT_DOUBLE,
FORMAT_LONGDOUBLE,
FORMAT_WIDTH /* For internal use */
} FormatType;
/* conversion and display flags */
enum {
FLAGS_NEW = 0,
FLAGS_SPACE = 1<<0,
FLAGS_SHOWSIGN = 1<<1,
FLAGS_LEFT = 1<<2,
FLAGS_ALT = 1<<3,
FLAGS_SHORT = 1<<4,
FLAGS_LONG = 1<<5,
FLAGS_LONGLONG = 1<<6,
FLAGS_LONGDOUBLE = 1<<7,
FLAGS_PAD_NIL = 1<<8,
FLAGS_UNSIGNED = 1<<9,
FLAGS_OCTAL = 1<<10,
FLAGS_HEX = 1<<11,
FLAGS_UPPER = 1<<12,
FLAGS_WIDTH = 1<<13, /* '*' or '*<num>$' used */
FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */
FLAGS_PREC = 1<<15, /* precision was specified */
FLAGS_PRECPARAM = 1<<16, /* precision PARAMETER was specified */
FLAGS_CHAR = 1<<17, /* %c story */
FLAGS_FLOATE = 1<<18, /* %e or %E */
FLAGS_FLOATG = 1<<19 /* %g or %G */
};
typedef struct {
FormatType type;
int flags;
long width; /* width OR width parameter number */
long precision; /* precision OR precision parameter number */
union {
char *str;
void *ptr;
union {
mp_intmax_t as_signed;
mp_uintmax_t as_unsigned;
} num;
double dnum;
} data;
} va_stack_t;
struct nsprintf {
char *buffer;
size_t length;
size_t max;
};
struct asprintf {
char *buffer; /* allocated buffer */
size_t len; /* length of string */
size_t alloc; /* length of alloc */
int fail; /* (!= 0) if an alloc has failed and thus
the output is not the complete data */
};
static long dprintf_DollarString(char *input, char **end)
{
int number=0;
while(ISDIGIT(*input)) {
number *= 10;
number += *input-'0';
input++;
}
if(number && ('$'==*input++)) {
*end = input;
return number;
}
return 0;
}
static bool dprintf_IsQualifierNoDollar(const char *fmt)
{
#if defined(MP_HAVE_INT_EXTENSIONS)
if(!strncmp(fmt, "I32", 3) || !strncmp(fmt, "I64", 3)) {
return TRUE;
}
#endif
switch(*fmt) {
case '-': case '+': case ' ': case '#': case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case 'h': case 'l': case 'L': case 'z': case 'q':
case '*': case 'O':
#if defined(MP_HAVE_INT_EXTENSIONS)
case 'I':
#endif
return TRUE;
default:
return FALSE;
}
}
/******************************************************************
*
* Pass 1:
* Create an index with the type of each parameter entry and its
* value (may vary in size)
*
* Returns zero on success.
*
******************************************************************/
static int dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
va_list arglist)
{
char *fmt = (char *)format;
int param_num = 0;
long this_param;
long width;
long precision;
int flags;
long max_param=0;
long i;
while(*fmt) {
if(*fmt++ == '%') {
if(*fmt == '%') {
fmt++;
continue; /* while */
}
flags = FLAGS_NEW;
/* Handle the positional case (N$) */
param_num++;
this_param = dprintf_DollarString(fmt, &fmt);
if(0 == this_param)
/* we got no positional, get the next counter */
this_param = param_num;
if(this_param > max_param)
max_param = this_param;
/*
* The parameter with number 'i' should be used. Next, we need
* to get SIZE and TYPE of the parameter. Add the information
* to our array.
*/
width = 0;
precision = 0;
/* Handle the flags */
while(dprintf_IsQualifierNoDollar(fmt)) {
#if defined(MP_HAVE_INT_EXTENSIONS)
if(!strncmp(fmt, "I32", 3)) {
flags |= FLAGS_LONG;
fmt += 3;
}
else if(!strncmp(fmt, "I64", 3)) {
flags |= FLAGS_LONGLONG;
fmt += 3;
}
else
#endif
switch(*fmt++) {
case ' ':
flags |= FLAGS_SPACE;
break;
case '+':
flags |= FLAGS_SHOWSIGN;
break;
case '-':
flags |= FLAGS_LEFT;
flags &= ~FLAGS_PAD_NIL;
break;
case '#':
flags |= FLAGS_ALT;
break;
case '.':
if('*' == *fmt) {
/* The precision is picked from a specified parameter */
flags |= FLAGS_PRECPARAM;
fmt++;
param_num++;
i = dprintf_DollarString(fmt, &fmt);
if(i)
precision = i;
else
precision = param_num;
if(precision > max_param)
max_param = precision;
}
else {
flags |= FLAGS_PREC;
precision = strtol(fmt, &fmt, 10);
}
break;
case 'h':
flags |= FLAGS_SHORT;
break;
#if defined(MP_HAVE_INT_EXTENSIONS)
case 'I':
#if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
flags |= FLAGS_LONGLONG;
#else
flags |= FLAGS_LONG;
#endif
break;
#endif
case 'l':
if(flags & FLAGS_LONG)
flags |= FLAGS_LONGLONG;
else
flags |= FLAGS_LONG;
break;
case 'L':
flags |= FLAGS_LONGDOUBLE;
break;
case 'q':
flags |= FLAGS_LONGLONG;
break;
case 'z':
/* the code below generates a warning if -Wunreachable-code is
used */
#if (SIZEOF_SIZE_T > CURL_SIZEOF_LONG)
flags |= FLAGS_LONGLONG;
#else
flags |= FLAGS_LONG;
#endif
break;
case 'O':
#if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
flags |= FLAGS_LONGLONG;
#else
flags |= FLAGS_LONG;
#endif
break;
case '0':
if(!(flags & FLAGS_LEFT))
flags |= FLAGS_PAD_NIL;
/* FALLTHROUGH */
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
flags |= FLAGS_WIDTH;
width = strtol(fmt-1, &fmt, 10);
break;
case '*': /* Special case */
flags |= FLAGS_WIDTHPARAM;
param_num++;
i = dprintf_DollarString(fmt, &fmt);
if(i)
width = i;
else
width = param_num;
if(width > max_param)
max_param=width;
break;
default:
break;
}
} /* switch */
/* Handle the specifier */
i = this_param - 1;
if((i < 0) || (i >= MAX_PARAMETERS))
/* out of allowed range */
return 1;
switch (*fmt) {
case 'S':
flags |= FLAGS_ALT;
/* FALLTHROUGH */
case 's':
vto[i].type = FORMAT_STRING;
break;
case 'n':
vto[i].type = FORMAT_INTPTR;
break;
case 'p':
vto[i].type = FORMAT_PTR;
break;
case 'd': case 'i':
vto[i].type = FORMAT_INT;
break;
case 'u':
vto[i].type = FORMAT_INT;
flags |= FLAGS_UNSIGNED;
break;
case 'o':
vto[i].type = FORMAT_INT;
flags |= FLAGS_OCTAL;
break;
case 'x':
vto[i].type = FORMAT_INT;
flags |= FLAGS_HEX|FLAGS_UNSIGNED;
break;
case 'X':
vto[i].type = FORMAT_INT;
flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED;
break;
case 'c':
vto[i].type = FORMAT_INT;
flags |= FLAGS_CHAR;
break;
case 'f':
vto[i].type = FORMAT_DOUBLE;
break;
case 'e':
vto[i].type = FORMAT_DOUBLE;
flags |= FLAGS_FLOATE;
break;
case 'E':
vto[i].type = FORMAT_DOUBLE;
flags |= FLAGS_FLOATE|FLAGS_UPPER;
break;
case 'g':
vto[i].type = FORMAT_DOUBLE;
flags |= FLAGS_FLOATG;
break;
case 'G':
vto[i].type = FORMAT_DOUBLE;
flags |= FLAGS_FLOATG|FLAGS_UPPER;
break;
default:
vto[i].type = FORMAT_UNKNOWN;
break;
} /* switch */
vto[i].flags = flags;
vto[i].width = width;
vto[i].precision = precision;
if(flags & FLAGS_WIDTHPARAM) {
/* we have the width specified from a parameter, so we make that
parameter's info setup properly */
long k = width - 1;
vto[i].width = k;
vto[k].type = FORMAT_WIDTH;
vto[k].flags = FLAGS_NEW;
/* can't use width or precision of width! */
vto[k].width = 0;
vto[k].precision = 0;
}
if(flags & FLAGS_PRECPARAM) {
/* we have the precision specified from a parameter, so we make that
parameter's info setup properly */
long k = precision - 1;
vto[i].precision = k;
vto[k].type = FORMAT_WIDTH;
vto[k].flags = FLAGS_NEW;
/* can't use width or precision of width! */
vto[k].width = 0;
vto[k].precision = 0;
}
*endpos++ = fmt + 1; /* end of this sequence */
}
}
/* Read the arg list parameters into our data list */
for(i=0; i<max_param; i++) {
/* Width/precision arguments must be read before the main argument
they are attached to */
if(vto[i].flags & FLAGS_WIDTHPARAM) {
vto[vto[i].width].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, int);
}
if(vto[i].flags & FLAGS_PRECPARAM) {
vto[vto[i].precision].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, int);
}
switch(vto[i].type) {
case FORMAT_STRING:
vto[i].data.str = va_arg(arglist, char *);
break;
case FORMAT_INTPTR:
case FORMAT_UNKNOWN:
case FORMAT_PTR:
vto[i].data.ptr = va_arg(arglist, void *);
break;
case FORMAT_INT:
#ifdef HAVE_LONG_LONG_TYPE
if((vto[i].flags & FLAGS_LONGLONG) && (vto[i].flags & FLAGS_UNSIGNED))
vto[i].data.num.as_unsigned =
(mp_uintmax_t)va_arg(arglist, mp_uintmax_t);
else if(vto[i].flags & FLAGS_LONGLONG)
vto[i].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, mp_intmax_t);
else
#endif
{
if((vto[i].flags & FLAGS_LONG) && (vto[i].flags & FLAGS_UNSIGNED))
vto[i].data.num.as_unsigned =
(mp_uintmax_t)va_arg(arglist, unsigned long);
else if(vto[i].flags & FLAGS_LONG)
vto[i].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, long);
else if(vto[i].flags & FLAGS_UNSIGNED)
vto[i].data.num.as_unsigned =
(mp_uintmax_t)va_arg(arglist, unsigned int);
else
vto[i].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, int);
}
break;
case FORMAT_DOUBLE:
vto[i].data.dnum = va_arg(arglist, double);
break;
case FORMAT_WIDTH:
/* Argument has been read. Silently convert it into an integer
* for later use
*/
vto[i].type = FORMAT_INT;
break;
default:
break;
}
}
return 0;
}
static int dprintf_formatf(
void *data, /* untouched by format(), just sent to the stream() function in
the second argument */
/* function pointer called for each output character */
int (*stream)(int, FILE *),
const char *format, /* %-formatted string */
va_list ap_save) /* list of parameters */
{
/* Base-36 digits for numbers. */
const char *digits = lower_digits;
/* Pointer into the format string. */
char *f;
/* Number of characters written. */
int done = 0;
long param; /* current parameter to read */
long param_num=0; /* parameter counter */
va_stack_t vto[MAX_PARAMETERS];
char *endpos[MAX_PARAMETERS];
char **end;
char work[BUFFSIZE];
va_stack_t *p;
/* 'workend' points to the final buffer byte position, but with an extra
byte as margin to avoid the (false?) warning Coverity gives us
otherwise */
char *workend = &work[sizeof(work) - 2];
/* Do the actual %-code parsing */
if(dprintf_Pass1(format, vto, endpos, ap_save))
return -1;
end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
created for us */
f = (char *)format;
while(*f != '\0') {
/* Format spec modifiers. */
int is_alt;
/* Width of a field. */
long width;
/* Precision of a field. */
long prec;
/* Decimal integer is negative. */
int is_neg;
/* Base of a number to be written. */
long base;
/* Integral values to be written. */
mp_uintmax_t num;
/* Used to convert negative in positive. */
mp_intmax_t signed_num;
char *w;
if(*f != '%') {
/* This isn't a format spec, so write everything out until the next one
OR end of string is reached. */
do {
OUTCHAR(*f);
} while(*++f && ('%' != *f));
continue;
}
++f;
/* Check for "%%". Note that although the ANSI standard lists
'%' as a conversion specifier, it says "The complete format
specification shall be `%%'," so we can avoid all the width
and precision processing. */
if(*f == '%') {
++f;
OUTCHAR('%');
continue;
}
/* If this is a positional parameter, the position must follow immediately
after the %, thus create a %<num>$ sequence */
param=dprintf_DollarString(f, &f);
if(!param)
param = param_num;
else
--param;
param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
third %s will pick the 3rd argument */
p = &vto[param];
/* pick up the specified width */
if(p->flags & FLAGS_WIDTHPARAM) {
width = (long)vto[p->width].data.num.as_signed;
param_num++; /* since the width is extracted from a parameter, we
must skip that to get to the next one properly */
if(width < 0) {
/* "A negative field width is taken as a '-' flag followed by a
positive field width." */
width = -width;
p->flags |= FLAGS_LEFT;
p->flags &= ~FLAGS_PAD_NIL;
}
}
else
width = p->width;
/* pick up the specified precision */
if(p->flags & FLAGS_PRECPARAM) {
prec = (long)vto[p->precision].data.num.as_signed;
param_num++; /* since the precision is extracted from a parameter, we
must skip that to get to the next one properly */
if(prec < 0)
/* "A negative precision is taken as if the precision were
omitted." */
prec = -1;
}
else if(p->flags & FLAGS_PREC)
prec = p->precision;
else
prec = -1;
is_alt = (p->flags & FLAGS_ALT) ? 1 : 0;
switch(p->type) {
case FORMAT_INT:
num = p->data.num.as_unsigned;
if(p->flags & FLAGS_CHAR) {
/* Character. */
if(!(p->flags & FLAGS_LEFT))
while(--width > 0)
OUTCHAR(' ');
OUTCHAR((char) num);
if(p->flags & FLAGS_LEFT)
while(--width > 0)
OUTCHAR(' ');
break;
}
if(p->flags & FLAGS_OCTAL) {
/* Octal unsigned integer. */
base = 8;
goto unsigned_number;
}
else if(p->flags & FLAGS_HEX) {
/* Hexadecimal unsigned integer. */
digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
base = 16;
goto unsigned_number;
}
else if(p->flags & FLAGS_UNSIGNED) {
/* Decimal unsigned integer. */
base = 10;
goto unsigned_number;
}
/* Decimal integer. */
base = 10;
is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0;
if(is_neg) {
/* signed_num might fail to hold absolute negative minimum by 1 */
signed_num = p->data.num.as_signed + (mp_intmax_t)1;
signed_num = -signed_num;
num = (mp_uintmax_t)signed_num;
num += (mp_uintmax_t)1;
}
goto number;
unsigned_number:
/* Unsigned number of base BASE. */
is_neg = 0;
number:
/* Number of base BASE. */
/* Supply a default precision if none was given. */
if(prec == -1)
prec = 1;
/* Put the number in WORK. */
w = workend;
while(num > 0) {
*w-- = digits[num % base];
num /= base;
}
width -= (long)(workend - w);
prec -= (long)(workend - w);
if(is_alt && base == 8 && prec <= 0) {
*w-- = '0';
--width;
}
if(prec > 0) {
width -= prec;
while(prec-- > 0)
*w-- = '0';
}
if(is_alt && base == 16)
width -= 2;
if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
--width;
if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
while(width-- > 0)
OUTCHAR(' ');
if(is_neg)
OUTCHAR('-');
else if(p->flags & FLAGS_SHOWSIGN)
OUTCHAR('+');
else if(p->flags & FLAGS_SPACE)
OUTCHAR(' ');
if(is_alt && base == 16) {
OUTCHAR('0');
if(p->flags & FLAGS_UPPER)
OUTCHAR('X');
else
OUTCHAR('x');
}
if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
while(width-- > 0)
OUTCHAR('0');
/* Write the number. */
while(++w <= workend) {
OUTCHAR(*w);
}
if(p->flags & FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
break;
case FORMAT_STRING:
/* String. */
{
static const char null[] = "(nil)";
const char *str;
size_t len;
str = (char *) p->data.str;
if(str == NULL) {
/* Write null[] if there's space. */
if(prec == -1 || prec >= (long) sizeof(null) - 1) {
str = null;
len = sizeof(null) - 1;
/* Disable quotes around (nil) */
p->flags &= (~FLAGS_ALT);
}
else {
str = "";
len = 0;
}
}
else if(prec != -1)
len = (size_t)prec;
else
len = strlen(str);
width -= (len > LONG_MAX) ? LONG_MAX : (long)len;
if(p->flags & FLAGS_ALT)
OUTCHAR('"');
if(!(p->flags&FLAGS_LEFT))
while(width-- > 0)
OUTCHAR(' ');
while((len-- > 0) && *str)
OUTCHAR(*str++);
if(p->flags&FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
if(p->flags & FLAGS_ALT)
OUTCHAR('"');
}
break;
case FORMAT_PTR:
/* Generic pointer. */
{
void *ptr;
ptr = (void *) p->data.ptr;
if(ptr != NULL) {
/* If the pointer is not NULL, write it as a %#x spec. */
base = 16;
digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
is_alt = 1;
num = (size_t) ptr;
is_neg = 0;
goto number;
}
else {
/* Write "(nil)" for a nil pointer. */
static const char strnil[] = "(nil)";
const char *point;
width -= (long)(sizeof(strnil) - 1);
if(p->flags & FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
for(point = strnil; *point != '\0'; ++point)
OUTCHAR(*point);
if(! (p->flags & FLAGS_LEFT))
while(width-- > 0)
OUTCHAR(' ');
}
}
break;
case FORMAT_DOUBLE:
{
char formatbuf[32]="%";
char *fptr = &formatbuf[1];
size_t left = sizeof(formatbuf)-strlen(formatbuf);
int len;
width = -1;
if(p->flags & FLAGS_WIDTH)
width = p->width;
else if(p->flags & FLAGS_WIDTHPARAM)
width = (long)vto[p->width].data.num.as_signed;
prec = -1;
if(p->flags & FLAGS_PREC)
prec = p->precision;
else if(p->flags & FLAGS_PRECPARAM)
prec = (long)vto[p->precision].data.num.as_signed;
if(p->flags & FLAGS_LEFT)
*fptr++ = '-';
if(p->flags & FLAGS_SHOWSIGN)
*fptr++ = '+';
if(p->flags & FLAGS_SPACE)
*fptr++ = ' ';
if(p->flags & FLAGS_ALT)
*fptr++ = '#';
*fptr = 0;
if(width >= 0) {
/* RECURSIVE USAGE */
len = curl_msnprintf(fptr, left, "%ld", width);
fptr += len;
left -= len;
}
if(prec >= 0) {
/* RECURSIVE USAGE */
len = curl_msnprintf(fptr, left, ".%ld", prec);
fptr += len;
}
if(p->flags & FLAGS_LONG)
*fptr++ = 'l';
if(p->flags & FLAGS_FLOATE)
*fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e');
else if(p->flags & FLAGS_FLOATG)
*fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g');
else
*fptr++ = 'f';
*fptr = 0; /* and a final zero termination */
/* NOTE NOTE NOTE!! Not all sprintf implementations return number of
output characters */
(sprintf)(work, formatbuf, p->data.dnum);
for(fptr=work; *fptr; fptr++)
OUTCHAR(*fptr);
}
break;
case FORMAT_INTPTR:
/* Answer the count of characters written. */
#ifdef HAVE_LONG_LONG_TYPE
if(p->flags & FLAGS_LONGLONG)
*(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done;
else
#endif
if(p->flags & FLAGS_LONG)
*(long *) p->data.ptr = (long)done;
else if(!(p->flags & FLAGS_SHORT))
*(int *) p->data.ptr = (int)done;
else
*(short *) p->data.ptr = (short)done;
break;
default:
break;
}
f = *end++; /* goto end of %-code */
}
return done;
}
/* fputc() look-alike */
static int addbyter(int output, FILE *data)
{
struct nsprintf *infop=(struct nsprintf *)data;
unsigned char outc = (unsigned char)output;
if(infop->length < infop->max) {
/* only do this if we haven't reached max length yet */
infop->buffer[0] = outc; /* store */
infop->buffer++; /* increase pointer */
infop->length++; /* we are now one byte larger */
return outc; /* fputc() returns like this on success */
}
return -1;
}
int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
va_list ap_save)
{
int retcode;
struct nsprintf info;
info.buffer = buffer;
info.length = 0;
info.max = maxlength;
retcode = dprintf_formatf(&info, addbyter, format, ap_save);
if((retcode != -1) && info.max) {
/* we terminate this with a zero byte */
if(info.max == info.length)
/* we're at maximum, scrap the last letter */
info.buffer[-1] = 0;
else
info.buffer[0] = 0;
}
return retcode;
}
int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
{
int retcode;
va_list ap_save; /* argument pointer */
va_start(ap_save, format);
retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
va_end(ap_save);
return retcode;
}
/* fputc() look-alike */
static int alloc_addbyter(int output, FILE *data)
{
struct asprintf *infop=(struct asprintf *)data;
unsigned char outc = (unsigned char)output;
if(!infop->buffer) {
infop->buffer = malloc(32);
if(!infop->buffer) {
infop->fail = 1;
return -1; /* fail */
}
infop->alloc = 32;
infop->len =0;
}
else if(infop->len+1 >= infop->alloc) {
char *newptr = NULL;
size_t newsize = infop->alloc*2;
/* detect wrap-around or other overflow problems */
if(newsize > infop->alloc)
newptr = realloc(infop->buffer, newsize);
if(!newptr) {
infop->fail = 1;
return -1; /* fail */
}
infop->buffer = newptr;
infop->alloc = newsize;
}
infop->buffer[ infop->len ] = outc;
infop->len++;
return outc; /* fputc() returns like this on success */
}
char *curl_maprintf(const char *format, ...)
{
va_list ap_save; /* argument pointer */
int retcode;
struct asprintf info;
info.buffer = NULL;
info.len = 0;
info.alloc = 0;
info.fail = 0;
va_start(ap_save, format);
retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
va_end(ap_save);
if((-1 == retcode) || info.fail) {
if(info.alloc)
free(info.buffer);
return NULL;
}
if(info.alloc) {
info.buffer[info.len] = 0; /* we terminate this with a zero byte */
return info.buffer;
}
else
return strdup("");
}
char *curl_mvaprintf(const char *format, va_list ap_save)
{
int retcode;
struct asprintf info;
info.buffer = NULL;
info.len = 0;
info.alloc = 0;
info.fail = 0;
retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
if((-1 == retcode) || info.fail) {
if(info.alloc)
free(info.buffer);
return NULL;
}
if(info.alloc) {
info.buffer[info.len] = 0; /* we terminate this with a zero byte */
return info.buffer;
}
else
return strdup("");
}
static int storebuffer(int output, FILE *data)
{
char **buffer = (char **)data;
unsigned char outc = (unsigned char)output;
**buffer = outc;
(*buffer)++;
return outc; /* act like fputc() ! */
}
int curl_msprintf(char *buffer, const char *format, ...)
{
va_list ap_save; /* argument pointer */
int retcode;
va_start(ap_save, format);
retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
va_end(ap_save);
*buffer=0; /* we terminate this with a zero byte */
return retcode;
}
int curl_mprintf(const char *format, ...)
{
int retcode;
va_list ap_save; /* argument pointer */
va_start(ap_save, format);
retcode = dprintf_formatf(stdout, fputc, format, ap_save);
va_end(ap_save);
return retcode;
}
int curl_mfprintf(FILE *whereto, const char *format, ...)
{
int retcode;
va_list ap_save; /* argument pointer */
va_start(ap_save, format);
retcode = dprintf_formatf(whereto, fputc, format, ap_save);
va_end(ap_save);
return retcode;
}
int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
{
int retcode;
retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
*buffer=0; /* we terminate this with a zero byte */
return retcode;
}
int curl_mvprintf(const char *format, va_list ap_save)
{
return dprintf_formatf(stdout, fputc, format, ap_save);
}
int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
{
return dprintf_formatf(whereto, fputc, format, ap_save);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5493_0 |
crossvul-cpp_data_bad_339_7 | /*
* sc.c: General functions
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#ifdef ENABLE_OPENSSL
#include <openssl/crypto.h> /* for OPENSSL_cleanse */
#endif
#include "internal.h"
#ifdef PACKAGE_VERSION
static const char *sc_version = PACKAGE_VERSION;
#else
static const char *sc_version = "(undef)";
#endif
const char *sc_get_version(void)
{
return sc_version;
}
int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen)
{
int err = SC_SUCCESS;
size_t left, count = 0, in_len;
if (in == NULL || out == NULL || outlen == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
left = *outlen;
in_len = strlen(in);
while (*in != '\0') {
int byte = 0, nybbles = 2;
while (nybbles-- && *in && *in != ':' && *in != ' ') {
char c;
byte <<= 4;
c = *in++;
if ('0' <= c && c <= '9')
c -= '0';
else
if ('a' <= c && c <= 'f')
c = c - 'a' + 10;
else
if ('A' <= c && c <= 'F')
c = c - 'A' + 10;
else {
err = SC_ERROR_INVALID_ARGUMENTS;
goto out;
}
byte |= c;
}
/* Detect premature end of string before byte is complete */
if (in_len > 1 && *in == '\0' && nybbles >= 0) {
err = SC_ERROR_INVALID_ARGUMENTS;
break;
}
if (*in == ':' || *in == ' ')
in++;
if (left <= 0) {
err = SC_ERROR_BUFFER_TOO_SMALL;
break;
}
out[count++] = (u8) byte;
left--;
}
out:
*outlen = count;
return err;
}
int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len,
int in_sep)
{
unsigned int n, sep_len;
char *pos, *end, sep;
sep = (char)in_sep;
sep_len = sep > 0 ? 1 : 0;
pos = out;
end = out + out_len;
for (n = 0; n < in_len; n++) {
if (pos + 3 + sep_len >= end)
return SC_ERROR_BUFFER_TOO_SMALL;
if (n && sep_len)
*pos++ = sep;
sprintf(pos, "%02x", in[n]);
pos += 2;
}
*pos = '\0';
return SC_SUCCESS;
}
/*
* Right trim all non-printable characters
*/
size_t sc_right_trim(u8 *buf, size_t len) {
size_t i;
if (!buf)
return 0;
if (len > 0) {
for(i = len-1; i > 0; i--) {
if(!isprint(buf[i])) {
buf[i] = '\0';
len--;
continue;
}
break;
}
}
return len;
}
u8 *ulong2bebytes(u8 *buf, unsigned long x)
{
if (buf != NULL) {
buf[3] = (u8) (x & 0xff);
buf[2] = (u8) ((x >> 8) & 0xff);
buf[1] = (u8) ((x >> 16) & 0xff);
buf[0] = (u8) ((x >> 24) & 0xff);
}
return buf;
}
u8 *ushort2bebytes(u8 *buf, unsigned short x)
{
if (buf != NULL) {
buf[1] = (u8) (x & 0xff);
buf[0] = (u8) ((x >> 8) & 0xff);
}
return buf;
}
unsigned long bebytes2ulong(const u8 *buf)
{
if (buf == NULL)
return 0UL;
return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]);
}
unsigned short bebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short) (buf[0] << 8 | buf[1]);
}
unsigned short lebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short)buf[1] << 8 | (unsigned short)buf[0];
}
void sc_init_oid(struct sc_object_id *oid)
{
int ii;
if (!oid)
return;
for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++)
oid->value[ii] = -1;
}
int sc_format_oid(struct sc_object_id *oid, const char *in)
{
int ii, ret = SC_ERROR_INVALID_ARGUMENTS;
const char *p;
char *q;
if (oid == NULL || in == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
sc_init_oid(oid);
p = in;
for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) {
oid->value[ii] = strtol(p, &q, 10);
if (!*q)
break;
if (!(q[0] == '.' && isdigit(q[1])))
goto out;
p = q + 1;
}
if (!sc_valid_oid(oid))
goto out;
ret = SC_SUCCESS;
out:
if (ret)
sc_init_oid(oid);
return ret;
}
int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2)
{
int i;
if (oid1 == NULL || oid2 == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) {
if (oid1->value[i] != oid2->value[i])
return 0;
if (oid1->value[i] == -1)
break;
}
return 1;
}
int sc_valid_oid(const struct sc_object_id *oid)
{
int ii;
if (!oid)
return 0;
if (oid->value[0] == -1 || oid->value[1] == -1)
return 0;
if (oid->value[0] > 2 || oid->value[1] > 39)
return 0;
for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++)
if (oid->value[ii])
break;
if (ii==SC_MAX_OBJECT_ID_OCTETS)
return 0;
return 1;
}
int sc_detect_card_presence(sc_reader_t *reader)
{
int r;
LOG_FUNC_CALLED(reader->ctx);
if (reader->ops->detect_card_presence == NULL)
LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED);
r = reader->ops->detect_card_presence(reader);
LOG_FUNC_RETURN(reader->ctx, r);
}
int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len,
int idx, int count)
{
if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(path, 0, sizeof(*path));
memcpy(path->value, id, id_len);
path->len = id_len;
path->type = type;
path->index = idx;
path->count = count;
return SC_SUCCESS;
}
void sc_format_path(const char *str, sc_path_t *path)
{
int type = SC_PATH_TYPE_PATH;
if (path) {
memset(path, 0, sizeof(*path));
if (*str == 'i' || *str == 'I') {
type = SC_PATH_TYPE_FILE_ID;
str++;
}
path->len = sizeof(path->value);
if (sc_hex_to_bin(str, path->value, &path->len) >= 0) {
path->type = type;
}
path->count = -1;
}
}
int sc_append_path(sc_path_t *dest, const sc_path_t *src)
{
return sc_concatenate_path(dest, dest, src);
}
int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen)
{
if (dest->len + idlen > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memcpy(dest->value + dest->len, id, idlen);
dest->len += idlen;
return SC_SUCCESS;
}
int sc_append_file_id(sc_path_t *dest, unsigned int fid)
{
u8 id[2] = { fid >> 8, fid & 0xff };
return sc_append_path_id(dest, id, 2);
}
int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2)
{
sc_path_t tpath;
if (d == NULL || p1 == NULL || p2 == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME)
/* we do not support concatenation of AIDs at the moment */
return SC_ERROR_NOT_SUPPORTED;
if (p1->len + p2->len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(&tpath, 0, sizeof(sc_path_t));
memcpy(tpath.value, p1->value, p1->len);
memcpy(tpath.value + p1->len, p2->value, p2->len);
tpath.len = p1->len + p2->len;
tpath.type = SC_PATH_TYPE_PATH;
/* use 'index' and 'count' entry of the second path object */
tpath.index = p2->index;
tpath.count = p2->count;
/* the result is currently always as path */
tpath.type = SC_PATH_TYPE_PATH;
*d = tpath;
return SC_SUCCESS;
}
const char *sc_print_path(const sc_path_t *path)
{
static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE];
if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS)
buffer[0] = '\0';
return buffer;
}
int sc_path_print(char *buf, size_t buflen, const sc_path_t *path)
{
size_t i;
if (buf == NULL || path == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (buflen < path->len * 2 + path->aid.len * 2 + 1)
return SC_ERROR_BUFFER_TOO_SMALL;
buf[0] = '\0';
if (path->aid.len) {
for (i = 0; i < path->aid.len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]);
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
}
for (i = 0; i < path->len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]);
if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME)
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
return SC_SUCCESS;
}
int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2)
{
return path1->len == path2->len
&& !memcmp(path1->value, path2->value, path1->len);
}
int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path)
{
sc_path_t tpath;
if (prefix->len > path->len)
return 0;
tpath = *path;
tpath.len = prefix->len;
return sc_compare_path(&tpath, prefix);
}
const sc_path_t *sc_get_mf_path(void)
{
static const sc_path_t mf_path = {
{0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2,
0,
0,
SC_PATH_TYPE_PATH,
{{0},0}
};
return &mf_path;
}
int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation,
unsigned int method, unsigned long key_ref)
{
sc_acl_entry_t *p, *_new;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return SC_ERROR_INVALID_ARGUMENTS;
}
switch (method) {
case SC_AC_NEVER:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 1;
return SC_SUCCESS;
case SC_AC_NONE:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 2;
return SC_SUCCESS;
case SC_AC_UNKNOWN:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 3;
return SC_SUCCESS;
default:
/* NONE and UNKNOWN get zapped when a new AC is added.
* If the ACL is NEVER, additional entries will be
* dropped silently. */
if (file->acl[operation] == (sc_acl_entry_t *) 1)
return SC_SUCCESS;
if (file->acl[operation] == (sc_acl_entry_t *) 2
|| file->acl[operation] == (sc_acl_entry_t *) 3)
file->acl[operation] = NULL;
}
/* If the entry is already present (e.g. due to the mapping)
* of the card's AC with OpenSC's), don't add it again. */
for (p = file->acl[operation]; p != NULL; p = p->next) {
if ((p->method == method) && (p->key_ref == key_ref))
return SC_SUCCESS;
}
_new = malloc(sizeof(sc_acl_entry_t));
if (_new == NULL)
return SC_ERROR_OUT_OF_MEMORY;
_new->method = method;
_new->key_ref = key_ref;
_new->next = NULL;
p = file->acl[operation];
if (p == NULL) {
file->acl[operation] = _new;
return SC_SUCCESS;
}
while (p->next != NULL)
p = p->next;
p->next = _new;
return SC_SUCCESS;
}
const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file,
unsigned int operation)
{
sc_acl_entry_t *p;
static const sc_acl_entry_t e_never = {
SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_none = {
SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_unknown = {
SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return NULL;
}
p = file->acl[operation];
if (p == (sc_acl_entry_t *) 1)
return &e_never;
if (p == (sc_acl_entry_t *) 2)
return &e_none;
if (p == (sc_acl_entry_t *) 3)
return &e_unknown;
return file->acl[operation];
}
void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation)
{
sc_acl_entry_t *e;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return;
}
e = file->acl[operation];
if (e == (sc_acl_entry_t *) 1 ||
e == (sc_acl_entry_t *) 2 ||
e == (sc_acl_entry_t *) 3) {
file->acl[operation] = NULL;
return;
}
while (e != NULL) {
sc_acl_entry_t *tmp = e->next;
free(e);
e = tmp;
}
file->acl[operation] = NULL;
}
sc_file_t * sc_file_new(void)
{
sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t));
if (file == NULL)
return NULL;
file->magic = SC_FILE_MAGIC;
return file;
}
void sc_file_free(sc_file_t *file)
{
unsigned int i;
if (file == NULL || !sc_file_valid(file))
return;
file->magic = 0;
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_clear_acl_entries(file, i);
if (file->sec_attr)
free(file->sec_attr);
if (file->prop_attr)
free(file->prop_attr);
if (file->type_attr)
free(file->type_attr);
if (file->encoded_content)
free(file->encoded_content);
free(file);
}
void sc_file_dup(sc_file_t **dest, const sc_file_t *src)
{
sc_file_t *newf;
const sc_acl_entry_t *e;
unsigned int op;
*dest = NULL;
if (!sc_file_valid(src))
return;
newf = sc_file_new();
if (newf == NULL)
return;
*dest = newf;
memcpy(&newf->path, &src->path, sizeof(struct sc_path));
memcpy(&newf->name, &src->name, sizeof(src->name));
newf->namelen = src->namelen;
newf->type = src->type;
newf->shareable = src->shareable;
newf->ef_structure = src->ef_structure;
newf->size = src->size;
newf->id = src->id;
newf->status = src->status;
for (op = 0; op < SC_MAX_AC_OPS; op++) {
newf->acl[op] = NULL;
e = sc_file_get_acl_entry(src, op);
if (e != NULL) {
if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0)
goto err;
}
}
newf->record_length = src->record_length;
newf->record_count = src->record_count;
if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0)
goto err;
if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0)
goto err;
if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0)
goto err;
if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0)
goto err;
return;
err:
sc_file_free(newf);
*dest = NULL;
}
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr,
size_t prop_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (prop_attr == NULL) {
if (file->prop_attr != NULL)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->prop_attr, prop_attr_len);
if (!tmp) {
if (file->prop_attr)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->prop_attr = tmp;
memcpy(file->prop_attr, prop_attr, prop_attr_len);
file->prop_attr_len = prop_attr_len;
return SC_SUCCESS;
}
int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr,
size_t type_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (type_attr == NULL) {
if (file->type_attr != NULL)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->type_attr, type_attr_len);
if (!tmp) {
if (file->type_attr)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->type_attr = tmp;
memcpy(file->type_attr, type_attr, type_attr_len);
file->type_attr_len = type_attr_len;
return SC_SUCCESS;
}
int sc_file_set_content(sc_file_t *file, const u8 *content,
size_t content_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (content == NULL) {
if (file->encoded_content != NULL)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->encoded_content, content_len);
if (!tmp) {
if (file->encoded_content)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->encoded_content = tmp;
memcpy(file->encoded_content, content, content_len);
file->encoded_content_len = content_len;
return SC_SUCCESS;
}
int sc_file_valid(const sc_file_t *file) {
if (file == NULL)
return 0;
return file->magic == SC_FILE_MAGIC;
}
int _sc_parse_atr(sc_reader_t *reader)
{
u8 *p = reader->atr.value;
int atr_len = (int) reader->atr.len;
int n_hist, x;
int tx[4] = {-1, -1, -1, -1};
int i, FI, DI;
const int Fi_table[] = {
372, 372, 558, 744, 1116, 1488, 1860, -1,
-1, 512, 768, 1024, 1536, 2048, -1, -1 };
const int f_table[] = {
40, 50, 60, 80, 120, 160, 200, -1,
-1, 50, 75, 100, 150, 200, -1, -1 };
const int Di_table[] = {
-1, 1, 2, 4, 8, 16, 32, -1,
12, 20, -1, -1, -1, -1, -1, -1 };
reader->atr_info.hist_bytes_len = 0;
reader->atr_info.hist_bytes = NULL;
if (atr_len == 0) {
sc_log(reader->ctx, "empty ATR - card not present?\n");
return SC_ERROR_INTERNAL;
}
if (p[0] != 0x3B && p[0] != 0x3F) {
sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]);
return SC_ERROR_INTERNAL;
}
n_hist = p[1] & 0x0F;
x = p[1] >> 4;
p += 2;
atr_len -= 2;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
if (tx[0] >= 0) {
reader->atr_info.FI = FI = tx[0] >> 4;
reader->atr_info.DI = DI = tx[0] & 0x0F;
reader->atr_info.Fi = Fi_table[FI];
reader->atr_info.f = f_table[FI];
reader->atr_info.Di = Di_table[DI];
} else {
reader->atr_info.Fi = -1;
reader->atr_info.f = -1;
reader->atr_info.Di = -1;
}
if (tx[2] >= 0)
reader->atr_info.N = tx[3];
else
reader->atr_info.N = -1;
while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) {
x = tx[3] >> 4;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
}
if (atr_len <= 0)
return SC_SUCCESS;
if (n_hist > atr_len)
n_hist = atr_len;
reader->atr_info.hist_bytes_len = n_hist;
reader->atr_info.hist_bytes = p;
return SC_SUCCESS;
}
void sc_mem_clear(void *ptr, size_t len)
{
if (len > 0) {
#ifdef ENABLE_OPENSSL
OPENSSL_cleanse(ptr, len);
#else
memset(ptr, 0, len);
#endif
}
}
int sc_mem_reverse(unsigned char *buf, size_t len)
{
unsigned char ch;
size_t ii;
if (!buf || !len)
return SC_ERROR_INVALID_ARGUMENTS;
for (ii = 0; ii < len / 2; ii++) {
ch = *(buf + ii);
*(buf + ii) = *(buf + len - 1 - ii);
*(buf + len - 1 - ii) = ch;
}
return SC_SUCCESS;
}
static int
sc_remote_apdu_allocate(struct sc_remote_data *rdata,
struct sc_remote_apdu **new_rapdu)
{
struct sc_remote_apdu *rapdu = NULL, *rr;
if (!rdata)
return SC_ERROR_INVALID_ARGUMENTS;
rapdu = calloc(1, sizeof(struct sc_remote_apdu));
if (rapdu == NULL)
return SC_ERROR_OUT_OF_MEMORY;
rapdu->apdu.data = &rapdu->sbuf[0];
rapdu->apdu.resp = &rapdu->rbuf[0];
rapdu->apdu.resplen = sizeof(rapdu->rbuf);
if (new_rapdu)
*new_rapdu = rapdu;
if (rdata->data == NULL) {
rdata->data = rapdu;
rdata->length = 1;
return SC_SUCCESS;
}
for (rr = rdata->data; rr->next; rr = rr->next)
;
rr->next = rapdu;
rdata->length++;
return SC_SUCCESS;
}
static void
sc_remote_apdu_free (struct sc_remote_data *rdata)
{
struct sc_remote_apdu *rapdu = NULL;
if (!rdata)
return;
rapdu = rdata->data;
while(rapdu) {
struct sc_remote_apdu *rr = rapdu->next;
free(rapdu);
rapdu = rr;
}
}
void sc_remote_data_init(struct sc_remote_data *rdata)
{
if (!rdata)
return;
memset(rdata, 0, sizeof(struct sc_remote_data));
rdata->alloc = sc_remote_apdu_allocate;
rdata->free = sc_remote_apdu_free;
}
static unsigned long sc_CRC_tab32[256];
static int sc_CRC_tab32_initialized = 0;
unsigned sc_crc32(const unsigned char *value, size_t len)
{
size_t ii, jj;
unsigned long crc;
unsigned long index, long_c;
if (!sc_CRC_tab32_initialized) {
for (ii=0; ii<256; ii++) {
crc = (unsigned long) ii;
for (jj=0; jj<8; jj++) {
if ( crc & 0x00000001L )
crc = ( crc >> 1 ) ^ 0xEDB88320l;
else
crc = crc >> 1;
}
sc_CRC_tab32[ii] = crc;
}
sc_CRC_tab32_initialized = 1;
}
crc = 0xffffffffL;
for (ii=0; ii<len; ii++) {
long_c = 0x000000ffL & (unsigned long) (*(value + ii));
index = crc ^ long_c;
crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ];
}
crc ^= 0xffffffff;
return crc%0xffff;
}
const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen)
{
if (buf != NULL) {
size_t idx;
u8 plain_tag = tag & 0xF0;
size_t expected_len = tag & 0x0F;
for (idx = 0; idx < len; idx++) {
if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len &&
(expected_len == 0 || expected_len == (buf[idx] & 0x0F))) {
if (outlen != NULL)
*outlen = buf[idx] & 0x0F;
return buf + (idx + 1);
}
idx += (buf[idx] & 0x0F);
}
}
return NULL;
}
/**************************** mutex functions ************************/
int sc_mutex_create(const sc_context_t *ctx, void **mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL)
return ctx->thread_ctx->create_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_lock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL)
return ctx->thread_ctx->lock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_unlock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL)
return ctx->thread_ctx->unlock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_destroy(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL)
return ctx->thread_ctx->destroy_mutex(mutex);
else
return SC_SUCCESS;
}
unsigned long sc_thread_id(const sc_context_t *ctx)
{
if (ctx == NULL || ctx->thread_ctx == NULL ||
ctx->thread_ctx->thread_id == NULL)
return 0UL;
else
return ctx->thread_ctx->thread_id();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_339_7 |
crossvul-cpp_data_good_2842_0 | /*
* Generic hugetlb support.
* (C) Nadia Yvette Chambers, April 2004
*/
#include <linux/list.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/seq_file.h>
#include <linux/sysctl.h>
#include <linux/highmem.h>
#include <linux/mmu_notifier.h>
#include <linux/nodemask.h>
#include <linux/pagemap.h>
#include <linux/mempolicy.h>
#include <linux/compiler.h>
#include <linux/cpuset.h>
#include <linux/mutex.h>
#include <linux/bootmem.h>
#include <linux/sysfs.h>
#include <linux/slab.h>
#include <linux/sched/signal.h>
#include <linux/rmap.h>
#include <linux/string_helpers.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/jhash.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/tlb.h>
#include <linux/io.h>
#include <linux/hugetlb.h>
#include <linux/hugetlb_cgroup.h>
#include <linux/node.h>
#include <linux/userfaultfd_k.h>
#include "internal.h"
int hugepages_treat_as_movable;
int hugetlb_max_hstate __read_mostly;
unsigned int default_hstate_idx;
struct hstate hstates[HUGE_MAX_HSTATE];
/*
* Minimum page order among possible hugepage sizes, set to a proper value
* at boot time.
*/
static unsigned int minimum_order __read_mostly = UINT_MAX;
__initdata LIST_HEAD(huge_boot_pages);
/* for command line parsing */
static struct hstate * __initdata parsed_hstate;
static unsigned long __initdata default_hstate_max_huge_pages;
static unsigned long __initdata default_hstate_size;
static bool __initdata parsed_valid_hugepagesz = true;
/*
* Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages,
* free_huge_pages, and surplus_huge_pages.
*/
DEFINE_SPINLOCK(hugetlb_lock);
/*
* Serializes faults on the same logical page. This is used to
* prevent spurious OOMs when the hugepage pool is fully utilized.
*/
static int num_fault_mutexes;
struct mutex *hugetlb_fault_mutex_table ____cacheline_aligned_in_smp;
/* Forward declaration */
static int hugetlb_acct_memory(struct hstate *h, long delta);
static inline void unlock_or_release_subpool(struct hugepage_subpool *spool)
{
bool free = (spool->count == 0) && (spool->used_hpages == 0);
spin_unlock(&spool->lock);
/* If no pages are used, and no other handles to the subpool
* remain, give up any reservations mased on minimum size and
* free the subpool */
if (free) {
if (spool->min_hpages != -1)
hugetlb_acct_memory(spool->hstate,
-spool->min_hpages);
kfree(spool);
}
}
struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
long min_hpages)
{
struct hugepage_subpool *spool;
spool = kzalloc(sizeof(*spool), GFP_KERNEL);
if (!spool)
return NULL;
spin_lock_init(&spool->lock);
spool->count = 1;
spool->max_hpages = max_hpages;
spool->hstate = h;
spool->min_hpages = min_hpages;
if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
kfree(spool);
return NULL;
}
spool->rsv_hpages = min_hpages;
return spool;
}
void hugepage_put_subpool(struct hugepage_subpool *spool)
{
spin_lock(&spool->lock);
BUG_ON(!spool->count);
spool->count--;
unlock_or_release_subpool(spool);
}
/*
* Subpool accounting for allocating and reserving pages.
* Return -ENOMEM if there are not enough resources to satisfy the
* the request. Otherwise, return the number of pages by which the
* global pools must be adjusted (upward). The returned value may
* only be different than the passed value (delta) in the case where
* a subpool minimum size must be manitained.
*/
static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
long delta)
{
long ret = delta;
if (!spool)
return ret;
spin_lock(&spool->lock);
if (spool->max_hpages != -1) { /* maximum size accounting */
if ((spool->used_hpages + delta) <= spool->max_hpages)
spool->used_hpages += delta;
else {
ret = -ENOMEM;
goto unlock_ret;
}
}
/* minimum size accounting */
if (spool->min_hpages != -1 && spool->rsv_hpages) {
if (delta > spool->rsv_hpages) {
/*
* Asking for more reserves than those already taken on
* behalf of subpool. Return difference.
*/
ret = delta - spool->rsv_hpages;
spool->rsv_hpages = 0;
} else {
ret = 0; /* reserves already accounted for */
spool->rsv_hpages -= delta;
}
}
unlock_ret:
spin_unlock(&spool->lock);
return ret;
}
/*
* Subpool accounting for freeing and unreserving pages.
* Return the number of global page reservations that must be dropped.
* The return value may only be different than the passed value (delta)
* in the case where a subpool minimum size must be maintained.
*/
static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
long delta)
{
long ret = delta;
if (!spool)
return delta;
spin_lock(&spool->lock);
if (spool->max_hpages != -1) /* maximum size accounting */
spool->used_hpages -= delta;
/* minimum size accounting */
if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
if (spool->rsv_hpages + delta <= spool->min_hpages)
ret = 0;
else
ret = spool->rsv_hpages + delta - spool->min_hpages;
spool->rsv_hpages += delta;
if (spool->rsv_hpages > spool->min_hpages)
spool->rsv_hpages = spool->min_hpages;
}
/*
* If hugetlbfs_put_super couldn't free spool due to an outstanding
* quota reference, free it now.
*/
unlock_or_release_subpool(spool);
return ret;
}
static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
{
return HUGETLBFS_SB(inode->i_sb)->spool;
}
static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
{
return subpool_inode(file_inode(vma->vm_file));
}
/*
* Region tracking -- allows tracking of reservations and instantiated pages
* across the pages in a mapping.
*
* The region data structures are embedded into a resv_map and protected
* by a resv_map's lock. The set of regions within the resv_map represent
* reservations for huge pages, or huge pages that have already been
* instantiated within the map. The from and to elements are huge page
* indicies into the associated mapping. from indicates the starting index
* of the region. to represents the first index past the end of the region.
*
* For example, a file region structure with from == 0 and to == 4 represents
* four huge pages in a mapping. It is important to note that the to element
* represents the first element past the end of the region. This is used in
* arithmetic as 4(to) - 0(from) = 4 huge pages in the region.
*
* Interval notation of the form [from, to) will be used to indicate that
* the endpoint from is inclusive and to is exclusive.
*/
struct file_region {
struct list_head link;
long from;
long to;
};
/*
* Add the huge page range represented by [f, t) to the reserve
* map. In the normal case, existing regions will be expanded
* to accommodate the specified range. Sufficient regions should
* exist for expansion due to the previous call to region_chg
* with the same range. However, it is possible that region_del
* could have been called after region_chg and modifed the map
* in such a way that no region exists to be expanded. In this
* case, pull a region descriptor from the cache associated with
* the map and use that for the new range.
*
* Return the number of new huge pages added to the map. This
* number is greater than or equal to zero.
*/
static long region_add(struct resv_map *resv, long f, long t)
{
struct list_head *head = &resv->regions;
struct file_region *rg, *nrg, *trg;
long add = 0;
spin_lock(&resv->lock);
/* Locate the region we are either in or before. */
list_for_each_entry(rg, head, link)
if (f <= rg->to)
break;
/*
* If no region exists which can be expanded to include the
* specified range, the list must have been modified by an
* interleving call to region_del(). Pull a region descriptor
* from the cache and use it for this range.
*/
if (&rg->link == head || t < rg->from) {
VM_BUG_ON(resv->region_cache_count <= 0);
resv->region_cache_count--;
nrg = list_first_entry(&resv->region_cache, struct file_region,
link);
list_del(&nrg->link);
nrg->from = f;
nrg->to = t;
list_add(&nrg->link, rg->link.prev);
add += t - f;
goto out_locked;
}
/* Round our left edge to the current segment if it encloses us. */
if (f > rg->from)
f = rg->from;
/* Check for and consume any regions we now overlap with. */
nrg = rg;
list_for_each_entry_safe(rg, trg, rg->link.prev, link) {
if (&rg->link == head)
break;
if (rg->from > t)
break;
/* If this area reaches higher then extend our area to
* include it completely. If this is not the first area
* which we intend to reuse, free it. */
if (rg->to > t)
t = rg->to;
if (rg != nrg) {
/* Decrement return value by the deleted range.
* Another range will span this area so that by
* end of routine add will be >= zero
*/
add -= (rg->to - rg->from);
list_del(&rg->link);
kfree(rg);
}
}
add += (nrg->from - f); /* Added to beginning of region */
nrg->from = f;
add += t - nrg->to; /* Added to end of region */
nrg->to = t;
out_locked:
resv->adds_in_progress--;
spin_unlock(&resv->lock);
VM_BUG_ON(add < 0);
return add;
}
/*
* Examine the existing reserve map and determine how many
* huge pages in the specified range [f, t) are NOT currently
* represented. This routine is called before a subsequent
* call to region_add that will actually modify the reserve
* map to add the specified range [f, t). region_chg does
* not change the number of huge pages represented by the
* map. However, if the existing regions in the map can not
* be expanded to represent the new range, a new file_region
* structure is added to the map as a placeholder. This is
* so that the subsequent region_add call will have all the
* regions it needs and will not fail.
*
* Upon entry, region_chg will also examine the cache of region descriptors
* associated with the map. If there are not enough descriptors cached, one
* will be allocated for the in progress add operation.
*
* Returns the number of huge pages that need to be added to the existing
* reservation map for the range [f, t). This number is greater or equal to
* zero. -ENOMEM is returned if a new file_region structure or cache entry
* is needed and can not be allocated.
*/
static long region_chg(struct resv_map *resv, long f, long t)
{
struct list_head *head = &resv->regions;
struct file_region *rg, *nrg = NULL;
long chg = 0;
retry:
spin_lock(&resv->lock);
retry_locked:
resv->adds_in_progress++;
/*
* Check for sufficient descriptors in the cache to accommodate
* the number of in progress add operations.
*/
if (resv->adds_in_progress > resv->region_cache_count) {
struct file_region *trg;
VM_BUG_ON(resv->adds_in_progress - resv->region_cache_count > 1);
/* Must drop lock to allocate a new descriptor. */
resv->adds_in_progress--;
spin_unlock(&resv->lock);
trg = kmalloc(sizeof(*trg), GFP_KERNEL);
if (!trg) {
kfree(nrg);
return -ENOMEM;
}
spin_lock(&resv->lock);
list_add(&trg->link, &resv->region_cache);
resv->region_cache_count++;
goto retry_locked;
}
/* Locate the region we are before or in. */
list_for_each_entry(rg, head, link)
if (f <= rg->to)
break;
/* If we are below the current region then a new region is required.
* Subtle, allocate a new region at the position but make it zero
* size such that we can guarantee to record the reservation. */
if (&rg->link == head || t < rg->from) {
if (!nrg) {
resv->adds_in_progress--;
spin_unlock(&resv->lock);
nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
if (!nrg)
return -ENOMEM;
nrg->from = f;
nrg->to = f;
INIT_LIST_HEAD(&nrg->link);
goto retry;
}
list_add(&nrg->link, rg->link.prev);
chg = t - f;
goto out_nrg;
}
/* Round our left edge to the current segment if it encloses us. */
if (f > rg->from)
f = rg->from;
chg = t - f;
/* Check for and consume any regions we now overlap with. */
list_for_each_entry(rg, rg->link.prev, link) {
if (&rg->link == head)
break;
if (rg->from > t)
goto out;
/* We overlap with this area, if it extends further than
* us then we must extend ourselves. Account for its
* existing reservation. */
if (rg->to > t) {
chg += rg->to - t;
t = rg->to;
}
chg -= rg->to - rg->from;
}
out:
spin_unlock(&resv->lock);
/* We already know we raced and no longer need the new region */
kfree(nrg);
return chg;
out_nrg:
spin_unlock(&resv->lock);
return chg;
}
/*
* Abort the in progress add operation. The adds_in_progress field
* of the resv_map keeps track of the operations in progress between
* calls to region_chg and region_add. Operations are sometimes
* aborted after the call to region_chg. In such cases, region_abort
* is called to decrement the adds_in_progress counter.
*
* NOTE: The range arguments [f, t) are not needed or used in this
* routine. They are kept to make reading the calling code easier as
* arguments will match the associated region_chg call.
*/
static void region_abort(struct resv_map *resv, long f, long t)
{
spin_lock(&resv->lock);
VM_BUG_ON(!resv->region_cache_count);
resv->adds_in_progress--;
spin_unlock(&resv->lock);
}
/*
* Delete the specified range [f, t) from the reserve map. If the
* t parameter is LONG_MAX, this indicates that ALL regions after f
* should be deleted. Locate the regions which intersect [f, t)
* and either trim, delete or split the existing regions.
*
* Returns the number of huge pages deleted from the reserve map.
* In the normal case, the return value is zero or more. In the
* case where a region must be split, a new region descriptor must
* be allocated. If the allocation fails, -ENOMEM will be returned.
* NOTE: If the parameter t == LONG_MAX, then we will never split
* a region and possibly return -ENOMEM. Callers specifying
* t == LONG_MAX do not need to check for -ENOMEM error.
*/
static long region_del(struct resv_map *resv, long f, long t)
{
struct list_head *head = &resv->regions;
struct file_region *rg, *trg;
struct file_region *nrg = NULL;
long del = 0;
retry:
spin_lock(&resv->lock);
list_for_each_entry_safe(rg, trg, head, link) {
/*
* Skip regions before the range to be deleted. file_region
* ranges are normally of the form [from, to). However, there
* may be a "placeholder" entry in the map which is of the form
* (from, to) with from == to. Check for placeholder entries
* at the beginning of the range to be deleted.
*/
if (rg->to <= f && (rg->to != rg->from || rg->to != f))
continue;
if (rg->from >= t)
break;
if (f > rg->from && t < rg->to) { /* Must split region */
/*
* Check for an entry in the cache before dropping
* lock and attempting allocation.
*/
if (!nrg &&
resv->region_cache_count > resv->adds_in_progress) {
nrg = list_first_entry(&resv->region_cache,
struct file_region,
link);
list_del(&nrg->link);
resv->region_cache_count--;
}
if (!nrg) {
spin_unlock(&resv->lock);
nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
if (!nrg)
return -ENOMEM;
goto retry;
}
del += t - f;
/* New entry for end of split region */
nrg->from = t;
nrg->to = rg->to;
INIT_LIST_HEAD(&nrg->link);
/* Original entry is trimmed */
rg->to = f;
list_add(&nrg->link, &rg->link);
nrg = NULL;
break;
}
if (f <= rg->from && t >= rg->to) { /* Remove entire region */
del += rg->to - rg->from;
list_del(&rg->link);
kfree(rg);
continue;
}
if (f <= rg->from) { /* Trim beginning of region */
del += t - rg->from;
rg->from = t;
} else { /* Trim end of region */
del += rg->to - f;
rg->to = f;
}
}
spin_unlock(&resv->lock);
kfree(nrg);
return del;
}
/*
* A rare out of memory error was encountered which prevented removal of
* the reserve map region for a page. The huge page itself was free'ed
* and removed from the page cache. This routine will adjust the subpool
* usage count, and the global reserve count if needed. By incrementing
* these counts, the reserve map entry which could not be deleted will
* appear as a "reserved" entry instead of simply dangling with incorrect
* counts.
*/
void hugetlb_fix_reserve_counts(struct inode *inode)
{
struct hugepage_subpool *spool = subpool_inode(inode);
long rsv_adjust;
rsv_adjust = hugepage_subpool_get_pages(spool, 1);
if (rsv_adjust) {
struct hstate *h = hstate_inode(inode);
hugetlb_acct_memory(h, 1);
}
}
/*
* Count and return the number of huge pages in the reserve map
* that intersect with the range [f, t).
*/
static long region_count(struct resv_map *resv, long f, long t)
{
struct list_head *head = &resv->regions;
struct file_region *rg;
long chg = 0;
spin_lock(&resv->lock);
/* Locate each segment we overlap with, and count that overlap. */
list_for_each_entry(rg, head, link) {
long seg_from;
long seg_to;
if (rg->to <= f)
continue;
if (rg->from >= t)
break;
seg_from = max(rg->from, f);
seg_to = min(rg->to, t);
chg += seg_to - seg_from;
}
spin_unlock(&resv->lock);
return chg;
}
/*
* Convert the address within this vma to the page offset within
* the mapping, in pagecache page units; huge pages here.
*/
static pgoff_t vma_hugecache_offset(struct hstate *h,
struct vm_area_struct *vma, unsigned long address)
{
return ((address - vma->vm_start) >> huge_page_shift(h)) +
(vma->vm_pgoff >> huge_page_order(h));
}
pgoff_t linear_hugepage_index(struct vm_area_struct *vma,
unsigned long address)
{
return vma_hugecache_offset(hstate_vma(vma), vma, address);
}
EXPORT_SYMBOL_GPL(linear_hugepage_index);
/*
* Return the size of the pages allocated when backing a VMA. In the majority
* cases this will be same size as used by the page table entries.
*/
unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
{
struct hstate *hstate;
if (!is_vm_hugetlb_page(vma))
return PAGE_SIZE;
hstate = hstate_vma(vma);
return 1UL << huge_page_shift(hstate);
}
EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
/*
* Return the page size being used by the MMU to back a VMA. In the majority
* of cases, the page size used by the kernel matches the MMU size. On
* architectures where it differs, an architecture-specific version of this
* function is required.
*/
#ifndef vma_mmu_pagesize
unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
{
return vma_kernel_pagesize(vma);
}
#endif
/*
* Flags for MAP_PRIVATE reservations. These are stored in the bottom
* bits of the reservation map pointer, which are always clear due to
* alignment.
*/
#define HPAGE_RESV_OWNER (1UL << 0)
#define HPAGE_RESV_UNMAPPED (1UL << 1)
#define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
/*
* These helpers are used to track how many pages are reserved for
* faults in a MAP_PRIVATE mapping. Only the process that called mmap()
* is guaranteed to have their future faults succeed.
*
* With the exception of reset_vma_resv_huge_pages() which is called at fork(),
* the reserve counters are updated with the hugetlb_lock held. It is safe
* to reset the VMA at fork() time as it is not in use yet and there is no
* chance of the global counters getting corrupted as a result of the values.
*
* The private mapping reservation is represented in a subtly different
* manner to a shared mapping. A shared mapping has a region map associated
* with the underlying file, this region map represents the backing file
* pages which have ever had a reservation assigned which this persists even
* after the page is instantiated. A private mapping has a region map
* associated with the original mmap which is attached to all VMAs which
* reference it, this region map represents those offsets which have consumed
* reservation ie. where pages have been instantiated.
*/
static unsigned long get_vma_private_data(struct vm_area_struct *vma)
{
return (unsigned long)vma->vm_private_data;
}
static void set_vma_private_data(struct vm_area_struct *vma,
unsigned long value)
{
vma->vm_private_data = (void *)value;
}
struct resv_map *resv_map_alloc(void)
{
struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL);
if (!resv_map || !rg) {
kfree(resv_map);
kfree(rg);
return NULL;
}
kref_init(&resv_map->refs);
spin_lock_init(&resv_map->lock);
INIT_LIST_HEAD(&resv_map->regions);
resv_map->adds_in_progress = 0;
INIT_LIST_HEAD(&resv_map->region_cache);
list_add(&rg->link, &resv_map->region_cache);
resv_map->region_cache_count = 1;
return resv_map;
}
void resv_map_release(struct kref *ref)
{
struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
struct list_head *head = &resv_map->region_cache;
struct file_region *rg, *trg;
/* Clear out any active regions before we release the map. */
region_del(resv_map, 0, LONG_MAX);
/* ... and any entries left in the cache */
list_for_each_entry_safe(rg, trg, head, link) {
list_del(&rg->link);
kfree(rg);
}
VM_BUG_ON(resv_map->adds_in_progress);
kfree(resv_map);
}
static inline struct resv_map *inode_resv_map(struct inode *inode)
{
return inode->i_mapping->private_data;
}
static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
{
VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
if (vma->vm_flags & VM_MAYSHARE) {
struct address_space *mapping = vma->vm_file->f_mapping;
struct inode *inode = mapping->host;
return inode_resv_map(inode);
} else {
return (struct resv_map *)(get_vma_private_data(vma) &
~HPAGE_RESV_MASK);
}
}
static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
{
VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
set_vma_private_data(vma, (get_vma_private_data(vma) &
HPAGE_RESV_MASK) | (unsigned long)map);
}
static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
{
VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
set_vma_private_data(vma, get_vma_private_data(vma) | flags);
}
static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
{
VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
return (get_vma_private_data(vma) & flag) != 0;
}
/* Reset counters to 0 and clear all HPAGE_RESV_* flags */
void reset_vma_resv_huge_pages(struct vm_area_struct *vma)
{
VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
if (!(vma->vm_flags & VM_MAYSHARE))
vma->vm_private_data = (void *)0;
}
/* Returns true if the VMA has associated reserve pages */
static bool vma_has_reserves(struct vm_area_struct *vma, long chg)
{
if (vma->vm_flags & VM_NORESERVE) {
/*
* This address is already reserved by other process(chg == 0),
* so, we should decrement reserved count. Without decrementing,
* reserve count remains after releasing inode, because this
* allocated page will go into page cache and is regarded as
* coming from reserved pool in releasing step. Currently, we
* don't have any other solution to deal with this situation
* properly, so add work-around here.
*/
if (vma->vm_flags & VM_MAYSHARE && chg == 0)
return true;
else
return false;
}
/* Shared mappings always use reserves */
if (vma->vm_flags & VM_MAYSHARE) {
/*
* We know VM_NORESERVE is not set. Therefore, there SHOULD
* be a region map for all pages. The only situation where
* there is no region map is if a hole was punched via
* fallocate. In this case, there really are no reverves to
* use. This situation is indicated if chg != 0.
*/
if (chg)
return false;
else
return true;
}
/*
* Only the process that called mmap() has reserves for
* private mappings.
*/
if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
/*
* Like the shared case above, a hole punch or truncate
* could have been performed on the private mapping.
* Examine the value of chg to determine if reserves
* actually exist or were previously consumed.
* Very Subtle - The value of chg comes from a previous
* call to vma_needs_reserves(). The reserve map for
* private mappings has different (opposite) semantics
* than that of shared mappings. vma_needs_reserves()
* has already taken this difference in semantics into
* account. Therefore, the meaning of chg is the same
* as in the shared case above. Code could easily be
* combined, but keeping it separate draws attention to
* subtle differences.
*/
if (chg)
return false;
else
return true;
}
return false;
}
static void enqueue_huge_page(struct hstate *h, struct page *page)
{
int nid = page_to_nid(page);
list_move(&page->lru, &h->hugepage_freelists[nid]);
h->free_huge_pages++;
h->free_huge_pages_node[nid]++;
}
static struct page *dequeue_huge_page_node_exact(struct hstate *h, int nid)
{
struct page *page;
list_for_each_entry(page, &h->hugepage_freelists[nid], lru)
if (!PageHWPoison(page))
break;
/*
* if 'non-isolated free hugepage' not found on the list,
* the allocation fails.
*/
if (&h->hugepage_freelists[nid] == &page->lru)
return NULL;
list_move(&page->lru, &h->hugepage_activelist);
set_page_refcounted(page);
h->free_huge_pages--;
h->free_huge_pages_node[nid]--;
return page;
}
static struct page *dequeue_huge_page_nodemask(struct hstate *h, gfp_t gfp_mask, int nid,
nodemask_t *nmask)
{
unsigned int cpuset_mems_cookie;
struct zonelist *zonelist;
struct zone *zone;
struct zoneref *z;
int node = -1;
zonelist = node_zonelist(nid, gfp_mask);
retry_cpuset:
cpuset_mems_cookie = read_mems_allowed_begin();
for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) {
struct page *page;
if (!cpuset_zone_allowed(zone, gfp_mask))
continue;
/*
* no need to ask again on the same node. Pool is node rather than
* zone aware
*/
if (zone_to_nid(zone) == node)
continue;
node = zone_to_nid(zone);
page = dequeue_huge_page_node_exact(h, node);
if (page)
return page;
}
if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie)))
goto retry_cpuset;
return NULL;
}
/* Movability of hugepages depends on migration support. */
static inline gfp_t htlb_alloc_mask(struct hstate *h)
{
if (hugepages_treat_as_movable || hugepage_migration_supported(h))
return GFP_HIGHUSER_MOVABLE;
else
return GFP_HIGHUSER;
}
static struct page *dequeue_huge_page_vma(struct hstate *h,
struct vm_area_struct *vma,
unsigned long address, int avoid_reserve,
long chg)
{
struct page *page;
struct mempolicy *mpol;
gfp_t gfp_mask;
nodemask_t *nodemask;
int nid;
/*
* A child process with MAP_PRIVATE mappings created by their parent
* have no page reserves. This check ensures that reservations are
* not "stolen". The child may still get SIGKILLed
*/
if (!vma_has_reserves(vma, chg) &&
h->free_huge_pages - h->resv_huge_pages == 0)
goto err;
/* If reserves cannot be used, ensure enough pages are in the pool */
if (avoid_reserve && h->free_huge_pages - h->resv_huge_pages == 0)
goto err;
gfp_mask = htlb_alloc_mask(h);
nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask);
if (page && !avoid_reserve && vma_has_reserves(vma, chg)) {
SetPagePrivate(page);
h->resv_huge_pages--;
}
mpol_cond_put(mpol);
return page;
err:
return NULL;
}
/*
* common helper functions for hstate_next_node_to_{alloc|free}.
* We may have allocated or freed a huge page based on a different
* nodes_allowed previously, so h->next_node_to_{alloc|free} might
* be outside of *nodes_allowed. Ensure that we use an allowed
* node for alloc or free.
*/
static int next_node_allowed(int nid, nodemask_t *nodes_allowed)
{
nid = next_node_in(nid, *nodes_allowed);
VM_BUG_ON(nid >= MAX_NUMNODES);
return nid;
}
static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed)
{
if (!node_isset(nid, *nodes_allowed))
nid = next_node_allowed(nid, nodes_allowed);
return nid;
}
/*
* returns the previously saved node ["this node"] from which to
* allocate a persistent huge page for the pool and advance the
* next node from which to allocate, handling wrap at end of node
* mask.
*/
static int hstate_next_node_to_alloc(struct hstate *h,
nodemask_t *nodes_allowed)
{
int nid;
VM_BUG_ON(!nodes_allowed);
nid = get_valid_node_allowed(h->next_nid_to_alloc, nodes_allowed);
h->next_nid_to_alloc = next_node_allowed(nid, nodes_allowed);
return nid;
}
/*
* helper for free_pool_huge_page() - return the previously saved
* node ["this node"] from which to free a huge page. Advance the
* next node id whether or not we find a free huge page to free so
* that the next attempt to free addresses the next node.
*/
static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed)
{
int nid;
VM_BUG_ON(!nodes_allowed);
nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed);
h->next_nid_to_free = next_node_allowed(nid, nodes_allowed);
return nid;
}
#define for_each_node_mask_to_alloc(hs, nr_nodes, node, mask) \
for (nr_nodes = nodes_weight(*mask); \
nr_nodes > 0 && \
((node = hstate_next_node_to_alloc(hs, mask)) || 1); \
nr_nodes--)
#define for_each_node_mask_to_free(hs, nr_nodes, node, mask) \
for (nr_nodes = nodes_weight(*mask); \
nr_nodes > 0 && \
((node = hstate_next_node_to_free(hs, mask)) || 1); \
nr_nodes--)
#ifdef CONFIG_ARCH_HAS_GIGANTIC_PAGE
static void destroy_compound_gigantic_page(struct page *page,
unsigned int order)
{
int i;
int nr_pages = 1 << order;
struct page *p = page + 1;
atomic_set(compound_mapcount_ptr(page), 0);
for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
clear_compound_head(p);
set_page_refcounted(p);
}
set_compound_order(page, 0);
__ClearPageHead(page);
}
static void free_gigantic_page(struct page *page, unsigned int order)
{
free_contig_range(page_to_pfn(page), 1 << order);
}
static int __alloc_gigantic_page(unsigned long start_pfn,
unsigned long nr_pages, gfp_t gfp_mask)
{
unsigned long end_pfn = start_pfn + nr_pages;
return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE,
gfp_mask);
}
static bool pfn_range_valid_gigantic(struct zone *z,
unsigned long start_pfn, unsigned long nr_pages)
{
unsigned long i, end_pfn = start_pfn + nr_pages;
struct page *page;
for (i = start_pfn; i < end_pfn; i++) {
if (!pfn_valid(i))
return false;
page = pfn_to_page(i);
if (page_zone(page) != z)
return false;
if (PageReserved(page))
return false;
if (page_count(page) > 0)
return false;
if (PageHuge(page))
return false;
}
return true;
}
static bool zone_spans_last_pfn(const struct zone *zone,
unsigned long start_pfn, unsigned long nr_pages)
{
unsigned long last_pfn = start_pfn + nr_pages - 1;
return zone_spans_pfn(zone, last_pfn);
}
static struct page *alloc_gigantic_page(int nid, struct hstate *h)
{
unsigned int order = huge_page_order(h);
unsigned long nr_pages = 1 << order;
unsigned long ret, pfn, flags;
struct zonelist *zonelist;
struct zone *zone;
struct zoneref *z;
gfp_t gfp_mask;
gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
zonelist = node_zonelist(nid, gfp_mask);
for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), NULL) {
spin_lock_irqsave(&zone->lock, flags);
pfn = ALIGN(zone->zone_start_pfn, nr_pages);
while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
if (pfn_range_valid_gigantic(zone, pfn, nr_pages)) {
/*
* We release the zone lock here because
* alloc_contig_range() will also lock the zone
* at some point. If there's an allocation
* spinning on this lock, it may win the race
* and cause alloc_contig_range() to fail...
*/
spin_unlock_irqrestore(&zone->lock, flags);
ret = __alloc_gigantic_page(pfn, nr_pages, gfp_mask);
if (!ret)
return pfn_to_page(pfn);
spin_lock_irqsave(&zone->lock, flags);
}
pfn += nr_pages;
}
spin_unlock_irqrestore(&zone->lock, flags);
}
return NULL;
}
static void prep_new_huge_page(struct hstate *h, struct page *page, int nid);
static void prep_compound_gigantic_page(struct page *page, unsigned int order);
static struct page *alloc_fresh_gigantic_page_node(struct hstate *h, int nid)
{
struct page *page;
page = alloc_gigantic_page(nid, h);
if (page) {
prep_compound_gigantic_page(page, huge_page_order(h));
prep_new_huge_page(h, page, nid);
}
return page;
}
static int alloc_fresh_gigantic_page(struct hstate *h,
nodemask_t *nodes_allowed)
{
struct page *page = NULL;
int nr_nodes, node;
for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
page = alloc_fresh_gigantic_page_node(h, node);
if (page)
return 1;
}
return 0;
}
#else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE */
static inline bool gigantic_page_supported(void) { return false; }
static inline void free_gigantic_page(struct page *page, unsigned int order) { }
static inline void destroy_compound_gigantic_page(struct page *page,
unsigned int order) { }
static inline int alloc_fresh_gigantic_page(struct hstate *h,
nodemask_t *nodes_allowed) { return 0; }
#endif
static void update_and_free_page(struct hstate *h, struct page *page)
{
int i;
if (hstate_is_gigantic(h) && !gigantic_page_supported())
return;
h->nr_huge_pages--;
h->nr_huge_pages_node[page_to_nid(page)]--;
for (i = 0; i < pages_per_huge_page(h); i++) {
page[i].flags &= ~(1 << PG_locked | 1 << PG_error |
1 << PG_referenced | 1 << PG_dirty |
1 << PG_active | 1 << PG_private |
1 << PG_writeback);
}
VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
set_page_refcounted(page);
if (hstate_is_gigantic(h)) {
destroy_compound_gigantic_page(page, huge_page_order(h));
free_gigantic_page(page, huge_page_order(h));
} else {
__free_pages(page, huge_page_order(h));
}
}
struct hstate *size_to_hstate(unsigned long size)
{
struct hstate *h;
for_each_hstate(h) {
if (huge_page_size(h) == size)
return h;
}
return NULL;
}
/*
* Test to determine whether the hugepage is "active/in-use" (i.e. being linked
* to hstate->hugepage_activelist.)
*
* This function can be called for tail pages, but never returns true for them.
*/
bool page_huge_active(struct page *page)
{
VM_BUG_ON_PAGE(!PageHuge(page), page);
return PageHead(page) && PagePrivate(&page[1]);
}
/* never called for tail page */
static void set_page_huge_active(struct page *page)
{
VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
SetPagePrivate(&page[1]);
}
static void clear_page_huge_active(struct page *page)
{
VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
ClearPagePrivate(&page[1]);
}
void free_huge_page(struct page *page)
{
/*
* Can't pass hstate in here because it is called from the
* compound page destructor.
*/
struct hstate *h = page_hstate(page);
int nid = page_to_nid(page);
struct hugepage_subpool *spool =
(struct hugepage_subpool *)page_private(page);
bool restore_reserve;
set_page_private(page, 0);
page->mapping = NULL;
VM_BUG_ON_PAGE(page_count(page), page);
VM_BUG_ON_PAGE(page_mapcount(page), page);
restore_reserve = PagePrivate(page);
ClearPagePrivate(page);
/*
* A return code of zero implies that the subpool will be under its
* minimum size if the reservation is not restored after page is free.
* Therefore, force restore_reserve operation.
*/
if (hugepage_subpool_put_pages(spool, 1) == 0)
restore_reserve = true;
spin_lock(&hugetlb_lock);
clear_page_huge_active(page);
hugetlb_cgroup_uncharge_page(hstate_index(h),
pages_per_huge_page(h), page);
if (restore_reserve)
h->resv_huge_pages++;
if (h->surplus_huge_pages_node[nid]) {
/* remove the page from active list */
list_del(&page->lru);
update_and_free_page(h, page);
h->surplus_huge_pages--;
h->surplus_huge_pages_node[nid]--;
} else {
arch_clear_hugepage_flags(page);
enqueue_huge_page(h, page);
}
spin_unlock(&hugetlb_lock);
}
static void prep_new_huge_page(struct hstate *h, struct page *page, int nid)
{
INIT_LIST_HEAD(&page->lru);
set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
spin_lock(&hugetlb_lock);
set_hugetlb_cgroup(page, NULL);
h->nr_huge_pages++;
h->nr_huge_pages_node[nid]++;
spin_unlock(&hugetlb_lock);
put_page(page); /* free it into the hugepage allocator */
}
static void prep_compound_gigantic_page(struct page *page, unsigned int order)
{
int i;
int nr_pages = 1 << order;
struct page *p = page + 1;
/* we rely on prep_new_huge_page to set the destructor */
set_compound_order(page, order);
__ClearPageReserved(page);
__SetPageHead(page);
for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
/*
* For gigantic hugepages allocated through bootmem at
* boot, it's safer to be consistent with the not-gigantic
* hugepages and clear the PG_reserved bit from all tail pages
* too. Otherwse drivers using get_user_pages() to access tail
* pages may get the reference counting wrong if they see
* PG_reserved set on a tail page (despite the head page not
* having PG_reserved set). Enforcing this consistency between
* head and tail pages allows drivers to optimize away a check
* on the head page when they need know if put_page() is needed
* after get_user_pages().
*/
__ClearPageReserved(p);
set_page_count(p, 0);
set_compound_head(p, page);
}
atomic_set(compound_mapcount_ptr(page), -1);
}
/*
* PageHuge() only returns true for hugetlbfs pages, but not for normal or
* transparent huge pages. See the PageTransHuge() documentation for more
* details.
*/
int PageHuge(struct page *page)
{
if (!PageCompound(page))
return 0;
page = compound_head(page);
return page[1].compound_dtor == HUGETLB_PAGE_DTOR;
}
EXPORT_SYMBOL_GPL(PageHuge);
/*
* PageHeadHuge() only returns true for hugetlbfs head page, but not for
* normal or transparent huge pages.
*/
int PageHeadHuge(struct page *page_head)
{
if (!PageHead(page_head))
return 0;
return get_compound_page_dtor(page_head) == free_huge_page;
}
pgoff_t __basepage_index(struct page *page)
{
struct page *page_head = compound_head(page);
pgoff_t index = page_index(page_head);
unsigned long compound_idx;
if (!PageHuge(page_head))
return page_index(page);
if (compound_order(page_head) >= MAX_ORDER)
compound_idx = page_to_pfn(page) - page_to_pfn(page_head);
else
compound_idx = page - page_head;
return (index << compound_order(page_head)) + compound_idx;
}
static struct page *alloc_fresh_huge_page_node(struct hstate *h, int nid)
{
struct page *page;
page = __alloc_pages_node(nid,
htlb_alloc_mask(h)|__GFP_COMP|__GFP_THISNODE|
__GFP_RETRY_MAYFAIL|__GFP_NOWARN,
huge_page_order(h));
if (page) {
prep_new_huge_page(h, page, nid);
}
return page;
}
static int alloc_fresh_huge_page(struct hstate *h, nodemask_t *nodes_allowed)
{
struct page *page;
int nr_nodes, node;
int ret = 0;
for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
page = alloc_fresh_huge_page_node(h, node);
if (page) {
ret = 1;
break;
}
}
if (ret)
count_vm_event(HTLB_BUDDY_PGALLOC);
else
count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
return ret;
}
/*
* Free huge page from pool from next node to free.
* Attempt to keep persistent huge pages more or less
* balanced over allowed nodes.
* Called with hugetlb_lock locked.
*/
static int free_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
bool acct_surplus)
{
int nr_nodes, node;
int ret = 0;
for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
/*
* If we're returning unused surplus pages, only examine
* nodes with surplus pages.
*/
if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
!list_empty(&h->hugepage_freelists[node])) {
struct page *page =
list_entry(h->hugepage_freelists[node].next,
struct page, lru);
list_del(&page->lru);
h->free_huge_pages--;
h->free_huge_pages_node[node]--;
if (acct_surplus) {
h->surplus_huge_pages--;
h->surplus_huge_pages_node[node]--;
}
update_and_free_page(h, page);
ret = 1;
break;
}
}
return ret;
}
/*
* Dissolve a given free hugepage into free buddy pages. This function does
* nothing for in-use (including surplus) hugepages. Returns -EBUSY if the
* number of free hugepages would be reduced below the number of reserved
* hugepages.
*/
int dissolve_free_huge_page(struct page *page)
{
int rc = 0;
spin_lock(&hugetlb_lock);
if (PageHuge(page) && !page_count(page)) {
struct page *head = compound_head(page);
struct hstate *h = page_hstate(head);
int nid = page_to_nid(head);
if (h->free_huge_pages - h->resv_huge_pages == 0) {
rc = -EBUSY;
goto out;
}
/*
* Move PageHWPoison flag from head page to the raw error page,
* which makes any subpages rather than the error page reusable.
*/
if (PageHWPoison(head) && page != head) {
SetPageHWPoison(page);
ClearPageHWPoison(head);
}
list_del(&head->lru);
h->free_huge_pages--;
h->free_huge_pages_node[nid]--;
h->max_huge_pages--;
update_and_free_page(h, head);
}
out:
spin_unlock(&hugetlb_lock);
return rc;
}
/*
* Dissolve free hugepages in a given pfn range. Used by memory hotplug to
* make specified memory blocks removable from the system.
* Note that this will dissolve a free gigantic hugepage completely, if any
* part of it lies within the given range.
* Also note that if dissolve_free_huge_page() returns with an error, all
* free hugepages that were dissolved before that error are lost.
*/
int dissolve_free_huge_pages(unsigned long start_pfn, unsigned long end_pfn)
{
unsigned long pfn;
struct page *page;
int rc = 0;
if (!hugepages_supported())
return rc;
for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << minimum_order) {
page = pfn_to_page(pfn);
if (PageHuge(page) && !page_count(page)) {
rc = dissolve_free_huge_page(page);
if (rc)
break;
}
}
return rc;
}
static struct page *__hugetlb_alloc_buddy_huge_page(struct hstate *h,
gfp_t gfp_mask, int nid, nodemask_t *nmask)
{
int order = huge_page_order(h);
gfp_mask |= __GFP_COMP|__GFP_RETRY_MAYFAIL|__GFP_NOWARN;
if (nid == NUMA_NO_NODE)
nid = numa_mem_id();
return __alloc_pages_nodemask(gfp_mask, order, nid, nmask);
}
static struct page *__alloc_buddy_huge_page(struct hstate *h, gfp_t gfp_mask,
int nid, nodemask_t *nmask)
{
struct page *page;
unsigned int r_nid;
if (hstate_is_gigantic(h))
return NULL;
/*
* Assume we will successfully allocate the surplus page to
* prevent racing processes from causing the surplus to exceed
* overcommit
*
* This however introduces a different race, where a process B
* tries to grow the static hugepage pool while alloc_pages() is
* called by process A. B will only examine the per-node
* counters in determining if surplus huge pages can be
* converted to normal huge pages in adjust_pool_surplus(). A
* won't be able to increment the per-node counter, until the
* lock is dropped by B, but B doesn't drop hugetlb_lock until
* no more huge pages can be converted from surplus to normal
* state (and doesn't try to convert again). Thus, we have a
* case where a surplus huge page exists, the pool is grown, and
* the surplus huge page still exists after, even though it
* should just have been converted to a normal huge page. This
* does not leak memory, though, as the hugepage will be freed
* once it is out of use. It also does not allow the counters to
* go out of whack in adjust_pool_surplus() as we don't modify
* the node values until we've gotten the hugepage and only the
* per-node value is checked there.
*/
spin_lock(&hugetlb_lock);
if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
spin_unlock(&hugetlb_lock);
return NULL;
} else {
h->nr_huge_pages++;
h->surplus_huge_pages++;
}
spin_unlock(&hugetlb_lock);
page = __hugetlb_alloc_buddy_huge_page(h, gfp_mask, nid, nmask);
spin_lock(&hugetlb_lock);
if (page) {
INIT_LIST_HEAD(&page->lru);
r_nid = page_to_nid(page);
set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
set_hugetlb_cgroup(page, NULL);
/*
* We incremented the global counters already
*/
h->nr_huge_pages_node[r_nid]++;
h->surplus_huge_pages_node[r_nid]++;
__count_vm_event(HTLB_BUDDY_PGALLOC);
} else {
h->nr_huge_pages--;
h->surplus_huge_pages--;
__count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
}
spin_unlock(&hugetlb_lock);
return page;
}
/*
* Use the VMA's mpolicy to allocate a huge page from the buddy.
*/
static
struct page *__alloc_buddy_huge_page_with_mpol(struct hstate *h,
struct vm_area_struct *vma, unsigned long addr)
{
struct page *page;
struct mempolicy *mpol;
gfp_t gfp_mask = htlb_alloc_mask(h);
int nid;
nodemask_t *nodemask;
nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask);
page = __alloc_buddy_huge_page(h, gfp_mask, nid, nodemask);
mpol_cond_put(mpol);
return page;
}
/*
* This allocation function is useful in the context where vma is irrelevant.
* E.g. soft-offlining uses this function because it only cares physical
* address of error page.
*/
struct page *alloc_huge_page_node(struct hstate *h, int nid)
{
gfp_t gfp_mask = htlb_alloc_mask(h);
struct page *page = NULL;
if (nid != NUMA_NO_NODE)
gfp_mask |= __GFP_THISNODE;
spin_lock(&hugetlb_lock);
if (h->free_huge_pages - h->resv_huge_pages > 0)
page = dequeue_huge_page_nodemask(h, gfp_mask, nid, NULL);
spin_unlock(&hugetlb_lock);
if (!page)
page = __alloc_buddy_huge_page(h, gfp_mask, nid, NULL);
return page;
}
struct page *alloc_huge_page_nodemask(struct hstate *h, int preferred_nid,
nodemask_t *nmask)
{
gfp_t gfp_mask = htlb_alloc_mask(h);
spin_lock(&hugetlb_lock);
if (h->free_huge_pages - h->resv_huge_pages > 0) {
struct page *page;
page = dequeue_huge_page_nodemask(h, gfp_mask, preferred_nid, nmask);
if (page) {
spin_unlock(&hugetlb_lock);
return page;
}
}
spin_unlock(&hugetlb_lock);
/* No reservations, try to overcommit */
return __alloc_buddy_huge_page(h, gfp_mask, preferred_nid, nmask);
}
/*
* Increase the hugetlb pool such that it can accommodate a reservation
* of size 'delta'.
*/
static int gather_surplus_pages(struct hstate *h, int delta)
{
struct list_head surplus_list;
struct page *page, *tmp;
int ret, i;
int needed, allocated;
bool alloc_ok = true;
needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
if (needed <= 0) {
h->resv_huge_pages += delta;
return 0;
}
allocated = 0;
INIT_LIST_HEAD(&surplus_list);
ret = -ENOMEM;
retry:
spin_unlock(&hugetlb_lock);
for (i = 0; i < needed; i++) {
page = __alloc_buddy_huge_page(h, htlb_alloc_mask(h),
NUMA_NO_NODE, NULL);
if (!page) {
alloc_ok = false;
break;
}
list_add(&page->lru, &surplus_list);
cond_resched();
}
allocated += i;
/*
* After retaking hugetlb_lock, we need to recalculate 'needed'
* because either resv_huge_pages or free_huge_pages may have changed.
*/
spin_lock(&hugetlb_lock);
needed = (h->resv_huge_pages + delta) -
(h->free_huge_pages + allocated);
if (needed > 0) {
if (alloc_ok)
goto retry;
/*
* We were not able to allocate enough pages to
* satisfy the entire reservation so we free what
* we've allocated so far.
*/
goto free;
}
/*
* The surplus_list now contains _at_least_ the number of extra pages
* needed to accommodate the reservation. Add the appropriate number
* of pages to the hugetlb pool and free the extras back to the buddy
* allocator. Commit the entire reservation here to prevent another
* process from stealing the pages as they are added to the pool but
* before they are reserved.
*/
needed += allocated;
h->resv_huge_pages += delta;
ret = 0;
/* Free the needed pages to the hugetlb pool */
list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
if ((--needed) < 0)
break;
/*
* This page is now managed by the hugetlb allocator and has
* no users -- drop the buddy allocator's reference.
*/
put_page_testzero(page);
VM_BUG_ON_PAGE(page_count(page), page);
enqueue_huge_page(h, page);
}
free:
spin_unlock(&hugetlb_lock);
/* Free unnecessary surplus pages to the buddy allocator */
list_for_each_entry_safe(page, tmp, &surplus_list, lru)
put_page(page);
spin_lock(&hugetlb_lock);
return ret;
}
/*
* This routine has two main purposes:
* 1) Decrement the reservation count (resv_huge_pages) by the value passed
* in unused_resv_pages. This corresponds to the prior adjustments made
* to the associated reservation map.
* 2) Free any unused surplus pages that may have been allocated to satisfy
* the reservation. As many as unused_resv_pages may be freed.
*
* Called with hugetlb_lock held. However, the lock could be dropped (and
* reacquired) during calls to cond_resched_lock. Whenever dropping the lock,
* we must make sure nobody else can claim pages we are in the process of
* freeing. Do this by ensuring resv_huge_page always is greater than the
* number of huge pages we plan to free when dropping the lock.
*/
static void return_unused_surplus_pages(struct hstate *h,
unsigned long unused_resv_pages)
{
unsigned long nr_pages;
/* Cannot return gigantic pages currently */
if (hstate_is_gigantic(h))
goto out;
/*
* Part (or even all) of the reservation could have been backed
* by pre-allocated pages. Only free surplus pages.
*/
nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
/*
* We want to release as many surplus pages as possible, spread
* evenly across all nodes with memory. Iterate across these nodes
* until we can no longer free unreserved surplus pages. This occurs
* when the nodes with surplus pages have no free pages.
* free_pool_huge_page() will balance the the freed pages across the
* on-line nodes with memory and will handle the hstate accounting.
*
* Note that we decrement resv_huge_pages as we free the pages. If
* we drop the lock, resv_huge_pages will still be sufficiently large
* to cover subsequent pages we may free.
*/
while (nr_pages--) {
h->resv_huge_pages--;
unused_resv_pages--;
if (!free_pool_huge_page(h, &node_states[N_MEMORY], 1))
goto out;
cond_resched_lock(&hugetlb_lock);
}
out:
/* Fully uncommit the reservation */
h->resv_huge_pages -= unused_resv_pages;
}
/*
* vma_needs_reservation, vma_commit_reservation and vma_end_reservation
* are used by the huge page allocation routines to manage reservations.
*
* vma_needs_reservation is called to determine if the huge page at addr
* within the vma has an associated reservation. If a reservation is
* needed, the value 1 is returned. The caller is then responsible for
* managing the global reservation and subpool usage counts. After
* the huge page has been allocated, vma_commit_reservation is called
* to add the page to the reservation map. If the page allocation fails,
* the reservation must be ended instead of committed. vma_end_reservation
* is called in such cases.
*
* In the normal case, vma_commit_reservation returns the same value
* as the preceding vma_needs_reservation call. The only time this
* is not the case is if a reserve map was changed between calls. It
* is the responsibility of the caller to notice the difference and
* take appropriate action.
*
* vma_add_reservation is used in error paths where a reservation must
* be restored when a newly allocated huge page must be freed. It is
* to be called after calling vma_needs_reservation to determine if a
* reservation exists.
*/
enum vma_resv_mode {
VMA_NEEDS_RESV,
VMA_COMMIT_RESV,
VMA_END_RESV,
VMA_ADD_RESV,
};
static long __vma_reservation_common(struct hstate *h,
struct vm_area_struct *vma, unsigned long addr,
enum vma_resv_mode mode)
{
struct resv_map *resv;
pgoff_t idx;
long ret;
resv = vma_resv_map(vma);
if (!resv)
return 1;
idx = vma_hugecache_offset(h, vma, addr);
switch (mode) {
case VMA_NEEDS_RESV:
ret = region_chg(resv, idx, idx + 1);
break;
case VMA_COMMIT_RESV:
ret = region_add(resv, idx, idx + 1);
break;
case VMA_END_RESV:
region_abort(resv, idx, idx + 1);
ret = 0;
break;
case VMA_ADD_RESV:
if (vma->vm_flags & VM_MAYSHARE)
ret = region_add(resv, idx, idx + 1);
else {
region_abort(resv, idx, idx + 1);
ret = region_del(resv, idx, idx + 1);
}
break;
default:
BUG();
}
if (vma->vm_flags & VM_MAYSHARE)
return ret;
else if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) && ret >= 0) {
/*
* In most cases, reserves always exist for private mappings.
* However, a file associated with mapping could have been
* hole punched or truncated after reserves were consumed.
* As subsequent fault on such a range will not use reserves.
* Subtle - The reserve map for private mappings has the
* opposite meaning than that of shared mappings. If NO
* entry is in the reserve map, it means a reservation exists.
* If an entry exists in the reserve map, it means the
* reservation has already been consumed. As a result, the
* return value of this routine is the opposite of the
* value returned from reserve map manipulation routines above.
*/
if (ret)
return 0;
else
return 1;
}
else
return ret < 0 ? ret : 0;
}
static long vma_needs_reservation(struct hstate *h,
struct vm_area_struct *vma, unsigned long addr)
{
return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
}
static long vma_commit_reservation(struct hstate *h,
struct vm_area_struct *vma, unsigned long addr)
{
return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
}
static void vma_end_reservation(struct hstate *h,
struct vm_area_struct *vma, unsigned long addr)
{
(void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
}
static long vma_add_reservation(struct hstate *h,
struct vm_area_struct *vma, unsigned long addr)
{
return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
}
/*
* This routine is called to restore a reservation on error paths. In the
* specific error paths, a huge page was allocated (via alloc_huge_page)
* and is about to be freed. If a reservation for the page existed,
* alloc_huge_page would have consumed the reservation and set PagePrivate
* in the newly allocated page. When the page is freed via free_huge_page,
* the global reservation count will be incremented if PagePrivate is set.
* However, free_huge_page can not adjust the reserve map. Adjust the
* reserve map here to be consistent with global reserve count adjustments
* to be made by free_huge_page.
*/
static void restore_reserve_on_error(struct hstate *h,
struct vm_area_struct *vma, unsigned long address,
struct page *page)
{
if (unlikely(PagePrivate(page))) {
long rc = vma_needs_reservation(h, vma, address);
if (unlikely(rc < 0)) {
/*
* Rare out of memory condition in reserve map
* manipulation. Clear PagePrivate so that
* global reserve count will not be incremented
* by free_huge_page. This will make it appear
* as though the reservation for this page was
* consumed. This may prevent the task from
* faulting in the page at a later time. This
* is better than inconsistent global huge page
* accounting of reserve counts.
*/
ClearPagePrivate(page);
} else if (rc) {
rc = vma_add_reservation(h, vma, address);
if (unlikely(rc < 0))
/*
* See above comment about rare out of
* memory condition.
*/
ClearPagePrivate(page);
} else
vma_end_reservation(h, vma, address);
}
}
struct page *alloc_huge_page(struct vm_area_struct *vma,
unsigned long addr, int avoid_reserve)
{
struct hugepage_subpool *spool = subpool_vma(vma);
struct hstate *h = hstate_vma(vma);
struct page *page;
long map_chg, map_commit;
long gbl_chg;
int ret, idx;
struct hugetlb_cgroup *h_cg;
idx = hstate_index(h);
/*
* Examine the region/reserve map to determine if the process
* has a reservation for the page to be allocated. A return
* code of zero indicates a reservation exists (no change).
*/
map_chg = gbl_chg = vma_needs_reservation(h, vma, addr);
if (map_chg < 0)
return ERR_PTR(-ENOMEM);
/*
* Processes that did not create the mapping will have no
* reserves as indicated by the region/reserve map. Check
* that the allocation will not exceed the subpool limit.
* Allocations for MAP_NORESERVE mappings also need to be
* checked against any subpool limit.
*/
if (map_chg || avoid_reserve) {
gbl_chg = hugepage_subpool_get_pages(spool, 1);
if (gbl_chg < 0) {
vma_end_reservation(h, vma, addr);
return ERR_PTR(-ENOSPC);
}
/*
* Even though there was no reservation in the region/reserve
* map, there could be reservations associated with the
* subpool that can be used. This would be indicated if the
* return value of hugepage_subpool_get_pages() is zero.
* However, if avoid_reserve is specified we still avoid even
* the subpool reservations.
*/
if (avoid_reserve)
gbl_chg = 1;
}
ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
if (ret)
goto out_subpool_put;
spin_lock(&hugetlb_lock);
/*
* glb_chg is passed to indicate whether or not a page must be taken
* from the global free pool (global change). gbl_chg == 0 indicates
* a reservation exists for the allocation.
*/
page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve, gbl_chg);
if (!page) {
spin_unlock(&hugetlb_lock);
page = __alloc_buddy_huge_page_with_mpol(h, vma, addr);
if (!page)
goto out_uncharge_cgroup;
if (!avoid_reserve && vma_has_reserves(vma, gbl_chg)) {
SetPagePrivate(page);
h->resv_huge_pages--;
}
spin_lock(&hugetlb_lock);
list_move(&page->lru, &h->hugepage_activelist);
/* Fall through */
}
hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, page);
spin_unlock(&hugetlb_lock);
set_page_private(page, (unsigned long)spool);
map_commit = vma_commit_reservation(h, vma, addr);
if (unlikely(map_chg > map_commit)) {
/*
* The page was added to the reservation map between
* vma_needs_reservation and vma_commit_reservation.
* This indicates a race with hugetlb_reserve_pages.
* Adjust for the subpool count incremented above AND
* in hugetlb_reserve_pages for the same page. Also,
* the reservation count added in hugetlb_reserve_pages
* no longer applies.
*/
long rsv_adjust;
rsv_adjust = hugepage_subpool_put_pages(spool, 1);
hugetlb_acct_memory(h, -rsv_adjust);
}
return page;
out_uncharge_cgroup:
hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
out_subpool_put:
if (map_chg || avoid_reserve)
hugepage_subpool_put_pages(spool, 1);
vma_end_reservation(h, vma, addr);
return ERR_PTR(-ENOSPC);
}
/*
* alloc_huge_page()'s wrapper which simply returns the page if allocation
* succeeds, otherwise NULL. This function is called from new_vma_page(),
* where no ERR_VALUE is expected to be returned.
*/
struct page *alloc_huge_page_noerr(struct vm_area_struct *vma,
unsigned long addr, int avoid_reserve)
{
struct page *page = alloc_huge_page(vma, addr, avoid_reserve);
if (IS_ERR(page))
page = NULL;
return page;
}
int alloc_bootmem_huge_page(struct hstate *h)
__attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
int __alloc_bootmem_huge_page(struct hstate *h)
{
struct huge_bootmem_page *m;
int nr_nodes, node;
for_each_node_mask_to_alloc(h, nr_nodes, node, &node_states[N_MEMORY]) {
void *addr;
addr = memblock_virt_alloc_try_nid_nopanic(
huge_page_size(h), huge_page_size(h),
0, BOOTMEM_ALLOC_ACCESSIBLE, node);
if (addr) {
/*
* Use the beginning of the huge page to store the
* huge_bootmem_page struct (until gather_bootmem
* puts them into the mem_map).
*/
m = addr;
goto found;
}
}
return 0;
found:
BUG_ON(!IS_ALIGNED(virt_to_phys(m), huge_page_size(h)));
/* Put them into a private list first because mem_map is not up yet */
list_add(&m->list, &huge_boot_pages);
m->hstate = h;
return 1;
}
static void __init prep_compound_huge_page(struct page *page,
unsigned int order)
{
if (unlikely(order > (MAX_ORDER - 1)))
prep_compound_gigantic_page(page, order);
else
prep_compound_page(page, order);
}
/* Put bootmem huge pages into the standard lists after mem_map is up */
static void __init gather_bootmem_prealloc(void)
{
struct huge_bootmem_page *m;
list_for_each_entry(m, &huge_boot_pages, list) {
struct hstate *h = m->hstate;
struct page *page;
#ifdef CONFIG_HIGHMEM
page = pfn_to_page(m->phys >> PAGE_SHIFT);
memblock_free_late(__pa(m),
sizeof(struct huge_bootmem_page));
#else
page = virt_to_page(m);
#endif
WARN_ON(page_count(page) != 1);
prep_compound_huge_page(page, h->order);
WARN_ON(PageReserved(page));
prep_new_huge_page(h, page, page_to_nid(page));
/*
* If we had gigantic hugepages allocated at boot time, we need
* to restore the 'stolen' pages to totalram_pages in order to
* fix confusing memory reports from free(1) and another
* side-effects, like CommitLimit going negative.
*/
if (hstate_is_gigantic(h))
adjust_managed_page_count(page, 1 << h->order);
}
}
static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
{
unsigned long i;
for (i = 0; i < h->max_huge_pages; ++i) {
if (hstate_is_gigantic(h)) {
if (!alloc_bootmem_huge_page(h))
break;
} else if (!alloc_fresh_huge_page(h,
&node_states[N_MEMORY]))
break;
cond_resched();
}
if (i < h->max_huge_pages) {
char buf[32];
string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
pr_warn("HugeTLB: allocating %lu of page size %s failed. Only allocated %lu hugepages.\n",
h->max_huge_pages, buf, i);
h->max_huge_pages = i;
}
}
static void __init hugetlb_init_hstates(void)
{
struct hstate *h;
for_each_hstate(h) {
if (minimum_order > huge_page_order(h))
minimum_order = huge_page_order(h);
/* oversize hugepages were init'ed in early boot */
if (!hstate_is_gigantic(h))
hugetlb_hstate_alloc_pages(h);
}
VM_BUG_ON(minimum_order == UINT_MAX);
}
static void __init report_hugepages(void)
{
struct hstate *h;
for_each_hstate(h) {
char buf[32];
string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
pr_info("HugeTLB registered %s page size, pre-allocated %ld pages\n",
buf, h->free_huge_pages);
}
}
#ifdef CONFIG_HIGHMEM
static void try_to_free_low(struct hstate *h, unsigned long count,
nodemask_t *nodes_allowed)
{
int i;
if (hstate_is_gigantic(h))
return;
for_each_node_mask(i, *nodes_allowed) {
struct page *page, *next;
struct list_head *freel = &h->hugepage_freelists[i];
list_for_each_entry_safe(page, next, freel, lru) {
if (count >= h->nr_huge_pages)
return;
if (PageHighMem(page))
continue;
list_del(&page->lru);
update_and_free_page(h, page);
h->free_huge_pages--;
h->free_huge_pages_node[page_to_nid(page)]--;
}
}
}
#else
static inline void try_to_free_low(struct hstate *h, unsigned long count,
nodemask_t *nodes_allowed)
{
}
#endif
/*
* Increment or decrement surplus_huge_pages. Keep node-specific counters
* balanced by operating on them in a round-robin fashion.
* Returns 1 if an adjustment was made.
*/
static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
int delta)
{
int nr_nodes, node;
VM_BUG_ON(delta != -1 && delta != 1);
if (delta < 0) {
for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
if (h->surplus_huge_pages_node[node])
goto found;
}
} else {
for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
if (h->surplus_huge_pages_node[node] <
h->nr_huge_pages_node[node])
goto found;
}
}
return 0;
found:
h->surplus_huge_pages += delta;
h->surplus_huge_pages_node[node] += delta;
return 1;
}
#define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
static unsigned long set_max_huge_pages(struct hstate *h, unsigned long count,
nodemask_t *nodes_allowed)
{
unsigned long min_count, ret;
if (hstate_is_gigantic(h) && !gigantic_page_supported())
return h->max_huge_pages;
/*
* Increase the pool size
* First take pages out of surplus state. Then make up the
* remaining difference by allocating fresh huge pages.
*
* We might race with __alloc_buddy_huge_page() here and be unable
* to convert a surplus huge page to a normal huge page. That is
* not critical, though, it just means the overall size of the
* pool might be one hugepage larger than it needs to be, but
* within all the constraints specified by the sysctls.
*/
spin_lock(&hugetlb_lock);
while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
if (!adjust_pool_surplus(h, nodes_allowed, -1))
break;
}
while (count > persistent_huge_pages(h)) {
/*
* If this allocation races such that we no longer need the
* page, free_huge_page will handle it by freeing the page
* and reducing the surplus.
*/
spin_unlock(&hugetlb_lock);
/* yield cpu to avoid soft lockup */
cond_resched();
if (hstate_is_gigantic(h))
ret = alloc_fresh_gigantic_page(h, nodes_allowed);
else
ret = alloc_fresh_huge_page(h, nodes_allowed);
spin_lock(&hugetlb_lock);
if (!ret)
goto out;
/* Bail for signals. Probably ctrl-c from user */
if (signal_pending(current))
goto out;
}
/*
* Decrease the pool size
* First return free pages to the buddy allocator (being careful
* to keep enough around to satisfy reservations). Then place
* pages into surplus state as needed so the pool will shrink
* to the desired size as pages become free.
*
* By placing pages into the surplus state independent of the
* overcommit value, we are allowing the surplus pool size to
* exceed overcommit. There are few sane options here. Since
* __alloc_buddy_huge_page() is checking the global counter,
* though, we'll note that we're not allowed to exceed surplus
* and won't grow the pool anywhere else. Not until one of the
* sysctls are changed, or the surplus pages go out of use.
*/
min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages;
min_count = max(count, min_count);
try_to_free_low(h, min_count, nodes_allowed);
while (min_count < persistent_huge_pages(h)) {
if (!free_pool_huge_page(h, nodes_allowed, 0))
break;
cond_resched_lock(&hugetlb_lock);
}
while (count < persistent_huge_pages(h)) {
if (!adjust_pool_surplus(h, nodes_allowed, 1))
break;
}
out:
ret = persistent_huge_pages(h);
spin_unlock(&hugetlb_lock);
return ret;
}
#define HSTATE_ATTR_RO(_name) \
static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
#define HSTATE_ATTR(_name) \
static struct kobj_attribute _name##_attr = \
__ATTR(_name, 0644, _name##_show, _name##_store)
static struct kobject *hugepages_kobj;
static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp);
static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp)
{
int i;
for (i = 0; i < HUGE_MAX_HSTATE; i++)
if (hstate_kobjs[i] == kobj) {
if (nidp)
*nidp = NUMA_NO_NODE;
return &hstates[i];
}
return kobj_to_node_hstate(kobj, nidp);
}
static ssize_t nr_hugepages_show_common(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
struct hstate *h;
unsigned long nr_huge_pages;
int nid;
h = kobj_to_hstate(kobj, &nid);
if (nid == NUMA_NO_NODE)
nr_huge_pages = h->nr_huge_pages;
else
nr_huge_pages = h->nr_huge_pages_node[nid];
return sprintf(buf, "%lu\n", nr_huge_pages);
}
static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
struct hstate *h, int nid,
unsigned long count, size_t len)
{
int err;
NODEMASK_ALLOC(nodemask_t, nodes_allowed, GFP_KERNEL | __GFP_NORETRY);
if (hstate_is_gigantic(h) && !gigantic_page_supported()) {
err = -EINVAL;
goto out;
}
if (nid == NUMA_NO_NODE) {
/*
* global hstate attribute
*/
if (!(obey_mempolicy &&
init_nodemask_of_mempolicy(nodes_allowed))) {
NODEMASK_FREE(nodes_allowed);
nodes_allowed = &node_states[N_MEMORY];
}
} else if (nodes_allowed) {
/*
* per node hstate attribute: adjust count to global,
* but restrict alloc/free to the specified node.
*/
count += h->nr_huge_pages - h->nr_huge_pages_node[nid];
init_nodemask_of_node(nodes_allowed, nid);
} else
nodes_allowed = &node_states[N_MEMORY];
h->max_huge_pages = set_max_huge_pages(h, count, nodes_allowed);
if (nodes_allowed != &node_states[N_MEMORY])
NODEMASK_FREE(nodes_allowed);
return len;
out:
NODEMASK_FREE(nodes_allowed);
return err;
}
static ssize_t nr_hugepages_store_common(bool obey_mempolicy,
struct kobject *kobj, const char *buf,
size_t len)
{
struct hstate *h;
unsigned long count;
int nid;
int err;
err = kstrtoul(buf, 10, &count);
if (err)
return err;
h = kobj_to_hstate(kobj, &nid);
return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len);
}
static ssize_t nr_hugepages_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return nr_hugepages_show_common(kobj, attr, buf);
}
static ssize_t nr_hugepages_store(struct kobject *kobj,
struct kobj_attribute *attr, const char *buf, size_t len)
{
return nr_hugepages_store_common(false, kobj, buf, len);
}
HSTATE_ATTR(nr_hugepages);
#ifdef CONFIG_NUMA
/*
* hstate attribute for optionally mempolicy-based constraint on persistent
* huge page alloc/free.
*/
static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return nr_hugepages_show_common(kobj, attr, buf);
}
static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj,
struct kobj_attribute *attr, const char *buf, size_t len)
{
return nr_hugepages_store_common(true, kobj, buf, len);
}
HSTATE_ATTR(nr_hugepages_mempolicy);
#endif
static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
struct hstate *h = kobj_to_hstate(kobj, NULL);
return sprintf(buf, "%lu\n", h->nr_overcommit_huge_pages);
}
static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
struct kobj_attribute *attr, const char *buf, size_t count)
{
int err;
unsigned long input;
struct hstate *h = kobj_to_hstate(kobj, NULL);
if (hstate_is_gigantic(h))
return -EINVAL;
err = kstrtoul(buf, 10, &input);
if (err)
return err;
spin_lock(&hugetlb_lock);
h->nr_overcommit_huge_pages = input;
spin_unlock(&hugetlb_lock);
return count;
}
HSTATE_ATTR(nr_overcommit_hugepages);
static ssize_t free_hugepages_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
struct hstate *h;
unsigned long free_huge_pages;
int nid;
h = kobj_to_hstate(kobj, &nid);
if (nid == NUMA_NO_NODE)
free_huge_pages = h->free_huge_pages;
else
free_huge_pages = h->free_huge_pages_node[nid];
return sprintf(buf, "%lu\n", free_huge_pages);
}
HSTATE_ATTR_RO(free_hugepages);
static ssize_t resv_hugepages_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
struct hstate *h = kobj_to_hstate(kobj, NULL);
return sprintf(buf, "%lu\n", h->resv_huge_pages);
}
HSTATE_ATTR_RO(resv_hugepages);
static ssize_t surplus_hugepages_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
struct hstate *h;
unsigned long surplus_huge_pages;
int nid;
h = kobj_to_hstate(kobj, &nid);
if (nid == NUMA_NO_NODE)
surplus_huge_pages = h->surplus_huge_pages;
else
surplus_huge_pages = h->surplus_huge_pages_node[nid];
return sprintf(buf, "%lu\n", surplus_huge_pages);
}
HSTATE_ATTR_RO(surplus_hugepages);
static struct attribute *hstate_attrs[] = {
&nr_hugepages_attr.attr,
&nr_overcommit_hugepages_attr.attr,
&free_hugepages_attr.attr,
&resv_hugepages_attr.attr,
&surplus_hugepages_attr.attr,
#ifdef CONFIG_NUMA
&nr_hugepages_mempolicy_attr.attr,
#endif
NULL,
};
static const struct attribute_group hstate_attr_group = {
.attrs = hstate_attrs,
};
static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent,
struct kobject **hstate_kobjs,
const struct attribute_group *hstate_attr_group)
{
int retval;
int hi = hstate_index(h);
hstate_kobjs[hi] = kobject_create_and_add(h->name, parent);
if (!hstate_kobjs[hi])
return -ENOMEM;
retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group);
if (retval)
kobject_put(hstate_kobjs[hi]);
return retval;
}
static void __init hugetlb_sysfs_init(void)
{
struct hstate *h;
int err;
hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
if (!hugepages_kobj)
return;
for_each_hstate(h) {
err = hugetlb_sysfs_add_hstate(h, hugepages_kobj,
hstate_kobjs, &hstate_attr_group);
if (err)
pr_err("Hugetlb: Unable to add hstate %s", h->name);
}
}
#ifdef CONFIG_NUMA
/*
* node_hstate/s - associate per node hstate attributes, via their kobjects,
* with node devices in node_devices[] using a parallel array. The array
* index of a node device or _hstate == node id.
* This is here to avoid any static dependency of the node device driver, in
* the base kernel, on the hugetlb module.
*/
struct node_hstate {
struct kobject *hugepages_kobj;
struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
};
static struct node_hstate node_hstates[MAX_NUMNODES];
/*
* A subset of global hstate attributes for node devices
*/
static struct attribute *per_node_hstate_attrs[] = {
&nr_hugepages_attr.attr,
&free_hugepages_attr.attr,
&surplus_hugepages_attr.attr,
NULL,
};
static const struct attribute_group per_node_hstate_attr_group = {
.attrs = per_node_hstate_attrs,
};
/*
* kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj.
* Returns node id via non-NULL nidp.
*/
static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
{
int nid;
for (nid = 0; nid < nr_node_ids; nid++) {
struct node_hstate *nhs = &node_hstates[nid];
int i;
for (i = 0; i < HUGE_MAX_HSTATE; i++)
if (nhs->hstate_kobjs[i] == kobj) {
if (nidp)
*nidp = nid;
return &hstates[i];
}
}
BUG();
return NULL;
}
/*
* Unregister hstate attributes from a single node device.
* No-op if no hstate attributes attached.
*/
static void hugetlb_unregister_node(struct node *node)
{
struct hstate *h;
struct node_hstate *nhs = &node_hstates[node->dev.id];
if (!nhs->hugepages_kobj)
return; /* no hstate attributes */
for_each_hstate(h) {
int idx = hstate_index(h);
if (nhs->hstate_kobjs[idx]) {
kobject_put(nhs->hstate_kobjs[idx]);
nhs->hstate_kobjs[idx] = NULL;
}
}
kobject_put(nhs->hugepages_kobj);
nhs->hugepages_kobj = NULL;
}
/*
* Register hstate attributes for a single node device.
* No-op if attributes already registered.
*/
static void hugetlb_register_node(struct node *node)
{
struct hstate *h;
struct node_hstate *nhs = &node_hstates[node->dev.id];
int err;
if (nhs->hugepages_kobj)
return; /* already allocated */
nhs->hugepages_kobj = kobject_create_and_add("hugepages",
&node->dev.kobj);
if (!nhs->hugepages_kobj)
return;
for_each_hstate(h) {
err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj,
nhs->hstate_kobjs,
&per_node_hstate_attr_group);
if (err) {
pr_err("Hugetlb: Unable to add hstate %s for node %d\n",
h->name, node->dev.id);
hugetlb_unregister_node(node);
break;
}
}
}
/*
* hugetlb init time: register hstate attributes for all registered node
* devices of nodes that have memory. All on-line nodes should have
* registered their associated device by this time.
*/
static void __init hugetlb_register_all_nodes(void)
{
int nid;
for_each_node_state(nid, N_MEMORY) {
struct node *node = node_devices[nid];
if (node->dev.id == nid)
hugetlb_register_node(node);
}
/*
* Let the node device driver know we're here so it can
* [un]register hstate attributes on node hotplug.
*/
register_hugetlbfs_with_node(hugetlb_register_node,
hugetlb_unregister_node);
}
#else /* !CONFIG_NUMA */
static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
{
BUG();
if (nidp)
*nidp = -1;
return NULL;
}
static void hugetlb_register_all_nodes(void) { }
#endif
static int __init hugetlb_init(void)
{
int i;
if (!hugepages_supported())
return 0;
if (!size_to_hstate(default_hstate_size)) {
if (default_hstate_size != 0) {
pr_err("HugeTLB: unsupported default_hugepagesz %lu. Reverting to %lu\n",
default_hstate_size, HPAGE_SIZE);
}
default_hstate_size = HPAGE_SIZE;
if (!size_to_hstate(default_hstate_size))
hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
}
default_hstate_idx = hstate_index(size_to_hstate(default_hstate_size));
if (default_hstate_max_huge_pages) {
if (!default_hstate.max_huge_pages)
default_hstate.max_huge_pages = default_hstate_max_huge_pages;
}
hugetlb_init_hstates();
gather_bootmem_prealloc();
report_hugepages();
hugetlb_sysfs_init();
hugetlb_register_all_nodes();
hugetlb_cgroup_file_init();
#ifdef CONFIG_SMP
num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
#else
num_fault_mutexes = 1;
#endif
hugetlb_fault_mutex_table =
kmalloc(sizeof(struct mutex) * num_fault_mutexes, GFP_KERNEL);
BUG_ON(!hugetlb_fault_mutex_table);
for (i = 0; i < num_fault_mutexes; i++)
mutex_init(&hugetlb_fault_mutex_table[i]);
return 0;
}
subsys_initcall(hugetlb_init);
/* Should be called on processing a hugepagesz=... option */
void __init hugetlb_bad_size(void)
{
parsed_valid_hugepagesz = false;
}
void __init hugetlb_add_hstate(unsigned int order)
{
struct hstate *h;
unsigned long i;
if (size_to_hstate(PAGE_SIZE << order)) {
pr_warn("hugepagesz= specified twice, ignoring\n");
return;
}
BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
BUG_ON(order == 0);
h = &hstates[hugetlb_max_hstate++];
h->order = order;
h->mask = ~((1ULL << (order + PAGE_SHIFT)) - 1);
h->nr_huge_pages = 0;
h->free_huge_pages = 0;
for (i = 0; i < MAX_NUMNODES; ++i)
INIT_LIST_HEAD(&h->hugepage_freelists[i]);
INIT_LIST_HEAD(&h->hugepage_activelist);
h->next_nid_to_alloc = first_memory_node;
h->next_nid_to_free = first_memory_node;
snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
huge_page_size(h)/1024);
parsed_hstate = h;
}
static int __init hugetlb_nrpages_setup(char *s)
{
unsigned long *mhp;
static unsigned long *last_mhp;
if (!parsed_valid_hugepagesz) {
pr_warn("hugepages = %s preceded by "
"an unsupported hugepagesz, ignoring\n", s);
parsed_valid_hugepagesz = true;
return 1;
}
/*
* !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter yet,
* so this hugepages= parameter goes to the "default hstate".
*/
else if (!hugetlb_max_hstate)
mhp = &default_hstate_max_huge_pages;
else
mhp = &parsed_hstate->max_huge_pages;
if (mhp == last_mhp) {
pr_warn("hugepages= specified twice without interleaving hugepagesz=, ignoring\n");
return 1;
}
if (sscanf(s, "%lu", mhp) <= 0)
*mhp = 0;
/*
* Global state is always initialized later in hugetlb_init.
* But we need to allocate >= MAX_ORDER hstates here early to still
* use the bootmem allocator.
*/
if (hugetlb_max_hstate && parsed_hstate->order >= MAX_ORDER)
hugetlb_hstate_alloc_pages(parsed_hstate);
last_mhp = mhp;
return 1;
}
__setup("hugepages=", hugetlb_nrpages_setup);
static int __init hugetlb_default_setup(char *s)
{
default_hstate_size = memparse(s, &s);
return 1;
}
__setup("default_hugepagesz=", hugetlb_default_setup);
static unsigned int cpuset_mems_nr(unsigned int *array)
{
int node;
unsigned int nr = 0;
for_each_node_mask(node, cpuset_current_mems_allowed)
nr += array[node];
return nr;
}
#ifdef CONFIG_SYSCTL
static int hugetlb_sysctl_handler_common(bool obey_mempolicy,
struct ctl_table *table, int write,
void __user *buffer, size_t *length, loff_t *ppos)
{
struct hstate *h = &default_hstate;
unsigned long tmp = h->max_huge_pages;
int ret;
if (!hugepages_supported())
return -EOPNOTSUPP;
table->data = &tmp;
table->maxlen = sizeof(unsigned long);
ret = proc_doulongvec_minmax(table, write, buffer, length, ppos);
if (ret)
goto out;
if (write)
ret = __nr_hugepages_store_common(obey_mempolicy, h,
NUMA_NO_NODE, tmp, *length);
out:
return ret;
}
int hugetlb_sysctl_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *length, loff_t *ppos)
{
return hugetlb_sysctl_handler_common(false, table, write,
buffer, length, ppos);
}
#ifdef CONFIG_NUMA
int hugetlb_mempolicy_sysctl_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *length, loff_t *ppos)
{
return hugetlb_sysctl_handler_common(true, table, write,
buffer, length, ppos);
}
#endif /* CONFIG_NUMA */
int hugetlb_overcommit_handler(struct ctl_table *table, int write,
void __user *buffer,
size_t *length, loff_t *ppos)
{
struct hstate *h = &default_hstate;
unsigned long tmp;
int ret;
if (!hugepages_supported())
return -EOPNOTSUPP;
tmp = h->nr_overcommit_huge_pages;
if (write && hstate_is_gigantic(h))
return -EINVAL;
table->data = &tmp;
table->maxlen = sizeof(unsigned long);
ret = proc_doulongvec_minmax(table, write, buffer, length, ppos);
if (ret)
goto out;
if (write) {
spin_lock(&hugetlb_lock);
h->nr_overcommit_huge_pages = tmp;
spin_unlock(&hugetlb_lock);
}
out:
return ret;
}
#endif /* CONFIG_SYSCTL */
void hugetlb_report_meminfo(struct seq_file *m)
{
struct hstate *h = &default_hstate;
if (!hugepages_supported())
return;
seq_printf(m,
"HugePages_Total: %5lu\n"
"HugePages_Free: %5lu\n"
"HugePages_Rsvd: %5lu\n"
"HugePages_Surp: %5lu\n"
"Hugepagesize: %8lu kB\n",
h->nr_huge_pages,
h->free_huge_pages,
h->resv_huge_pages,
h->surplus_huge_pages,
1UL << (huge_page_order(h) + PAGE_SHIFT - 10));
}
int hugetlb_report_node_meminfo(int nid, char *buf)
{
struct hstate *h = &default_hstate;
if (!hugepages_supported())
return 0;
return sprintf(buf,
"Node %d HugePages_Total: %5u\n"
"Node %d HugePages_Free: %5u\n"
"Node %d HugePages_Surp: %5u\n",
nid, h->nr_huge_pages_node[nid],
nid, h->free_huge_pages_node[nid],
nid, h->surplus_huge_pages_node[nid]);
}
void hugetlb_show_meminfo(void)
{
struct hstate *h;
int nid;
if (!hugepages_supported())
return;
for_each_node_state(nid, N_MEMORY)
for_each_hstate(h)
pr_info("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
nid,
h->nr_huge_pages_node[nid],
h->free_huge_pages_node[nid],
h->surplus_huge_pages_node[nid],
1UL << (huge_page_order(h) + PAGE_SHIFT - 10));
}
void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
{
seq_printf(m, "HugetlbPages:\t%8lu kB\n",
atomic_long_read(&mm->hugetlb_usage) << (PAGE_SHIFT - 10));
}
/* Return the number pages of memory we physically have, in PAGE_SIZE units. */
unsigned long hugetlb_total_pages(void)
{
struct hstate *h;
unsigned long nr_total_pages = 0;
for_each_hstate(h)
nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
return nr_total_pages;
}
static int hugetlb_acct_memory(struct hstate *h, long delta)
{
int ret = -ENOMEM;
spin_lock(&hugetlb_lock);
/*
* When cpuset is configured, it breaks the strict hugetlb page
* reservation as the accounting is done on a global variable. Such
* reservation is completely rubbish in the presence of cpuset because
* the reservation is not checked against page availability for the
* current cpuset. Application can still potentially OOM'ed by kernel
* with lack of free htlb page in cpuset that the task is in.
* Attempt to enforce strict accounting with cpuset is almost
* impossible (or too ugly) because cpuset is too fluid that
* task or memory node can be dynamically moved between cpusets.
*
* The change of semantics for shared hugetlb mapping with cpuset is
* undesirable. However, in order to preserve some of the semantics,
* we fall back to check against current free page availability as
* a best attempt and hopefully to minimize the impact of changing
* semantics that cpuset has.
*/
if (delta > 0) {
if (gather_surplus_pages(h, delta) < 0)
goto out;
if (delta > cpuset_mems_nr(h->free_huge_pages_node)) {
return_unused_surplus_pages(h, delta);
goto out;
}
}
ret = 0;
if (delta < 0)
return_unused_surplus_pages(h, (unsigned long) -delta);
out:
spin_unlock(&hugetlb_lock);
return ret;
}
static void hugetlb_vm_op_open(struct vm_area_struct *vma)
{
struct resv_map *resv = vma_resv_map(vma);
/*
* This new VMA should share its siblings reservation map if present.
* The VMA will only ever have a valid reservation map pointer where
* it is being copied for another still existing VMA. As that VMA
* has a reference to the reservation map it cannot disappear until
* after this open call completes. It is therefore safe to take a
* new reference here without additional locking.
*/
if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
kref_get(&resv->refs);
}
static void hugetlb_vm_op_close(struct vm_area_struct *vma)
{
struct hstate *h = hstate_vma(vma);
struct resv_map *resv = vma_resv_map(vma);
struct hugepage_subpool *spool = subpool_vma(vma);
unsigned long reserve, start, end;
long gbl_reserve;
if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
return;
start = vma_hugecache_offset(h, vma, vma->vm_start);
end = vma_hugecache_offset(h, vma, vma->vm_end);
reserve = (end - start) - region_count(resv, start, end);
kref_put(&resv->refs, resv_map_release);
if (reserve) {
/*
* Decrement reserve counts. The global reserve count may be
* adjusted if the subpool has a minimum size.
*/
gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
hugetlb_acct_memory(h, -gbl_reserve);
}
}
/*
* We cannot handle pagefaults against hugetlb pages at all. They cause
* handle_mm_fault() to try to instantiate regular-sized pages in the
* hugegpage VMA. do_page_fault() is supposed to trap this, so BUG is we get
* this far.
*/
static int hugetlb_vm_op_fault(struct vm_fault *vmf)
{
BUG();
return 0;
}
const struct vm_operations_struct hugetlb_vm_ops = {
.fault = hugetlb_vm_op_fault,
.open = hugetlb_vm_op_open,
.close = hugetlb_vm_op_close,
};
static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
int writable)
{
pte_t entry;
if (writable) {
entry = huge_pte_mkwrite(huge_pte_mkdirty(mk_huge_pte(page,
vma->vm_page_prot)));
} else {
entry = huge_pte_wrprotect(mk_huge_pte(page,
vma->vm_page_prot));
}
entry = pte_mkyoung(entry);
entry = pte_mkhuge(entry);
entry = arch_make_huge_pte(entry, vma, page, writable);
return entry;
}
static void set_huge_ptep_writable(struct vm_area_struct *vma,
unsigned long address, pte_t *ptep)
{
pte_t entry;
entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(ptep)));
if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
update_mmu_cache(vma, address, ptep);
}
bool is_hugetlb_entry_migration(pte_t pte)
{
swp_entry_t swp;
if (huge_pte_none(pte) || pte_present(pte))
return false;
swp = pte_to_swp_entry(pte);
if (non_swap_entry(swp) && is_migration_entry(swp))
return true;
else
return false;
}
static int is_hugetlb_entry_hwpoisoned(pte_t pte)
{
swp_entry_t swp;
if (huge_pte_none(pte) || pte_present(pte))
return 0;
swp = pte_to_swp_entry(pte);
if (non_swap_entry(swp) && is_hwpoison_entry(swp))
return 1;
else
return 0;
}
int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
struct vm_area_struct *vma)
{
pte_t *src_pte, *dst_pte, entry;
struct page *ptepage;
unsigned long addr;
int cow;
struct hstate *h = hstate_vma(vma);
unsigned long sz = huge_page_size(h);
unsigned long mmun_start; /* For mmu_notifiers */
unsigned long mmun_end; /* For mmu_notifiers */
int ret = 0;
cow = (vma->vm_flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE;
mmun_start = vma->vm_start;
mmun_end = vma->vm_end;
if (cow)
mmu_notifier_invalidate_range_start(src, mmun_start, mmun_end);
for (addr = vma->vm_start; addr < vma->vm_end; addr += sz) {
spinlock_t *src_ptl, *dst_ptl;
src_pte = huge_pte_offset(src, addr, sz);
if (!src_pte)
continue;
dst_pte = huge_pte_alloc(dst, addr, sz);
if (!dst_pte) {
ret = -ENOMEM;
break;
}
/* If the pagetables are shared don't copy or take references */
if (dst_pte == src_pte)
continue;
dst_ptl = huge_pte_lock(h, dst, dst_pte);
src_ptl = huge_pte_lockptr(h, src, src_pte);
spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
entry = huge_ptep_get(src_pte);
if (huge_pte_none(entry)) { /* skip none entry */
;
} else if (unlikely(is_hugetlb_entry_migration(entry) ||
is_hugetlb_entry_hwpoisoned(entry))) {
swp_entry_t swp_entry = pte_to_swp_entry(entry);
if (is_write_migration_entry(swp_entry) && cow) {
/*
* COW mappings require pages in both
* parent and child to be set to read.
*/
make_migration_entry_read(&swp_entry);
entry = swp_entry_to_pte(swp_entry);
set_huge_swap_pte_at(src, addr, src_pte,
entry, sz);
}
set_huge_swap_pte_at(dst, addr, dst_pte, entry, sz);
} else {
if (cow) {
huge_ptep_set_wrprotect(src, addr, src_pte);
mmu_notifier_invalidate_range(src, mmun_start,
mmun_end);
}
entry = huge_ptep_get(src_pte);
ptepage = pte_page(entry);
get_page(ptepage);
page_dup_rmap(ptepage, true);
set_huge_pte_at(dst, addr, dst_pte, entry);
hugetlb_count_add(pages_per_huge_page(h), dst);
}
spin_unlock(src_ptl);
spin_unlock(dst_ptl);
}
if (cow)
mmu_notifier_invalidate_range_end(src, mmun_start, mmun_end);
return ret;
}
void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
unsigned long start, unsigned long end,
struct page *ref_page)
{
struct mm_struct *mm = vma->vm_mm;
unsigned long address;
pte_t *ptep;
pte_t pte;
spinlock_t *ptl;
struct page *page;
struct hstate *h = hstate_vma(vma);
unsigned long sz = huge_page_size(h);
const unsigned long mmun_start = start; /* For mmu_notifiers */
const unsigned long mmun_end = end; /* For mmu_notifiers */
WARN_ON(!is_vm_hugetlb_page(vma));
BUG_ON(start & ~huge_page_mask(h));
BUG_ON(end & ~huge_page_mask(h));
/*
* This is a hugetlb vma, all the pte entries should point
* to huge page.
*/
tlb_remove_check_page_size_change(tlb, sz);
tlb_start_vma(tlb, vma);
mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
address = start;
for (; address < end; address += sz) {
ptep = huge_pte_offset(mm, address, sz);
if (!ptep)
continue;
ptl = huge_pte_lock(h, mm, ptep);
if (huge_pmd_unshare(mm, &address, ptep)) {
spin_unlock(ptl);
continue;
}
pte = huge_ptep_get(ptep);
if (huge_pte_none(pte)) {
spin_unlock(ptl);
continue;
}
/*
* Migrating hugepage or HWPoisoned hugepage is already
* unmapped and its refcount is dropped, so just clear pte here.
*/
if (unlikely(!pte_present(pte))) {
huge_pte_clear(mm, address, ptep, sz);
spin_unlock(ptl);
continue;
}
page = pte_page(pte);
/*
* If a reference page is supplied, it is because a specific
* page is being unmapped, not a range. Ensure the page we
* are about to unmap is the actual page of interest.
*/
if (ref_page) {
if (page != ref_page) {
spin_unlock(ptl);
continue;
}
/*
* Mark the VMA as having unmapped its page so that
* future faults in this VMA will fail rather than
* looking like data was lost
*/
set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
}
pte = huge_ptep_get_and_clear(mm, address, ptep);
tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
if (huge_pte_dirty(pte))
set_page_dirty(page);
hugetlb_count_sub(pages_per_huge_page(h), mm);
page_remove_rmap(page, true);
spin_unlock(ptl);
tlb_remove_page_size(tlb, page, huge_page_size(h));
/*
* Bail out after unmapping reference page if supplied
*/
if (ref_page)
break;
}
mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
tlb_end_vma(tlb, vma);
}
void __unmap_hugepage_range_final(struct mmu_gather *tlb,
struct vm_area_struct *vma, unsigned long start,
unsigned long end, struct page *ref_page)
{
__unmap_hugepage_range(tlb, vma, start, end, ref_page);
/*
* Clear this flag so that x86's huge_pmd_share page_table_shareable
* test will fail on a vma being torn down, and not grab a page table
* on its way out. We're lucky that the flag has such an appropriate
* name, and can in fact be safely cleared here. We could clear it
* before the __unmap_hugepage_range above, but all that's necessary
* is to clear it before releasing the i_mmap_rwsem. This works
* because in the context this is called, the VMA is about to be
* destroyed and the i_mmap_rwsem is held.
*/
vma->vm_flags &= ~VM_MAYSHARE;
}
void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
unsigned long end, struct page *ref_page)
{
struct mm_struct *mm;
struct mmu_gather tlb;
mm = vma->vm_mm;
tlb_gather_mmu(&tlb, mm, start, end);
__unmap_hugepage_range(&tlb, vma, start, end, ref_page);
tlb_finish_mmu(&tlb, start, end);
}
/*
* This is called when the original mapper is failing to COW a MAP_PRIVATE
* mappping it owns the reserve page for. The intention is to unmap the page
* from other VMAs and let the children be SIGKILLed if they are faulting the
* same region.
*/
static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
struct page *page, unsigned long address)
{
struct hstate *h = hstate_vma(vma);
struct vm_area_struct *iter_vma;
struct address_space *mapping;
pgoff_t pgoff;
/*
* vm_pgoff is in PAGE_SIZE units, hence the different calculation
* from page cache lookup which is in HPAGE_SIZE units.
*/
address = address & huge_page_mask(h);
pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
vma->vm_pgoff;
mapping = vma->vm_file->f_mapping;
/*
* Take the mapping lock for the duration of the table walk. As
* this mapping should be shared between all the VMAs,
* __unmap_hugepage_range() is called as the lock is already held
*/
i_mmap_lock_write(mapping);
vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
/* Do not unmap the current VMA */
if (iter_vma == vma)
continue;
/*
* Shared VMAs have their own reserves and do not affect
* MAP_PRIVATE accounting but it is possible that a shared
* VMA is using the same page so check and skip such VMAs.
*/
if (iter_vma->vm_flags & VM_MAYSHARE)
continue;
/*
* Unmap the page from other VMAs without their own reserves.
* They get marked to be SIGKILLed if they fault in these
* areas. This is because a future no-page fault on this VMA
* could insert a zeroed page instead of the data existing
* from the time of fork. This would look like data corruption
*/
if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
unmap_hugepage_range(iter_vma, address,
address + huge_page_size(h), page);
}
i_mmap_unlock_write(mapping);
}
/*
* Hugetlb_cow() should be called with page lock of the original hugepage held.
* Called with hugetlb_instantiation_mutex held and pte_page locked so we
* cannot race with other handlers or page migration.
* Keep the pte_same checks anyway to make transition from the mutex easier.
*/
static int hugetlb_cow(struct mm_struct *mm, struct vm_area_struct *vma,
unsigned long address, pte_t *ptep,
struct page *pagecache_page, spinlock_t *ptl)
{
pte_t pte;
struct hstate *h = hstate_vma(vma);
struct page *old_page, *new_page;
int ret = 0, outside_reserve = 0;
unsigned long mmun_start; /* For mmu_notifiers */
unsigned long mmun_end; /* For mmu_notifiers */
pte = huge_ptep_get(ptep);
old_page = pte_page(pte);
retry_avoidcopy:
/* If no-one else is actually using this page, avoid the copy
* and just make the page writable */
if (page_mapcount(old_page) == 1 && PageAnon(old_page)) {
page_move_anon_rmap(old_page, vma);
set_huge_ptep_writable(vma, address, ptep);
return 0;
}
/*
* If the process that created a MAP_PRIVATE mapping is about to
* perform a COW due to a shared page count, attempt to satisfy
* the allocation without using the existing reserves. The pagecache
* page is used to determine if the reserve at this address was
* consumed or not. If reserves were used, a partial faulted mapping
* at the time of fork() could consume its reserves on COW instead
* of the full address range.
*/
if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
old_page != pagecache_page)
outside_reserve = 1;
get_page(old_page);
/*
* Drop page table lock as buddy allocator may be called. It will
* be acquired again before returning to the caller, as expected.
*/
spin_unlock(ptl);
new_page = alloc_huge_page(vma, address, outside_reserve);
if (IS_ERR(new_page)) {
/*
* If a process owning a MAP_PRIVATE mapping fails to COW,
* it is due to references held by a child and an insufficient
* huge page pool. To guarantee the original mappers
* reliability, unmap the page from child processes. The child
* may get SIGKILLed if it later faults.
*/
if (outside_reserve) {
put_page(old_page);
BUG_ON(huge_pte_none(pte));
unmap_ref_private(mm, vma, old_page, address);
BUG_ON(huge_pte_none(pte));
spin_lock(ptl);
ptep = huge_pte_offset(mm, address & huge_page_mask(h),
huge_page_size(h));
if (likely(ptep &&
pte_same(huge_ptep_get(ptep), pte)))
goto retry_avoidcopy;
/*
* race occurs while re-acquiring page table
* lock, and our job is done.
*/
return 0;
}
ret = (PTR_ERR(new_page) == -ENOMEM) ?
VM_FAULT_OOM : VM_FAULT_SIGBUS;
goto out_release_old;
}
/*
* When the original hugepage is shared one, it does not have
* anon_vma prepared.
*/
if (unlikely(anon_vma_prepare(vma))) {
ret = VM_FAULT_OOM;
goto out_release_all;
}
copy_user_huge_page(new_page, old_page, address, vma,
pages_per_huge_page(h));
__SetPageUptodate(new_page);
set_page_huge_active(new_page);
mmun_start = address & huge_page_mask(h);
mmun_end = mmun_start + huge_page_size(h);
mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
/*
* Retake the page table lock to check for racing updates
* before the page tables are altered
*/
spin_lock(ptl);
ptep = huge_pte_offset(mm, address & huge_page_mask(h),
huge_page_size(h));
if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) {
ClearPagePrivate(new_page);
/* Break COW */
huge_ptep_clear_flush(vma, address, ptep);
mmu_notifier_invalidate_range(mm, mmun_start, mmun_end);
set_huge_pte_at(mm, address, ptep,
make_huge_pte(vma, new_page, 1));
page_remove_rmap(old_page, true);
hugepage_add_new_anon_rmap(new_page, vma, address);
/* Make the old page be freed below */
new_page = old_page;
}
spin_unlock(ptl);
mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
out_release_all:
restore_reserve_on_error(h, vma, address, new_page);
put_page(new_page);
out_release_old:
put_page(old_page);
spin_lock(ptl); /* Caller expects lock to be held */
return ret;
}
/* Return the pagecache page at a given address within a VMA */
static struct page *hugetlbfs_pagecache_page(struct hstate *h,
struct vm_area_struct *vma, unsigned long address)
{
struct address_space *mapping;
pgoff_t idx;
mapping = vma->vm_file->f_mapping;
idx = vma_hugecache_offset(h, vma, address);
return find_lock_page(mapping, idx);
}
/*
* Return whether there is a pagecache page to back given address within VMA.
* Caller follow_hugetlb_page() holds page_table_lock so we cannot lock_page.
*/
static bool hugetlbfs_pagecache_present(struct hstate *h,
struct vm_area_struct *vma, unsigned long address)
{
struct address_space *mapping;
pgoff_t idx;
struct page *page;
mapping = vma->vm_file->f_mapping;
idx = vma_hugecache_offset(h, vma, address);
page = find_get_page(mapping, idx);
if (page)
put_page(page);
return page != NULL;
}
int huge_add_to_page_cache(struct page *page, struct address_space *mapping,
pgoff_t idx)
{
struct inode *inode = mapping->host;
struct hstate *h = hstate_inode(inode);
int err = add_to_page_cache(page, mapping, idx, GFP_KERNEL);
if (err)
return err;
ClearPagePrivate(page);
spin_lock(&inode->i_lock);
inode->i_blocks += blocks_per_huge_page(h);
spin_unlock(&inode->i_lock);
return 0;
}
static int hugetlb_no_page(struct mm_struct *mm, struct vm_area_struct *vma,
struct address_space *mapping, pgoff_t idx,
unsigned long address, pte_t *ptep, unsigned int flags)
{
struct hstate *h = hstate_vma(vma);
int ret = VM_FAULT_SIGBUS;
int anon_rmap = 0;
unsigned long size;
struct page *page;
pte_t new_pte;
spinlock_t *ptl;
/*
* Currently, we are forced to kill the process in the event the
* original mapper has unmapped pages from the child due to a failed
* COW. Warn that such a situation has occurred as it may not be obvious
*/
if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
current->pid);
return ret;
}
/*
* Use page lock to guard against racing truncation
* before we get page_table_lock.
*/
retry:
page = find_lock_page(mapping, idx);
if (!page) {
size = i_size_read(mapping->host) >> huge_page_shift(h);
if (idx >= size)
goto out;
/*
* Check for page in userfault range
*/
if (userfaultfd_missing(vma)) {
u32 hash;
struct vm_fault vmf = {
.vma = vma,
.address = address,
.flags = flags,
/*
* Hard to debug if it ends up being
* used by a callee that assumes
* something about the other
* uninitialized fields... same as in
* memory.c
*/
};
/*
* hugetlb_fault_mutex must be dropped before
* handling userfault. Reacquire after handling
* fault to make calling code simpler.
*/
hash = hugetlb_fault_mutex_hash(h, mm, vma, mapping,
idx, address);
mutex_unlock(&hugetlb_fault_mutex_table[hash]);
ret = handle_userfault(&vmf, VM_UFFD_MISSING);
mutex_lock(&hugetlb_fault_mutex_table[hash]);
goto out;
}
page = alloc_huge_page(vma, address, 0);
if (IS_ERR(page)) {
ret = PTR_ERR(page);
if (ret == -ENOMEM)
ret = VM_FAULT_OOM;
else
ret = VM_FAULT_SIGBUS;
goto out;
}
clear_huge_page(page, address, pages_per_huge_page(h));
__SetPageUptodate(page);
set_page_huge_active(page);
if (vma->vm_flags & VM_MAYSHARE) {
int err = huge_add_to_page_cache(page, mapping, idx);
if (err) {
put_page(page);
if (err == -EEXIST)
goto retry;
goto out;
}
} else {
lock_page(page);
if (unlikely(anon_vma_prepare(vma))) {
ret = VM_FAULT_OOM;
goto backout_unlocked;
}
anon_rmap = 1;
}
} else {
/*
* If memory error occurs between mmap() and fault, some process
* don't have hwpoisoned swap entry for errored virtual address.
* So we need to block hugepage fault by PG_hwpoison bit check.
*/
if (unlikely(PageHWPoison(page))) {
ret = VM_FAULT_HWPOISON |
VM_FAULT_SET_HINDEX(hstate_index(h));
goto backout_unlocked;
}
}
/*
* If we are going to COW a private mapping later, we examine the
* pending reservations for this page now. This will ensure that
* any allocations necessary to record that reservation occur outside
* the spinlock.
*/
if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
if (vma_needs_reservation(h, vma, address) < 0) {
ret = VM_FAULT_OOM;
goto backout_unlocked;
}
/* Just decrements count, does not deallocate */
vma_end_reservation(h, vma, address);
}
ptl = huge_pte_lock(h, mm, ptep);
size = i_size_read(mapping->host) >> huge_page_shift(h);
if (idx >= size)
goto backout;
ret = 0;
if (!huge_pte_none(huge_ptep_get(ptep)))
goto backout;
if (anon_rmap) {
ClearPagePrivate(page);
hugepage_add_new_anon_rmap(page, vma, address);
} else
page_dup_rmap(page, true);
new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE)
&& (vma->vm_flags & VM_SHARED)));
set_huge_pte_at(mm, address, ptep, new_pte);
hugetlb_count_add(pages_per_huge_page(h), mm);
if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
/* Optimization, do the COW without a second fault */
ret = hugetlb_cow(mm, vma, address, ptep, page, ptl);
}
spin_unlock(ptl);
unlock_page(page);
out:
return ret;
backout:
spin_unlock(ptl);
backout_unlocked:
unlock_page(page);
restore_reserve_on_error(h, vma, address, page);
put_page(page);
goto out;
}
#ifdef CONFIG_SMP
u32 hugetlb_fault_mutex_hash(struct hstate *h, struct mm_struct *mm,
struct vm_area_struct *vma,
struct address_space *mapping,
pgoff_t idx, unsigned long address)
{
unsigned long key[2];
u32 hash;
if (vma->vm_flags & VM_SHARED) {
key[0] = (unsigned long) mapping;
key[1] = idx;
} else {
key[0] = (unsigned long) mm;
key[1] = address >> huge_page_shift(h);
}
hash = jhash2((u32 *)&key, sizeof(key)/sizeof(u32), 0);
return hash & (num_fault_mutexes - 1);
}
#else
/*
* For uniprocesor systems we always use a single mutex, so just
* return 0 and avoid the hashing overhead.
*/
u32 hugetlb_fault_mutex_hash(struct hstate *h, struct mm_struct *mm,
struct vm_area_struct *vma,
struct address_space *mapping,
pgoff_t idx, unsigned long address)
{
return 0;
}
#endif
int hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
unsigned long address, unsigned int flags)
{
pte_t *ptep, entry;
spinlock_t *ptl;
int ret;
u32 hash;
pgoff_t idx;
struct page *page = NULL;
struct page *pagecache_page = NULL;
struct hstate *h = hstate_vma(vma);
struct address_space *mapping;
int need_wait_lock = 0;
address &= huge_page_mask(h);
ptep = huge_pte_offset(mm, address, huge_page_size(h));
if (ptep) {
entry = huge_ptep_get(ptep);
if (unlikely(is_hugetlb_entry_migration(entry))) {
migration_entry_wait_huge(vma, mm, ptep);
return 0;
} else if (unlikely(is_hugetlb_entry_hwpoisoned(entry)))
return VM_FAULT_HWPOISON_LARGE |
VM_FAULT_SET_HINDEX(hstate_index(h));
} else {
ptep = huge_pte_alloc(mm, address, huge_page_size(h));
if (!ptep)
return VM_FAULT_OOM;
}
mapping = vma->vm_file->f_mapping;
idx = vma_hugecache_offset(h, vma, address);
/*
* Serialize hugepage allocation and instantiation, so that we don't
* get spurious allocation failures if two CPUs race to instantiate
* the same page in the page cache.
*/
hash = hugetlb_fault_mutex_hash(h, mm, vma, mapping, idx, address);
mutex_lock(&hugetlb_fault_mutex_table[hash]);
entry = huge_ptep_get(ptep);
if (huge_pte_none(entry)) {
ret = hugetlb_no_page(mm, vma, mapping, idx, address, ptep, flags);
goto out_mutex;
}
ret = 0;
/*
* entry could be a migration/hwpoison entry at this point, so this
* check prevents the kernel from going below assuming that we have
* a active hugepage in pagecache. This goto expects the 2nd page fault,
* and is_hugetlb_entry_(migration|hwpoisoned) check will properly
* handle it.
*/
if (!pte_present(entry))
goto out_mutex;
/*
* If we are going to COW the mapping later, we examine the pending
* reservations for this page now. This will ensure that any
* allocations necessary to record that reservation occur outside the
* spinlock. For private mappings, we also lookup the pagecache
* page now as it is used to determine if a reservation has been
* consumed.
*/
if ((flags & FAULT_FLAG_WRITE) && !huge_pte_write(entry)) {
if (vma_needs_reservation(h, vma, address) < 0) {
ret = VM_FAULT_OOM;
goto out_mutex;
}
/* Just decrements count, does not deallocate */
vma_end_reservation(h, vma, address);
if (!(vma->vm_flags & VM_MAYSHARE))
pagecache_page = hugetlbfs_pagecache_page(h,
vma, address);
}
ptl = huge_pte_lock(h, mm, ptep);
/* Check for a racing update before calling hugetlb_cow */
if (unlikely(!pte_same(entry, huge_ptep_get(ptep))))
goto out_ptl;
/*
* hugetlb_cow() requires page locks of pte_page(entry) and
* pagecache_page, so here we need take the former one
* when page != pagecache_page or !pagecache_page.
*/
page = pte_page(entry);
if (page != pagecache_page)
if (!trylock_page(page)) {
need_wait_lock = 1;
goto out_ptl;
}
get_page(page);
if (flags & FAULT_FLAG_WRITE) {
if (!huge_pte_write(entry)) {
ret = hugetlb_cow(mm, vma, address, ptep,
pagecache_page, ptl);
goto out_put_page;
}
entry = huge_pte_mkdirty(entry);
}
entry = pte_mkyoung(entry);
if (huge_ptep_set_access_flags(vma, address, ptep, entry,
flags & FAULT_FLAG_WRITE))
update_mmu_cache(vma, address, ptep);
out_put_page:
if (page != pagecache_page)
unlock_page(page);
put_page(page);
out_ptl:
spin_unlock(ptl);
if (pagecache_page) {
unlock_page(pagecache_page);
put_page(pagecache_page);
}
out_mutex:
mutex_unlock(&hugetlb_fault_mutex_table[hash]);
/*
* Generally it's safe to hold refcount during waiting page lock. But
* here we just wait to defer the next page fault to avoid busy loop and
* the page is not used after unlocked before returning from the current
* page fault. So we are safe from accessing freed page, even if we wait
* here without taking refcount.
*/
if (need_wait_lock)
wait_on_page_locked(page);
return ret;
}
/*
* Used by userfaultfd UFFDIO_COPY. Based on mcopy_atomic_pte with
* modifications for huge pages.
*/
int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm,
pte_t *dst_pte,
struct vm_area_struct *dst_vma,
unsigned long dst_addr,
unsigned long src_addr,
struct page **pagep)
{
struct address_space *mapping;
pgoff_t idx;
unsigned long size;
int vm_shared = dst_vma->vm_flags & VM_SHARED;
struct hstate *h = hstate_vma(dst_vma);
pte_t _dst_pte;
spinlock_t *ptl;
int ret;
struct page *page;
if (!*pagep) {
ret = -ENOMEM;
page = alloc_huge_page(dst_vma, dst_addr, 0);
if (IS_ERR(page))
goto out;
ret = copy_huge_page_from_user(page,
(const void __user *) src_addr,
pages_per_huge_page(h), false);
/* fallback to copy_from_user outside mmap_sem */
if (unlikely(ret)) {
ret = -EFAULT;
*pagep = page;
/* don't free the page */
goto out;
}
} else {
page = *pagep;
*pagep = NULL;
}
/*
* The memory barrier inside __SetPageUptodate makes sure that
* preceding stores to the page contents become visible before
* the set_pte_at() write.
*/
__SetPageUptodate(page);
set_page_huge_active(page);
mapping = dst_vma->vm_file->f_mapping;
idx = vma_hugecache_offset(h, dst_vma, dst_addr);
/*
* If shared, add to page cache
*/
if (vm_shared) {
size = i_size_read(mapping->host) >> huge_page_shift(h);
ret = -EFAULT;
if (idx >= size)
goto out_release_nounlock;
/*
* Serialization between remove_inode_hugepages() and
* huge_add_to_page_cache() below happens through the
* hugetlb_fault_mutex_table that here must be hold by
* the caller.
*/
ret = huge_add_to_page_cache(page, mapping, idx);
if (ret)
goto out_release_nounlock;
}
ptl = huge_pte_lockptr(h, dst_mm, dst_pte);
spin_lock(ptl);
/*
* Recheck the i_size after holding PT lock to make sure not
* to leave any page mapped (as page_mapped()) beyond the end
* of the i_size (remove_inode_hugepages() is strict about
* enforcing that). If we bail out here, we'll also leave a
* page in the radix tree in the vm_shared case beyond the end
* of the i_size, but remove_inode_hugepages() will take care
* of it as soon as we drop the hugetlb_fault_mutex_table.
*/
size = i_size_read(mapping->host) >> huge_page_shift(h);
ret = -EFAULT;
if (idx >= size)
goto out_release_unlock;
ret = -EEXIST;
if (!huge_pte_none(huge_ptep_get(dst_pte)))
goto out_release_unlock;
if (vm_shared) {
page_dup_rmap(page, true);
} else {
ClearPagePrivate(page);
hugepage_add_new_anon_rmap(page, dst_vma, dst_addr);
}
_dst_pte = make_huge_pte(dst_vma, page, dst_vma->vm_flags & VM_WRITE);
if (dst_vma->vm_flags & VM_WRITE)
_dst_pte = huge_pte_mkdirty(_dst_pte);
_dst_pte = pte_mkyoung(_dst_pte);
set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
(void)huge_ptep_set_access_flags(dst_vma, dst_addr, dst_pte, _dst_pte,
dst_vma->vm_flags & VM_WRITE);
hugetlb_count_add(pages_per_huge_page(h), dst_mm);
/* No need to invalidate - it was non-present before */
update_mmu_cache(dst_vma, dst_addr, dst_pte);
spin_unlock(ptl);
if (vm_shared)
unlock_page(page);
ret = 0;
out:
return ret;
out_release_unlock:
spin_unlock(ptl);
if (vm_shared)
unlock_page(page);
out_release_nounlock:
put_page(page);
goto out;
}
long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
struct page **pages, struct vm_area_struct **vmas,
unsigned long *position, unsigned long *nr_pages,
long i, unsigned int flags, int *nonblocking)
{
unsigned long pfn_offset;
unsigned long vaddr = *position;
unsigned long remainder = *nr_pages;
struct hstate *h = hstate_vma(vma);
int err = -EFAULT;
while (vaddr < vma->vm_end && remainder) {
pte_t *pte;
spinlock_t *ptl = NULL;
int absent;
struct page *page;
/*
* If we have a pending SIGKILL, don't keep faulting pages and
* potentially allocating memory.
*/
if (unlikely(fatal_signal_pending(current))) {
remainder = 0;
break;
}
/*
* Some archs (sparc64, sh*) have multiple pte_ts to
* each hugepage. We have to make sure we get the
* first, for the page indexing below to work.
*
* Note that page table lock is not held when pte is null.
*/
pte = huge_pte_offset(mm, vaddr & huge_page_mask(h),
huge_page_size(h));
if (pte)
ptl = huge_pte_lock(h, mm, pte);
absent = !pte || huge_pte_none(huge_ptep_get(pte));
/*
* When coredumping, it suits get_dump_page if we just return
* an error where there's an empty slot with no huge pagecache
* to back it. This way, we avoid allocating a hugepage, and
* the sparse dumpfile avoids allocating disk blocks, but its
* huge holes still show up with zeroes where they need to be.
*/
if (absent && (flags & FOLL_DUMP) &&
!hugetlbfs_pagecache_present(h, vma, vaddr)) {
if (pte)
spin_unlock(ptl);
remainder = 0;
break;
}
/*
* We need call hugetlb_fault for both hugepages under migration
* (in which case hugetlb_fault waits for the migration,) and
* hwpoisoned hugepages (in which case we need to prevent the
* caller from accessing to them.) In order to do this, we use
* here is_swap_pte instead of is_hugetlb_entry_migration and
* is_hugetlb_entry_hwpoisoned. This is because it simply covers
* both cases, and because we can't follow correct pages
* directly from any kind of swap entries.
*/
if (absent || is_swap_pte(huge_ptep_get(pte)) ||
((flags & FOLL_WRITE) &&
!huge_pte_write(huge_ptep_get(pte)))) {
int ret;
unsigned int fault_flags = 0;
if (pte)
spin_unlock(ptl);
if (flags & FOLL_WRITE)
fault_flags |= FAULT_FLAG_WRITE;
if (nonblocking)
fault_flags |= FAULT_FLAG_ALLOW_RETRY;
if (flags & FOLL_NOWAIT)
fault_flags |= FAULT_FLAG_ALLOW_RETRY |
FAULT_FLAG_RETRY_NOWAIT;
if (flags & FOLL_TRIED) {
VM_WARN_ON_ONCE(fault_flags &
FAULT_FLAG_ALLOW_RETRY);
fault_flags |= FAULT_FLAG_TRIED;
}
ret = hugetlb_fault(mm, vma, vaddr, fault_flags);
if (ret & VM_FAULT_ERROR) {
err = vm_fault_to_errno(ret, flags);
remainder = 0;
break;
}
if (ret & VM_FAULT_RETRY) {
if (nonblocking)
*nonblocking = 0;
*nr_pages = 0;
/*
* VM_FAULT_RETRY must not return an
* error, it will return zero
* instead.
*
* No need to update "position" as the
* caller will not check it after
* *nr_pages is set to 0.
*/
return i;
}
continue;
}
pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
page = pte_page(huge_ptep_get(pte));
same_page:
if (pages) {
pages[i] = mem_map_offset(page, pfn_offset);
get_page(pages[i]);
}
if (vmas)
vmas[i] = vma;
vaddr += PAGE_SIZE;
++pfn_offset;
--remainder;
++i;
if (vaddr < vma->vm_end && remainder &&
pfn_offset < pages_per_huge_page(h)) {
/*
* We use pfn_offset to avoid touching the pageframes
* of this compound page.
*/
goto same_page;
}
spin_unlock(ptl);
}
*nr_pages = remainder;
/*
* setting position is actually required only if remainder is
* not zero but it's faster not to add a "if (remainder)"
* branch.
*/
*position = vaddr;
return i ? i : err;
}
#ifndef __HAVE_ARCH_FLUSH_HUGETLB_TLB_RANGE
/*
* ARCHes with special requirements for evicting HUGETLB backing TLB entries can
* implement this.
*/
#define flush_hugetlb_tlb_range(vma, addr, end) flush_tlb_range(vma, addr, end)
#endif
unsigned long hugetlb_change_protection(struct vm_area_struct *vma,
unsigned long address, unsigned long end, pgprot_t newprot)
{
struct mm_struct *mm = vma->vm_mm;
unsigned long start = address;
pte_t *ptep;
pte_t pte;
struct hstate *h = hstate_vma(vma);
unsigned long pages = 0;
BUG_ON(address >= end);
flush_cache_range(vma, address, end);
mmu_notifier_invalidate_range_start(mm, start, end);
i_mmap_lock_write(vma->vm_file->f_mapping);
for (; address < end; address += huge_page_size(h)) {
spinlock_t *ptl;
ptep = huge_pte_offset(mm, address, huge_page_size(h));
if (!ptep)
continue;
ptl = huge_pte_lock(h, mm, ptep);
if (huge_pmd_unshare(mm, &address, ptep)) {
pages++;
spin_unlock(ptl);
continue;
}
pte = huge_ptep_get(ptep);
if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) {
spin_unlock(ptl);
continue;
}
if (unlikely(is_hugetlb_entry_migration(pte))) {
swp_entry_t entry = pte_to_swp_entry(pte);
if (is_write_migration_entry(entry)) {
pte_t newpte;
make_migration_entry_read(&entry);
newpte = swp_entry_to_pte(entry);
set_huge_swap_pte_at(mm, address, ptep,
newpte, huge_page_size(h));
pages++;
}
spin_unlock(ptl);
continue;
}
if (!huge_pte_none(pte)) {
pte = huge_ptep_get_and_clear(mm, address, ptep);
pte = pte_mkhuge(huge_pte_modify(pte, newprot));
pte = arch_make_huge_pte(pte, vma, NULL, 0);
set_huge_pte_at(mm, address, ptep, pte);
pages++;
}
spin_unlock(ptl);
}
/*
* Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare
* may have cleared our pud entry and done put_page on the page table:
* once we release i_mmap_rwsem, another task can do the final put_page
* and that page table be reused and filled with junk.
*/
flush_hugetlb_tlb_range(vma, start, end);
mmu_notifier_invalidate_range(mm, start, end);
i_mmap_unlock_write(vma->vm_file->f_mapping);
mmu_notifier_invalidate_range_end(mm, start, end);
return pages << h->order;
}
int hugetlb_reserve_pages(struct inode *inode,
long from, long to,
struct vm_area_struct *vma,
vm_flags_t vm_flags)
{
long ret, chg;
struct hstate *h = hstate_inode(inode);
struct hugepage_subpool *spool = subpool_inode(inode);
struct resv_map *resv_map;
long gbl_reserve;
/*
* Only apply hugepage reservation if asked. At fault time, an
* attempt will be made for VM_NORESERVE to allocate a page
* without using reserves
*/
if (vm_flags & VM_NORESERVE)
return 0;
/*
* Shared mappings base their reservation on the number of pages that
* are already allocated on behalf of the file. Private mappings need
* to reserve the full area even if read-only as mprotect() may be
* called to make the mapping read-write. Assume !vma is a shm mapping
*/
if (!vma || vma->vm_flags & VM_MAYSHARE) {
resv_map = inode_resv_map(inode);
chg = region_chg(resv_map, from, to);
} else {
resv_map = resv_map_alloc();
if (!resv_map)
return -ENOMEM;
chg = to - from;
set_vma_resv_map(vma, resv_map);
set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
}
if (chg < 0) {
ret = chg;
goto out_err;
}
/*
* There must be enough pages in the subpool for the mapping. If
* the subpool has a minimum size, there may be some global
* reservations already in place (gbl_reserve).
*/
gbl_reserve = hugepage_subpool_get_pages(spool, chg);
if (gbl_reserve < 0) {
ret = -ENOSPC;
goto out_err;
}
/*
* Check enough hugepages are available for the reservation.
* Hand the pages back to the subpool if there are not
*/
ret = hugetlb_acct_memory(h, gbl_reserve);
if (ret < 0) {
/* put back original number of pages, chg */
(void)hugepage_subpool_put_pages(spool, chg);
goto out_err;
}
/*
* Account for the reservations made. Shared mappings record regions
* that have reservations as they are shared by multiple VMAs.
* When the last VMA disappears, the region map says how much
* the reservation was and the page cache tells how much of
* the reservation was consumed. Private mappings are per-VMA and
* only the consumed reservations are tracked. When the VMA
* disappears, the original reservation is the VMA size and the
* consumed reservations are stored in the map. Hence, nothing
* else has to be done for private mappings here
*/
if (!vma || vma->vm_flags & VM_MAYSHARE) {
long add = region_add(resv_map, from, to);
if (unlikely(chg > add)) {
/*
* pages in this range were added to the reserve
* map between region_chg and region_add. This
* indicates a race with alloc_huge_page. Adjust
* the subpool and reserve counts modified above
* based on the difference.
*/
long rsv_adjust;
rsv_adjust = hugepage_subpool_put_pages(spool,
chg - add);
hugetlb_acct_memory(h, -rsv_adjust);
}
}
return 0;
out_err:
if (!vma || vma->vm_flags & VM_MAYSHARE)
/* Don't call region_abort if region_chg failed */
if (chg >= 0)
region_abort(resv_map, from, to);
if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
kref_put(&resv_map->refs, resv_map_release);
return ret;
}
long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
long freed)
{
struct hstate *h = hstate_inode(inode);
struct resv_map *resv_map = inode_resv_map(inode);
long chg = 0;
struct hugepage_subpool *spool = subpool_inode(inode);
long gbl_reserve;
if (resv_map) {
chg = region_del(resv_map, start, end);
/*
* region_del() can fail in the rare case where a region
* must be split and another region descriptor can not be
* allocated. If end == LONG_MAX, it will not fail.
*/
if (chg < 0)
return chg;
}
spin_lock(&inode->i_lock);
inode->i_blocks -= (blocks_per_huge_page(h) * freed);
spin_unlock(&inode->i_lock);
/*
* If the subpool has a minimum size, the number of global
* reservations to be released may be adjusted.
*/
gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
hugetlb_acct_memory(h, -gbl_reserve);
return 0;
}
#ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
static unsigned long page_table_shareable(struct vm_area_struct *svma,
struct vm_area_struct *vma,
unsigned long addr, pgoff_t idx)
{
unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
svma->vm_start;
unsigned long sbase = saddr & PUD_MASK;
unsigned long s_end = sbase + PUD_SIZE;
/* Allow segments to share if only one is marked locked */
unsigned long vm_flags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
unsigned long svm_flags = svma->vm_flags & VM_LOCKED_CLEAR_MASK;
/*
* match the virtual addresses, permission and the alignment of the
* page table page.
*/
if (pmd_index(addr) != pmd_index(saddr) ||
vm_flags != svm_flags ||
sbase < svma->vm_start || svma->vm_end < s_end)
return 0;
return saddr;
}
static bool vma_shareable(struct vm_area_struct *vma, unsigned long addr)
{
unsigned long base = addr & PUD_MASK;
unsigned long end = base + PUD_SIZE;
/*
* check on proper vm_flags and page table alignment
*/
if (vma->vm_flags & VM_MAYSHARE &&
vma->vm_start <= base && end <= vma->vm_end)
return true;
return false;
}
/*
* Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
* and returns the corresponding pte. While this is not necessary for the
* !shared pmd case because we can allocate the pmd later as well, it makes the
* code much cleaner. pmd allocation is essential for the shared case because
* pud has to be populated inside the same i_mmap_rwsem section - otherwise
* racing tasks could either miss the sharing (see huge_pte_offset) or select a
* bad pmd for sharing.
*/
pte_t *huge_pmd_share(struct mm_struct *mm, unsigned long addr, pud_t *pud)
{
struct vm_area_struct *vma = find_vma(mm, addr);
struct address_space *mapping = vma->vm_file->f_mapping;
pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
vma->vm_pgoff;
struct vm_area_struct *svma;
unsigned long saddr;
pte_t *spte = NULL;
pte_t *pte;
spinlock_t *ptl;
if (!vma_shareable(vma, addr))
return (pte_t *)pmd_alloc(mm, pud, addr);
i_mmap_lock_write(mapping);
vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
if (svma == vma)
continue;
saddr = page_table_shareable(svma, vma, addr, idx);
if (saddr) {
spte = huge_pte_offset(svma->vm_mm, saddr,
vma_mmu_pagesize(svma));
if (spte) {
get_page(virt_to_page(spte));
break;
}
}
}
if (!spte)
goto out;
ptl = huge_pte_lock(hstate_vma(vma), mm, spte);
if (pud_none(*pud)) {
pud_populate(mm, pud,
(pmd_t *)((unsigned long)spte & PAGE_MASK));
mm_inc_nr_pmds(mm);
} else {
put_page(virt_to_page(spte));
}
spin_unlock(ptl);
out:
pte = (pte_t *)pmd_alloc(mm, pud, addr);
i_mmap_unlock_write(mapping);
return pte;
}
/*
* unmap huge page backed by shared pte.
*
* Hugetlb pte page is ref counted at the time of mapping. If pte is shared
* indicated by page_count > 1, unmap is achieved by clearing pud and
* decrementing the ref count. If count == 1, the pte page is not shared.
*
* called with page table lock held.
*
* returns: 1 successfully unmapped a shared pte page
* 0 the underlying pte page is not shared, or it is the last user
*/
int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep)
{
pgd_t *pgd = pgd_offset(mm, *addr);
p4d_t *p4d = p4d_offset(pgd, *addr);
pud_t *pud = pud_offset(p4d, *addr);
BUG_ON(page_count(virt_to_page(ptep)) == 0);
if (page_count(virt_to_page(ptep)) == 1)
return 0;
pud_clear(pud);
put_page(virt_to_page(ptep));
mm_dec_nr_pmds(mm);
*addr = ALIGN(*addr, HPAGE_SIZE * PTRS_PER_PTE) - HPAGE_SIZE;
return 1;
}
#define want_pmd_share() (1)
#else /* !CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
pte_t *huge_pmd_share(struct mm_struct *mm, unsigned long addr, pud_t *pud)
{
return NULL;
}
int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep)
{
return 0;
}
#define want_pmd_share() (0)
#endif /* CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
#ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
pte_t *huge_pte_alloc(struct mm_struct *mm,
unsigned long addr, unsigned long sz)
{
pgd_t *pgd;
p4d_t *p4d;
pud_t *pud;
pte_t *pte = NULL;
pgd = pgd_offset(mm, addr);
p4d = p4d_offset(pgd, addr);
pud = pud_alloc(mm, p4d, addr);
if (pud) {
if (sz == PUD_SIZE) {
pte = (pte_t *)pud;
} else {
BUG_ON(sz != PMD_SIZE);
if (want_pmd_share() && pud_none(*pud))
pte = huge_pmd_share(mm, addr, pud);
else
pte = (pte_t *)pmd_alloc(mm, pud, addr);
}
}
BUG_ON(pte && pte_present(*pte) && !pte_huge(*pte));
return pte;
}
/*
* huge_pte_offset() - Walk the page table to resolve the hugepage
* entry at address @addr
*
* Return: Pointer to page table or swap entry (PUD or PMD) for
* address @addr, or NULL if a p*d_none() entry is encountered and the
* size @sz doesn't match the hugepage size at this level of the page
* table.
*/
pte_t *huge_pte_offset(struct mm_struct *mm,
unsigned long addr, unsigned long sz)
{
pgd_t *pgd;
p4d_t *p4d;
pud_t *pud;
pmd_t *pmd;
pgd = pgd_offset(mm, addr);
if (!pgd_present(*pgd))
return NULL;
p4d = p4d_offset(pgd, addr);
if (!p4d_present(*p4d))
return NULL;
pud = pud_offset(p4d, addr);
if (sz != PUD_SIZE && pud_none(*pud))
return NULL;
/* hugepage or swap? */
if (pud_huge(*pud) || !pud_present(*pud))
return (pte_t *)pud;
pmd = pmd_offset(pud, addr);
if (sz != PMD_SIZE && pmd_none(*pmd))
return NULL;
/* hugepage or swap? */
if (pmd_huge(*pmd) || !pmd_present(*pmd))
return (pte_t *)pmd;
return NULL;
}
#endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
/*
* These functions are overwritable if your architecture needs its own
* behavior.
*/
struct page * __weak
follow_huge_addr(struct mm_struct *mm, unsigned long address,
int write)
{
return ERR_PTR(-EINVAL);
}
struct page * __weak
follow_huge_pd(struct vm_area_struct *vma,
unsigned long address, hugepd_t hpd, int flags, int pdshift)
{
WARN(1, "hugepd follow called with no support for hugepage directory format\n");
return NULL;
}
struct page * __weak
follow_huge_pmd(struct mm_struct *mm, unsigned long address,
pmd_t *pmd, int flags)
{
struct page *page = NULL;
spinlock_t *ptl;
pte_t pte;
retry:
ptl = pmd_lockptr(mm, pmd);
spin_lock(ptl);
/*
* make sure that the address range covered by this pmd is not
* unmapped from other threads.
*/
if (!pmd_huge(*pmd))
goto out;
pte = huge_ptep_get((pte_t *)pmd);
if (pte_present(pte)) {
page = pmd_page(*pmd) + ((address & ~PMD_MASK) >> PAGE_SHIFT);
if (flags & FOLL_GET)
get_page(page);
} else {
if (is_hugetlb_entry_migration(pte)) {
spin_unlock(ptl);
__migration_entry_wait(mm, (pte_t *)pmd, ptl);
goto retry;
}
/*
* hwpoisoned entry is treated as no_page_table in
* follow_page_mask().
*/
}
out:
spin_unlock(ptl);
return page;
}
struct page * __weak
follow_huge_pud(struct mm_struct *mm, unsigned long address,
pud_t *pud, int flags)
{
if (flags & FOLL_GET)
return NULL;
return pte_page(*(pte_t *)pud) + ((address & ~PUD_MASK) >> PAGE_SHIFT);
}
struct page * __weak
follow_huge_pgd(struct mm_struct *mm, unsigned long address, pgd_t *pgd, int flags)
{
if (flags & FOLL_GET)
return NULL;
return pte_page(*(pte_t *)pgd) + ((address & ~PGDIR_MASK) >> PAGE_SHIFT);
}
bool isolate_huge_page(struct page *page, struct list_head *list)
{
bool ret = true;
VM_BUG_ON_PAGE(!PageHead(page), page);
spin_lock(&hugetlb_lock);
if (!page_huge_active(page) || !get_page_unless_zero(page)) {
ret = false;
goto unlock;
}
clear_page_huge_active(page);
list_move_tail(&page->lru, list);
unlock:
spin_unlock(&hugetlb_lock);
return ret;
}
void putback_active_hugepage(struct page *page)
{
VM_BUG_ON_PAGE(!PageHead(page), page);
spin_lock(&hugetlb_lock);
set_page_huge_active(page);
list_move_tail(&page->lru, &(page_hstate(page))->hugepage_activelist);
spin_unlock(&hugetlb_lock);
put_page(page);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2842_0 |
crossvul-cpp_data_bad_339_2 | /*
* card-muscle.c: Support for MuscleCard Applet from musclecard.com
*
* Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include "internal.h"
#include "cardctl.h"
#include "muscle.h"
#include "muscle-filesystem.h"
#include "types.h"
#include "opensc.h"
static struct sc_card_operations muscle_ops;
static const struct sc_card_operations *iso_ops = NULL;
static struct sc_card_driver muscle_drv = {
"MuscleApplet",
"muscle",
&muscle_ops,
NULL, 0, NULL
};
static struct sc_atr_table muscle_atrs[] = {
/* Tyfone JCOP 242R2 cards */
{ "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL },
/* Aladdin eToken PRO USB 72K Java */
{ "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL },
/* JCOP31 v2.4.1 contact interface */
{ "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL },
/* JCOP31 v2.4.1 RF interface */
{ "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
#define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data )
#define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs )
typedef struct muscle_private {
sc_security_env_t env;
unsigned short verifiedPins;
mscfs_t *fs;
int rsa_key_ref;
} muscle_private_t;
static int muscle_finish(sc_card_t *card)
{
muscle_private_t *priv = MUSCLE_DATA(card);
mscfs_free(priv->fs);
free(priv);
return 0;
}
static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 };
static int muscle_match_card(sc_card_t *card)
{
sc_apdu_t apdu;
u8 response[64];
int r;
/* Since we send an APDU, the card's logout function may be called...
* however it's not always properly nulled out... */
card->ops->logout = NULL;
if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) {
/* Muscle applet is present, check the protocol version to be sure */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00);
apdu.cla = 0xB0;
apdu.le = 64;
apdu.resplen = 64;
apdu.resp = response;
r = sc_transmit_apdu(card, &apdu);
if (r == SC_SUCCESS && response[0] == 0x01) {
card->type = SC_CARD_TYPE_MUSCLE_V1;
} else {
card->type = SC_CARD_TYPE_MUSCLE_GENERIC;
}
return 1;
}
return 0;
}
/* Since Musclecard has a different ACL system then PKCS15
* objects need to have their READ/UPDATE/DELETE permissions mapped for files
* and directory ACLS need to be set
* For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here
*/
static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl)
{
unsigned short acl_entry = 0;
while(acl) {
int key = acl->key_ref;
int method = acl->method;
switch(method) {
case SC_AC_NEVER:
return 0xFFFF;
/* Ignore... other items overwrite these */
case SC_AC_NONE:
case SC_AC_UNKNOWN:
break;
case SC_AC_CHV:
acl_entry |= (1 << key); /* Assuming key 0 == SO */
break;
case SC_AC_AUT:
case SC_AC_TERM:
case SC_AC_PRO:
default:
/* Ignored */
break;
}
acl = acl->next;
}
return acl_entry;
}
static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm)
{
assert(read_perm && write_perm && delete_perm);
*read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ));
*write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE));
*delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE));
}
static int muscle_create_directory(sc_card_t *card, sc_file_t *file)
{
mscfs_t *fs = MUSCLE_FS(card);
msc_id objectId;
u8* oid = objectId.id;
unsigned id = file->id;
unsigned short read_perm = 0, write_perm = 0, delete_perm = 0;
int objectSize;
int r;
if(id == 0) /* No null name files */
return SC_ERROR_INVALID_ARGUMENTS;
/* No nesting directories */
if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00)
return SC_ERROR_NOT_SUPPORTED;
oid[0] = ((id & 0xFF00) >> 8) & 0xFF;
oid[1] = id & 0xFF;
oid[2] = oid[3] = 0;
objectSize = file->size;
muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm);
r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm);
mscfs_clear_cache(fs);
if(r >= 0) return 0;
return r;
}
static int muscle_create_file(sc_card_t *card, sc_file_t *file)
{
mscfs_t *fs = MUSCLE_FS(card);
int objectSize = file->size;
unsigned short read_perm = 0, write_perm = 0, delete_perm = 0;
msc_id objectId;
int r;
if(file->type == SC_FILE_TYPE_DF)
return muscle_create_directory(card, file);
if(file->type != SC_FILE_TYPE_WORKING_EF)
return SC_ERROR_NOT_SUPPORTED;
if(file->id == 0) /* No null name files */
return SC_ERROR_INVALID_ARGUMENTS;
muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm);
mscfs_lookup_local(fs, file->id, &objectId);
r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm);
mscfs_clear_cache(fs);
if(r >= 0) return 0;
return r;
}
static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags)
{
mscfs_t *fs = MUSCLE_FS(card);
int r;
msc_id objectId;
u8* oid = objectId.id;
mscfs_file_t *file;
r = mscfs_check_selection(fs, -1);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
file = &fs->cache.array[fs->currentFileIndex];
objectId = file->objectId;
/* memcpy(objectId.id, file->objectId.id, 4); */
if(!file->ef) {
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
}
r = msc_read_object(card, objectId, idx, buf, count);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags)
{
mscfs_t *fs = MUSCLE_FS(card);
int r;
mscfs_file_t *file;
msc_id objectId;
u8* oid = objectId.id;
r = mscfs_check_selection(fs, -1);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
file = &fs->cache.array[fs->currentFileIndex];
objectId = file->objectId;
/* memcpy(objectId.id, file->objectId.id, 4); */
if(!file->ef) {
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
}
if(file->size < idx + count) {
int newFileSize = idx + count;
u8* buffer = malloc(newFileSize);
if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
r = msc_read_object(card, objectId, 0, buffer, file->size);
/* TODO: RETRIEVE ACLS */
if(r < 0) goto update_bin_free_buffer;
r = msc_delete_object(card, objectId, 0);
if(r < 0) goto update_bin_free_buffer;
r = msc_create_object(card, objectId, newFileSize, 0,0,0);
if(r < 0) goto update_bin_free_buffer;
memcpy(buffer + idx, buf, count);
r = msc_update_object(card, objectId, 0, buffer, newFileSize);
if(r < 0) goto update_bin_free_buffer;
file->size = newFileSize;
update_bin_free_buffer:
free(buffer);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
} else {
r = msc_update_object(card, objectId, idx, buf, count);
}
/* mscfs_clear_cache(fs); */
return r;
}
/* TODO: Evaluate correctness */
static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data)
{
mscfs_t *fs = MUSCLE_FS(card);
msc_id id = file_data->objectId;
u8* oid = id.id;
int r;
if(!file_data->ef) {
int x;
mscfs_file_t *childFile;
/* Delete children */
mscfs_check_cache(fs);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"DELETING Children of: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
for(x = 0; x < fs->cache.size; x++) {
msc_id objectId;
childFile = &fs->cache.array[x];
objectId = childFile->objectId;
if(0 == memcmp(oid + 2, objectId.id, 2)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"DELETING: %02X%02X%02X%02X\n",
objectId.id[0],objectId.id[1],
objectId.id[2],objectId.id[3]);
r = muscle_delete_mscfs_file(card, childFile);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
}
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
/* ??? objectId = objectId >> 16; */
}
if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4))
|| (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) {
}
r = msc_delete_object(card, id, 1);
/* Check if its the root... this file generally is virtual
* So don't return an error if it fails */
if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4))
|| (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4)))
return 0;
if(r < 0) {
printf("ID: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
return 0;
}
static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in)
{
mscfs_t *fs = MUSCLE_FS(card);
mscfs_file_t *file_data = NULL;
int r = 0;
r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
r = muscle_delete_mscfs_file(card, file_data);
mscfs_clear_cache(fs);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
return 0;
}
static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl)
{
int key;
/* Everybody by default.... */
sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0);
if(acl == 0xFFFF) {
sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0);
return;
}
for(key = 0; key < 16; key++) {
if(acl >> key & 1) {
sc_file_add_acl_entry(file, operation, SC_AC_CHV, key);
}
}
}
static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data)
{
muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read);
muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write);
muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write);
muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete);
}
static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data)
{
muscle_load_single_acl(file, SC_AC_OP_SELECT, 0);
muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0);
muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF);
muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete);
muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write);
}
/* Required type = -1 for don't care, 1 for EF, 0 for DF */
static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType)
{
mscfs_t *fs = MUSCLE_FS(card);
mscfs_file_t *file_data = NULL;
int pathlen = path_in->len;
int r = 0;
int objectIndex;
u8* oid;
mscfs_check_cache(fs);
r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
/* Check if its the right type */
if(requiredType >= 0 && requiredType != file_data->ef) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
oid = file_data->objectId.id;
/* Is it a file or directory */
if(file_data->ef) {
fs->currentPath[0] = oid[0];
fs->currentPath[1] = oid[1];
fs->currentFile[0] = oid[2];
fs->currentFile[1] = oid[3];
} else {
fs->currentPath[0] = oid[pathlen - 2];
fs->currentPath[1] = oid[pathlen - 1];
fs->currentFile[0] = 0;
fs->currentFile[1] = 0;
}
fs->currentFileIndex = objectIndex;
if(file_out) {
sc_file_t *file;
file = sc_file_new();
file->path = *path_in;
file->size = file_data->size;
file->id = (oid[2] << 8) | oid[3];
if(!file_data->ef) {
file->type = SC_FILE_TYPE_DF;
} else {
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
}
/* Setup ACLS */
if(file_data->ef) {
muscle_load_file_acls(file, file_data);
} else {
muscle_load_dir_acls(file, file_data);
/* Setup directory acls... */
}
file->magic = SC_FILE_MAGIC;
*file_out = file;
}
return 0;
}
static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in,
sc_file_t **file_out)
{
int r;
assert(card != NULL && path_in != NULL);
switch (path_in->type) {
case SC_PATH_TYPE_FILE_ID:
r = select_item(card, path_in, file_out, 1);
break;
case SC_PATH_TYPE_DF_NAME:
r = select_item(card, path_in, file_out, 0);
break;
case SC_PATH_TYPE_PATH:
r = select_item(card, path_in, file_out, -1);
break;
default:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if(r > 0) r = 0;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
static int _listFile(mscfs_file_t *file, int reset, void *udata)
{
int next = reset ? 0x00 : 0x01;
return msc_list_objects( (sc_card_t*)udata, next, file);
}
static int muscle_init(sc_card_t *card)
{
muscle_private_t *priv;
card->name = "MuscleApplet";
card->drv_data = malloc(sizeof(muscle_private_t));
if(!card->drv_data) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
memset(card->drv_data, 0, sizeof(muscle_private_t));
priv = MUSCLE_DATA(card);
priv->verifiedPins = 0;
priv->fs = mscfs_new();
if(!priv->fs) {
free(card->drv_data);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
priv->fs->udata = card;
priv->fs->listFile = _listFile;
card->cla = 0xB0;
card->flags |= SC_CARD_FLAG_RNG;
card->caps |= SC_CARD_CAP_RNG;
/* Card type detection */
_sc_match_atr(card, muscle_atrs, &card->type);
if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) {
card->caps |= SC_CARD_CAP_APDU_EXT;
}
if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) {
card->caps |= SC_CARD_CAP_APDU_EXT;
}
if (!(card->caps & SC_CARD_CAP_APDU_EXT)) {
card->max_recv_size = 255;
card->max_send_size = 255;
}
if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) {
/* Tyfone JCOP v242R2 card that doesn't support extended APDUs */
}
/* FIXME: Card type detection */
if (1) {
unsigned long flags;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
flags |= SC_ALGORITHM_ONBOARD_KEY_GEN;
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return SC_SUCCESS;
}
static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid= fs->cache.array[x].objectId.id;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count+=2;
}
}
return count;
}
static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd,
int *tries_left)
{
muscle_private_t* priv = MUSCLE_DATA(card);
const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH;
u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH];
switch(cmd->cmd) {
case SC_PIN_CMD_VERIFY:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
int r;
msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len);
cmd->apdu = &apdu;
cmd->pin1.offset = 5;
r = iso_ops->pin_cmd(card, cmd, tries_left);
if(r >= 0)
priv->verifiedPins |= (1 << cmd->pin_reference);
return r;
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
case SC_PIN_CMD_CHANGE:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len);
cmd->apdu = &apdu;
return iso_ops->pin_cmd(card, cmd, tries_left);
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
case SC_PIN_CMD_UNBLOCK:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len);
cmd->apdu = &apdu;
return iso_ops->pin_cmd(card, cmd, tries_left);
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n");
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info)
{
/* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */
switch(info->keyType) {
case 1: /* RSA */
return msc_extract_rsa_public_key(card,
info->keyLocation,
&info->modLength,
&info->modValue,
&info->expLength,
&info->expValue);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info)
{
/* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */
switch(info->keyType) {
case 0x02: /* RSA_PRIVATE */
case 0x03: /* RSA_PRIVATE_CRT */
return msc_import_key(card,
info->keyLocation,
info);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info)
{
return msc_generate_keypair(card,
info->privateKeyLocation,
info->publicKeyLocation,
info->keyType,
info->keySize,
0);
}
static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info)
{
muscle_private_t* priv = MUSCLE_DATA(card);
info->verifiedPins = priv->verifiedPins;
return 0;
}
static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data)
{
switch(request) {
case SC_CARDCTL_MUSCLE_GENERATE_KEY:
return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data);
case SC_CARDCTL_MUSCLE_EXTRACT_KEY:
return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data);
case SC_CARDCTL_MUSCLE_IMPORT_KEY:
return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data);
case SC_CARDCTL_MUSCLE_VERIFIED_PINS:
return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data);
default:
return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */
}
}
static int muscle_set_security_env(sc_card_t *card,
const sc_security_env_t *env,
int se_num)
{
muscle_private_t* priv = MUSCLE_DATA(card);
if (env->operation != SC_SEC_OPERATION_SIGN &&
env->operation != SC_SEC_OPERATION_DECIPHER) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (env->algorithm != SC_ALGORITHM_RSA) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* ADJUST FOR PKCS1 padding support for decryption only */
if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) ||
(env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
if (env->key_ref_len != 1 ||
(env->key_ref[0] > 0x0F)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
priv->rsa_key_ref = env->key_ref[0];
}
if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT)
if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n");
return SC_ERROR_NOT_SUPPORTED;
} */
priv->env = *env;
return 0;
}
static int muscle_restore_security_env(sc_card_t *card, int se_num)
{
muscle_private_t* priv = MUSCLE_DATA(card);
memset(&priv->env, 0, sizeof(priv->env));
return 0;
}
static int muscle_decipher(sc_card_t * card,
const u8 * crgram, size_t crgram_len, u8 * out,
size_t out_len)
{
muscle_private_t* priv = MUSCLE_DATA(card);
u8 key_id;
int r;
/* sanity check */
if (priv->env.operation != SC_SEC_OPERATION_DECIPHER)
return SC_ERROR_INVALID_ARGUMENTS;
key_id = priv->rsa_key_ref * 2; /* Private key */
if (out_len < crgram_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small");
return SC_ERROR_BUFFER_TOO_SMALL;
}
r = msc_compute_crypt(card,
key_id,
0x00, /* RSA NO PADDING */
0x04, /* decrypt */
crgram,
out,
crgram_len,
out_len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed");
return r;
}
static int muscle_compute_signature(sc_card_t *card, const u8 *data,
size_t data_len, u8 * out, size_t outlen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
u8 key_id;
int r;
key_id = priv->rsa_key_ref * 2; /* Private key */
if (outlen < data_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small");
return SC_ERROR_BUFFER_TOO_SMALL;
}
r = msc_compute_crypt(card,
key_id,
0x00, /* RSA NO PADDING */
0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */
data,
out,
data_len,
outlen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed");
return r;
}
static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
if (len == 0)
return SC_SUCCESS;
else {
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL,
msc_get_challenge(card, len, 0, NULL, rnd),
"GET CHALLENGE cmd failed");
return (int) len;
}
}
static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) {
if(sw1 == 0x9C) {
switch(sw2) {
case 0x01: /* SW_NO_MEMORY_LEFT */
return SC_ERROR_NOT_ENOUGH_MEMORY;
case 0x02: /* SW_AUTH_FAILED */
return SC_ERROR_PIN_CODE_INCORRECT;
case 0x03: /* SW_OPERATION_NOT_ALLOWED */
return SC_ERROR_NOT_ALLOWED;
case 0x05: /* SW_UNSUPPORTED_FEATURE */
return SC_ERROR_NO_CARD_SUPPORT;
case 0x06: /* SW_UNAUTHORIZED */
return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
case 0x07: /* SW_OBJECT_NOT_FOUND */
return SC_ERROR_FILE_NOT_FOUND;
case 0x08: /* SW_OBJECT_EXISTS */
return SC_ERROR_FILE_ALREADY_EXISTS;
case 0x09: /* SW_INCORRECT_ALG */
return SC_ERROR_INCORRECT_PARAMETERS;
case 0x0B: /* SW_SIGNATURE_INVALID */
return SC_ERROR_CARD_CMD_FAILED;
case 0x0C: /* SW_IDENTITY_BLOCKED */
return SC_ERROR_AUTH_METHOD_BLOCKED;
case 0x0F: /* SW_INVALID_PARAMETER */
case 0x10: /* SW_INCORRECT_P1 */
case 0x11: /* SW_INCORRECT_P2 */
return SC_ERROR_INCORRECT_PARAMETERS;
}
}
return iso_ops->check_sw(card, sw1, sw2);
}
static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (was_reset > 0) {
if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) {
r = SC_ERROR_INVALID_CARD;
}
}
LOG_FUNC_RETURN(card->ctx, r);
}
static struct sc_card_driver * sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
muscle_ops = *iso_drv->ops;
muscle_ops.check_sw = muscle_check_sw;
muscle_ops.pin_cmd = muscle_pin_cmd;
muscle_ops.match_card = muscle_match_card;
muscle_ops.init = muscle_init;
muscle_ops.finish = muscle_finish;
muscle_ops.get_challenge = muscle_get_challenge;
muscle_ops.set_security_env = muscle_set_security_env;
muscle_ops.restore_security_env = muscle_restore_security_env;
muscle_ops.compute_signature = muscle_compute_signature;
muscle_ops.decipher = muscle_decipher;
muscle_ops.card_ctl = muscle_card_ctl;
muscle_ops.read_binary = muscle_read_binary;
muscle_ops.update_binary = muscle_update_binary;
muscle_ops.create_file = muscle_create_file;
muscle_ops.select_file = muscle_select_file;
muscle_ops.delete_file = muscle_delete_file;
muscle_ops.list_files = muscle_list_files;
muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained;
return &muscle_drv;
}
struct sc_card_driver * sc_get_muscle_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_339_2 |
crossvul-cpp_data_bad_4270_0 | /*
** $Id: ldo.c $
** Stack and Call structure of Lua
** See Copyright Notice in lua.h
*/
#define ldo_c
#define LUA_CORE
#include "lprefix.h"
#include <setjmp.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lapi.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#include "lundump.h"
#include "lvm.h"
#include "lzio.h"
#define errorstatus(s) ((s) > LUA_YIELD)
/*
** {======================================================
** Error-recovery functions
** =======================================================
*/
/*
** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
** default, Lua handles errors with exceptions when compiling as
** C++ code, with _longjmp/_setjmp when asked to use them, and with
** longjmp/setjmp otherwise.
*/
#if !defined(LUAI_THROW) /* { */
#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */
/* C++ exceptions */
#define LUAI_THROW(L,c) throw(c)
#define LUAI_TRY(L,c,a) \
try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
#define luai_jmpbuf int /* dummy variable */
#elif defined(LUA_USE_POSIX) /* }{ */
/* in POSIX, try _longjmp/_setjmp (more efficient) */
#define LUAI_THROW(L,c) _longjmp((c)->b, 1)
#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }
#define luai_jmpbuf jmp_buf
#else /* }{ */
/* ISO C handling with long jumps */
#define LUAI_THROW(L,c) longjmp((c)->b, 1)
#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
#define luai_jmpbuf jmp_buf
#endif /* } */
#endif /* } */
/* chain list of long jump buffers */
struct lua_longjmp {
struct lua_longjmp *previous;
luai_jmpbuf b;
volatile int status; /* error code */
};
void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {
switch (errcode) {
case LUA_ERRMEM: { /* memory error? */
setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
break;
}
case LUA_ERRERR: {
setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
break;
}
case CLOSEPROTECT: {
setnilvalue(s2v(oldtop)); /* no error message */
break;
}
default: {
setobjs2s(L, oldtop, L->top - 1); /* error message on current top */
break;
}
}
L->top = oldtop + 1;
}
l_noret luaD_throw (lua_State *L, int errcode) {
if (L->errorJmp) { /* thread has an error handler? */
L->errorJmp->status = errcode; /* set status */
LUAI_THROW(L, L->errorJmp); /* jump to it */
}
else { /* thread has no error handler */
global_State *g = G(L);
errcode = luaF_close(L, L->stack, errcode); /* close all upvalues */
L->status = cast_byte(errcode); /* mark it as dead */
if (g->mainthread->errorJmp) { /* main thread has a handler? */
setobjs2s(L, g->mainthread->top++, L->top - 1); /* copy error obj. */
luaD_throw(g->mainthread, errcode); /* re-throw in main thread */
}
else { /* no handler at all; abort */
if (g->panic) { /* panic function? */
luaD_seterrorobj(L, errcode, L->top); /* assume EXTRA_STACK */
if (L->ci->top < L->top)
L->ci->top = L->top; /* pushing msg. can break this invariant */
lua_unlock(L);
g->panic(L); /* call panic function (last chance to jump out) */
}
abort();
}
}
}
int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
global_State *g = G(L);
l_uint32 oldnCcalls = g->Cstacklimit - (L->nCcalls + L->nci);
struct lua_longjmp lj;
lj.status = LUA_OK;
lj.previous = L->errorJmp; /* chain new error handler */
L->errorJmp = &lj;
LUAI_TRY(L, &lj,
(*f)(L, ud);
);
L->errorJmp = lj.previous; /* restore old error handler */
L->nCcalls = g->Cstacklimit - oldnCcalls - L->nci;
return lj.status;
}
/* }====================================================== */
/*
** {==================================================================
** Stack reallocation
** ===================================================================
*/
static void correctstack (lua_State *L, StkId oldstack, StkId newstack) {
CallInfo *ci;
UpVal *up;
if (oldstack == newstack)
return; /* stack address did not change */
L->top = (L->top - oldstack) + newstack;
for (up = L->openupval; up != NULL; up = up->u.open.next)
up->v = s2v((uplevel(up) - oldstack) + newstack);
for (ci = L->ci; ci != NULL; ci = ci->previous) {
ci->top = (ci->top - oldstack) + newstack;
ci->func = (ci->func - oldstack) + newstack;
if (isLua(ci))
ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */
}
}
/* some space for error handling */
#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)
int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
int lim = L->stacksize;
StkId newstack = luaM_reallocvector(L, L->stack, lim, newsize, StackValue);
lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK);
if (unlikely(newstack == NULL)) { /* reallocation failed? */
if (raiseerror)
luaM_error(L);
else return 0; /* do not raise an error */
}
for (; lim < newsize; lim++)
setnilvalue(s2v(newstack + lim)); /* erase new segment */
correctstack(L, L->stack, newstack);
L->stack = newstack;
L->stacksize = newsize;
L->stack_last = L->stack + newsize - EXTRA_STACK;
return 1;
}
/*
** Try to grow the stack by at least 'n' elements. when 'raiseerror'
** is true, raises any error; otherwise, return 0 in case of errors.
*/
int luaD_growstack (lua_State *L, int n, int raiseerror) {
int size = L->stacksize;
int newsize = 2 * size; /* tentative new size */
if (unlikely(size > LUAI_MAXSTACK)) { /* need more space after extra size? */
if (raiseerror)
luaD_throw(L, LUA_ERRERR); /* error inside message handler */
else return 0;
}
else {
int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;
if (newsize > LUAI_MAXSTACK) /* cannot cross the limit */
newsize = LUAI_MAXSTACK;
if (newsize < needed) /* but must respect what was asked for */
newsize = needed;
if (unlikely(newsize > LUAI_MAXSTACK)) { /* stack overflow? */
/* add extra size to be able to handle the error message */
luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
if (raiseerror)
luaG_runerror(L, "stack overflow");
else return 0;
}
} /* else no errors */
return luaD_reallocstack(L, newsize, raiseerror);
}
static int stackinuse (lua_State *L) {
CallInfo *ci;
StkId lim = L->top;
for (ci = L->ci; ci != NULL; ci = ci->previous) {
if (lim < ci->top) lim = ci->top;
}
lua_assert(lim <= L->stack_last);
return cast_int(lim - L->stack) + 1; /* part of stack in use */
}
void luaD_shrinkstack (lua_State *L) {
int inuse = stackinuse(L);
int goodsize = inuse + BASIC_STACK_SIZE;
if (goodsize > LUAI_MAXSTACK)
goodsize = LUAI_MAXSTACK; /* respect stack limit */
/* if thread is currently not handling a stack overflow and its
good size is smaller than current size, shrink its stack */
if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) && goodsize < L->stacksize)
luaD_reallocstack(L, goodsize, 0); /* ok if that fails */
else /* don't change stack */
condmovestack(L,{},{}); /* (change only for debugging) */
luaE_shrinkCI(L); /* shrink CI list */
}
void luaD_inctop (lua_State *L) {
luaD_checkstack(L, 1);
L->top++;
}
/* }================================================================== */
/*
** Call a hook for the given event. Make sure there is a hook to be
** called. (Both 'L->hook' and 'L->hookmask', which trigger this
** function, can be changed asynchronously by signals.)
*/
void luaD_hook (lua_State *L, int event, int line,
int ftransfer, int ntransfer) {
lua_Hook hook = L->hook;
if (hook && L->allowhook) { /* make sure there is a hook */
int mask = CIST_HOOKED;
CallInfo *ci = L->ci;
ptrdiff_t top = savestack(L, L->top);
ptrdiff_t ci_top = savestack(L, ci->top);
lua_Debug ar;
ar.event = event;
ar.currentline = line;
ar.i_ci = ci;
if (ntransfer != 0) {
mask |= CIST_TRAN; /* 'ci' has transfer information */
ci->u2.transferinfo.ftransfer = ftransfer;
ci->u2.transferinfo.ntransfer = ntransfer;
}
luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
if (L->top + LUA_MINSTACK > ci->top)
ci->top = L->top + LUA_MINSTACK;
L->allowhook = 0; /* cannot call hooks inside a hook */
ci->callstatus |= mask;
lua_unlock(L);
(*hook)(L, &ar);
lua_lock(L);
lua_assert(!L->allowhook);
L->allowhook = 1;
ci->top = restorestack(L, ci_top);
L->top = restorestack(L, top);
ci->callstatus &= ~mask;
}
}
/*
** Executes a call hook for Lua functions. This function is called
** whenever 'hookmask' is not zero, so it checks whether call hooks are
** active.
*/
void luaD_hookcall (lua_State *L, CallInfo *ci) {
int hook = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL : LUA_HOOKCALL;
Proto *p;
if (!(L->hookmask & LUA_MASKCALL)) /* some other hook? */
return; /* don't call hook */
p = clLvalue(s2v(ci->func))->p;
L->top = ci->top; /* prepare top */
ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
luaD_hook(L, hook, -1, 1, p->numparams);
ci->u.l.savedpc--; /* correct 'pc' */
}
static StkId rethook (lua_State *L, CallInfo *ci, StkId firstres, int nres) {
ptrdiff_t oldtop = savestack(L, L->top); /* hook may change top */
int delta = 0;
if (isLuacode(ci)) {
Proto *p = ci_func(ci)->p;
if (p->is_vararg)
delta = ci->u.l.nextraargs + p->numparams + 1;
if (L->top < ci->top)
L->top = ci->top; /* correct top to run hook */
}
if (L->hookmask & LUA_MASKRET) { /* is return hook on? */
int ftransfer;
ci->func += delta; /* if vararg, back to virtual 'func' */
ftransfer = cast(unsigned short, firstres - ci->func);
luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */
ci->func -= delta;
}
if (isLua(ci = ci->previous))
L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* update 'oldpc' */
return restorestack(L, oldtop);
}
/*
** Check whether 'func' has a '__call' metafield. If so, put it in the
** stack, below original 'func', so that 'luaD_call' can call it. Raise
** an error if there is no '__call' metafield.
*/
void luaD_tryfuncTM (lua_State *L, StkId func) {
const TValue *tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);
StkId p;
if (unlikely(ttisnil(tm)))
luaG_typeerror(L, s2v(func), "call"); /* nothing to call */
for (p = L->top; p > func; p--) /* open space for metamethod */
setobjs2s(L, p, p-1);
L->top++; /* stack space pre-allocated by the caller */
setobj2s(L, func, tm); /* metamethod is the new function to be called */
}
/*
** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.
** Handle most typical cases (zero results for commands, one result for
** expressions, multiple results for tail calls/single parameters)
** separated.
*/
static void moveresults (lua_State *L, StkId res, int nres, int wanted) {
StkId firstresult;
int i;
switch (wanted) { /* handle typical cases separately */
case 0: /* no values needed */
L->top = res;
return;
case 1: /* one value needed */
if (nres == 0) /* no results? */
setnilvalue(s2v(res)); /* adjust with nil */
else
setobjs2s(L, res, L->top - nres); /* move it to proper place */
L->top = res + 1;
return;
case LUA_MULTRET:
wanted = nres; /* we want all results */
break;
default: /* multiple results (or to-be-closed variables) */
if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */
ptrdiff_t savedres = savestack(L, res);
luaF_close(L, res, LUA_OK); /* may change the stack */
res = restorestack(L, savedres);
wanted = codeNresults(wanted); /* correct value */
if (wanted == LUA_MULTRET)
wanted = nres;
}
break;
}
firstresult = L->top - nres; /* index of first result */
/* move all results to correct place */
for (i = 0; i < nres && i < wanted; i++)
setobjs2s(L, res + i, firstresult + i);
for (; i < wanted; i++) /* complete wanted number of results */
setnilvalue(s2v(res + i));
L->top = res + wanted; /* top points after the last result */
}
/*
** Finishes a function call: calls hook if necessary, removes CallInfo,
** moves current number of results to proper place.
*/
void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
if (L->hookmask)
L->top = rethook(L, ci, L->top - nres, nres);
L->ci = ci->previous; /* back to caller */
/* move results to proper place */
moveresults(L, ci->func, nres, ci->nresults);
}
#define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L))
/*
** Prepare a function for a tail call, building its call info on top
** of the current call info. 'narg1' is the number of arguments plus 1
** (so that it includes the function itself).
*/
void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int narg1) {
Proto *p = clLvalue(s2v(func))->p;
int fsize = p->maxstacksize; /* frame size */
int nfixparams = p->numparams;
int i;
for (i = 0; i < narg1; i++) /* move down function and arguments */
setobjs2s(L, ci->func + i, func + i);
checkstackGC(L, fsize);
func = ci->func; /* moved-down function */
for (; narg1 <= nfixparams; narg1++)
setnilvalue(s2v(func + narg1)); /* complete missing arguments */
ci->top = func + 1 + fsize; /* top for new function */
lua_assert(ci->top <= L->stack_last);
ci->u.l.savedpc = p->code; /* starting point */
ci->callstatus |= CIST_TAIL;
L->top = func + narg1; /* set top */
}
/*
** Call a function (C or Lua). The function to be called is at *func.
** The arguments are on the stack, right after the function.
** When returns, all the results are on the stack, starting at the original
** function position.
*/
void luaD_call (lua_State *L, StkId func, int nresults) {
lua_CFunction f;
retry:
switch (ttypetag(s2v(func))) {
case LUA_VCCL: /* C closure */
f = clCvalue(s2v(func))->f;
goto Cfunc;
case LUA_VLCF: /* light C function */
f = fvalue(s2v(func));
Cfunc: {
int n; /* number of returns */
CallInfo *ci;
checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
L->ci = ci = next_ci(L);
ci->nresults = nresults;
ci->callstatus = CIST_C;
ci->top = L->top + LUA_MINSTACK;
ci->func = func;
lua_assert(ci->top <= L->stack_last);
if (L->hookmask & LUA_MASKCALL) {
int narg = cast_int(L->top - func) - 1;
luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
}
lua_unlock(L);
n = (*f)(L); /* do the actual call */
lua_lock(L);
api_checknelems(L, n);
luaD_poscall(L, ci, n);
break;
}
case LUA_VLCL: { /* Lua function */
CallInfo *ci;
Proto *p = clLvalue(s2v(func))->p;
int narg = cast_int(L->top - func) - 1; /* number of real arguments */
int nfixparams = p->numparams;
int fsize = p->maxstacksize; /* frame size */
checkstackGCp(L, fsize, func);
L->ci = ci = next_ci(L);
ci->nresults = nresults;
ci->u.l.savedpc = p->code; /* starting point */
ci->callstatus = 0;
ci->top = func + 1 + fsize;
ci->func = func;
L->ci = ci;
for (; narg < nfixparams; narg++)
setnilvalue(s2v(L->top++)); /* complete missing arguments */
lua_assert(ci->top <= L->stack_last);
luaV_execute(L, ci); /* run the function */
break;
}
default: { /* not a function */
checkstackGCp(L, 1, func); /* space for metamethod */
luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
goto retry; /* try again with metamethod */
}
}
}
/*
** Similar to 'luaD_call', but does not allow yields during the call.
** If there is a stack overflow, freeing all CI structures will
** force the subsequent call to invoke 'luaE_extendCI', which then
** will raise any errors.
*/
void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
incXCcalls(L);
if (getCcalls(L) <= CSTACKERR) /* possible stack overflow? */
luaE_freeCI(L);
luaD_call(L, func, nResults);
decXCcalls(L);
}
/*
** Completes the execution of an interrupted C function, calling its
** continuation function.
*/
static void finishCcall (lua_State *L, int status) {
CallInfo *ci = L->ci;
int n;
/* must have a continuation and must be able to call it */
lua_assert(ci->u.c.k != NULL && yieldable(L));
/* error status can only happen in a protected call */
lua_assert((ci->callstatus & CIST_YPCALL) || status == LUA_YIELD);
if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */
ci->callstatus &= ~CIST_YPCALL; /* continuation is also inside it */
L->errfunc = ci->u.c.old_errfunc; /* with the same error function */
}
/* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already
handled */
adjustresults(L, ci->nresults);
lua_unlock(L);
n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation function */
lua_lock(L);
api_checknelems(L, n);
luaD_poscall(L, ci, n); /* finish 'luaD_call' */
}
/*
** Executes "full continuation" (everything in the stack) of a
** previously interrupted coroutine until the stack is empty (or another
** interruption long-jumps out of the loop). If the coroutine is
** recovering from an error, 'ud' points to the error status, which must
** be passed to the first continuation function (otherwise the default
** status is LUA_YIELD).
*/
static void unroll (lua_State *L, void *ud) {
CallInfo *ci;
if (ud != NULL) /* error status? */
finishCcall(L, *(int *)ud); /* finish 'lua_pcallk' callee */
while ((ci = L->ci) != &L->base_ci) { /* something in the stack */
if (!isLua(ci)) /* C function? */
finishCcall(L, LUA_YIELD); /* complete its execution */
else { /* Lua function */
luaV_finishOp(L); /* finish interrupted instruction */
luaV_execute(L, ci); /* execute down to higher C 'boundary' */
}
}
}
/*
** Try to find a suspended protected call (a "recover point") for the
** given thread.
*/
static CallInfo *findpcall (lua_State *L) {
CallInfo *ci;
for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
if (ci->callstatus & CIST_YPCALL)
return ci;
}
return NULL; /* no pending pcall */
}
/*
** Recovers from an error in a coroutine. Finds a recover point (if
** there is one) and completes the execution of the interrupted
** 'luaD_pcall'. If there is no recover point, returns zero.
*/
static int recover (lua_State *L, int status) {
StkId oldtop;
CallInfo *ci = findpcall(L);
if (ci == NULL) return 0; /* no recovery point */
/* "finish" luaD_pcall */
oldtop = restorestack(L, ci->u2.funcidx);
luaF_close(L, oldtop, status); /* may change the stack */
oldtop = restorestack(L, ci->u2.funcidx);
luaD_seterrorobj(L, status, oldtop);
L->ci = ci;
L->allowhook = getoah(ci->callstatus); /* restore original 'allowhook' */
luaD_shrinkstack(L);
L->errfunc = ci->u.c.old_errfunc;
return 1; /* continue running the coroutine */
}
/*
** Signal an error in the call to 'lua_resume', not in the execution
** of the coroutine itself. (Such errors should not be handled by any
** coroutine error handler and should not kill the coroutine.)
*/
static int resume_error (lua_State *L, const char *msg, int narg) {
L->top -= narg; /* remove args from the stack */
setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */
api_incr_top(L);
lua_unlock(L);
return LUA_ERRRUN;
}
/*
** Do the work for 'lua_resume' in protected mode. Most of the work
** depends on the status of the coroutine: initial state, suspended
** inside a hook, or regularly suspended (optionally with a continuation
** function), plus erroneous cases: non-suspended coroutine or dead
** coroutine.
*/
static void resume (lua_State *L, void *ud) {
int n = *(cast(int*, ud)); /* number of arguments */
StkId firstArg = L->top - n; /* first argument */
CallInfo *ci = L->ci;
if (L->status == LUA_OK) { /* starting a coroutine? */
luaD_call(L, firstArg - 1, LUA_MULTRET);
}
else { /* resuming from previous yield */
lua_assert(L->status == LUA_YIELD);
L->status = LUA_OK; /* mark that it is running (again) */
if (isLua(ci)) /* yielded inside a hook? */
luaV_execute(L, ci); /* just continue running Lua code */
else { /* 'common' yield */
if (ci->u.c.k != NULL) { /* does it have a continuation function? */
lua_unlock(L);
n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
lua_lock(L);
api_checknelems(L, n);
}
luaD_poscall(L, ci, n); /* finish 'luaD_call' */
}
unroll(L, NULL); /* run continuation */
}
}
LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
int *nresults) {
int status;
lua_lock(L);
if (L->status == LUA_OK) { /* may be starting a coroutine */
if (L->ci != &L->base_ci) /* not in base level? */
return resume_error(L, "cannot resume non-suspended coroutine", nargs);
else if (L->top - (L->ci->func + 1) == nargs) /* no function? */
return resume_error(L, "cannot resume dead coroutine", nargs);
}
else if (L->status != LUA_YIELD) /* ended with errors? */
return resume_error(L, "cannot resume dead coroutine", nargs);
if (from == NULL)
L->nCcalls = CSTACKTHREAD;
else /* correct 'nCcalls' for this thread */
L->nCcalls = getCcalls(from) - L->nci - CSTACKCF;
if (L->nCcalls <= CSTACKERR)
return resume_error(L, "C stack overflow", nargs);
luai_userstateresume(L, nargs);
api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
status = luaD_rawrunprotected(L, resume, &nargs);
/* continue running after recoverable errors */
while (errorstatus(status) && recover(L, status)) {
/* unroll continuation */
status = luaD_rawrunprotected(L, unroll, &status);
}
if (likely(!errorstatus(status)))
lua_assert(status == L->status); /* normal end or yield */
else { /* unrecoverable error */
L->status = cast_byte(status); /* mark thread as 'dead' */
luaD_seterrorobj(L, status, L->top); /* push error message */
L->ci->top = L->top;
}
*nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
: cast_int(L->top - (L->ci->func + 1));
lua_unlock(L);
return status;
}
LUA_API int lua_isyieldable (lua_State *L) {
return yieldable(L);
}
LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
lua_KFunction k) {
CallInfo *ci;
luai_userstateyield(L, nresults);
lua_lock(L);
ci = L->ci;
api_checknelems(L, nresults);
if (unlikely(!yieldable(L))) {
if (L != G(L)->mainthread)
luaG_runerror(L, "attempt to yield across a C-call boundary");
else
luaG_runerror(L, "attempt to yield from outside a coroutine");
}
L->status = LUA_YIELD;
if (isLua(ci)) { /* inside a hook? */
lua_assert(!isLuacode(ci));
api_check(L, k == NULL, "hooks cannot continue after yielding");
ci->u2.nyield = 0; /* no results */
}
else {
if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
ci->u.c.ctx = ctx; /* save context */
ci->u2.nyield = nresults; /* save number of results */
luaD_throw(L, LUA_YIELD);
}
lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
lua_unlock(L);
return 0; /* return to 'luaD_hook' */
}
/*
** Call the C function 'func' in protected mode, restoring basic
** thread information ('allowhook', etc.) and in particular
** its stack level in case of errors.
*/
int luaD_pcall (lua_State *L, Pfunc func, void *u,
ptrdiff_t old_top, ptrdiff_t ef) {
int status;
CallInfo *old_ci = L->ci;
lu_byte old_allowhooks = L->allowhook;
ptrdiff_t old_errfunc = L->errfunc;
L->errfunc = ef;
status = luaD_rawrunprotected(L, func, u);
if (unlikely(status != LUA_OK)) { /* an error occurred? */
StkId oldtop = restorestack(L, old_top);
L->ci = old_ci;
L->allowhook = old_allowhooks;
status = luaF_close(L, oldtop, status);
oldtop = restorestack(L, old_top); /* previous call may change stack */
luaD_seterrorobj(L, status, oldtop);
luaD_shrinkstack(L);
}
L->errfunc = old_errfunc;
return status;
}
/*
** Execute a protected parser.
*/
struct SParser { /* data to 'f_parser' */
ZIO *z;
Mbuffer buff; /* dynamic structure used by the scanner */
Dyndata dyd; /* dynamic structures used by the parser */
const char *mode;
const char *name;
};
static void checkmode (lua_State *L, const char *mode, const char *x) {
if (mode && strchr(mode, x[0]) == NULL) {
luaO_pushfstring(L,
"attempt to load a %s chunk (mode is '%s')", x, mode);
luaD_throw(L, LUA_ERRSYNTAX);
}
}
static void f_parser (lua_State *L, void *ud) {
LClosure *cl;
struct SParser *p = cast(struct SParser *, ud);
int c = zgetc(p->z); /* read first character */
if (c == LUA_SIGNATURE[0]) {
checkmode(L, p->mode, "binary");
cl = luaU_undump(L, p->z, p->name);
}
else {
checkmode(L, p->mode, "text");
cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
}
lua_assert(cl->nupvalues == cl->p->sizeupvalues);
luaF_initupvals(L, cl);
}
int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
const char *mode) {
struct SParser p;
int status;
incnny(L); /* cannot yield during parsing */
p.z = z; p.name = name; p.mode = mode;
p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
p.dyd.label.arr = NULL; p.dyd.label.size = 0;
luaZ_initbuffer(L, &p.buff);
status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
luaZ_freebuffer(L, &p.buff);
luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
decnny(L);
return status;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4270_0 |
crossvul-cpp_data_good_4779_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M AAA PPPP %
% MM MM A A P P %
% M M M AAAAA PPPP %
% M M A A P %
% M M A A P %
% %
% %
% Read/Write Image Colormaps As An Image File. %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/histogram.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteMAPImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMAPImage() reads an image of raw RGB colormap and colormap index
% bytes and returns it. It allocates the memory necessary for the new Image
% structure and returns a pointer to the new image.
%
% The format of the ReadMAPImage method is:
%
% Image *ReadMAPImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadMAPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
depth,
packet_size,
quantum;
ssize_t
count,
y;
unsigned char
*colormap,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
image->storage_class=PseudoClass;
status=AcquireImageColormap(image,(size_t)
(image->offset != 0 ? image->offset : 256));
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read image colormap.
*/
count=ReadBlob(image,packet_size*image->colors,colormap);
if (count != (ssize_t) (packet_size*image->colors))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
p=colormap;
if (image->depth <= 8)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].red=(Quantum) quantum;
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].green=(Quantum) quantum;
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].blue=(Quantum) quantum;
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Read image pixels.
*/
packet_size=(size_t) (depth/8);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
count=ReadBlob(image,(size_t) packet_size*image->columns,pixels);
if (count != (ssize_t) (packet_size*image->columns))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p);
p++;
if (image->colors > 256)
{
index=ConstrainColormapIndex(image,((size_t) index << 8)+(*p));
p++;
}
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (y < (ssize_t) image->rows)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterMAPImage() adds attributes for the MAP image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterMAPImage method is:
%
% size_t RegisterMAPImage(void)
%
*/
ModuleExport size_t RegisterMAPImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("MAP");
entry->decoder=(DecodeImageHandler *) ReadMAPImage;
entry->encoder=(EncodeImageHandler *) WriteMAPImage;
entry->adjoin=MagickFalse;
entry->format_type=ExplicitFormatType;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Colormap intensities and indices");
entry->module=ConstantString("MAP");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterMAPImage() removes format registrations made by the
% MAP module from the list of supported formats.
%
% The format of the UnregisterMAPImage method is:
%
% UnregisterMAPImage(void)
%
*/
ModuleExport void UnregisterMAPImage(void)
{
(void) UnregisterMagickInfo("MAP");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMAPImage() writes an image to a file as red, green, and blue
% colormap bytes followed by the colormap indexes.
%
% The format of the WriteMAPImage method is:
%
% MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
%
*/
static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
depth,
packet_size;
ssize_t
y;
unsigned char
*colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Allocate colormap.
*/
if (IsPaletteImage(image,&image->exception) == MagickFalse)
(void) SetImageType(image,PaletteType);
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Write colormap to file.
*/
q=colormap;
q=colormap;
if (image->colors <= 256)
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) & 0xff);;
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff);
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
/*
Write image pixels to file.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->colors > 256)
*q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8);
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4779_1 |
crossvul-cpp_data_bad_339_3 | /*
* card-tcos.c: Support for TCOS cards
*
* Copyright (C) 2011 Peter Koch <pk@opensc-project.org>
* Copyright (C) 2002 g10 Code GmbH
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table tcos_atrs[] = {
/* Infineon SLE44 */
{ "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66S */
{ "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX320P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX322P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Philips P5CT072 */
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
/* Philips P5CT080 */
{ "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static struct sc_card_operations tcos_ops;
static struct sc_card_driver tcos_drv = {
"TCOS 3.0",
"tcos",
&tcos_ops,
NULL, 0, NULL
};
static const struct sc_card_operations *iso_ops = NULL;
typedef struct tcos_data_st {
unsigned int pad_flags;
unsigned int next_sign;
} tcos_data;
static int tcos_finish(sc_card_t *card)
{
free(card->drv_data);
return 0;
}
static int tcos_match_card(sc_card_t *card)
{
int i;
i = _sc_match_atr(card, tcos_atrs, &card->type);
if (i < 0)
return 0;
return 1;
}
static int tcos_init(sc_card_t *card)
{
unsigned long flags;
tcos_data *data = malloc(sizeof(tcos_data));
if (!data) return SC_ERROR_OUT_OF_MEMORY;
card->name = "TCOS";
card->drv_data = (void *)data;
card->cla = 0x00;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
if (card->type == SC_CARD_TYPE_TCOS_V3) {
card->caps |= SC_CARD_CAP_APDU_EXT;
_sc_card_add_rsa_alg(card, 1280, flags, 0);
_sc_card_add_rsa_alg(card, 1536, flags, 0);
_sc_card_add_rsa_alg(card, 1792, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return 0;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static int tcos_construct_fci(const sc_file_t *file,
u8 *out, size_t *outlen)
{
u8 *p = out;
u8 buf[64];
size_t n;
/* FIXME: possible buffer overflow */
*p++ = 0x6F; /* FCI */
p++;
/* File size */
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x81, buf, 2, p, 16, &p);
/* File descriptor */
n = 0;
buf[n] = file->shareable ? 0x40 : 0;
switch (file->type) {
case SC_FILE_TYPE_WORKING_EF:
break;
case SC_FILE_TYPE_DF:
buf[0] |= 0x38;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
buf[n++] |= file->ef_structure & 7;
if ( (file->ef_structure & 7) > 1) {
/* record structured file */
buf[n++] = 0x41; /* indicate 3rd byte */
buf[n++] = file->record_length;
}
sc_asn1_put_tag(0x82, buf, n, p, 8, &p);
/* File identifier */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, 16, &p);
/* Directory name */
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen) {
sc_asn1_put_tag(0x84, file->name, file->namelen,
p, 16, &p);
}
else {
/* TCOS needs one, so we use a faked one */
snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu",
(unsigned long) time (NULL));
sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p);
}
}
/* File descriptor extension */
if (file->prop_attr_len && file->prop_attr) {
n = file->prop_attr_len;
memcpy(buf, file->prop_attr, n);
}
else {
n = 0;
buf[n++] = 0x01; /* not invalidated, permanent */
if (file->type == SC_FILE_TYPE_WORKING_EF)
buf[n++] = 0x00; /* generic data file */
}
sc_asn1_put_tag(0x85, buf, n, p, 16, &p);
/* Security attributes */
if (file->sec_attr_len && file->sec_attr) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
n = file->sec_attr_len;
}
else {
/* no attributes given - fall back to default one */
memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */
memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */
memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */
memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/
n = 24;
}
sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p);
/* fixup length of FCI */
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int tcos_create_file(sc_card_t *card, sc_file_t *file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
r = tcos_construct_fci(file, sbuf, &len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.cla |= 0x80; /* this is an proprietary extension */
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static unsigned int map_operations (int commandbyte )
{
unsigned int op = (unsigned int)-1;
switch ( (commandbyte & 0xfe) ) {
case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break;
case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break;
case 0xe0: /* create */ op = SC_AC_OP_CREATE; break;
case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break;
case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break;
case 0x82: /* external auth */ op = SC_AC_OP_READ; break;
case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break;
case 0x88: /* internal auth */ op = SC_AC_OP_READ; break;
case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break;
case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break;
case 0xb0: /* read binary */ op = SC_AC_OP_READ; break;
case 0xb2: /* read record */ op = SC_AC_OP_READ; break;
case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break;
case 0xa4: /* select */ op = SC_AC_OP_SELECT; break;
case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break;
case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break;
case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break;
case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break;
case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break;
case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break;
}
return op;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static void parse_sec_attr(sc_card_t *card,
sc_file_t *file, const u8 *buf, size_t len)
{
unsigned int op;
/* list directory is not covered by ACLs - so always add an entry */
sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
/* FIXME: check for what LOCK is used */
sc_file_add_acl_entry (file, SC_AC_OP_LOCK,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
for (; len >= 6; len -= 6, buf += 6) {
/* FIXME: temporary hacks */
if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */
sc_file_add_acl_entry (file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/
sc_file_add_acl_entry (file, SC_AC_OP_READ,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/
sc_file_add_acl_entry (file, SC_AC_OP_UPDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */
sc_file_add_acl_entry (file, SC_AC_OP_WRITE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_CREATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
}
else {
/* the first byte tells use the command or the
command group. We have to mask bit 0
because this one distinguish between AND/OR
combination of PINs*/
op = map_operations (buf[0]);
if (op == (unsigned int)-1)
{
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Unknown security command byte %02x\n",
buf[0]);
continue;
}
if (!buf[1])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_CHV, buf[1]);
if (!buf[2] && !buf[3])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_TERM,
(buf[2]<<8)|buf[3]);
}
}
}
static int tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
unsigned int i;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){
int j, len=apdu.resp[i+1];
unsigned char type=apdu.resp[i], *d=apdu.resp+i+2;
switch (type) {
case 0x80:
case 0x81:
file->size=0;
for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j];
break;
case 0x82:
file->shareable = (d[0] & 0x40) ? 1 : 0;
file->ef_structure = d[0] & 7;
switch ((d[0]>>3) & 7) {
case 0: file->type = SC_FILE_TYPE_WORKING_EF; break;
case 7: file->type = SC_FILE_TYPE_DF; break;
default:
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x83:
file->id = (d[0]<<8) | d[1];
break;
case 0x84:
memcpy(file->name, d, len);
file->namelen = len;
break;
case 0x86:
sc_file_set_sec_attr(file, d, len);
break;
default:
if (len>0) sc_file_set_prop_attr(file, d, len);
}
}
file->magic = SC_FILE_MAGIC;
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1;
int r, count = 0;
assert(card != NULL);
ctx = card->ctx;
for (p1=1; p1<=2; p1++) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue;
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed");
if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL;
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n",
apdu.resplen / 2, p1 == 1 ? "DF" : "EF");
memcpy(buf, apdu.resp, apdu.resplen);
buf += apdu.resplen;
buflen -= apdu.resplen;
count += apdu.resplen;
}
return count;
}
static int tcos_delete_file(sc_card_t *card, const sc_path_t *path)
{
int r;
u8 sbuf[2];
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
sbuf[0] = path->value[0];
sbuf[1] = path->value[1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p;
int r, default_key, tcos3;
tcos_data *data;
assert(card != NULL && env != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT))
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"No Key-Reference in SecEnvironment\n");
else
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n",
env->key_ref[0], env->key_ref_len);
/* Key-Reference 0x80 ?? */
default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n", tcos3,
!!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
data->pad_flags = env->algorithm_flags;
data->next_sign = default_key;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8);
p = sbuf;
*p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10;
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
*p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84;
*p++ = env->key_ref_len;
memcpy(p, env->key_ref, env->key_ref_len);
p += env->key_ref_len;
}
apdu.data = sbuf;
apdu.lc = apdu.datalen = (p - sbuf);
r=sc_transmit_apdu(card, &apdu);
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"%s: APDU transmit failed", sc_strerror(r));
return r;
}
if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Detected Signature-Only key\n");
if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS;
}
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_restore_security_env(sc_card_t *card, int se_num)
{
return 0;
}
static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen)
{
size_t i, dlen=datalen;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
int tcos3, r;
assert(card != NULL && data != NULL && out != NULL);
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
if(((tcos_data *)card->drv_data)->next_sign){
if(datalen>48){
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A);
memcpy(sbuf, data, datalen);
dlen=datalen;
} else {
int keylen= tcos3 ? 256 : 128;
sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = tcos3 ? 256 : 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) {
int keylen=128;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
}
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len = apdu.resplen>outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
tcos_data *data;
int tcos3, r;
assert(card != NULL && crgram != NULL && out != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n",tcos3,
!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = crgram_len;
apdu.data = sbuf;
apdu.lc = apdu.datalen = crgram_len+1;
sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);
memcpy(sbuf+1, crgram, crgram_len);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;
unsigned int offset=0;
if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){
offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset;
offset=(offset<len-1) ? offset+1 : 0;
}
memcpy(out, apdu.resp+offset, len-offset);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
/* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the
NullPIN method will be activated, otherwise the permanent operation
will be done on the active file. */
static int tcos_setperm(sc_card_t *card, int enable_nullpin)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 0;
apdu.datalen = 0;
apdu.data = NULL;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
if (!serial)
return SC_ERROR_INVALID_ARGUMENTS;
/* see if we have cached serial number */
if (card->serialnr.len) {
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
card->serialnr.len = sizeof card->serialnr.value;
r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0);
if (r < 0) {
card->serialnr.len = 0;
return r;
}
/* copy and return serial number */
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_TCOS_SETPERM:
return tcos_setperm(card, !!ptr);
case SC_CARDCTL_GET_SERIALNR:
return tcos_get_serialnr(card, (sc_serial_number_t *)ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
struct sc_card_driver * sc_get_tcos_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL) iso_ops = iso_drv->ops;
tcos_ops = *iso_drv->ops;
tcos_ops.match_card = tcos_match_card;
tcos_ops.init = tcos_init;
tcos_ops.finish = tcos_finish;
tcos_ops.create_file = tcos_create_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.select_file = tcos_select_file;
tcos_ops.list_files = tcos_list_files;
tcos_ops.delete_file = tcos_delete_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.compute_signature = tcos_compute_signature;
tcos_ops.decipher = tcos_decipher;
tcos_ops.restore_security_env = tcos_restore_security_env;
tcos_ops.card_ctl = tcos_card_ctl;
return &tcos_drv;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_339_3 |
crossvul-cpp_data_bad_2131_3 | /*
* HID driver for some monterey "special" devices
*
* Copyright (c) 1999 Andreas Gal
* Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
* Copyright (c) 2006-2007 Jiri Kosina
* Copyright (c) 2008 Jiri Slaby
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <linux/device.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
static __u8 *mr_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 30 && rdesc[29] == 0x05 && rdesc[30] == 0x09) {
hid_info(hdev, "fixing up button/consumer in HID report descriptor\n");
rdesc[30] = 0x0c;
}
return rdesc;
}
#define mr_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \
EV_KEY, (c))
static int mr_input_mapping(struct hid_device *hdev, struct hid_input *hi,
struct hid_field *field, struct hid_usage *usage,
unsigned long **bit, int *max)
{
if ((usage->hid & HID_USAGE_PAGE) != HID_UP_CONSUMER)
return 0;
switch (usage->hid & HID_USAGE) {
case 0x156: mr_map_key_clear(KEY_WORDPROCESSOR); break;
case 0x157: mr_map_key_clear(KEY_SPREADSHEET); break;
case 0x158: mr_map_key_clear(KEY_PRESENTATION); break;
case 0x15c: mr_map_key_clear(KEY_STOP); break;
default:
return 0;
}
return 1;
}
static const struct hid_device_id mr_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_MONTEREY, USB_DEVICE_ID_GENIUS_KB29E) },
{ }
};
MODULE_DEVICE_TABLE(hid, mr_devices);
static struct hid_driver mr_driver = {
.name = "monterey",
.id_table = mr_devices,
.report_fixup = mr_report_fixup,
.input_mapping = mr_input_mapping,
};
module_hid_driver(mr_driver);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2131_3 |
crossvul-cpp_data_bad_5120_0 | /*
* AirSpy SDR driver
*
* Copyright (C) 2014 Antti Palosaari <crope@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-event.h>
#include <media/videobuf2-v4l2.h>
#include <media/videobuf2-vmalloc.h>
/* AirSpy USB API commands (from AirSpy Library) */
enum {
CMD_INVALID = 0x00,
CMD_RECEIVER_MODE = 0x01,
CMD_SI5351C_WRITE = 0x02,
CMD_SI5351C_READ = 0x03,
CMD_R820T_WRITE = 0x04,
CMD_R820T_READ = 0x05,
CMD_SPIFLASH_ERASE = 0x06,
CMD_SPIFLASH_WRITE = 0x07,
CMD_SPIFLASH_READ = 0x08,
CMD_BOARD_ID_READ = 0x09,
CMD_VERSION_STRING_READ = 0x0a,
CMD_BOARD_PARTID_SERIALNO_READ = 0x0b,
CMD_SET_SAMPLE_RATE = 0x0c,
CMD_SET_FREQ = 0x0d,
CMD_SET_LNA_GAIN = 0x0e,
CMD_SET_MIXER_GAIN = 0x0f,
CMD_SET_VGA_GAIN = 0x10,
CMD_SET_LNA_AGC = 0x11,
CMD_SET_MIXER_AGC = 0x12,
CMD_SET_PACKING = 0x13,
};
/*
* bEndpointAddress 0x81 EP 1 IN
* Transfer Type Bulk
* wMaxPacketSize 0x0200 1x 512 bytes
*/
#define MAX_BULK_BUFS (6)
#define BULK_BUFFER_SIZE (128 * 512)
static const struct v4l2_frequency_band bands[] = {
{
.tuner = 0,
.type = V4L2_TUNER_ADC,
.index = 0,
.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
.rangelow = 20000000,
.rangehigh = 20000000,
},
};
static const struct v4l2_frequency_band bands_rf[] = {
{
.tuner = 1,
.type = V4L2_TUNER_RF,
.index = 0,
.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
.rangelow = 24000000,
.rangehigh = 1750000000,
},
};
/* stream formats */
struct airspy_format {
char *name;
u32 pixelformat;
u32 buffersize;
};
/* format descriptions for capture and preview */
static struct airspy_format formats[] = {
{
.name = "Real U12LE",
.pixelformat = V4L2_SDR_FMT_RU12LE,
.buffersize = BULK_BUFFER_SIZE,
},
};
static const unsigned int NUM_FORMATS = ARRAY_SIZE(formats);
/* intermediate buffers with raw data from the USB device */
struct airspy_frame_buf {
/* common v4l buffer stuff -- must be first */
struct vb2_v4l2_buffer vb;
struct list_head list;
};
struct airspy {
#define POWER_ON 1
#define USB_STATE_URB_BUF 2
unsigned long flags;
struct device *dev;
struct usb_device *udev;
struct video_device vdev;
struct v4l2_device v4l2_dev;
/* videobuf2 queue and queued buffers list */
struct vb2_queue vb_queue;
struct list_head queued_bufs;
spinlock_t queued_bufs_lock; /* Protects queued_bufs */
unsigned sequence; /* Buffer sequence counter */
unsigned int vb_full; /* vb is full and packets dropped */
/* Note if taking both locks v4l2_lock must always be locked first! */
struct mutex v4l2_lock; /* Protects everything else */
struct mutex vb_queue_lock; /* Protects vb_queue and capt_file */
struct urb *urb_list[MAX_BULK_BUFS];
int buf_num;
unsigned long buf_size;
u8 *buf_list[MAX_BULK_BUFS];
dma_addr_t dma_addr[MAX_BULK_BUFS];
int urbs_initialized;
int urbs_submitted;
/* USB control message buffer */
#define BUF_SIZE 128
u8 buf[BUF_SIZE];
/* Current configuration */
unsigned int f_adc;
unsigned int f_rf;
u32 pixelformat;
u32 buffersize;
/* Controls */
struct v4l2_ctrl_handler hdl;
struct v4l2_ctrl *lna_gain_auto;
struct v4l2_ctrl *lna_gain;
struct v4l2_ctrl *mixer_gain_auto;
struct v4l2_ctrl *mixer_gain;
struct v4l2_ctrl *if_gain;
/* Sample rate calc */
unsigned long jiffies_next;
unsigned int sample;
unsigned int sample_measured;
};
#define airspy_dbg_usb_control_msg(_dev, _r, _t, _v, _i, _b, _l) { \
char *_direction; \
if (_t & USB_DIR_IN) \
_direction = "<<<"; \
else \
_direction = ">>>"; \
dev_dbg(_dev, "%02x %02x %02x %02x %02x %02x %02x %02x %s %*ph\n", \
_t, _r, _v & 0xff, _v >> 8, _i & 0xff, _i >> 8, \
_l & 0xff, _l >> 8, _direction, _l, _b); \
}
/* execute firmware command */
static int airspy_ctrl_msg(struct airspy *s, u8 request, u16 value, u16 index,
u8 *data, u16 size)
{
int ret;
unsigned int pipe;
u8 requesttype;
switch (request) {
case CMD_RECEIVER_MODE:
case CMD_SET_FREQ:
pipe = usb_sndctrlpipe(s->udev, 0);
requesttype = (USB_TYPE_VENDOR | USB_DIR_OUT);
break;
case CMD_BOARD_ID_READ:
case CMD_VERSION_STRING_READ:
case CMD_BOARD_PARTID_SERIALNO_READ:
case CMD_SET_LNA_GAIN:
case CMD_SET_MIXER_GAIN:
case CMD_SET_VGA_GAIN:
case CMD_SET_LNA_AGC:
case CMD_SET_MIXER_AGC:
pipe = usb_rcvctrlpipe(s->udev, 0);
requesttype = (USB_TYPE_VENDOR | USB_DIR_IN);
break;
default:
dev_err(s->dev, "Unknown command %02x\n", request);
ret = -EINVAL;
goto err;
}
/* write request */
if (!(requesttype & USB_DIR_IN))
memcpy(s->buf, data, size);
ret = usb_control_msg(s->udev, pipe, request, requesttype, value,
index, s->buf, size, 1000);
airspy_dbg_usb_control_msg(s->dev, request, requesttype, value,
index, s->buf, size);
if (ret < 0) {
dev_err(s->dev, "usb_control_msg() failed %d request %02x\n",
ret, request);
goto err;
}
/* read request */
if (requesttype & USB_DIR_IN)
memcpy(data, s->buf, size);
return 0;
err:
return ret;
}
/* Private functions */
static struct airspy_frame_buf *airspy_get_next_fill_buf(struct airspy *s)
{
unsigned long flags;
struct airspy_frame_buf *buf = NULL;
spin_lock_irqsave(&s->queued_bufs_lock, flags);
if (list_empty(&s->queued_bufs))
goto leave;
buf = list_entry(s->queued_bufs.next,
struct airspy_frame_buf, list);
list_del(&buf->list);
leave:
spin_unlock_irqrestore(&s->queued_bufs_lock, flags);
return buf;
}
static unsigned int airspy_convert_stream(struct airspy *s,
void *dst, void *src, unsigned int src_len)
{
unsigned int dst_len;
if (s->pixelformat == V4L2_SDR_FMT_RU12LE) {
memcpy(dst, src, src_len);
dst_len = src_len;
} else {
dst_len = 0;
}
/* calculate sample rate and output it in 10 seconds intervals */
if (unlikely(time_is_before_jiffies(s->jiffies_next))) {
#define MSECS 10000UL
unsigned int msecs = jiffies_to_msecs(jiffies -
s->jiffies_next + msecs_to_jiffies(MSECS));
unsigned int samples = s->sample - s->sample_measured;
s->jiffies_next = jiffies + msecs_to_jiffies(MSECS);
s->sample_measured = s->sample;
dev_dbg(s->dev, "slen=%u samples=%u msecs=%u sample rate=%lu\n",
src_len, samples, msecs,
samples * 1000UL / msecs);
}
/* total number of samples */
s->sample += src_len / 2;
return dst_len;
}
/*
* This gets called for the bulk stream pipe. This is done in interrupt
* time, so it has to be fast, not crash, and not stall. Neat.
*/
static void airspy_urb_complete(struct urb *urb)
{
struct airspy *s = urb->context;
struct airspy_frame_buf *fbuf;
dev_dbg_ratelimited(s->dev, "status=%d length=%d/%d errors=%d\n",
urb->status, urb->actual_length,
urb->transfer_buffer_length, urb->error_count);
switch (urb->status) {
case 0: /* success */
case -ETIMEDOUT: /* NAK */
break;
case -ECONNRESET: /* kill */
case -ENOENT:
case -ESHUTDOWN:
return;
default: /* error */
dev_err_ratelimited(s->dev, "URB failed %d\n", urb->status);
break;
}
if (likely(urb->actual_length > 0)) {
void *ptr;
unsigned int len;
/* get free framebuffer */
fbuf = airspy_get_next_fill_buf(s);
if (unlikely(fbuf == NULL)) {
s->vb_full++;
dev_notice_ratelimited(s->dev,
"videobuf is full, %d packets dropped\n",
s->vb_full);
goto skip;
}
/* fill framebuffer */
ptr = vb2_plane_vaddr(&fbuf->vb.vb2_buf, 0);
len = airspy_convert_stream(s, ptr, urb->transfer_buffer,
urb->actual_length);
vb2_set_plane_payload(&fbuf->vb.vb2_buf, 0, len);
fbuf->vb.vb2_buf.timestamp = ktime_get_ns();
fbuf->vb.sequence = s->sequence++;
vb2_buffer_done(&fbuf->vb.vb2_buf, VB2_BUF_STATE_DONE);
}
skip:
usb_submit_urb(urb, GFP_ATOMIC);
}
static int airspy_kill_urbs(struct airspy *s)
{
int i;
for (i = s->urbs_submitted - 1; i >= 0; i--) {
dev_dbg(s->dev, "kill urb=%d\n", i);
/* stop the URB */
usb_kill_urb(s->urb_list[i]);
}
s->urbs_submitted = 0;
return 0;
}
static int airspy_submit_urbs(struct airspy *s)
{
int i, ret;
for (i = 0; i < s->urbs_initialized; i++) {
dev_dbg(s->dev, "submit urb=%d\n", i);
ret = usb_submit_urb(s->urb_list[i], GFP_ATOMIC);
if (ret) {
dev_err(s->dev, "Could not submit URB no. %d - get them all back\n",
i);
airspy_kill_urbs(s);
return ret;
}
s->urbs_submitted++;
}
return 0;
}
static int airspy_free_stream_bufs(struct airspy *s)
{
if (test_bit(USB_STATE_URB_BUF, &s->flags)) {
while (s->buf_num) {
s->buf_num--;
dev_dbg(s->dev, "free buf=%d\n", s->buf_num);
usb_free_coherent(s->udev, s->buf_size,
s->buf_list[s->buf_num],
s->dma_addr[s->buf_num]);
}
}
clear_bit(USB_STATE_URB_BUF, &s->flags);
return 0;
}
static int airspy_alloc_stream_bufs(struct airspy *s)
{
s->buf_num = 0;
s->buf_size = BULK_BUFFER_SIZE;
dev_dbg(s->dev, "all in all I will use %u bytes for streaming\n",
MAX_BULK_BUFS * BULK_BUFFER_SIZE);
for (s->buf_num = 0; s->buf_num < MAX_BULK_BUFS; s->buf_num++) {
s->buf_list[s->buf_num] = usb_alloc_coherent(s->udev,
BULK_BUFFER_SIZE, GFP_ATOMIC,
&s->dma_addr[s->buf_num]);
if (!s->buf_list[s->buf_num]) {
dev_dbg(s->dev, "alloc buf=%d failed\n", s->buf_num);
airspy_free_stream_bufs(s);
return -ENOMEM;
}
dev_dbg(s->dev, "alloc buf=%d %p (dma %llu)\n", s->buf_num,
s->buf_list[s->buf_num],
(long long)s->dma_addr[s->buf_num]);
set_bit(USB_STATE_URB_BUF, &s->flags);
}
return 0;
}
static int airspy_free_urbs(struct airspy *s)
{
int i;
airspy_kill_urbs(s);
for (i = s->urbs_initialized - 1; i >= 0; i--) {
if (s->urb_list[i]) {
dev_dbg(s->dev, "free urb=%d\n", i);
/* free the URBs */
usb_free_urb(s->urb_list[i]);
}
}
s->urbs_initialized = 0;
return 0;
}
static int airspy_alloc_urbs(struct airspy *s)
{
int i, j;
/* allocate the URBs */
for (i = 0; i < MAX_BULK_BUFS; i++) {
dev_dbg(s->dev, "alloc urb=%d\n", i);
s->urb_list[i] = usb_alloc_urb(0, GFP_ATOMIC);
if (!s->urb_list[i]) {
dev_dbg(s->dev, "failed\n");
for (j = 0; j < i; j++)
usb_free_urb(s->urb_list[j]);
return -ENOMEM;
}
usb_fill_bulk_urb(s->urb_list[i],
s->udev,
usb_rcvbulkpipe(s->udev, 0x81),
s->buf_list[i],
BULK_BUFFER_SIZE,
airspy_urb_complete, s);
s->urb_list[i]->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
s->urb_list[i]->transfer_dma = s->dma_addr[i];
s->urbs_initialized++;
}
return 0;
}
/* Must be called with vb_queue_lock hold */
static void airspy_cleanup_queued_bufs(struct airspy *s)
{
unsigned long flags;
dev_dbg(s->dev, "\n");
spin_lock_irqsave(&s->queued_bufs_lock, flags);
while (!list_empty(&s->queued_bufs)) {
struct airspy_frame_buf *buf;
buf = list_entry(s->queued_bufs.next,
struct airspy_frame_buf, list);
list_del(&buf->list);
vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
}
spin_unlock_irqrestore(&s->queued_bufs_lock, flags);
}
/* The user yanked out the cable... */
static void airspy_disconnect(struct usb_interface *intf)
{
struct v4l2_device *v = usb_get_intfdata(intf);
struct airspy *s = container_of(v, struct airspy, v4l2_dev);
dev_dbg(s->dev, "\n");
mutex_lock(&s->vb_queue_lock);
mutex_lock(&s->v4l2_lock);
/* No need to keep the urbs around after disconnection */
s->udev = NULL;
v4l2_device_disconnect(&s->v4l2_dev);
video_unregister_device(&s->vdev);
mutex_unlock(&s->v4l2_lock);
mutex_unlock(&s->vb_queue_lock);
v4l2_device_put(&s->v4l2_dev);
}
/* Videobuf2 operations */
static int airspy_queue_setup(struct vb2_queue *vq,
unsigned int *nbuffers,
unsigned int *nplanes, unsigned int sizes[], void *alloc_ctxs[])
{
struct airspy *s = vb2_get_drv_priv(vq);
dev_dbg(s->dev, "nbuffers=%d\n", *nbuffers);
/* Need at least 8 buffers */
if (vq->num_buffers + *nbuffers < 8)
*nbuffers = 8 - vq->num_buffers;
*nplanes = 1;
sizes[0] = PAGE_ALIGN(s->buffersize);
dev_dbg(s->dev, "nbuffers=%d sizes[0]=%d\n", *nbuffers, sizes[0]);
return 0;
}
static void airspy_buf_queue(struct vb2_buffer *vb)
{
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
struct airspy *s = vb2_get_drv_priv(vb->vb2_queue);
struct airspy_frame_buf *buf =
container_of(vbuf, struct airspy_frame_buf, vb);
unsigned long flags;
/* Check the device has not disconnected between prep and queuing */
if (unlikely(!s->udev)) {
vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
return;
}
spin_lock_irqsave(&s->queued_bufs_lock, flags);
list_add_tail(&buf->list, &s->queued_bufs);
spin_unlock_irqrestore(&s->queued_bufs_lock, flags);
}
static int airspy_start_streaming(struct vb2_queue *vq, unsigned int count)
{
struct airspy *s = vb2_get_drv_priv(vq);
int ret;
dev_dbg(s->dev, "\n");
if (!s->udev)
return -ENODEV;
mutex_lock(&s->v4l2_lock);
s->sequence = 0;
set_bit(POWER_ON, &s->flags);
ret = airspy_alloc_stream_bufs(s);
if (ret)
goto err_clear_bit;
ret = airspy_alloc_urbs(s);
if (ret)
goto err_free_stream_bufs;
ret = airspy_submit_urbs(s);
if (ret)
goto err_free_urbs;
/* start hardware streaming */
ret = airspy_ctrl_msg(s, CMD_RECEIVER_MODE, 1, 0, NULL, 0);
if (ret)
goto err_kill_urbs;
goto exit_mutex_unlock;
err_kill_urbs:
airspy_kill_urbs(s);
err_free_urbs:
airspy_free_urbs(s);
err_free_stream_bufs:
airspy_free_stream_bufs(s);
err_clear_bit:
clear_bit(POWER_ON, &s->flags);
/* return all queued buffers to vb2 */
{
struct airspy_frame_buf *buf, *tmp;
list_for_each_entry_safe(buf, tmp, &s->queued_bufs, list) {
list_del(&buf->list);
vb2_buffer_done(&buf->vb.vb2_buf,
VB2_BUF_STATE_QUEUED);
}
}
exit_mutex_unlock:
mutex_unlock(&s->v4l2_lock);
return ret;
}
static void airspy_stop_streaming(struct vb2_queue *vq)
{
struct airspy *s = vb2_get_drv_priv(vq);
dev_dbg(s->dev, "\n");
mutex_lock(&s->v4l2_lock);
/* stop hardware streaming */
airspy_ctrl_msg(s, CMD_RECEIVER_MODE, 0, 0, NULL, 0);
airspy_kill_urbs(s);
airspy_free_urbs(s);
airspy_free_stream_bufs(s);
airspy_cleanup_queued_bufs(s);
clear_bit(POWER_ON, &s->flags);
mutex_unlock(&s->v4l2_lock);
}
static struct vb2_ops airspy_vb2_ops = {
.queue_setup = airspy_queue_setup,
.buf_queue = airspy_buf_queue,
.start_streaming = airspy_start_streaming,
.stop_streaming = airspy_stop_streaming,
.wait_prepare = vb2_ops_wait_prepare,
.wait_finish = vb2_ops_wait_finish,
};
static int airspy_querycap(struct file *file, void *fh,
struct v4l2_capability *cap)
{
struct airspy *s = video_drvdata(file);
strlcpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver));
strlcpy(cap->card, s->vdev.name, sizeof(cap->card));
usb_make_path(s->udev, cap->bus_info, sizeof(cap->bus_info));
cap->device_caps = V4L2_CAP_SDR_CAPTURE | V4L2_CAP_STREAMING |
V4L2_CAP_READWRITE | V4L2_CAP_TUNER;
cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
static int airspy_enum_fmt_sdr_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
if (f->index >= NUM_FORMATS)
return -EINVAL;
strlcpy(f->description, formats[f->index].name, sizeof(f->description));
f->pixelformat = formats[f->index].pixelformat;
return 0;
}
static int airspy_g_fmt_sdr_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct airspy *s = video_drvdata(file);
f->fmt.sdr.pixelformat = s->pixelformat;
f->fmt.sdr.buffersize = s->buffersize;
memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
return 0;
}
static int airspy_s_fmt_sdr_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct airspy *s = video_drvdata(file);
struct vb2_queue *q = &s->vb_queue;
int i;
if (vb2_is_busy(q))
return -EBUSY;
memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
for (i = 0; i < NUM_FORMATS; i++) {
if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
s->pixelformat = formats[i].pixelformat;
s->buffersize = formats[i].buffersize;
f->fmt.sdr.buffersize = formats[i].buffersize;
return 0;
}
}
s->pixelformat = formats[0].pixelformat;
s->buffersize = formats[0].buffersize;
f->fmt.sdr.pixelformat = formats[0].pixelformat;
f->fmt.sdr.buffersize = formats[0].buffersize;
return 0;
}
static int airspy_try_fmt_sdr_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
int i;
memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
for (i = 0; i < NUM_FORMATS; i++) {
if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
f->fmt.sdr.buffersize = formats[i].buffersize;
return 0;
}
}
f->fmt.sdr.pixelformat = formats[0].pixelformat;
f->fmt.sdr.buffersize = formats[0].buffersize;
return 0;
}
static int airspy_s_tuner(struct file *file, void *priv,
const struct v4l2_tuner *v)
{
int ret;
if (v->index == 0)
ret = 0;
else if (v->index == 1)
ret = 0;
else
ret = -EINVAL;
return ret;
}
static int airspy_g_tuner(struct file *file, void *priv, struct v4l2_tuner *v)
{
int ret;
if (v->index == 0) {
strlcpy(v->name, "AirSpy ADC", sizeof(v->name));
v->type = V4L2_TUNER_ADC;
v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
v->rangelow = bands[0].rangelow;
v->rangehigh = bands[0].rangehigh;
ret = 0;
} else if (v->index == 1) {
strlcpy(v->name, "AirSpy RF", sizeof(v->name));
v->type = V4L2_TUNER_RF;
v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
v->rangelow = bands_rf[0].rangelow;
v->rangehigh = bands_rf[0].rangehigh;
ret = 0;
} else {
ret = -EINVAL;
}
return ret;
}
static int airspy_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct airspy *s = video_drvdata(file);
int ret;
if (f->tuner == 0) {
f->type = V4L2_TUNER_ADC;
f->frequency = s->f_adc;
dev_dbg(s->dev, "ADC frequency=%u Hz\n", s->f_adc);
ret = 0;
} else if (f->tuner == 1) {
f->type = V4L2_TUNER_RF;
f->frequency = s->f_rf;
dev_dbg(s->dev, "RF frequency=%u Hz\n", s->f_rf);
ret = 0;
} else {
ret = -EINVAL;
}
return ret;
}
static int airspy_s_frequency(struct file *file, void *priv,
const struct v4l2_frequency *f)
{
struct airspy *s = video_drvdata(file);
int ret;
u8 buf[4];
if (f->tuner == 0) {
s->f_adc = clamp_t(unsigned int, f->frequency,
bands[0].rangelow,
bands[0].rangehigh);
dev_dbg(s->dev, "ADC frequency=%u Hz\n", s->f_adc);
ret = 0;
} else if (f->tuner == 1) {
s->f_rf = clamp_t(unsigned int, f->frequency,
bands_rf[0].rangelow,
bands_rf[0].rangehigh);
dev_dbg(s->dev, "RF frequency=%u Hz\n", s->f_rf);
buf[0] = (s->f_rf >> 0) & 0xff;
buf[1] = (s->f_rf >> 8) & 0xff;
buf[2] = (s->f_rf >> 16) & 0xff;
buf[3] = (s->f_rf >> 24) & 0xff;
ret = airspy_ctrl_msg(s, CMD_SET_FREQ, 0, 0, buf, 4);
} else {
ret = -EINVAL;
}
return ret;
}
static int airspy_enum_freq_bands(struct file *file, void *priv,
struct v4l2_frequency_band *band)
{
int ret;
if (band->tuner == 0) {
if (band->index >= ARRAY_SIZE(bands)) {
ret = -EINVAL;
} else {
*band = bands[band->index];
ret = 0;
}
} else if (band->tuner == 1) {
if (band->index >= ARRAY_SIZE(bands_rf)) {
ret = -EINVAL;
} else {
*band = bands_rf[band->index];
ret = 0;
}
} else {
ret = -EINVAL;
}
return ret;
}
static const struct v4l2_ioctl_ops airspy_ioctl_ops = {
.vidioc_querycap = airspy_querycap,
.vidioc_enum_fmt_sdr_cap = airspy_enum_fmt_sdr_cap,
.vidioc_g_fmt_sdr_cap = airspy_g_fmt_sdr_cap,
.vidioc_s_fmt_sdr_cap = airspy_s_fmt_sdr_cap,
.vidioc_try_fmt_sdr_cap = airspy_try_fmt_sdr_cap,
.vidioc_reqbufs = vb2_ioctl_reqbufs,
.vidioc_create_bufs = vb2_ioctl_create_bufs,
.vidioc_prepare_buf = vb2_ioctl_prepare_buf,
.vidioc_querybuf = vb2_ioctl_querybuf,
.vidioc_qbuf = vb2_ioctl_qbuf,
.vidioc_dqbuf = vb2_ioctl_dqbuf,
.vidioc_streamon = vb2_ioctl_streamon,
.vidioc_streamoff = vb2_ioctl_streamoff,
.vidioc_g_tuner = airspy_g_tuner,
.vidioc_s_tuner = airspy_s_tuner,
.vidioc_g_frequency = airspy_g_frequency,
.vidioc_s_frequency = airspy_s_frequency,
.vidioc_enum_freq_bands = airspy_enum_freq_bands,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
.vidioc_log_status = v4l2_ctrl_log_status,
};
static const struct v4l2_file_operations airspy_fops = {
.owner = THIS_MODULE,
.open = v4l2_fh_open,
.release = vb2_fop_release,
.read = vb2_fop_read,
.poll = vb2_fop_poll,
.mmap = vb2_fop_mmap,
.unlocked_ioctl = video_ioctl2,
};
static struct video_device airspy_template = {
.name = "AirSpy SDR",
.release = video_device_release_empty,
.fops = &airspy_fops,
.ioctl_ops = &airspy_ioctl_ops,
};
static void airspy_video_release(struct v4l2_device *v)
{
struct airspy *s = container_of(v, struct airspy, v4l2_dev);
v4l2_ctrl_handler_free(&s->hdl);
v4l2_device_unregister(&s->v4l2_dev);
kfree(s);
}
static int airspy_set_lna_gain(struct airspy *s)
{
int ret;
u8 u8tmp;
dev_dbg(s->dev, "lna auto=%d->%d val=%d->%d\n",
s->lna_gain_auto->cur.val, s->lna_gain_auto->val,
s->lna_gain->cur.val, s->lna_gain->val);
ret = airspy_ctrl_msg(s, CMD_SET_LNA_AGC, 0, s->lna_gain_auto->val,
&u8tmp, 1);
if (ret)
goto err;
if (s->lna_gain_auto->val == false) {
ret = airspy_ctrl_msg(s, CMD_SET_LNA_GAIN, 0, s->lna_gain->val,
&u8tmp, 1);
if (ret)
goto err;
}
err:
if (ret)
dev_dbg(s->dev, "failed=%d\n", ret);
return ret;
}
static int airspy_set_mixer_gain(struct airspy *s)
{
int ret;
u8 u8tmp;
dev_dbg(s->dev, "mixer auto=%d->%d val=%d->%d\n",
s->mixer_gain_auto->cur.val, s->mixer_gain_auto->val,
s->mixer_gain->cur.val, s->mixer_gain->val);
ret = airspy_ctrl_msg(s, CMD_SET_MIXER_AGC, 0, s->mixer_gain_auto->val,
&u8tmp, 1);
if (ret)
goto err;
if (s->mixer_gain_auto->val == false) {
ret = airspy_ctrl_msg(s, CMD_SET_MIXER_GAIN, 0,
s->mixer_gain->val, &u8tmp, 1);
if (ret)
goto err;
}
err:
if (ret)
dev_dbg(s->dev, "failed=%d\n", ret);
return ret;
}
static int airspy_set_if_gain(struct airspy *s)
{
int ret;
u8 u8tmp;
dev_dbg(s->dev, "val=%d->%d\n", s->if_gain->cur.val, s->if_gain->val);
ret = airspy_ctrl_msg(s, CMD_SET_VGA_GAIN, 0, s->if_gain->val,
&u8tmp, 1);
if (ret)
dev_dbg(s->dev, "failed=%d\n", ret);
return ret;
}
static int airspy_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct airspy *s = container_of(ctrl->handler, struct airspy, hdl);
int ret;
switch (ctrl->id) {
case V4L2_CID_RF_TUNER_LNA_GAIN_AUTO:
case V4L2_CID_RF_TUNER_LNA_GAIN:
ret = airspy_set_lna_gain(s);
break;
case V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO:
case V4L2_CID_RF_TUNER_MIXER_GAIN:
ret = airspy_set_mixer_gain(s);
break;
case V4L2_CID_RF_TUNER_IF_GAIN:
ret = airspy_set_if_gain(s);
break;
default:
dev_dbg(s->dev, "unknown ctrl: id=%d name=%s\n",
ctrl->id, ctrl->name);
ret = -EINVAL;
}
return ret;
}
static const struct v4l2_ctrl_ops airspy_ctrl_ops = {
.s_ctrl = airspy_s_ctrl,
};
static int airspy_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct airspy *s;
int ret;
u8 u8tmp, buf[BUF_SIZE];
s = kzalloc(sizeof(struct airspy), GFP_KERNEL);
if (s == NULL) {
dev_err(&intf->dev, "Could not allocate memory for state\n");
return -ENOMEM;
}
mutex_init(&s->v4l2_lock);
mutex_init(&s->vb_queue_lock);
spin_lock_init(&s->queued_bufs_lock);
INIT_LIST_HEAD(&s->queued_bufs);
s->dev = &intf->dev;
s->udev = interface_to_usbdev(intf);
s->f_adc = bands[0].rangelow;
s->f_rf = bands_rf[0].rangelow;
s->pixelformat = formats[0].pixelformat;
s->buffersize = formats[0].buffersize;
/* Detect device */
ret = airspy_ctrl_msg(s, CMD_BOARD_ID_READ, 0, 0, &u8tmp, 1);
if (ret == 0)
ret = airspy_ctrl_msg(s, CMD_VERSION_STRING_READ, 0, 0,
buf, BUF_SIZE);
if (ret) {
dev_err(s->dev, "Could not detect board\n");
goto err_free_mem;
}
buf[BUF_SIZE - 1] = '\0';
dev_info(s->dev, "Board ID: %02x\n", u8tmp);
dev_info(s->dev, "Firmware version: %s\n", buf);
/* Init videobuf2 queue structure */
s->vb_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE;
s->vb_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
s->vb_queue.drv_priv = s;
s->vb_queue.buf_struct_size = sizeof(struct airspy_frame_buf);
s->vb_queue.ops = &airspy_vb2_ops;
s->vb_queue.mem_ops = &vb2_vmalloc_memops;
s->vb_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
ret = vb2_queue_init(&s->vb_queue);
if (ret) {
dev_err(s->dev, "Could not initialize vb2 queue\n");
goto err_free_mem;
}
/* Init video_device structure */
s->vdev = airspy_template;
s->vdev.queue = &s->vb_queue;
s->vdev.queue->lock = &s->vb_queue_lock;
video_set_drvdata(&s->vdev, s);
/* Register the v4l2_device structure */
s->v4l2_dev.release = airspy_video_release;
ret = v4l2_device_register(&intf->dev, &s->v4l2_dev);
if (ret) {
dev_err(s->dev, "Failed to register v4l2-device (%d)\n", ret);
goto err_free_mem;
}
/* Register controls */
v4l2_ctrl_handler_init(&s->hdl, 5);
s->lna_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_LNA_GAIN_AUTO, 0, 1, 1, 0);
s->lna_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_LNA_GAIN, 0, 14, 1, 8);
v4l2_ctrl_auto_cluster(2, &s->lna_gain_auto, 0, false);
s->mixer_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO, 0, 1, 1, 0);
s->mixer_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_MIXER_GAIN, 0, 15, 1, 8);
v4l2_ctrl_auto_cluster(2, &s->mixer_gain_auto, 0, false);
s->if_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_IF_GAIN, 0, 15, 1, 0);
if (s->hdl.error) {
ret = s->hdl.error;
dev_err(s->dev, "Could not initialize controls\n");
goto err_free_controls;
}
v4l2_ctrl_handler_setup(&s->hdl);
s->v4l2_dev.ctrl_handler = &s->hdl;
s->vdev.v4l2_dev = &s->v4l2_dev;
s->vdev.lock = &s->v4l2_lock;
ret = video_register_device(&s->vdev, VFL_TYPE_SDR, -1);
if (ret) {
dev_err(s->dev, "Failed to register as video device (%d)\n",
ret);
goto err_unregister_v4l2_dev;
}
dev_info(s->dev, "Registered as %s\n",
video_device_node_name(&s->vdev));
dev_notice(s->dev, "SDR API is still slightly experimental and functionality changes may follow\n");
return 0;
err_free_controls:
v4l2_ctrl_handler_free(&s->hdl);
err_unregister_v4l2_dev:
v4l2_device_unregister(&s->v4l2_dev);
err_free_mem:
kfree(s);
return ret;
}
/* USB device ID list */
static struct usb_device_id airspy_id_table[] = {
{ USB_DEVICE(0x1d50, 0x60a1) }, /* AirSpy */
{ }
};
MODULE_DEVICE_TABLE(usb, airspy_id_table);
/* USB subsystem interface */
static struct usb_driver airspy_driver = {
.name = KBUILD_MODNAME,
.probe = airspy_probe,
.disconnect = airspy_disconnect,
.id_table = airspy_id_table,
};
module_usb_driver(airspy_driver);
MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
MODULE_DESCRIPTION("AirSpy SDR");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5120_0 |
crossvul-cpp_data_bad_4788_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L AAA BBBB EEEEE L %
% L A A B B E L %
% L AAAAA BBBB EEE L %
% L A A B B E L %
% LLLLL A A BBBB EEEEE LLLLL %
% %
% %
% Read ASCII String As An Image. %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/annotate.h"
#include "magick/artifact.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/draw.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/utility.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d L A B E L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadLABELImage() reads a LABEL image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadLABELImage method is:
%
% Image *ReadLABELImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadLABELImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
geometry[MaxTextExtent],
*property;
const char
*label;
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
TypeMetric
metrics;
size_t
height,
width;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
(void) ResetImagePage(image,"0x0+0+0");
property=InterpretImageProperties(image_info,image,image_info->filename);
(void) SetImageProperty(image,"label",property);
property=DestroyString(property);
label=GetImageProperty(image,"label");
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->text=ConstantString(label);
metrics.width=0;
metrics.ascent=0.0;
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if ((image->columns == 0) && (image->rows == 0))
{
image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5);
image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
}
else
if (((image->columns == 0) || (image->rows == 0)) ||
(fabs(image_info->pointsize) < MagickEpsilon))
{
double
high,
low;
/*
Auto fit text into bounding box.
*/
for ( ; ; draw_info->pointsize*=2.0)
{
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width >= image->columns) && (height >= image->rows))
break;
}
else
if (((image->columns != 0) && (width >= image->columns)) ||
((image->rows != 0) && (height >= image->rows)))
break;
}
high=draw_info->pointsize;
for (low=1.0; (high-low) > 0.5; )
{
draw_info->pointsize=(low+high)/2.0;
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width < image->columns) && (height < image->rows))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
else
if (((image->columns != 0) && (width < image->columns)) ||
((image->rows != 0) && (height < image->rows)))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
draw_info->pointsize=(low+high)/2.0-0.5;
}
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image->columns == 0)
image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5);
if (image->columns == 0)
image->columns=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5);
if (image->rows == 0)
image->rows=(size_t) (metrics.ascent-metrics.descent+
draw_info->stroke_width+0.5);
if (image->rows == 0)
image->rows=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (SetImageBackgroundColor(image) == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Draw label.
*/
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
draw_info->direction == RightToLeftDirection ? image->columns-
metrics.bounds.x2 : 0.0,draw_info->gravity == UndefinedGravity ?
metrics.ascent : 0.0);
draw_info->geometry=AcquireString(geometry);
status=AnnotateImage(image,draw_info);
if (image_info->pointsize == 0.0)
{
char
pointsize[MaxTextExtent];
(void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g",
draw_info->pointsize);
(void) SetImageProperty(image,"label:pointsize",pointsize);
}
draw_info=DestroyDrawInfo(draw_info);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r L A B E L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterLABELImage() adds properties for the LABEL image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterLABELImage method is:
%
% size_t RegisterLABELImage(void)
%
*/
ModuleExport size_t RegisterLABELImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("LABEL");
entry->decoder=(DecodeImageHandler *) ReadLABELImage;
entry->adjoin=MagickFalse;
entry->format_type=ImplicitFormatType;
entry->description=ConstantString("Image label");
entry->module=ConstantString("LABEL");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r L A B E L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterLABELImage() removes format registrations made by the
% LABEL module from the list of supported formats.
%
% The format of the UnregisterLABELImage method is:
%
% UnregisterLABELImage(void)
%
*/
ModuleExport void UnregisterLABELImage(void)
{
(void) UnregisterMagickInfo("LABEL");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4788_0 |
crossvul-cpp_data_bad_5252_2 | /*
Mac-Telnet - Connect to RouterOS or mactelnetd devices via MAC address
Copyright (C) 2010, Håkon Nessjøen <haakon.nessjoen@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#define _BSD_SOURCE
#include <libintl.h>
#include <locale.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#ifdef __LINUX__
#include <linux/if_ether.h>
#endif
#include <arpa/inet.h>
#include <netinet/in.h>
#if defined(__FreeBSD__) || defined(__APPLE__)
#include <net/ethernet.h>
#include <sys/types.h>
#include <sys/socket.h>
#else
#include <netinet/ether.h>
#endif
#include <time.h>
#if defined(__APPLE__)
# include <libkern/OSByteOrder.h>
# define le32toh OSSwapLittleToHostInt32
#elif defined(__FreeBSD__)
#include <sys/endian.h>
#else
#include <endian.h>
#endif
#include "protocol.h"
#include "config.h"
#define _(String) gettext (String)
int init_packet(struct mt_packet *packet, enum mt_ptype ptype, unsigned char *srcmac, unsigned char *dstmac, unsigned short sessionkey, unsigned int counter) {
unsigned char *data = packet->data;
/* Packet version */
data[0] = 1;
/* Packet type */
data[1] = ptype;
/* src ethernet address */
memcpy(data + 2, srcmac, ETH_ALEN);
/* dst ethernet address */
memcpy(data + 8, dstmac, ETH_ALEN);
/* Session key */
sessionkey = htons(sessionkey);
memcpy(data + (mt_direction_fromserver ? 16 : 14), &sessionkey, sizeof(sessionkey));
/* Client type: Mac Telnet */
memcpy(data + (mt_direction_fromserver ? 14 : 16), &mt_mactelnet_clienttype, sizeof(mt_mactelnet_clienttype));
/* Received/sent data counter */
counter = htonl(counter);
memcpy(data + 18, &counter, sizeof(counter));
/* 22 bytes header */
packet->size = 22;
return 22;
}
int add_control_packet(struct mt_packet *packet, enum mt_cptype cptype, void *cpdata, unsigned short data_len) {
unsigned char *data = packet->data + packet->size;
unsigned int act_size = data_len + (cptype == MT_CPTYPE_PLAINDATA ? 0 : MT_CPHEADER_LEN);
/* Something is really wrong. Packets should never become over 1500 bytes */
if (packet->size + act_size > MT_PACKET_LEN) {
fprintf(stderr, _("add_control_packet: ERROR, too large packet. Exceeds %d bytes\n"), MT_PACKET_LEN);
return -1;
//exit(1);
}
/* PLAINDATA isn't really a controlpacket, but we handle it here, since
parseControlPacket also parses raw data as PLAINDATA */
if (cptype == MT_CPTYPE_PLAINDATA) {
memcpy(data, cpdata, data_len);
packet->size += data_len;
return data_len;
}
/* Control Packet Magic id */
memcpy(data, mt_mactelnet_cpmagic, sizeof(mt_mactelnet_cpmagic));
/* Control packet type */
data[4] = cptype;
/* Data length */
#if BYTE_ORDER == LITTLE_ENDIAN
{
unsigned int templen;
templen = htonl(data_len);
memcpy(data + 5, &templen, sizeof(templen));
}
#else
memcpy(data + 5, &data_len, sizeof(data_len));
#endif
/* Insert data */
if (data_len > 0) {
memcpy(data + MT_CPHEADER_LEN, cpdata, data_len);
}
packet->size += act_size;
/* Control packet header length + data length */
return act_size;
}
int init_pingpacket(struct mt_packet *packet, unsigned char *srcmac, unsigned char *dstmac) {
init_packet(packet, MT_PTYPE_PING, srcmac, dstmac, 0, 0);
/* Zero out sessionkey & counter */
bzero(packet->data + 14, 4);
/* Remove data counter field from header */
packet->size -= 4;
return packet->size;
}
int init_pongpacket(struct mt_packet *packet, unsigned char *srcmac, unsigned char *dstmac) {
init_packet(packet, MT_PTYPE_PONG, srcmac, dstmac, 0, 0);
/* Zero out sessionkey & counter */
bzero(packet->data + 14, 4);
/* Remove data counter field from header */
packet->size -= 4;
return packet->size;
}
int add_packetdata(struct mt_packet *packet, unsigned char *data, unsigned short length) {
if (packet->size + length > MT_PACKET_LEN) {
fprintf(stderr, _("add_control_packet: ERROR, too large packet. Exceeds %d bytes\n"), MT_PACKET_LEN);
return -1;
}
memcpy(packet->data + packet->size, data, length);
packet->size += length;
return length;
}
void parse_packet(unsigned char *data, struct mt_mactelnet_hdr *pkthdr) {
/* Packet version */
pkthdr->ver = data[0];
/* Packet type */
pkthdr->ptype = data[1];
/* src ethernet addr */
memcpy(pkthdr->srcaddr, data + 2, ETH_ALEN);
/* dst ethernet addr */
memcpy(pkthdr->dstaddr, data + 8, ETH_ALEN);
/* Session key */
memcpy(&(pkthdr->seskey), data + (mt_direction_fromserver ? 14 : 16), sizeof(pkthdr->seskey));
pkthdr->seskey = ntohs(pkthdr->seskey);
/* server type */
memcpy(&(pkthdr->clienttype), data + (mt_direction_fromserver ? 16 : 14), 2);
/* Received/sent data counter */
memcpy(&(pkthdr->counter), data + 18, sizeof(pkthdr->counter));
pkthdr->counter = ntohl(pkthdr->counter);
/* Set pointer to actual data */
pkthdr->data = data + 22;
}
int parse_control_packet(unsigned char *packetdata, unsigned short data_len, struct mt_mactelnet_control_hdr *cpkthdr) {
static unsigned char *int_data;
static unsigned int int_data_len;
static unsigned int int_pos;
unsigned char *data;
/* Store info so we can call this function once with data,
and then several times for each control packets. Letting this function
control the data position. */
if (packetdata != NULL) {
if (data_len == 0) {
return 0;
}
int_data = packetdata;
int_data_len = data_len;
int_pos = 0;
}
/* No more data to parse? */
if (int_pos >= int_data_len) {
return 0;
}
/* Set current position in data buffer */
data = int_data + int_pos;
/* Check for valid minimum packet length & magic header */
if ((int_data_len - int_pos) >= MT_CPHEADER_LEN && memcmp(data, &mt_mactelnet_cpmagic, 4) == 0) {
/* Control packet type */
cpkthdr->cptype = data[4];
/* Control packet data length */
memcpy(&(cpkthdr->length), data + 5, sizeof(cpkthdr->length));
cpkthdr->length = ntohl(cpkthdr->length);
/* We want no buffer overflows */
if (cpkthdr->length > int_data_len - MT_CPHEADER_LEN - int_pos) {
cpkthdr->length = int_data_len - MT_CPHEADER_LEN - int_pos;
}
/* Set pointer to actual data */
cpkthdr->data = data + MT_CPHEADER_LEN;
/* Remember old position, for next call */
int_pos += cpkthdr->length + MT_CPHEADER_LEN;
/* Read data successfully */
return 1;
} else {
/* Mark data as raw terminal data */
cpkthdr->cptype = MT_CPTYPE_PLAINDATA;
cpkthdr->length = int_data_len - int_pos;
cpkthdr->data = data;
/* Consume the whole rest of the packet */
int_pos = int_data_len;
/* Read data successfully */
return 1;
}
}
int mndp_init_packet(struct mt_packet *packet, unsigned char version, unsigned char ttl) {
struct mt_mndp_hdr *header = (struct mt_mndp_hdr *)packet->data;
header->version = version;
header->ttl = ttl;
header->cksum = 0;
packet->size = sizeof(*header);
return sizeof(*header);
}
int mndp_add_attribute(struct mt_packet *packet, enum mt_mndp_attrtype attrtype, void *attrdata, unsigned short data_len) {
unsigned char *data = packet->data + packet->size;
unsigned short type = attrtype;
unsigned short len = data_len;
/* Something is really wrong. Packets should never become over 1500 bytes */
if (packet->size + 4 + data_len > MT_PACKET_LEN) {
fprintf(stderr, _("mndp_add_attribute: ERROR, too large packet. Exceeds %d bytes\n"), MT_PACKET_LEN);
return -1;
}
type = htons(type);
memcpy(data, &type, sizeof(type));
len = htons(len);
memcpy(data + 2, &len, sizeof(len));
memcpy(data + 4, attrdata, data_len);
packet->size += 4 + data_len;
return 4 + data_len;
}
struct mt_mndp_info *parse_mndp(const unsigned char *data, const int packet_len) {
const unsigned char *p;
static struct mt_mndp_info packet;
struct mt_mndp_info *packetp = &packet;
struct mt_mndp_hdr *mndp_hdr;
/* Check for valid packet length */
if (packet_len < 18) {
return NULL;
}
bzero(packetp, sizeof(*packetp));
mndp_hdr = (struct mt_mndp_hdr*)data;
memcpy(&packetp->header, mndp_hdr, sizeof(struct mt_mndp_hdr));
p = data + sizeof(struct mt_mndp_hdr);
while(p + 4 < data + packet_len) {
unsigned short type, len;
memcpy(&type, p, 2);
memcpy(&len, p + 2, 2);
type = ntohs(type);
len = ntohs(len);
p += 4;
/* Check if len is invalid */
if (p + len > data + packet_len) {
fprintf(stderr, "%s: invalid data: "
"%p + %u > %p + %d\n",
__func__, p, len, data, packet_len);
break;
}
switch (type) {
case MT_MNDPTYPE_ADDRESS:
if (len >= ETH_ALEN) {
memcpy(packetp->address, p, ETH_ALEN);
}
break;
case MT_MNDPTYPE_IDENTITY:
if (len >= MT_MNDP_MAX_STRING_SIZE) {
len = MT_MNDP_MAX_STRING_SIZE - 1;
}
memcpy(packetp->identity, p, len);
packetp->identity[len] = '\0';
break;
case MT_MNDPTYPE_PLATFORM:
if (len >= MT_MNDP_MAX_STRING_SIZE) {
len = MT_MNDP_MAX_STRING_SIZE - 1;
}
memcpy(packetp->platform, p, len);
packetp->platform[len] = '\0';
break;
case MT_MNDPTYPE_VERSION:
if (len >= MT_MNDP_MAX_STRING_SIZE) {
len = MT_MNDP_MAX_STRING_SIZE - 1;
}
memcpy(packetp->version, p, len);
packetp->version[len] = '\0';
break;
case MT_MNDPTYPE_TIMESTAMP:
if (len >= 4) {
memcpy(&packetp->uptime, p, 4);
/* Seems like ping uptime is transmitted as little endian? */
packetp->uptime = le32toh(packetp->uptime);
}
break;
case MT_MNDPTYPE_HARDWARE:
if (len >= MT_MNDP_MAX_STRING_SIZE) {
len = MT_MNDP_MAX_STRING_SIZE - 1;
}
memcpy(packetp->hardware, p, len);
packetp->hardware[len] = '\0';
break;
case MT_MNDPTYPE_SOFTID:
if (len >= MT_MNDP_MAX_STRING_SIZE) {
len = MT_MNDP_MAX_STRING_SIZE - 1;
}
memcpy(packetp->softid, p, len);
packetp->softid[len] = '\0';
break;
case MT_MNDPTYPE_IFNAME:
if (len >= MT_MNDP_MAX_STRING_SIZE) {
len = MT_MNDP_MAX_STRING_SIZE - 1;
}
memcpy(packetp->ifname, p, len);
packetp->ifname[len] = '\0';
break;
/*default:
Unhandled MNDP type
*/
}
p += len;
}
return packetp;
}
int query_mndp(const char *identity, unsigned char *mac) {
int fastlookup = 0;
int sock, length;
int optval = 1;
struct sockaddr_in si_me, si_remote;
unsigned char buff[MT_PACKET_LEN];
unsigned int message = 0;
struct timeval timeout;
time_t start_time;
fd_set read_fds;
struct mt_mndp_info *packet;
start_time = time(0);
/* Open a UDP socket handle */
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
/* Allow to share socket */
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
/* Set initialize address/port */
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(MT_MNDP_PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
/* Bind to specified address/port */
if (bind(sock, (struct sockaddr *)&si_me, sizeof(si_me)) == -1) {
fprintf(stderr, _("Error binding to %s:%d\n"), inet_ntoa(si_me.sin_addr), MT_MNDP_PORT);
close(sock);
return 0;
}
/* Set the socket to allow sending broadcast packets */
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &optval, sizeof (optval));
/* Request routers identify themselves */
memset((char *) &si_remote, 0, sizeof(si_remote));
si_remote.sin_family = AF_INET;
si_remote.sin_port = htons(MT_MNDP_PORT);
si_remote.sin_addr.s_addr = htonl(INADDR_BROADCAST);
if (sendto(sock, &message, sizeof (message), 0, (struct sockaddr *)&si_remote, sizeof(si_remote)) == -1) {
fprintf(stderr, _("Unable to send broadcast packet: Router lookup will be slow\n"));
fastlookup = 0;
} else {
fastlookup = 1;
}
while (1) {
/* Timeout, in case we receive a lot of packets, but from the wrong routers */
if (time(0) - start_time > (fastlookup ? MT_MNDP_TIMEOUT : MT_MNDP_LONGTIMEOUT)) {
goto done;
}
FD_ZERO(&read_fds);
FD_SET(sock, &read_fds);
timeout.tv_sec = fastlookup ? MT_MNDP_TIMEOUT : MT_MNDP_LONGTIMEOUT;
timeout.tv_usec = 0;
select(sock + 1, &read_fds, NULL, NULL, &timeout);
if (!FD_ISSET(sock, &read_fds)) {
goto done;
}
/* Read UDP packet */
length = recvfrom(sock, buff, sizeof(buff), 0, 0, 0);
if (length < 0) {
goto done;
}
/* Parse MNDP packet */
packet = parse_mndp(buff, length);
if (packet != NULL) {
if (strcasecmp(identity, packet->identity) == 0) {
memcpy(mac, packet->address, ETH_ALEN);
close(sock);
return 1;
}
}
}
done:
close(sock);
return 0;
}
/*
* This function accepts either a full MAC address using : or - as seperators.
* Or a router hostname. The hostname will be searched for via MNDP broadcast packets.
*/
int query_mndp_or_mac(char *address, unsigned char *dstmac, int verbose) {
char *p = address;
int colons = 0;
int dashs = 0;
while (*p++) {
if (*p == ':') {
colons++;
}
else if (*p == '-') {
dashs++;
}
}
/*
* Windows users often enter macs with dash instead
* of colon.
*/
if (colons == 0 && dashs == 5) {
p = address;
while (*p++) {
if (*p == '-') {
*p = ':';
}
}
colons = dashs;
}
if (colons != 5) {
/*
* Not a valid mac-address.
* Search for Router by identity name, using MNDP
*/
if (verbose) {
fprintf(stderr, _("Searching for '%s'..."), address);
}
if (!query_mndp(address, dstmac)) {
if (verbose) {
fprintf(stderr, _("not found\n"));
}
return 0;
}
/* Router found, display mac and continue */
if (verbose) {
fprintf(stderr, _("found\n"));
}
} else {
/* Convert mac address string to ether_addr struct */
#if defined(__APPLE__)
struct ether_addr* dstmac_buf = ether_aton(address);
memcpy(dstmac, dstmac_buf, sizeof(struct ether_addr));
#else
ether_aton_r(address, (struct ether_addr *)dstmac);
#endif
}
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5252_2 |
crossvul-cpp_data_bad_4888_0 | /*
* Driver for Cadence QSPI Controller
*
* Copyright Altera Corporation (C) 2012-2014. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 <linux/clk.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/spi-nor.h>
#include <linux/of_device.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/spi/spi.h>
#include <linux/timer.h>
#define CQSPI_NAME "cadence-qspi"
#define CQSPI_MAX_CHIPSELECT 16
struct cqspi_st;
struct cqspi_flash_pdata {
struct spi_nor nor;
struct cqspi_st *cqspi;
u32 clk_rate;
u32 read_delay;
u32 tshsl_ns;
u32 tsd2d_ns;
u32 tchsh_ns;
u32 tslch_ns;
u8 inst_width;
u8 addr_width;
u8 data_width;
u8 cs;
bool registered;
};
struct cqspi_st {
struct platform_device *pdev;
struct clk *clk;
unsigned int sclk;
void __iomem *iobase;
void __iomem *ahb_base;
struct completion transfer_complete;
struct mutex bus_mutex;
int current_cs;
int current_page_size;
int current_erase_size;
int current_addr_width;
unsigned long master_ref_clk_hz;
bool is_decoded_cs;
u32 fifo_depth;
u32 fifo_width;
u32 trigger_address;
struct cqspi_flash_pdata f_pdata[CQSPI_MAX_CHIPSELECT];
};
/* Operation timeout value */
#define CQSPI_TIMEOUT_MS 500
#define CQSPI_READ_TIMEOUT_MS 10
/* Instruction type */
#define CQSPI_INST_TYPE_SINGLE 0
#define CQSPI_INST_TYPE_DUAL 1
#define CQSPI_INST_TYPE_QUAD 2
#define CQSPI_DUMMY_CLKS_PER_BYTE 8
#define CQSPI_DUMMY_BYTES_MAX 4
#define CQSPI_DUMMY_CLKS_MAX 31
#define CQSPI_STIG_DATA_LEN_MAX 8
/* Register map */
#define CQSPI_REG_CONFIG 0x00
#define CQSPI_REG_CONFIG_ENABLE_MASK BIT(0)
#define CQSPI_REG_CONFIG_DECODE_MASK BIT(9)
#define CQSPI_REG_CONFIG_CHIPSELECT_LSB 10
#define CQSPI_REG_CONFIG_DMA_MASK BIT(15)
#define CQSPI_REG_CONFIG_BAUD_LSB 19
#define CQSPI_REG_CONFIG_IDLE_LSB 31
#define CQSPI_REG_CONFIG_CHIPSELECT_MASK 0xF
#define CQSPI_REG_CONFIG_BAUD_MASK 0xF
#define CQSPI_REG_RD_INSTR 0x04
#define CQSPI_REG_RD_INSTR_OPCODE_LSB 0
#define CQSPI_REG_RD_INSTR_TYPE_INSTR_LSB 8
#define CQSPI_REG_RD_INSTR_TYPE_ADDR_LSB 12
#define CQSPI_REG_RD_INSTR_TYPE_DATA_LSB 16
#define CQSPI_REG_RD_INSTR_MODE_EN_LSB 20
#define CQSPI_REG_RD_INSTR_DUMMY_LSB 24
#define CQSPI_REG_RD_INSTR_TYPE_INSTR_MASK 0x3
#define CQSPI_REG_RD_INSTR_TYPE_ADDR_MASK 0x3
#define CQSPI_REG_RD_INSTR_TYPE_DATA_MASK 0x3
#define CQSPI_REG_RD_INSTR_DUMMY_MASK 0x1F
#define CQSPI_REG_WR_INSTR 0x08
#define CQSPI_REG_WR_INSTR_OPCODE_LSB 0
#define CQSPI_REG_WR_INSTR_TYPE_ADDR_LSB 12
#define CQSPI_REG_WR_INSTR_TYPE_DATA_LSB 16
#define CQSPI_REG_DELAY 0x0C
#define CQSPI_REG_DELAY_TSLCH_LSB 0
#define CQSPI_REG_DELAY_TCHSH_LSB 8
#define CQSPI_REG_DELAY_TSD2D_LSB 16
#define CQSPI_REG_DELAY_TSHSL_LSB 24
#define CQSPI_REG_DELAY_TSLCH_MASK 0xFF
#define CQSPI_REG_DELAY_TCHSH_MASK 0xFF
#define CQSPI_REG_DELAY_TSD2D_MASK 0xFF
#define CQSPI_REG_DELAY_TSHSL_MASK 0xFF
#define CQSPI_REG_READCAPTURE 0x10
#define CQSPI_REG_READCAPTURE_BYPASS_LSB 0
#define CQSPI_REG_READCAPTURE_DELAY_LSB 1
#define CQSPI_REG_READCAPTURE_DELAY_MASK 0xF
#define CQSPI_REG_SIZE 0x14
#define CQSPI_REG_SIZE_ADDRESS_LSB 0
#define CQSPI_REG_SIZE_PAGE_LSB 4
#define CQSPI_REG_SIZE_BLOCK_LSB 16
#define CQSPI_REG_SIZE_ADDRESS_MASK 0xF
#define CQSPI_REG_SIZE_PAGE_MASK 0xFFF
#define CQSPI_REG_SIZE_BLOCK_MASK 0x3F
#define CQSPI_REG_SRAMPARTITION 0x18
#define CQSPI_REG_INDIRECTTRIGGER 0x1C
#define CQSPI_REG_DMA 0x20
#define CQSPI_REG_DMA_SINGLE_LSB 0
#define CQSPI_REG_DMA_BURST_LSB 8
#define CQSPI_REG_DMA_SINGLE_MASK 0xFF
#define CQSPI_REG_DMA_BURST_MASK 0xFF
#define CQSPI_REG_REMAP 0x24
#define CQSPI_REG_MODE_BIT 0x28
#define CQSPI_REG_SDRAMLEVEL 0x2C
#define CQSPI_REG_SDRAMLEVEL_RD_LSB 0
#define CQSPI_REG_SDRAMLEVEL_WR_LSB 16
#define CQSPI_REG_SDRAMLEVEL_RD_MASK 0xFFFF
#define CQSPI_REG_SDRAMLEVEL_WR_MASK 0xFFFF
#define CQSPI_REG_IRQSTATUS 0x40
#define CQSPI_REG_IRQMASK 0x44
#define CQSPI_REG_INDIRECTRD 0x60
#define CQSPI_REG_INDIRECTRD_START_MASK BIT(0)
#define CQSPI_REG_INDIRECTRD_CANCEL_MASK BIT(1)
#define CQSPI_REG_INDIRECTRD_DONE_MASK BIT(5)
#define CQSPI_REG_INDIRECTRDWATERMARK 0x64
#define CQSPI_REG_INDIRECTRDSTARTADDR 0x68
#define CQSPI_REG_INDIRECTRDBYTES 0x6C
#define CQSPI_REG_CMDCTRL 0x90
#define CQSPI_REG_CMDCTRL_EXECUTE_MASK BIT(0)
#define CQSPI_REG_CMDCTRL_INPROGRESS_MASK BIT(1)
#define CQSPI_REG_CMDCTRL_WR_BYTES_LSB 12
#define CQSPI_REG_CMDCTRL_WR_EN_LSB 15
#define CQSPI_REG_CMDCTRL_ADD_BYTES_LSB 16
#define CQSPI_REG_CMDCTRL_ADDR_EN_LSB 19
#define CQSPI_REG_CMDCTRL_RD_BYTES_LSB 20
#define CQSPI_REG_CMDCTRL_RD_EN_LSB 23
#define CQSPI_REG_CMDCTRL_OPCODE_LSB 24
#define CQSPI_REG_CMDCTRL_WR_BYTES_MASK 0x7
#define CQSPI_REG_CMDCTRL_ADD_BYTES_MASK 0x3
#define CQSPI_REG_CMDCTRL_RD_BYTES_MASK 0x7
#define CQSPI_REG_INDIRECTWR 0x70
#define CQSPI_REG_INDIRECTWR_START_MASK BIT(0)
#define CQSPI_REG_INDIRECTWR_CANCEL_MASK BIT(1)
#define CQSPI_REG_INDIRECTWR_DONE_MASK BIT(5)
#define CQSPI_REG_INDIRECTWRWATERMARK 0x74
#define CQSPI_REG_INDIRECTWRSTARTADDR 0x78
#define CQSPI_REG_INDIRECTWRBYTES 0x7C
#define CQSPI_REG_CMDADDRESS 0x94
#define CQSPI_REG_CMDREADDATALOWER 0xA0
#define CQSPI_REG_CMDREADDATAUPPER 0xA4
#define CQSPI_REG_CMDWRITEDATALOWER 0xA8
#define CQSPI_REG_CMDWRITEDATAUPPER 0xAC
/* Interrupt status bits */
#define CQSPI_REG_IRQ_MODE_ERR BIT(0)
#define CQSPI_REG_IRQ_UNDERFLOW BIT(1)
#define CQSPI_REG_IRQ_IND_COMP BIT(2)
#define CQSPI_REG_IRQ_IND_RD_REJECT BIT(3)
#define CQSPI_REG_IRQ_WR_PROTECTED_ERR BIT(4)
#define CQSPI_REG_IRQ_ILLEGAL_AHB_ERR BIT(5)
#define CQSPI_REG_IRQ_WATERMARK BIT(6)
#define CQSPI_REG_IRQ_IND_SRAM_FULL BIT(12)
#define CQSPI_IRQ_MASK_RD (CQSPI_REG_IRQ_WATERMARK | \
CQSPI_REG_IRQ_IND_SRAM_FULL | \
CQSPI_REG_IRQ_IND_COMP)
#define CQSPI_IRQ_MASK_WR (CQSPI_REG_IRQ_IND_COMP | \
CQSPI_REG_IRQ_WATERMARK | \
CQSPI_REG_IRQ_UNDERFLOW)
#define CQSPI_IRQ_STATUS_MASK 0x1FFFF
static int cqspi_wait_for_bit(void __iomem *reg, const u32 mask, bool clear)
{
unsigned long end = jiffies + msecs_to_jiffies(CQSPI_TIMEOUT_MS);
u32 val;
while (1) {
val = readl(reg);
if (clear)
val = ~val;
val &= mask;
if (val == mask)
return 0;
if (time_after(jiffies, end))
return -ETIMEDOUT;
}
}
static bool cqspi_is_idle(struct cqspi_st *cqspi)
{
u32 reg = readl(cqspi->iobase + CQSPI_REG_CONFIG);
return reg & (1 << CQSPI_REG_CONFIG_IDLE_LSB);
}
static u32 cqspi_get_rd_sram_level(struct cqspi_st *cqspi)
{
u32 reg = readl(cqspi->iobase + CQSPI_REG_SDRAMLEVEL);
reg >>= CQSPI_REG_SDRAMLEVEL_RD_LSB;
return reg & CQSPI_REG_SDRAMLEVEL_RD_MASK;
}
static irqreturn_t cqspi_irq_handler(int this_irq, void *dev)
{
struct cqspi_st *cqspi = dev;
unsigned int irq_status;
/* Read interrupt status */
irq_status = readl(cqspi->iobase + CQSPI_REG_IRQSTATUS);
/* Clear interrupt */
writel(irq_status, cqspi->iobase + CQSPI_REG_IRQSTATUS);
irq_status &= CQSPI_IRQ_MASK_RD | CQSPI_IRQ_MASK_WR;
if (irq_status)
complete(&cqspi->transfer_complete);
return IRQ_HANDLED;
}
static unsigned int cqspi_calc_rdreg(struct spi_nor *nor, const u8 opcode)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
u32 rdreg = 0;
rdreg |= f_pdata->inst_width << CQSPI_REG_RD_INSTR_TYPE_INSTR_LSB;
rdreg |= f_pdata->addr_width << CQSPI_REG_RD_INSTR_TYPE_ADDR_LSB;
rdreg |= f_pdata->data_width << CQSPI_REG_RD_INSTR_TYPE_DATA_LSB;
return rdreg;
}
static int cqspi_wait_idle(struct cqspi_st *cqspi)
{
const unsigned int poll_idle_retry = 3;
unsigned int count = 0;
unsigned long timeout;
timeout = jiffies + msecs_to_jiffies(CQSPI_TIMEOUT_MS);
while (1) {
/*
* Read few times in succession to ensure the controller
* is indeed idle, that is, the bit does not transition
* low again.
*/
if (cqspi_is_idle(cqspi))
count++;
else
count = 0;
if (count >= poll_idle_retry)
return 0;
if (time_after(jiffies, timeout)) {
/* Timeout, in busy mode. */
dev_err(&cqspi->pdev->dev,
"QSPI is still busy after %dms timeout.\n",
CQSPI_TIMEOUT_MS);
return -ETIMEDOUT;
}
cpu_relax();
}
}
static int cqspi_exec_flash_cmd(struct cqspi_st *cqspi, unsigned int reg)
{
void __iomem *reg_base = cqspi->iobase;
int ret;
/* Write the CMDCTRL without start execution. */
writel(reg, reg_base + CQSPI_REG_CMDCTRL);
/* Start execute */
reg |= CQSPI_REG_CMDCTRL_EXECUTE_MASK;
writel(reg, reg_base + CQSPI_REG_CMDCTRL);
/* Polling for completion. */
ret = cqspi_wait_for_bit(reg_base + CQSPI_REG_CMDCTRL,
CQSPI_REG_CMDCTRL_INPROGRESS_MASK, 1);
if (ret) {
dev_err(&cqspi->pdev->dev,
"Flash command execution timed out.\n");
return ret;
}
/* Polling QSPI idle status. */
return cqspi_wait_idle(cqspi);
}
static int cqspi_command_read(struct spi_nor *nor,
const u8 *txbuf, const unsigned n_tx,
u8 *rxbuf, const unsigned n_rx)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int rdreg;
unsigned int reg;
unsigned int read_len;
int status;
if (!n_rx || n_rx > CQSPI_STIG_DATA_LEN_MAX || !rxbuf) {
dev_err(nor->dev, "Invalid input argument, len %d rxbuf 0x%p\n",
n_rx, rxbuf);
return -EINVAL;
}
reg = txbuf[0] << CQSPI_REG_CMDCTRL_OPCODE_LSB;
rdreg = cqspi_calc_rdreg(nor, txbuf[0]);
writel(rdreg, reg_base + CQSPI_REG_RD_INSTR);
reg |= (0x1 << CQSPI_REG_CMDCTRL_RD_EN_LSB);
/* 0 means 1 byte. */
reg |= (((n_rx - 1) & CQSPI_REG_CMDCTRL_RD_BYTES_MASK)
<< CQSPI_REG_CMDCTRL_RD_BYTES_LSB);
status = cqspi_exec_flash_cmd(cqspi, reg);
if (status)
return status;
reg = readl(reg_base + CQSPI_REG_CMDREADDATALOWER);
/* Put the read value into rx_buf */
read_len = (n_rx > 4) ? 4 : n_rx;
memcpy(rxbuf, ®, read_len);
rxbuf += read_len;
if (n_rx > 4) {
reg = readl(reg_base + CQSPI_REG_CMDREADDATAUPPER);
read_len = n_rx - read_len;
memcpy(rxbuf, ®, read_len);
}
return 0;
}
static int cqspi_command_write(struct spi_nor *nor, const u8 opcode,
const u8 *txbuf, const unsigned n_tx)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int reg;
unsigned int data;
int ret;
if (n_tx > 4 || (n_tx && !txbuf)) {
dev_err(nor->dev,
"Invalid input argument, cmdlen %d txbuf 0x%p\n",
n_tx, txbuf);
return -EINVAL;
}
reg = opcode << CQSPI_REG_CMDCTRL_OPCODE_LSB;
if (n_tx) {
reg |= (0x1 << CQSPI_REG_CMDCTRL_WR_EN_LSB);
reg |= ((n_tx - 1) & CQSPI_REG_CMDCTRL_WR_BYTES_MASK)
<< CQSPI_REG_CMDCTRL_WR_BYTES_LSB;
data = 0;
memcpy(&data, txbuf, n_tx);
writel(data, reg_base + CQSPI_REG_CMDWRITEDATALOWER);
}
ret = cqspi_exec_flash_cmd(cqspi, reg);
return ret;
}
static int cqspi_command_write_addr(struct spi_nor *nor,
const u8 opcode, const unsigned int addr)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int reg;
reg = opcode << CQSPI_REG_CMDCTRL_OPCODE_LSB;
reg |= (0x1 << CQSPI_REG_CMDCTRL_ADDR_EN_LSB);
reg |= ((nor->addr_width - 1) & CQSPI_REG_CMDCTRL_ADD_BYTES_MASK)
<< CQSPI_REG_CMDCTRL_ADD_BYTES_LSB;
writel(addr, reg_base + CQSPI_REG_CMDADDRESS);
return cqspi_exec_flash_cmd(cqspi, reg);
}
static int cqspi_indirect_read_setup(struct spi_nor *nor,
const unsigned int from_addr)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int dummy_clk = 0;
unsigned int reg;
writel(from_addr, reg_base + CQSPI_REG_INDIRECTRDSTARTADDR);
reg = nor->read_opcode << CQSPI_REG_RD_INSTR_OPCODE_LSB;
reg |= cqspi_calc_rdreg(nor, nor->read_opcode);
/* Setup dummy clock cycles */
dummy_clk = nor->read_dummy;
if (dummy_clk > CQSPI_DUMMY_CLKS_MAX)
dummy_clk = CQSPI_DUMMY_CLKS_MAX;
if (dummy_clk / 8) {
reg |= (1 << CQSPI_REG_RD_INSTR_MODE_EN_LSB);
/* Set mode bits high to ensure chip doesn't enter XIP */
writel(0xFF, reg_base + CQSPI_REG_MODE_BIT);
/* Need to subtract the mode byte (8 clocks). */
if (f_pdata->inst_width != CQSPI_INST_TYPE_QUAD)
dummy_clk -= 8;
if (dummy_clk)
reg |= (dummy_clk & CQSPI_REG_RD_INSTR_DUMMY_MASK)
<< CQSPI_REG_RD_INSTR_DUMMY_LSB;
}
writel(reg, reg_base + CQSPI_REG_RD_INSTR);
/* Set address width */
reg = readl(reg_base + CQSPI_REG_SIZE);
reg &= ~CQSPI_REG_SIZE_ADDRESS_MASK;
reg |= (nor->addr_width - 1);
writel(reg, reg_base + CQSPI_REG_SIZE);
return 0;
}
static int cqspi_indirect_read_execute(struct spi_nor *nor,
u8 *rxbuf, const unsigned n_rx)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
void __iomem *ahb_base = cqspi->ahb_base;
unsigned int remaining = n_rx;
unsigned int bytes_to_read = 0;
int ret = 0;
writel(remaining, reg_base + CQSPI_REG_INDIRECTRDBYTES);
/* Clear all interrupts. */
writel(CQSPI_IRQ_STATUS_MASK, reg_base + CQSPI_REG_IRQSTATUS);
writel(CQSPI_IRQ_MASK_RD, reg_base + CQSPI_REG_IRQMASK);
reinit_completion(&cqspi->transfer_complete);
writel(CQSPI_REG_INDIRECTRD_START_MASK,
reg_base + CQSPI_REG_INDIRECTRD);
while (remaining > 0) {
ret = wait_for_completion_timeout(&cqspi->transfer_complete,
msecs_to_jiffies
(CQSPI_READ_TIMEOUT_MS));
bytes_to_read = cqspi_get_rd_sram_level(cqspi);
if (!ret && bytes_to_read == 0) {
dev_err(nor->dev, "Indirect read timeout, no bytes\n");
ret = -ETIMEDOUT;
goto failrd;
}
while (bytes_to_read != 0) {
bytes_to_read *= cqspi->fifo_width;
bytes_to_read = bytes_to_read > remaining ?
remaining : bytes_to_read;
readsl(ahb_base, rxbuf, DIV_ROUND_UP(bytes_to_read, 4));
rxbuf += bytes_to_read;
remaining -= bytes_to_read;
bytes_to_read = cqspi_get_rd_sram_level(cqspi);
}
if (remaining > 0)
reinit_completion(&cqspi->transfer_complete);
}
/* Check indirect done status */
ret = cqspi_wait_for_bit(reg_base + CQSPI_REG_INDIRECTRD,
CQSPI_REG_INDIRECTRD_DONE_MASK, 0);
if (ret) {
dev_err(nor->dev,
"Indirect read completion error (%i)\n", ret);
goto failrd;
}
/* Disable interrupt */
writel(0, reg_base + CQSPI_REG_IRQMASK);
/* Clear indirect completion status */
writel(CQSPI_REG_INDIRECTRD_DONE_MASK, reg_base + CQSPI_REG_INDIRECTRD);
return 0;
failrd:
/* Disable interrupt */
writel(0, reg_base + CQSPI_REG_IRQMASK);
/* Cancel the indirect read */
writel(CQSPI_REG_INDIRECTWR_CANCEL_MASK,
reg_base + CQSPI_REG_INDIRECTRD);
return ret;
}
static int cqspi_indirect_write_setup(struct spi_nor *nor,
const unsigned int to_addr)
{
unsigned int reg;
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
/* Set opcode. */
reg = nor->program_opcode << CQSPI_REG_WR_INSTR_OPCODE_LSB;
writel(reg, reg_base + CQSPI_REG_WR_INSTR);
reg = cqspi_calc_rdreg(nor, nor->program_opcode);
writel(reg, reg_base + CQSPI_REG_RD_INSTR);
writel(to_addr, reg_base + CQSPI_REG_INDIRECTWRSTARTADDR);
reg = readl(reg_base + CQSPI_REG_SIZE);
reg &= ~CQSPI_REG_SIZE_ADDRESS_MASK;
reg |= (nor->addr_width - 1);
writel(reg, reg_base + CQSPI_REG_SIZE);
return 0;
}
static int cqspi_indirect_write_execute(struct spi_nor *nor,
const u8 *txbuf, const unsigned n_tx)
{
const unsigned int page_size = nor->page_size;
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int remaining = n_tx;
unsigned int write_bytes;
int ret;
writel(remaining, reg_base + CQSPI_REG_INDIRECTWRBYTES);
/* Clear all interrupts. */
writel(CQSPI_IRQ_STATUS_MASK, reg_base + CQSPI_REG_IRQSTATUS);
writel(CQSPI_IRQ_MASK_WR, reg_base + CQSPI_REG_IRQMASK);
reinit_completion(&cqspi->transfer_complete);
writel(CQSPI_REG_INDIRECTWR_START_MASK,
reg_base + CQSPI_REG_INDIRECTWR);
while (remaining > 0) {
write_bytes = remaining > page_size ? page_size : remaining;
writesl(cqspi->ahb_base, txbuf, DIV_ROUND_UP(write_bytes, 4));
ret = wait_for_completion_timeout(&cqspi->transfer_complete,
msecs_to_jiffies
(CQSPI_TIMEOUT_MS));
if (!ret) {
dev_err(nor->dev, "Indirect write timeout\n");
ret = -ETIMEDOUT;
goto failwr;
}
txbuf += write_bytes;
remaining -= write_bytes;
if (remaining > 0)
reinit_completion(&cqspi->transfer_complete);
}
/* Check indirect done status */
ret = cqspi_wait_for_bit(reg_base + CQSPI_REG_INDIRECTWR,
CQSPI_REG_INDIRECTWR_DONE_MASK, 0);
if (ret) {
dev_err(nor->dev,
"Indirect write completion error (%i)\n", ret);
goto failwr;
}
/* Disable interrupt. */
writel(0, reg_base + CQSPI_REG_IRQMASK);
/* Clear indirect completion status */
writel(CQSPI_REG_INDIRECTWR_DONE_MASK, reg_base + CQSPI_REG_INDIRECTWR);
cqspi_wait_idle(cqspi);
return 0;
failwr:
/* Disable interrupt. */
writel(0, reg_base + CQSPI_REG_IRQMASK);
/* Cancel the indirect write */
writel(CQSPI_REG_INDIRECTWR_CANCEL_MASK,
reg_base + CQSPI_REG_INDIRECTWR);
return ret;
}
static void cqspi_chipselect(struct spi_nor *nor)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int chip_select = f_pdata->cs;
unsigned int reg;
reg = readl(reg_base + CQSPI_REG_CONFIG);
if (cqspi->is_decoded_cs) {
reg |= CQSPI_REG_CONFIG_DECODE_MASK;
} else {
reg &= ~CQSPI_REG_CONFIG_DECODE_MASK;
/* Convert CS if without decoder.
* CS0 to 4b'1110
* CS1 to 4b'1101
* CS2 to 4b'1011
* CS3 to 4b'0111
*/
chip_select = 0xF & ~(1 << chip_select);
}
reg &= ~(CQSPI_REG_CONFIG_CHIPSELECT_MASK
<< CQSPI_REG_CONFIG_CHIPSELECT_LSB);
reg |= (chip_select & CQSPI_REG_CONFIG_CHIPSELECT_MASK)
<< CQSPI_REG_CONFIG_CHIPSELECT_LSB;
writel(reg, reg_base + CQSPI_REG_CONFIG);
}
static void cqspi_configure_cs_and_sizes(struct spi_nor *nor)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *iobase = cqspi->iobase;
unsigned int reg;
/* configure page size and block size. */
reg = readl(iobase + CQSPI_REG_SIZE);
reg &= ~(CQSPI_REG_SIZE_PAGE_MASK << CQSPI_REG_SIZE_PAGE_LSB);
reg &= ~(CQSPI_REG_SIZE_BLOCK_MASK << CQSPI_REG_SIZE_BLOCK_LSB);
reg &= ~CQSPI_REG_SIZE_ADDRESS_MASK;
reg |= (nor->page_size << CQSPI_REG_SIZE_PAGE_LSB);
reg |= (ilog2(nor->mtd.erasesize) << CQSPI_REG_SIZE_BLOCK_LSB);
reg |= (nor->addr_width - 1);
writel(reg, iobase + CQSPI_REG_SIZE);
/* configure the chip select */
cqspi_chipselect(nor);
/* Store the new configuration of the controller */
cqspi->current_page_size = nor->page_size;
cqspi->current_erase_size = nor->mtd.erasesize;
cqspi->current_addr_width = nor->addr_width;
}
static unsigned int calculate_ticks_for_ns(const unsigned int ref_clk_hz,
const unsigned int ns_val)
{
unsigned int ticks;
ticks = ref_clk_hz / 1000; /* kHz */
ticks = DIV_ROUND_UP(ticks * ns_val, 1000000);
return ticks;
}
static void cqspi_delay(struct spi_nor *nor)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *iobase = cqspi->iobase;
const unsigned int ref_clk_hz = cqspi->master_ref_clk_hz;
unsigned int tshsl, tchsh, tslch, tsd2d;
unsigned int reg;
unsigned int tsclk;
/* calculate the number of ref ticks for one sclk tick */
tsclk = DIV_ROUND_UP(ref_clk_hz, cqspi->sclk);
tshsl = calculate_ticks_for_ns(ref_clk_hz, f_pdata->tshsl_ns);
/* this particular value must be at least one sclk */
if (tshsl < tsclk)
tshsl = tsclk;
tchsh = calculate_ticks_for_ns(ref_clk_hz, f_pdata->tchsh_ns);
tslch = calculate_ticks_for_ns(ref_clk_hz, f_pdata->tslch_ns);
tsd2d = calculate_ticks_for_ns(ref_clk_hz, f_pdata->tsd2d_ns);
reg = (tshsl & CQSPI_REG_DELAY_TSHSL_MASK)
<< CQSPI_REG_DELAY_TSHSL_LSB;
reg |= (tchsh & CQSPI_REG_DELAY_TCHSH_MASK)
<< CQSPI_REG_DELAY_TCHSH_LSB;
reg |= (tslch & CQSPI_REG_DELAY_TSLCH_MASK)
<< CQSPI_REG_DELAY_TSLCH_LSB;
reg |= (tsd2d & CQSPI_REG_DELAY_TSD2D_MASK)
<< CQSPI_REG_DELAY_TSD2D_LSB;
writel(reg, iobase + CQSPI_REG_DELAY);
}
static void cqspi_config_baudrate_div(struct cqspi_st *cqspi)
{
const unsigned int ref_clk_hz = cqspi->master_ref_clk_hz;
void __iomem *reg_base = cqspi->iobase;
u32 reg, div;
/* Recalculate the baudrate divisor based on QSPI specification. */
div = DIV_ROUND_UP(ref_clk_hz, 2 * cqspi->sclk) - 1;
reg = readl(reg_base + CQSPI_REG_CONFIG);
reg &= ~(CQSPI_REG_CONFIG_BAUD_MASK << CQSPI_REG_CONFIG_BAUD_LSB);
reg |= (div & CQSPI_REG_CONFIG_BAUD_MASK) << CQSPI_REG_CONFIG_BAUD_LSB;
writel(reg, reg_base + CQSPI_REG_CONFIG);
}
static void cqspi_readdata_capture(struct cqspi_st *cqspi,
const unsigned int bypass,
const unsigned int delay)
{
void __iomem *reg_base = cqspi->iobase;
unsigned int reg;
reg = readl(reg_base + CQSPI_REG_READCAPTURE);
if (bypass)
reg |= (1 << CQSPI_REG_READCAPTURE_BYPASS_LSB);
else
reg &= ~(1 << CQSPI_REG_READCAPTURE_BYPASS_LSB);
reg &= ~(CQSPI_REG_READCAPTURE_DELAY_MASK
<< CQSPI_REG_READCAPTURE_DELAY_LSB);
reg |= (delay & CQSPI_REG_READCAPTURE_DELAY_MASK)
<< CQSPI_REG_READCAPTURE_DELAY_LSB;
writel(reg, reg_base + CQSPI_REG_READCAPTURE);
}
static void cqspi_controller_enable(struct cqspi_st *cqspi, bool enable)
{
void __iomem *reg_base = cqspi->iobase;
unsigned int reg;
reg = readl(reg_base + CQSPI_REG_CONFIG);
if (enable)
reg |= CQSPI_REG_CONFIG_ENABLE_MASK;
else
reg &= ~CQSPI_REG_CONFIG_ENABLE_MASK;
writel(reg, reg_base + CQSPI_REG_CONFIG);
}
static void cqspi_configure(struct spi_nor *nor)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
const unsigned int sclk = f_pdata->clk_rate;
int switch_cs = (cqspi->current_cs != f_pdata->cs);
int switch_ck = (cqspi->sclk != sclk);
if ((cqspi->current_page_size != nor->page_size) ||
(cqspi->current_erase_size != nor->mtd.erasesize) ||
(cqspi->current_addr_width != nor->addr_width))
switch_cs = 1;
if (switch_cs || switch_ck)
cqspi_controller_enable(cqspi, 0);
/* Switch chip select. */
if (switch_cs) {
cqspi->current_cs = f_pdata->cs;
cqspi_configure_cs_and_sizes(nor);
}
/* Setup baudrate divisor and delays */
if (switch_ck) {
cqspi->sclk = sclk;
cqspi_config_baudrate_div(cqspi);
cqspi_delay(nor);
cqspi_readdata_capture(cqspi, 1, f_pdata->read_delay);
}
if (switch_cs || switch_ck)
cqspi_controller_enable(cqspi, 1);
}
static int cqspi_set_protocol(struct spi_nor *nor, const int read)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
f_pdata->inst_width = CQSPI_INST_TYPE_SINGLE;
f_pdata->addr_width = CQSPI_INST_TYPE_SINGLE;
f_pdata->data_width = CQSPI_INST_TYPE_SINGLE;
if (read) {
switch (nor->flash_read) {
case SPI_NOR_NORMAL:
case SPI_NOR_FAST:
f_pdata->data_width = CQSPI_INST_TYPE_SINGLE;
break;
case SPI_NOR_DUAL:
f_pdata->data_width = CQSPI_INST_TYPE_DUAL;
break;
case SPI_NOR_QUAD:
f_pdata->data_width = CQSPI_INST_TYPE_QUAD;
break;
default:
return -EINVAL;
}
}
cqspi_configure(nor);
return 0;
}
static ssize_t cqspi_write(struct spi_nor *nor, loff_t to,
size_t len, const u_char *buf)
{
int ret;
ret = cqspi_set_protocol(nor, 0);
if (ret)
return ret;
ret = cqspi_indirect_write_setup(nor, to);
if (ret)
return ret;
ret = cqspi_indirect_write_execute(nor, buf, len);
if (ret)
return ret;
return (ret < 0) ? ret : len;
}
static ssize_t cqspi_read(struct spi_nor *nor, loff_t from,
size_t len, u_char *buf)
{
int ret;
ret = cqspi_set_protocol(nor, 1);
if (ret)
return ret;
ret = cqspi_indirect_read_setup(nor, from);
if (ret)
return ret;
ret = cqspi_indirect_read_execute(nor, buf, len);
if (ret)
return ret;
return (ret < 0) ? ret : len;
}
static int cqspi_erase(struct spi_nor *nor, loff_t offs)
{
int ret;
ret = cqspi_set_protocol(nor, 0);
if (ret)
return ret;
/* Send write enable, then erase commands. */
ret = nor->write_reg(nor, SPINOR_OP_WREN, NULL, 0);
if (ret)
return ret;
/* Set up command buffer. */
ret = cqspi_command_write_addr(nor, nor->erase_opcode, offs);
if (ret)
return ret;
return 0;
}
static int cqspi_prep(struct spi_nor *nor, enum spi_nor_ops ops)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
mutex_lock(&cqspi->bus_mutex);
return 0;
}
static void cqspi_unprep(struct spi_nor *nor, enum spi_nor_ops ops)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
mutex_unlock(&cqspi->bus_mutex);
}
static int cqspi_read_reg(struct spi_nor *nor, u8 opcode, u8 *buf, int len)
{
int ret;
ret = cqspi_set_protocol(nor, 0);
if (!ret)
ret = cqspi_command_read(nor, &opcode, 1, buf, len);
return ret;
}
static int cqspi_write_reg(struct spi_nor *nor, u8 opcode, u8 *buf, int len)
{
int ret;
ret = cqspi_set_protocol(nor, 0);
if (!ret)
ret = cqspi_command_write(nor, opcode, buf, len);
return ret;
}
static int cqspi_of_get_flash_pdata(struct platform_device *pdev,
struct cqspi_flash_pdata *f_pdata,
struct device_node *np)
{
if (of_property_read_u32(np, "cdns,read-delay", &f_pdata->read_delay)) {
dev_err(&pdev->dev, "couldn't determine read-delay\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,tshsl-ns", &f_pdata->tshsl_ns)) {
dev_err(&pdev->dev, "couldn't determine tshsl-ns\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,tsd2d-ns", &f_pdata->tsd2d_ns)) {
dev_err(&pdev->dev, "couldn't determine tsd2d-ns\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,tchsh-ns", &f_pdata->tchsh_ns)) {
dev_err(&pdev->dev, "couldn't determine tchsh-ns\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,tslch-ns", &f_pdata->tslch_ns)) {
dev_err(&pdev->dev, "couldn't determine tslch-ns\n");
return -ENXIO;
}
if (of_property_read_u32(np, "spi-max-frequency", &f_pdata->clk_rate)) {
dev_err(&pdev->dev, "couldn't determine spi-max-frequency\n");
return -ENXIO;
}
return 0;
}
static int cqspi_of_get_pdata(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct cqspi_st *cqspi = platform_get_drvdata(pdev);
cqspi->is_decoded_cs = of_property_read_bool(np, "cdns,is-decoded-cs");
if (of_property_read_u32(np, "cdns,fifo-depth", &cqspi->fifo_depth)) {
dev_err(&pdev->dev, "couldn't determine fifo-depth\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,fifo-width", &cqspi->fifo_width)) {
dev_err(&pdev->dev, "couldn't determine fifo-width\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,trigger-address",
&cqspi->trigger_address)) {
dev_err(&pdev->dev, "couldn't determine trigger-address\n");
return -ENXIO;
}
return 0;
}
static void cqspi_controller_init(struct cqspi_st *cqspi)
{
cqspi_controller_enable(cqspi, 0);
/* Configure the remap address register, no remap */
writel(0, cqspi->iobase + CQSPI_REG_REMAP);
/* Disable all interrupts. */
writel(0, cqspi->iobase + CQSPI_REG_IRQMASK);
/* Configure the SRAM split to 1:1 . */
writel(cqspi->fifo_depth / 2, cqspi->iobase + CQSPI_REG_SRAMPARTITION);
/* Load indirect trigger address. */
writel(cqspi->trigger_address,
cqspi->iobase + CQSPI_REG_INDIRECTTRIGGER);
/* Program read watermark -- 1/2 of the FIFO. */
writel(cqspi->fifo_depth * cqspi->fifo_width / 2,
cqspi->iobase + CQSPI_REG_INDIRECTRDWATERMARK);
/* Program write watermark -- 1/8 of the FIFO. */
writel(cqspi->fifo_depth * cqspi->fifo_width / 8,
cqspi->iobase + CQSPI_REG_INDIRECTWRWATERMARK);
cqspi_controller_enable(cqspi, 1);
}
static int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np)
{
struct platform_device *pdev = cqspi->pdev;
struct device *dev = &pdev->dev;
struct cqspi_flash_pdata *f_pdata;
struct spi_nor *nor;
struct mtd_info *mtd;
unsigned int cs;
int i, ret;
/* Get flash device data */
for_each_available_child_of_node(dev->of_node, np) {
if (of_property_read_u32(np, "reg", &cs)) {
dev_err(dev, "Couldn't determine chip select.\n");
goto err;
}
if (cs > CQSPI_MAX_CHIPSELECT) {
dev_err(dev, "Chip select %d out of range.\n", cs);
goto err;
}
f_pdata = &cqspi->f_pdata[cs];
f_pdata->cqspi = cqspi;
f_pdata->cs = cs;
ret = cqspi_of_get_flash_pdata(pdev, f_pdata, np);
if (ret)
goto err;
nor = &f_pdata->nor;
mtd = &nor->mtd;
mtd->priv = nor;
nor->dev = dev;
spi_nor_set_flash_node(nor, np);
nor->priv = f_pdata;
nor->read_reg = cqspi_read_reg;
nor->write_reg = cqspi_write_reg;
nor->read = cqspi_read;
nor->write = cqspi_write;
nor->erase = cqspi_erase;
nor->prepare = cqspi_prep;
nor->unprepare = cqspi_unprep;
mtd->name = devm_kasprintf(dev, GFP_KERNEL, "%s.%d",
dev_name(dev), cs);
if (!mtd->name) {
ret = -ENOMEM;
goto err;
}
ret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD);
if (ret)
goto err;
ret = mtd_device_register(mtd, NULL, 0);
if (ret)
goto err;
f_pdata->registered = true;
}
return 0;
err:
for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++)
if (cqspi->f_pdata[i].registered)
mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd);
return ret;
}
static int cqspi_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct device *dev = &pdev->dev;
struct cqspi_st *cqspi;
struct resource *res;
struct resource *res_ahb;
int ret;
int irq;
cqspi = devm_kzalloc(dev, sizeof(*cqspi), GFP_KERNEL);
if (!cqspi)
return -ENOMEM;
mutex_init(&cqspi->bus_mutex);
cqspi->pdev = pdev;
platform_set_drvdata(pdev, cqspi);
/* Obtain configuration from OF. */
ret = cqspi_of_get_pdata(pdev);
if (ret) {
dev_err(dev, "Cannot get mandatory OF data.\n");
return -ENODEV;
}
/* Obtain QSPI clock. */
cqspi->clk = devm_clk_get(dev, NULL);
if (IS_ERR(cqspi->clk)) {
dev_err(dev, "Cannot claim QSPI clock.\n");
return PTR_ERR(cqspi->clk);
}
/* Obtain and remap controller address. */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
cqspi->iobase = devm_ioremap_resource(dev, res);
if (IS_ERR(cqspi->iobase)) {
dev_err(dev, "Cannot remap controller address.\n");
return PTR_ERR(cqspi->iobase);
}
/* Obtain and remap AHB address. */
res_ahb = platform_get_resource(pdev, IORESOURCE_MEM, 1);
cqspi->ahb_base = devm_ioremap_resource(dev, res_ahb);
if (IS_ERR(cqspi->ahb_base)) {
dev_err(dev, "Cannot remap AHB address.\n");
return PTR_ERR(cqspi->ahb_base);
}
init_completion(&cqspi->transfer_complete);
/* Obtain IRQ line. */
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(dev, "Cannot obtain IRQ.\n");
return -ENXIO;
}
ret = clk_prepare_enable(cqspi->clk);
if (ret) {
dev_err(dev, "Cannot enable QSPI clock.\n");
return ret;
}
cqspi->master_ref_clk_hz = clk_get_rate(cqspi->clk);
ret = devm_request_irq(dev, irq, cqspi_irq_handler, 0,
pdev->name, cqspi);
if (ret) {
dev_err(dev, "Cannot request IRQ.\n");
goto probe_irq_failed;
}
cqspi_wait_idle(cqspi);
cqspi_controller_init(cqspi);
cqspi->current_cs = -1;
cqspi->sclk = 0;
ret = cqspi_setup_flash(cqspi, np);
if (ret) {
dev_err(dev, "Cadence QSPI NOR probe failed %d\n", ret);
goto probe_setup_failed;
}
return ret;
probe_irq_failed:
cqspi_controller_enable(cqspi, 0);
probe_setup_failed:
clk_disable_unprepare(cqspi->clk);
return ret;
}
static int cqspi_remove(struct platform_device *pdev)
{
struct cqspi_st *cqspi = platform_get_drvdata(pdev);
int i;
for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++)
if (cqspi->f_pdata[i].registered)
mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd);
cqspi_controller_enable(cqspi, 0);
clk_disable_unprepare(cqspi->clk);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int cqspi_suspend(struct device *dev)
{
struct cqspi_st *cqspi = dev_get_drvdata(dev);
cqspi_controller_enable(cqspi, 0);
return 0;
}
static int cqspi_resume(struct device *dev)
{
struct cqspi_st *cqspi = dev_get_drvdata(dev);
cqspi_controller_enable(cqspi, 1);
return 0;
}
static const struct dev_pm_ops cqspi__dev_pm_ops = {
.suspend = cqspi_suspend,
.resume = cqspi_resume,
};
#define CQSPI_DEV_PM_OPS (&cqspi__dev_pm_ops)
#else
#define CQSPI_DEV_PM_OPS NULL
#endif
static struct of_device_id const cqspi_dt_ids[] = {
{.compatible = "cdns,qspi-nor",},
{ /* end of table */ }
};
MODULE_DEVICE_TABLE(of, cqspi_dt_ids);
static struct platform_driver cqspi_platform_driver = {
.probe = cqspi_probe,
.remove = cqspi_remove,
.driver = {
.name = CQSPI_NAME,
.pm = CQSPI_DEV_PM_OPS,
.of_match_table = cqspi_dt_ids,
},
};
module_platform_driver(cqspi_platform_driver);
MODULE_DESCRIPTION("Cadence QSPI Controller Driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:" CQSPI_NAME);
MODULE_AUTHOR("Ley Foon Tan <lftan@altera.com>");
MODULE_AUTHOR("Graham Moore <grmoore@opensource.altera.com>");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4888_0 |
crossvul-cpp_data_good_5289_0 | /*
*******************************************************************************
** O.S : Linux
** FILE NAME : arcmsr_hba.c
** BY : Nick Cheng, C.L. Huang
** Description: SCSI RAID Device Driver for Areca RAID Controller
*******************************************************************************
** Copyright (C) 2002 - 2014, Areca Technology Corporation All rights reserved
**
** Web site: www.areca.com.tw
** E-mail: support@areca.com.tw
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License version 2 as
** published by the Free Software Foundation.
** 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.
*******************************************************************************
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING,BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION)HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE)ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************
** For history of changes, see Documentation/scsi/ChangeLog.arcmsr
** Firmware Specification, see Documentation/scsi/arcmsr_spec.txt
*******************************************************************************
*/
#include <linux/module.h>
#include <linux/reboot.h>
#include <linux/spinlock.h>
#include <linux/pci_ids.h>
#include <linux/interrupt.h>
#include <linux/moduleparam.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/timer.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/aer.h>
#include <linux/circ_buf.h>
#include <asm/dma.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_transport.h>
#include <scsi/scsicam.h>
#include "arcmsr.h"
MODULE_AUTHOR("Nick Cheng, C.L. Huang <support@areca.com.tw>");
MODULE_DESCRIPTION("Areca ARC11xx/12xx/16xx/188x SAS/SATA RAID Controller Driver");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_VERSION(ARCMSR_DRIVER_VERSION);
#define ARCMSR_SLEEPTIME 10
#define ARCMSR_RETRYCOUNT 12
static wait_queue_head_t wait_q;
static int arcmsr_iop_message_xfer(struct AdapterControlBlock *acb,
struct scsi_cmnd *cmd);
static int arcmsr_iop_confirm(struct AdapterControlBlock *acb);
static int arcmsr_abort(struct scsi_cmnd *);
static int arcmsr_bus_reset(struct scsi_cmnd *);
static int arcmsr_bios_param(struct scsi_device *sdev,
struct block_device *bdev, sector_t capacity, int *info);
static int arcmsr_queue_command(struct Scsi_Host *h, struct scsi_cmnd *cmd);
static int arcmsr_probe(struct pci_dev *pdev,
const struct pci_device_id *id);
static int arcmsr_suspend(struct pci_dev *pdev, pm_message_t state);
static int arcmsr_resume(struct pci_dev *pdev);
static void arcmsr_remove(struct pci_dev *pdev);
static void arcmsr_shutdown(struct pci_dev *pdev);
static void arcmsr_iop_init(struct AdapterControlBlock *acb);
static void arcmsr_free_ccb_pool(struct AdapterControlBlock *acb);
static u32 arcmsr_disable_outbound_ints(struct AdapterControlBlock *acb);
static void arcmsr_enable_outbound_ints(struct AdapterControlBlock *acb,
u32 intmask_org);
static void arcmsr_stop_adapter_bgrb(struct AdapterControlBlock *acb);
static void arcmsr_hbaA_flush_cache(struct AdapterControlBlock *acb);
static void arcmsr_hbaB_flush_cache(struct AdapterControlBlock *acb);
static void arcmsr_request_device_map(unsigned long pacb);
static void arcmsr_hbaA_request_device_map(struct AdapterControlBlock *acb);
static void arcmsr_hbaB_request_device_map(struct AdapterControlBlock *acb);
static void arcmsr_hbaC_request_device_map(struct AdapterControlBlock *acb);
static void arcmsr_message_isr_bh_fn(struct work_struct *work);
static bool arcmsr_get_firmware_spec(struct AdapterControlBlock *acb);
static void arcmsr_start_adapter_bgrb(struct AdapterControlBlock *acb);
static void arcmsr_hbaC_message_isr(struct AdapterControlBlock *pACB);
static void arcmsr_hbaD_message_isr(struct AdapterControlBlock *acb);
static void arcmsr_hardware_reset(struct AdapterControlBlock *acb);
static const char *arcmsr_info(struct Scsi_Host *);
static irqreturn_t arcmsr_interrupt(struct AdapterControlBlock *acb);
static void arcmsr_free_irq(struct pci_dev *, struct AdapterControlBlock *);
static void arcmsr_wait_firmware_ready(struct AdapterControlBlock *acb);
static int arcmsr_adjust_disk_queue_depth(struct scsi_device *sdev, int queue_depth)
{
if (queue_depth > ARCMSR_MAX_CMD_PERLUN)
queue_depth = ARCMSR_MAX_CMD_PERLUN;
return scsi_change_queue_depth(sdev, queue_depth);
}
static struct scsi_host_template arcmsr_scsi_host_template = {
.module = THIS_MODULE,
.name = "Areca SAS/SATA RAID driver",
.info = arcmsr_info,
.queuecommand = arcmsr_queue_command,
.eh_abort_handler = arcmsr_abort,
.eh_bus_reset_handler = arcmsr_bus_reset,
.bios_param = arcmsr_bios_param,
.change_queue_depth = arcmsr_adjust_disk_queue_depth,
.can_queue = ARCMSR_MAX_OUTSTANDING_CMD,
.this_id = ARCMSR_SCSI_INITIATOR_ID,
.sg_tablesize = ARCMSR_DEFAULT_SG_ENTRIES,
.max_sectors = ARCMSR_MAX_XFER_SECTORS_C,
.cmd_per_lun = ARCMSR_MAX_CMD_PERLUN,
.use_clustering = ENABLE_CLUSTERING,
.shost_attrs = arcmsr_host_attrs,
.no_write_same = 1,
};
static struct pci_device_id arcmsr_device_id_table[] = {
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1110),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1120),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1130),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1160),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1170),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1200),
.driver_data = ACB_ADAPTER_TYPE_B},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1201),
.driver_data = ACB_ADAPTER_TYPE_B},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1202),
.driver_data = ACB_ADAPTER_TYPE_B},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1203),
.driver_data = ACB_ADAPTER_TYPE_B},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1210),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1214),
.driver_data = ACB_ADAPTER_TYPE_D},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1220),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1230),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1260),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1270),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1280),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1380),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1381),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1680),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1681),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1880),
.driver_data = ACB_ADAPTER_TYPE_C},
{0, 0}, /* Terminating entry */
};
MODULE_DEVICE_TABLE(pci, arcmsr_device_id_table);
static struct pci_driver arcmsr_pci_driver = {
.name = "arcmsr",
.id_table = arcmsr_device_id_table,
.probe = arcmsr_probe,
.remove = arcmsr_remove,
.suspend = arcmsr_suspend,
.resume = arcmsr_resume,
.shutdown = arcmsr_shutdown,
};
/*
****************************************************************************
****************************************************************************
*/
static void arcmsr_free_mu(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_B:
case ACB_ADAPTER_TYPE_D: {
dma_free_coherent(&acb->pdev->dev, acb->roundup_ccbsize,
acb->dma_coherent2, acb->dma_coherent_handle2);
break;
}
}
}
static bool arcmsr_remap_pciregion(struct AdapterControlBlock *acb)
{
struct pci_dev *pdev = acb->pdev;
switch (acb->adapter_type){
case ACB_ADAPTER_TYPE_A:{
acb->pmuA = ioremap(pci_resource_start(pdev,0), pci_resource_len(pdev,0));
if (!acb->pmuA) {
printk(KERN_NOTICE "arcmsr%d: memory mapping region fail \n", acb->host->host_no);
return false;
}
break;
}
case ACB_ADAPTER_TYPE_B:{
void __iomem *mem_base0, *mem_base1;
mem_base0 = ioremap(pci_resource_start(pdev, 0), pci_resource_len(pdev, 0));
if (!mem_base0) {
printk(KERN_NOTICE "arcmsr%d: memory mapping region fail \n", acb->host->host_no);
return false;
}
mem_base1 = ioremap(pci_resource_start(pdev, 2), pci_resource_len(pdev, 2));
if (!mem_base1) {
iounmap(mem_base0);
printk(KERN_NOTICE "arcmsr%d: memory mapping region fail \n", acb->host->host_no);
return false;
}
acb->mem_base0 = mem_base0;
acb->mem_base1 = mem_base1;
break;
}
case ACB_ADAPTER_TYPE_C:{
acb->pmuC = ioremap_nocache(pci_resource_start(pdev, 1), pci_resource_len(pdev, 1));
if (!acb->pmuC) {
printk(KERN_NOTICE "arcmsr%d: memory mapping region fail \n", acb->host->host_no);
return false;
}
if (readl(&acb->pmuC->outbound_doorbell) & ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE_DOORBELL_CLEAR, &acb->pmuC->outbound_doorbell_clear);/*clear interrupt*/
return true;
}
break;
}
case ACB_ADAPTER_TYPE_D: {
void __iomem *mem_base0;
unsigned long addr, range, flags;
addr = (unsigned long)pci_resource_start(pdev, 0);
range = pci_resource_len(pdev, 0);
flags = pci_resource_flags(pdev, 0);
mem_base0 = ioremap(addr, range);
if (!mem_base0) {
pr_notice("arcmsr%d: memory mapping region fail\n",
acb->host->host_no);
return false;
}
acb->mem_base0 = mem_base0;
break;
}
}
return true;
}
static void arcmsr_unmap_pciregion(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:{
iounmap(acb->pmuA);
}
break;
case ACB_ADAPTER_TYPE_B:{
iounmap(acb->mem_base0);
iounmap(acb->mem_base1);
}
break;
case ACB_ADAPTER_TYPE_C:{
iounmap(acb->pmuC);
}
break;
case ACB_ADAPTER_TYPE_D:
iounmap(acb->mem_base0);
break;
}
}
static irqreturn_t arcmsr_do_interrupt(int irq, void *dev_id)
{
irqreturn_t handle_state;
struct AdapterControlBlock *acb = dev_id;
handle_state = arcmsr_interrupt(acb);
return handle_state;
}
static int arcmsr_bios_param(struct scsi_device *sdev,
struct block_device *bdev, sector_t capacity, int *geom)
{
int ret, heads, sectors, cylinders, total_capacity;
unsigned char *buffer;/* return copy of block device's partition table */
buffer = scsi_bios_ptable(bdev);
if (buffer) {
ret = scsi_partsize(buffer, capacity, &geom[2], &geom[0], &geom[1]);
kfree(buffer);
if (ret != -1)
return ret;
}
total_capacity = capacity;
heads = 64;
sectors = 32;
cylinders = total_capacity / (heads * sectors);
if (cylinders > 1024) {
heads = 255;
sectors = 63;
cylinders = total_capacity / (heads * sectors);
}
geom[0] = heads;
geom[1] = sectors;
geom[2] = cylinders;
return 0;
}
static uint8_t arcmsr_hbaA_wait_msgint_ready(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
int i;
for (i = 0; i < 2000; i++) {
if (readl(®->outbound_intstatus) &
ARCMSR_MU_OUTBOUND_MESSAGE0_INT) {
writel(ARCMSR_MU_OUTBOUND_MESSAGE0_INT,
®->outbound_intstatus);
return true;
}
msleep(10);
} /* max 20 seconds */
return false;
}
static uint8_t arcmsr_hbaB_wait_msgint_ready(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
int i;
for (i = 0; i < 2000; i++) {
if (readl(reg->iop2drv_doorbell)
& ARCMSR_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_MESSAGE_INT_CLEAR_PATTERN,
reg->iop2drv_doorbell);
writel(ARCMSR_DRV2IOP_END_OF_INTERRUPT,
reg->drv2iop_doorbell);
return true;
}
msleep(10);
} /* max 20 seconds */
return false;
}
static uint8_t arcmsr_hbaC_wait_msgint_ready(struct AdapterControlBlock *pACB)
{
struct MessageUnit_C __iomem *phbcmu = pACB->pmuC;
int i;
for (i = 0; i < 2000; i++) {
if (readl(&phbcmu->outbound_doorbell)
& ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE_DOORBELL_CLEAR,
&phbcmu->outbound_doorbell_clear); /*clear interrupt*/
return true;
}
msleep(10);
} /* max 20 seconds */
return false;
}
static bool arcmsr_hbaD_wait_msgint_ready(struct AdapterControlBlock *pACB)
{
struct MessageUnit_D *reg = pACB->pmuD;
int i;
for (i = 0; i < 2000; i++) {
if (readl(reg->outbound_doorbell)
& ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE,
reg->outbound_doorbell);
return true;
}
msleep(10);
} /* max 20 seconds */
return false;
}
static void arcmsr_hbaA_flush_cache(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
int retry_count = 30;
writel(ARCMSR_INBOUND_MESG0_FLUSH_CACHE, ®->inbound_msgaddr0);
do {
if (arcmsr_hbaA_wait_msgint_ready(acb))
break;
else {
retry_count--;
printk(KERN_NOTICE "arcmsr%d: wait 'flush adapter cache' \
timeout, retry count down = %d \n", acb->host->host_no, retry_count);
}
} while (retry_count != 0);
}
static void arcmsr_hbaB_flush_cache(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
int retry_count = 30;
writel(ARCMSR_MESSAGE_FLUSH_CACHE, reg->drv2iop_doorbell);
do {
if (arcmsr_hbaB_wait_msgint_ready(acb))
break;
else {
retry_count--;
printk(KERN_NOTICE "arcmsr%d: wait 'flush adapter cache' \
timeout,retry count down = %d \n", acb->host->host_no, retry_count);
}
} while (retry_count != 0);
}
static void arcmsr_hbaC_flush_cache(struct AdapterControlBlock *pACB)
{
struct MessageUnit_C __iomem *reg = pACB->pmuC;
int retry_count = 30;/* enlarge wait flush adapter cache time: 10 minute */
writel(ARCMSR_INBOUND_MESG0_FLUSH_CACHE, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
do {
if (arcmsr_hbaC_wait_msgint_ready(pACB)) {
break;
} else {
retry_count--;
printk(KERN_NOTICE "arcmsr%d: wait 'flush adapter cache' \
timeout,retry count down = %d \n", pACB->host->host_no, retry_count);
}
} while (retry_count != 0);
return;
}
static void arcmsr_hbaD_flush_cache(struct AdapterControlBlock *pACB)
{
int retry_count = 15;
struct MessageUnit_D *reg = pACB->pmuD;
writel(ARCMSR_INBOUND_MESG0_FLUSH_CACHE, reg->inbound_msgaddr0);
do {
if (arcmsr_hbaD_wait_msgint_ready(pACB))
break;
retry_count--;
pr_notice("arcmsr%d: wait 'flush adapter "
"cache' timeout, retry count down = %d\n",
pACB->host->host_no, retry_count);
} while (retry_count != 0);
}
static void arcmsr_flush_adapter_cache(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
arcmsr_hbaA_flush_cache(acb);
}
break;
case ACB_ADAPTER_TYPE_B: {
arcmsr_hbaB_flush_cache(acb);
}
break;
case ACB_ADAPTER_TYPE_C: {
arcmsr_hbaC_flush_cache(acb);
}
break;
case ACB_ADAPTER_TYPE_D:
arcmsr_hbaD_flush_cache(acb);
break;
}
}
static bool arcmsr_alloc_io_queue(struct AdapterControlBlock *acb)
{
bool rtn = true;
void *dma_coherent;
dma_addr_t dma_coherent_handle;
struct pci_dev *pdev = acb->pdev;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg;
acb->roundup_ccbsize = roundup(sizeof(struct MessageUnit_B), 32);
dma_coherent = dma_zalloc_coherent(&pdev->dev, acb->roundup_ccbsize,
&dma_coherent_handle, GFP_KERNEL);
if (!dma_coherent) {
pr_notice("arcmsr%d: DMA allocation failed\n", acb->host->host_no);
return false;
}
acb->dma_coherent_handle2 = dma_coherent_handle;
acb->dma_coherent2 = dma_coherent;
reg = (struct MessageUnit_B *)dma_coherent;
acb->pmuB = reg;
if (acb->pdev->device == PCI_DEVICE_ID_ARECA_1203) {
reg->drv2iop_doorbell = MEM_BASE0(ARCMSR_DRV2IOP_DOORBELL_1203);
reg->drv2iop_doorbell_mask = MEM_BASE0(ARCMSR_DRV2IOP_DOORBELL_MASK_1203);
reg->iop2drv_doorbell = MEM_BASE0(ARCMSR_IOP2DRV_DOORBELL_1203);
reg->iop2drv_doorbell_mask = MEM_BASE0(ARCMSR_IOP2DRV_DOORBELL_MASK_1203);
} else {
reg->drv2iop_doorbell = MEM_BASE0(ARCMSR_DRV2IOP_DOORBELL);
reg->drv2iop_doorbell_mask = MEM_BASE0(ARCMSR_DRV2IOP_DOORBELL_MASK);
reg->iop2drv_doorbell = MEM_BASE0(ARCMSR_IOP2DRV_DOORBELL);
reg->iop2drv_doorbell_mask = MEM_BASE0(ARCMSR_IOP2DRV_DOORBELL_MASK);
}
reg->message_wbuffer = MEM_BASE1(ARCMSR_MESSAGE_WBUFFER);
reg->message_rbuffer = MEM_BASE1(ARCMSR_MESSAGE_RBUFFER);
reg->message_rwbuffer = MEM_BASE1(ARCMSR_MESSAGE_RWBUFFER);
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg;
acb->roundup_ccbsize = roundup(sizeof(struct MessageUnit_D), 32);
dma_coherent = dma_zalloc_coherent(&pdev->dev, acb->roundup_ccbsize,
&dma_coherent_handle, GFP_KERNEL);
if (!dma_coherent) {
pr_notice("arcmsr%d: DMA allocation failed\n", acb->host->host_no);
return false;
}
acb->dma_coherent_handle2 = dma_coherent_handle;
acb->dma_coherent2 = dma_coherent;
reg = (struct MessageUnit_D *)dma_coherent;
acb->pmuD = reg;
reg->chip_id = MEM_BASE0(ARCMSR_ARC1214_CHIP_ID);
reg->cpu_mem_config = MEM_BASE0(ARCMSR_ARC1214_CPU_MEMORY_CONFIGURATION);
reg->i2o_host_interrupt_mask = MEM_BASE0(ARCMSR_ARC1214_I2_HOST_INTERRUPT_MASK);
reg->sample_at_reset = MEM_BASE0(ARCMSR_ARC1214_SAMPLE_RESET);
reg->reset_request = MEM_BASE0(ARCMSR_ARC1214_RESET_REQUEST);
reg->host_int_status = MEM_BASE0(ARCMSR_ARC1214_MAIN_INTERRUPT_STATUS);
reg->pcief0_int_enable = MEM_BASE0(ARCMSR_ARC1214_PCIE_F0_INTERRUPT_ENABLE);
reg->inbound_msgaddr0 = MEM_BASE0(ARCMSR_ARC1214_INBOUND_MESSAGE0);
reg->inbound_msgaddr1 = MEM_BASE0(ARCMSR_ARC1214_INBOUND_MESSAGE1);
reg->outbound_msgaddr0 = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_MESSAGE0);
reg->outbound_msgaddr1 = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_MESSAGE1);
reg->inbound_doorbell = MEM_BASE0(ARCMSR_ARC1214_INBOUND_DOORBELL);
reg->outbound_doorbell = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_DOORBELL);
reg->outbound_doorbell_enable = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_DOORBELL_ENABLE);
reg->inboundlist_base_low = MEM_BASE0(ARCMSR_ARC1214_INBOUND_LIST_BASE_LOW);
reg->inboundlist_base_high = MEM_BASE0(ARCMSR_ARC1214_INBOUND_LIST_BASE_HIGH);
reg->inboundlist_write_pointer = MEM_BASE0(ARCMSR_ARC1214_INBOUND_LIST_WRITE_POINTER);
reg->outboundlist_base_low = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_LIST_BASE_LOW);
reg->outboundlist_base_high = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_LIST_BASE_HIGH);
reg->outboundlist_copy_pointer = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_LIST_COPY_POINTER);
reg->outboundlist_read_pointer = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_LIST_READ_POINTER);
reg->outboundlist_interrupt_cause = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_INTERRUPT_CAUSE);
reg->outboundlist_interrupt_enable = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_INTERRUPT_ENABLE);
reg->message_wbuffer = MEM_BASE0(ARCMSR_ARC1214_MESSAGE_WBUFFER);
reg->message_rbuffer = MEM_BASE0(ARCMSR_ARC1214_MESSAGE_RBUFFER);
reg->msgcode_rwbuffer = MEM_BASE0(ARCMSR_ARC1214_MESSAGE_RWBUFFER);
}
break;
default:
break;
}
return rtn;
}
static int arcmsr_alloc_ccb_pool(struct AdapterControlBlock *acb)
{
struct pci_dev *pdev = acb->pdev;
void *dma_coherent;
dma_addr_t dma_coherent_handle;
struct CommandControlBlock *ccb_tmp;
int i = 0, j = 0;
dma_addr_t cdb_phyaddr;
unsigned long roundup_ccbsize;
unsigned long max_xfer_len;
unsigned long max_sg_entrys;
uint32_t firm_config_version;
for (i = 0; i < ARCMSR_MAX_TARGETID; i++)
for (j = 0; j < ARCMSR_MAX_TARGETLUN; j++)
acb->devstate[i][j] = ARECA_RAID_GONE;
max_xfer_len = ARCMSR_MAX_XFER_LEN;
max_sg_entrys = ARCMSR_DEFAULT_SG_ENTRIES;
firm_config_version = acb->firm_cfg_version;
if((firm_config_version & 0xFF) >= 3){
max_xfer_len = (ARCMSR_CDB_SG_PAGE_LENGTH << ((firm_config_version >> 8) & 0xFF)) * 1024;/* max 4M byte */
max_sg_entrys = (max_xfer_len/4096);
}
acb->host->max_sectors = max_xfer_len/512;
acb->host->sg_tablesize = max_sg_entrys;
roundup_ccbsize = roundup(sizeof(struct CommandControlBlock) + (max_sg_entrys - 1) * sizeof(struct SG64ENTRY), 32);
acb->uncache_size = roundup_ccbsize * ARCMSR_MAX_FREECCB_NUM;
dma_coherent = dma_alloc_coherent(&pdev->dev, acb->uncache_size, &dma_coherent_handle, GFP_KERNEL);
if(!dma_coherent){
printk(KERN_NOTICE "arcmsr%d: dma_alloc_coherent got error\n", acb->host->host_no);
return -ENOMEM;
}
acb->dma_coherent = dma_coherent;
acb->dma_coherent_handle = dma_coherent_handle;
memset(dma_coherent, 0, acb->uncache_size);
ccb_tmp = dma_coherent;
acb->vir2phy_offset = (unsigned long)dma_coherent - (unsigned long)dma_coherent_handle;
for(i = 0; i < ARCMSR_MAX_FREECCB_NUM; i++){
cdb_phyaddr = dma_coherent_handle + offsetof(struct CommandControlBlock, arcmsr_cdb);
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:
case ACB_ADAPTER_TYPE_B:
ccb_tmp->cdb_phyaddr = cdb_phyaddr >> 5;
break;
case ACB_ADAPTER_TYPE_C:
case ACB_ADAPTER_TYPE_D:
ccb_tmp->cdb_phyaddr = cdb_phyaddr;
break;
}
acb->pccb_pool[i] = ccb_tmp;
ccb_tmp->acb = acb;
INIT_LIST_HEAD(&ccb_tmp->list);
list_add_tail(&ccb_tmp->list, &acb->ccb_free_list);
ccb_tmp = (struct CommandControlBlock *)((unsigned long)ccb_tmp + roundup_ccbsize);
dma_coherent_handle = dma_coherent_handle + roundup_ccbsize;
}
return 0;
}
static void arcmsr_message_isr_bh_fn(struct work_struct *work)
{
struct AdapterControlBlock *acb = container_of(work,
struct AdapterControlBlock, arcmsr_do_message_isr_bh);
char *acb_dev_map = (char *)acb->device_map;
uint32_t __iomem *signature = NULL;
char __iomem *devicemap = NULL;
int target, lun;
struct scsi_device *psdev;
char diff, temp;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
signature = (uint32_t __iomem *)(®->message_rwbuffer[0]);
devicemap = (char __iomem *)(®->message_rwbuffer[21]);
break;
}
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
signature = (uint32_t __iomem *)(®->message_rwbuffer[0]);
devicemap = (char __iomem *)(®->message_rwbuffer[21]);
break;
}
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
signature = (uint32_t __iomem *)(®->msgcode_rwbuffer[0]);
devicemap = (char __iomem *)(®->msgcode_rwbuffer[21]);
break;
}
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
signature = (uint32_t __iomem *)(®->msgcode_rwbuffer[0]);
devicemap = (char __iomem *)(®->msgcode_rwbuffer[21]);
break;
}
}
atomic_inc(&acb->rq_map_token);
if (readl(signature) != ARCMSR_SIGNATURE_GET_CONFIG)
return;
for (target = 0; target < ARCMSR_MAX_TARGETID - 1;
target++) {
temp = readb(devicemap);
diff = (*acb_dev_map) ^ temp;
if (diff != 0) {
*acb_dev_map = temp;
for (lun = 0; lun < ARCMSR_MAX_TARGETLUN;
lun++) {
if ((diff & 0x01) == 1 &&
(temp & 0x01) == 1) {
scsi_add_device(acb->host,
0, target, lun);
} else if ((diff & 0x01) == 1
&& (temp & 0x01) == 0) {
psdev = scsi_device_lookup(acb->host,
0, target, lun);
if (psdev != NULL) {
scsi_remove_device(psdev);
scsi_device_put(psdev);
}
}
temp >>= 1;
diff >>= 1;
}
}
devicemap++;
acb_dev_map++;
}
}
static int
arcmsr_request_irq(struct pci_dev *pdev, struct AdapterControlBlock *acb)
{
int i, j, r;
struct msix_entry entries[ARCMST_NUM_MSIX_VECTORS];
for (i = 0; i < ARCMST_NUM_MSIX_VECTORS; i++)
entries[i].entry = i;
r = pci_enable_msix_range(pdev, entries, 1, ARCMST_NUM_MSIX_VECTORS);
if (r < 0)
goto msi_int;
acb->msix_vector_count = r;
for (i = 0; i < r; i++) {
if (request_irq(entries[i].vector,
arcmsr_do_interrupt, 0, "arcmsr", acb)) {
pr_warn("arcmsr%d: request_irq =%d failed!\n",
acb->host->host_no, entries[i].vector);
for (j = 0 ; j < i ; j++)
free_irq(entries[j].vector, acb);
pci_disable_msix(pdev);
goto msi_int;
}
acb->entries[i] = entries[i];
}
acb->acb_flags |= ACB_F_MSIX_ENABLED;
pr_info("arcmsr%d: msi-x enabled\n", acb->host->host_no);
return SUCCESS;
msi_int:
if (pci_enable_msi_exact(pdev, 1) < 0)
goto legacy_int;
if (request_irq(pdev->irq, arcmsr_do_interrupt,
IRQF_SHARED, "arcmsr", acb)) {
pr_warn("arcmsr%d: request_irq =%d failed!\n",
acb->host->host_no, pdev->irq);
pci_disable_msi(pdev);
goto legacy_int;
}
acb->acb_flags |= ACB_F_MSI_ENABLED;
pr_info("arcmsr%d: msi enabled\n", acb->host->host_no);
return SUCCESS;
legacy_int:
if (request_irq(pdev->irq, arcmsr_do_interrupt,
IRQF_SHARED, "arcmsr", acb)) {
pr_warn("arcmsr%d: request_irq = %d failed!\n",
acb->host->host_no, pdev->irq);
return FAILED;
}
return SUCCESS;
}
static int arcmsr_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
struct Scsi_Host *host;
struct AdapterControlBlock *acb;
uint8_t bus,dev_fun;
int error;
error = pci_enable_device(pdev);
if(error){
return -ENODEV;
}
host = scsi_host_alloc(&arcmsr_scsi_host_template, sizeof(struct AdapterControlBlock));
if(!host){
goto pci_disable_dev;
}
error = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
if(error){
error = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if(error){
printk(KERN_WARNING
"scsi%d: No suitable DMA mask available\n",
host->host_no);
goto scsi_host_release;
}
}
init_waitqueue_head(&wait_q);
bus = pdev->bus->number;
dev_fun = pdev->devfn;
acb = (struct AdapterControlBlock *) host->hostdata;
memset(acb,0,sizeof(struct AdapterControlBlock));
acb->pdev = pdev;
acb->host = host;
host->max_lun = ARCMSR_MAX_TARGETLUN;
host->max_id = ARCMSR_MAX_TARGETID; /*16:8*/
host->max_cmd_len = 16; /*this is issue of 64bit LBA ,over 2T byte*/
host->can_queue = ARCMSR_MAX_OUTSTANDING_CMD;
host->cmd_per_lun = ARCMSR_MAX_CMD_PERLUN;
host->this_id = ARCMSR_SCSI_INITIATOR_ID;
host->unique_id = (bus << 8) | dev_fun;
pci_set_drvdata(pdev, host);
pci_set_master(pdev);
error = pci_request_regions(pdev, "arcmsr");
if(error){
goto scsi_host_release;
}
spin_lock_init(&acb->eh_lock);
spin_lock_init(&acb->ccblist_lock);
spin_lock_init(&acb->postq_lock);
spin_lock_init(&acb->doneq_lock);
spin_lock_init(&acb->rqbuffer_lock);
spin_lock_init(&acb->wqbuffer_lock);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_RQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->acb_flags &= ~ACB_F_SCSISTOPADAPTER;
INIT_LIST_HEAD(&acb->ccb_free_list);
acb->adapter_type = id->driver_data;
error = arcmsr_remap_pciregion(acb);
if(!error){
goto pci_release_regs;
}
error = arcmsr_alloc_io_queue(acb);
if (!error)
goto unmap_pci_region;
error = arcmsr_get_firmware_spec(acb);
if(!error){
goto free_hbb_mu;
}
error = arcmsr_alloc_ccb_pool(acb);
if(error){
goto free_hbb_mu;
}
error = scsi_add_host(host, &pdev->dev);
if(error){
goto free_ccb_pool;
}
if (arcmsr_request_irq(pdev, acb) == FAILED)
goto scsi_host_remove;
arcmsr_iop_init(acb);
INIT_WORK(&acb->arcmsr_do_message_isr_bh, arcmsr_message_isr_bh_fn);
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
init_timer(&acb->eternal_timer);
acb->eternal_timer.expires = jiffies + msecs_to_jiffies(6 * HZ);
acb->eternal_timer.data = (unsigned long) acb;
acb->eternal_timer.function = &arcmsr_request_device_map;
add_timer(&acb->eternal_timer);
if(arcmsr_alloc_sysfs_attr(acb))
goto out_free_sysfs;
scsi_scan_host(host);
return 0;
out_free_sysfs:
del_timer_sync(&acb->eternal_timer);
flush_work(&acb->arcmsr_do_message_isr_bh);
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
arcmsr_free_irq(pdev, acb);
scsi_host_remove:
scsi_remove_host(host);
free_ccb_pool:
arcmsr_free_ccb_pool(acb);
free_hbb_mu:
arcmsr_free_mu(acb);
unmap_pci_region:
arcmsr_unmap_pciregion(acb);
pci_release_regs:
pci_release_regions(pdev);
scsi_host_release:
scsi_host_put(host);
pci_disable_dev:
pci_disable_device(pdev);
return -ENODEV;
}
static void arcmsr_free_irq(struct pci_dev *pdev,
struct AdapterControlBlock *acb)
{
int i;
if (acb->acb_flags & ACB_F_MSI_ENABLED) {
free_irq(pdev->irq, acb);
pci_disable_msi(pdev);
} else if (acb->acb_flags & ACB_F_MSIX_ENABLED) {
for (i = 0; i < acb->msix_vector_count; i++)
free_irq(acb->entries[i].vector, acb);
pci_disable_msix(pdev);
} else
free_irq(pdev->irq, acb);
}
static int arcmsr_suspend(struct pci_dev *pdev, pm_message_t state)
{
uint32_t intmask_org;
struct Scsi_Host *host = pci_get_drvdata(pdev);
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *)host->hostdata;
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_free_irq(pdev, acb);
del_timer_sync(&acb->eternal_timer);
flush_work(&acb->arcmsr_do_message_isr_bh);
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
pci_set_drvdata(pdev, host);
pci_save_state(pdev);
pci_disable_device(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
static int arcmsr_resume(struct pci_dev *pdev)
{
int error;
struct Scsi_Host *host = pci_get_drvdata(pdev);
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *)host->hostdata;
pci_set_power_state(pdev, PCI_D0);
pci_enable_wake(pdev, PCI_D0, 0);
pci_restore_state(pdev);
if (pci_enable_device(pdev)) {
pr_warn("%s: pci_enable_device error\n", __func__);
return -ENODEV;
}
error = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
if (error) {
error = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (error) {
pr_warn("scsi%d: No suitable DMA mask available\n",
host->host_no);
goto controller_unregister;
}
}
pci_set_master(pdev);
if (arcmsr_request_irq(pdev, acb) == FAILED)
goto controller_stop;
arcmsr_iop_init(acb);
INIT_WORK(&acb->arcmsr_do_message_isr_bh, arcmsr_message_isr_bh_fn);
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
init_timer(&acb->eternal_timer);
acb->eternal_timer.expires = jiffies + msecs_to_jiffies(6 * HZ);
acb->eternal_timer.data = (unsigned long) acb;
acb->eternal_timer.function = &arcmsr_request_device_map;
add_timer(&acb->eternal_timer);
return 0;
controller_stop:
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
controller_unregister:
scsi_remove_host(host);
arcmsr_free_ccb_pool(acb);
arcmsr_unmap_pciregion(acb);
pci_release_regions(pdev);
scsi_host_put(host);
pci_disable_device(pdev);
return -ENODEV;
}
static uint8_t arcmsr_hbaA_abort_allcmd(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
writel(ARCMSR_INBOUND_MESG0_ABORT_CMD, ®->inbound_msgaddr0);
if (!arcmsr_hbaA_wait_msgint_ready(acb)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'abort all outstanding command' timeout\n"
, acb->host->host_no);
return false;
}
return true;
}
static uint8_t arcmsr_hbaB_abort_allcmd(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
writel(ARCMSR_MESSAGE_ABORT_CMD, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'abort all outstanding command' timeout\n"
, acb->host->host_no);
return false;
}
return true;
}
static uint8_t arcmsr_hbaC_abort_allcmd(struct AdapterControlBlock *pACB)
{
struct MessageUnit_C __iomem *reg = pACB->pmuC;
writel(ARCMSR_INBOUND_MESG0_ABORT_CMD, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
if (!arcmsr_hbaC_wait_msgint_ready(pACB)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'abort all outstanding command' timeout\n"
, pACB->host->host_no);
return false;
}
return true;
}
static uint8_t arcmsr_hbaD_abort_allcmd(struct AdapterControlBlock *pACB)
{
struct MessageUnit_D *reg = pACB->pmuD;
writel(ARCMSR_INBOUND_MESG0_ABORT_CMD, reg->inbound_msgaddr0);
if (!arcmsr_hbaD_wait_msgint_ready(pACB)) {
pr_notice("arcmsr%d: wait 'abort all outstanding "
"command' timeout\n", pACB->host->host_no);
return false;
}
return true;
}
static uint8_t arcmsr_abort_allcmd(struct AdapterControlBlock *acb)
{
uint8_t rtnval = 0;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
rtnval = arcmsr_hbaA_abort_allcmd(acb);
}
break;
case ACB_ADAPTER_TYPE_B: {
rtnval = arcmsr_hbaB_abort_allcmd(acb);
}
break;
case ACB_ADAPTER_TYPE_C: {
rtnval = arcmsr_hbaC_abort_allcmd(acb);
}
break;
case ACB_ADAPTER_TYPE_D:
rtnval = arcmsr_hbaD_abort_allcmd(acb);
break;
}
return rtnval;
}
static void arcmsr_pci_unmap_dma(struct CommandControlBlock *ccb)
{
struct scsi_cmnd *pcmd = ccb->pcmd;
scsi_dma_unmap(pcmd);
}
static void arcmsr_ccb_complete(struct CommandControlBlock *ccb)
{
struct AdapterControlBlock *acb = ccb->acb;
struct scsi_cmnd *pcmd = ccb->pcmd;
unsigned long flags;
atomic_dec(&acb->ccboutstandingcount);
arcmsr_pci_unmap_dma(ccb);
ccb->startdone = ARCMSR_CCB_DONE;
spin_lock_irqsave(&acb->ccblist_lock, flags);
list_add_tail(&ccb->list, &acb->ccb_free_list);
spin_unlock_irqrestore(&acb->ccblist_lock, flags);
pcmd->scsi_done(pcmd);
}
static void arcmsr_report_sense_info(struct CommandControlBlock *ccb)
{
struct scsi_cmnd *pcmd = ccb->pcmd;
struct SENSE_DATA *sensebuffer = (struct SENSE_DATA *)pcmd->sense_buffer;
pcmd->result = DID_OK << 16;
if (sensebuffer) {
int sense_data_length =
sizeof(struct SENSE_DATA) < SCSI_SENSE_BUFFERSIZE
? sizeof(struct SENSE_DATA) : SCSI_SENSE_BUFFERSIZE;
memset(sensebuffer, 0, SCSI_SENSE_BUFFERSIZE);
memcpy(sensebuffer, ccb->arcmsr_cdb.SenseData, sense_data_length);
sensebuffer->ErrorCode = SCSI_SENSE_CURRENT_ERRORS;
sensebuffer->Valid = 1;
}
}
static u32 arcmsr_disable_outbound_ints(struct AdapterControlBlock *acb)
{
u32 orig_mask = 0;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A : {
struct MessageUnit_A __iomem *reg = acb->pmuA;
orig_mask = readl(®->outbound_intmask);
writel(orig_mask|ARCMSR_MU_OUTBOUND_ALL_INTMASKENABLE, \
®->outbound_intmask);
}
break;
case ACB_ADAPTER_TYPE_B : {
struct MessageUnit_B *reg = acb->pmuB;
orig_mask = readl(reg->iop2drv_doorbell_mask);
writel(0, reg->iop2drv_doorbell_mask);
}
break;
case ACB_ADAPTER_TYPE_C:{
struct MessageUnit_C __iomem *reg = acb->pmuC;
/* disable all outbound interrupt */
orig_mask = readl(®->host_int_mask); /* disable outbound message0 int */
writel(orig_mask|ARCMSR_HBCMU_ALL_INTMASKENABLE, ®->host_int_mask);
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
/* disable all outbound interrupt */
writel(ARCMSR_ARC1214_ALL_INT_DISABLE, reg->pcief0_int_enable);
}
break;
}
return orig_mask;
}
static void arcmsr_report_ccb_state(struct AdapterControlBlock *acb,
struct CommandControlBlock *ccb, bool error)
{
uint8_t id, lun;
id = ccb->pcmd->device->id;
lun = ccb->pcmd->device->lun;
if (!error) {
if (acb->devstate[id][lun] == ARECA_RAID_GONE)
acb->devstate[id][lun] = ARECA_RAID_GOOD;
ccb->pcmd->result = DID_OK << 16;
arcmsr_ccb_complete(ccb);
}else{
switch (ccb->arcmsr_cdb.DeviceStatus) {
case ARCMSR_DEV_SELECT_TIMEOUT: {
acb->devstate[id][lun] = ARECA_RAID_GONE;
ccb->pcmd->result = DID_NO_CONNECT << 16;
arcmsr_ccb_complete(ccb);
}
break;
case ARCMSR_DEV_ABORTED:
case ARCMSR_DEV_INIT_FAIL: {
acb->devstate[id][lun] = ARECA_RAID_GONE;
ccb->pcmd->result = DID_BAD_TARGET << 16;
arcmsr_ccb_complete(ccb);
}
break;
case ARCMSR_DEV_CHECK_CONDITION: {
acb->devstate[id][lun] = ARECA_RAID_GOOD;
arcmsr_report_sense_info(ccb);
arcmsr_ccb_complete(ccb);
}
break;
default:
printk(KERN_NOTICE
"arcmsr%d: scsi id = %d lun = %d isr get command error done, \
but got unknown DeviceStatus = 0x%x \n"
, acb->host->host_no
, id
, lun
, ccb->arcmsr_cdb.DeviceStatus);
acb->devstate[id][lun] = ARECA_RAID_GONE;
ccb->pcmd->result = DID_NO_CONNECT << 16;
arcmsr_ccb_complete(ccb);
break;
}
}
}
static void arcmsr_drain_donequeue(struct AdapterControlBlock *acb, struct CommandControlBlock *pCCB, bool error)
{
int id, lun;
if ((pCCB->acb != acb) || (pCCB->startdone != ARCMSR_CCB_START)) {
if (pCCB->startdone == ARCMSR_CCB_ABORTED) {
struct scsi_cmnd *abortcmd = pCCB->pcmd;
if (abortcmd) {
id = abortcmd->device->id;
lun = abortcmd->device->lun;
abortcmd->result |= DID_ABORT << 16;
arcmsr_ccb_complete(pCCB);
printk(KERN_NOTICE "arcmsr%d: pCCB ='0x%p' isr got aborted command \n",
acb->host->host_no, pCCB);
}
return;
}
printk(KERN_NOTICE "arcmsr%d: isr get an illegal ccb command \
done acb = '0x%p'"
"ccb = '0x%p' ccbacb = '0x%p' startdone = 0x%x"
" ccboutstandingcount = %d \n"
, acb->host->host_no
, acb
, pCCB
, pCCB->acb
, pCCB->startdone
, atomic_read(&acb->ccboutstandingcount));
return;
}
arcmsr_report_ccb_state(acb, pCCB, error);
}
static void arcmsr_done4abort_postqueue(struct AdapterControlBlock *acb)
{
int i = 0;
uint32_t flag_ccb, ccb_cdb_phy;
struct ARCMSR_CDB *pARCMSR_CDB;
bool error;
struct CommandControlBlock *pCCB;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
uint32_t outbound_intstatus;
outbound_intstatus = readl(®->outbound_intstatus) &
acb->outbound_int_enable;
/*clear and abort all outbound posted Q*/
writel(outbound_intstatus, ®->outbound_intstatus);/*clear interrupt*/
while(((flag_ccb = readl(®->outbound_queueport)) != 0xFFFFFFFF)
&& (i++ < ARCMSR_MAX_OUTSTANDING_CMD)) {
pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset + (flag_ccb << 5));/*frame must be 32 bytes aligned*/
pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
}
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
/*clear all outbound posted Q*/
writel(ARCMSR_DOORBELL_INT_CLEAR_PATTERN, reg->iop2drv_doorbell); /* clear doorbell interrupt */
for (i = 0; i < ARCMSR_MAX_HBB_POSTQUEUE; i++) {
flag_ccb = reg->done_qbuffer[i];
if (flag_ccb != 0) {
reg->done_qbuffer[i] = 0;
pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset+(flag_ccb << 5));/*frame must be 32 bytes aligned*/
pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
}
reg->post_qbuffer[i] = 0;
}
reg->doneq_index = 0;
reg->postq_index = 0;
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
while ((readl(®->host_int_status) & ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR) && (i++ < ARCMSR_MAX_OUTSTANDING_CMD)) {
/*need to do*/
flag_ccb = readl(®->outbound_queueport_low);
ccb_cdb_phy = (flag_ccb & 0xFFFFFFF0);
pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset+ccb_cdb_phy);/*frame must be 32 bytes aligned*/
pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1) ? true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
}
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *pmu = acb->pmuD;
uint32_t outbound_write_pointer;
uint32_t doneq_index, index_stripped, addressLow, residual, toggle;
unsigned long flags;
residual = atomic_read(&acb->ccboutstandingcount);
for (i = 0; i < residual; i++) {
spin_lock_irqsave(&acb->doneq_lock, flags);
outbound_write_pointer =
pmu->done_qbuffer[0].addressLow + 1;
doneq_index = pmu->doneq_index;
if ((doneq_index & 0xFFF) !=
(outbound_write_pointer & 0xFFF)) {
toggle = doneq_index & 0x4000;
index_stripped = (doneq_index & 0xFFF) + 1;
index_stripped %= ARCMSR_MAX_ARC1214_DONEQUEUE;
pmu->doneq_index = index_stripped ? (index_stripped | toggle) :
((toggle ^ 0x4000) + 1);
doneq_index = pmu->doneq_index;
spin_unlock_irqrestore(&acb->doneq_lock, flags);
addressLow = pmu->done_qbuffer[doneq_index &
0xFFF].addressLow;
ccb_cdb_phy = (addressLow & 0xFFFFFFF0);
pARCMSR_CDB = (struct ARCMSR_CDB *)
(acb->vir2phy_offset + ccb_cdb_phy);
pCCB = container_of(pARCMSR_CDB,
struct CommandControlBlock, arcmsr_cdb);
error = (addressLow &
ARCMSR_CCBREPLY_FLAG_ERROR_MODE1) ?
true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
writel(doneq_index,
pmu->outboundlist_read_pointer);
} else {
spin_unlock_irqrestore(&acb->doneq_lock, flags);
mdelay(10);
}
}
pmu->postq_index = 0;
pmu->doneq_index = 0x40FF;
}
break;
}
}
static void arcmsr_remove(struct pci_dev *pdev)
{
struct Scsi_Host *host = pci_get_drvdata(pdev);
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *) host->hostdata;
int poll_count = 0;
arcmsr_free_sysfs_attr(acb);
scsi_remove_host(host);
flush_work(&acb->arcmsr_do_message_isr_bh);
del_timer_sync(&acb->eternal_timer);
arcmsr_disable_outbound_ints(acb);
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
acb->acb_flags |= ACB_F_SCSISTOPADAPTER;
acb->acb_flags &= ~ACB_F_IOP_INITED;
for (poll_count = 0; poll_count < ARCMSR_MAX_OUTSTANDING_CMD; poll_count++){
if (!atomic_read(&acb->ccboutstandingcount))
break;
arcmsr_interrupt(acb);/* FIXME: need spinlock */
msleep(25);
}
if (atomic_read(&acb->ccboutstandingcount)) {
int i;
arcmsr_abort_allcmd(acb);
arcmsr_done4abort_postqueue(acb);
for (i = 0; i < ARCMSR_MAX_FREECCB_NUM; i++) {
struct CommandControlBlock *ccb = acb->pccb_pool[i];
if (ccb->startdone == ARCMSR_CCB_START) {
ccb->startdone = ARCMSR_CCB_ABORTED;
ccb->pcmd->result = DID_ABORT << 16;
arcmsr_ccb_complete(ccb);
}
}
}
arcmsr_free_irq(pdev, acb);
arcmsr_free_ccb_pool(acb);
arcmsr_free_mu(acb);
arcmsr_unmap_pciregion(acb);
pci_release_regions(pdev);
scsi_host_put(host);
pci_disable_device(pdev);
}
static void arcmsr_shutdown(struct pci_dev *pdev)
{
struct Scsi_Host *host = pci_get_drvdata(pdev);
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *)host->hostdata;
del_timer_sync(&acb->eternal_timer);
arcmsr_disable_outbound_ints(acb);
arcmsr_free_irq(pdev, acb);
flush_work(&acb->arcmsr_do_message_isr_bh);
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
}
static int arcmsr_module_init(void)
{
int error = 0;
error = pci_register_driver(&arcmsr_pci_driver);
return error;
}
static void arcmsr_module_exit(void)
{
pci_unregister_driver(&arcmsr_pci_driver);
}
module_init(arcmsr_module_init);
module_exit(arcmsr_module_exit);
static void arcmsr_enable_outbound_ints(struct AdapterControlBlock *acb,
u32 intmask_org)
{
u32 mask;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
mask = intmask_org & ~(ARCMSR_MU_OUTBOUND_POSTQUEUE_INTMASKENABLE |
ARCMSR_MU_OUTBOUND_DOORBELL_INTMASKENABLE|
ARCMSR_MU_OUTBOUND_MESSAGE0_INTMASKENABLE);
writel(mask, ®->outbound_intmask);
acb->outbound_int_enable = ~(intmask_org & mask) & 0x000000ff;
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
mask = intmask_org | (ARCMSR_IOP2DRV_DATA_WRITE_OK |
ARCMSR_IOP2DRV_DATA_READ_OK |
ARCMSR_IOP2DRV_CDB_DONE |
ARCMSR_IOP2DRV_MESSAGE_CMD_DONE);
writel(mask, reg->iop2drv_doorbell_mask);
acb->outbound_int_enable = (intmask_org | mask) & 0x0000000f;
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
mask = ~(ARCMSR_HBCMU_UTILITY_A_ISR_MASK | ARCMSR_HBCMU_OUTBOUND_DOORBELL_ISR_MASK|ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR_MASK);
writel(intmask_org & mask, ®->host_int_mask);
acb->outbound_int_enable = ~(intmask_org & mask) & 0x0000000f;
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
mask = ARCMSR_ARC1214_ALL_INT_ENABLE;
writel(intmask_org | mask, reg->pcief0_int_enable);
break;
}
}
}
static int arcmsr_build_ccb(struct AdapterControlBlock *acb,
struct CommandControlBlock *ccb, struct scsi_cmnd *pcmd)
{
struct ARCMSR_CDB *arcmsr_cdb = (struct ARCMSR_CDB *)&ccb->arcmsr_cdb;
int8_t *psge = (int8_t *)&arcmsr_cdb->u;
__le32 address_lo, address_hi;
int arccdbsize = 0x30;
__le32 length = 0;
int i;
struct scatterlist *sg;
int nseg;
ccb->pcmd = pcmd;
memset(arcmsr_cdb, 0, sizeof(struct ARCMSR_CDB));
arcmsr_cdb->TargetID = pcmd->device->id;
arcmsr_cdb->LUN = pcmd->device->lun;
arcmsr_cdb->Function = 1;
arcmsr_cdb->msgContext = 0;
memcpy(arcmsr_cdb->Cdb, pcmd->cmnd, pcmd->cmd_len);
nseg = scsi_dma_map(pcmd);
if (unlikely(nseg > acb->host->sg_tablesize || nseg < 0))
return FAILED;
scsi_for_each_sg(pcmd, sg, nseg, i) {
/* Get the physical address of the current data pointer */
length = cpu_to_le32(sg_dma_len(sg));
address_lo = cpu_to_le32(dma_addr_lo32(sg_dma_address(sg)));
address_hi = cpu_to_le32(dma_addr_hi32(sg_dma_address(sg)));
if (address_hi == 0) {
struct SG32ENTRY *pdma_sg = (struct SG32ENTRY *)psge;
pdma_sg->address = address_lo;
pdma_sg->length = length;
psge += sizeof (struct SG32ENTRY);
arccdbsize += sizeof (struct SG32ENTRY);
} else {
struct SG64ENTRY *pdma_sg = (struct SG64ENTRY *)psge;
pdma_sg->addresshigh = address_hi;
pdma_sg->address = address_lo;
pdma_sg->length = length|cpu_to_le32(IS_SG64_ADDR);
psge += sizeof (struct SG64ENTRY);
arccdbsize += sizeof (struct SG64ENTRY);
}
}
arcmsr_cdb->sgcount = (uint8_t)nseg;
arcmsr_cdb->DataLength = scsi_bufflen(pcmd);
arcmsr_cdb->msgPages = arccdbsize/0x100 + (arccdbsize % 0x100 ? 1 : 0);
if ( arccdbsize > 256)
arcmsr_cdb->Flags |= ARCMSR_CDB_FLAG_SGL_BSIZE;
if (pcmd->sc_data_direction == DMA_TO_DEVICE)
arcmsr_cdb->Flags |= ARCMSR_CDB_FLAG_WRITE;
ccb->arc_cdb_size = arccdbsize;
return SUCCESS;
}
static void arcmsr_post_ccb(struct AdapterControlBlock *acb, struct CommandControlBlock *ccb)
{
uint32_t cdb_phyaddr = ccb->cdb_phyaddr;
struct ARCMSR_CDB *arcmsr_cdb = (struct ARCMSR_CDB *)&ccb->arcmsr_cdb;
atomic_inc(&acb->ccboutstandingcount);
ccb->startdone = ARCMSR_CCB_START;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
if (arcmsr_cdb->Flags & ARCMSR_CDB_FLAG_SGL_BSIZE)
writel(cdb_phyaddr | ARCMSR_CCBPOST_FLAG_SGL_BSIZE,
®->inbound_queueport);
else
writel(cdb_phyaddr, ®->inbound_queueport);
break;
}
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
uint32_t ending_index, index = reg->postq_index;
ending_index = ((index + 1) % ARCMSR_MAX_HBB_POSTQUEUE);
reg->post_qbuffer[ending_index] = 0;
if (arcmsr_cdb->Flags & ARCMSR_CDB_FLAG_SGL_BSIZE) {
reg->post_qbuffer[index] =
cdb_phyaddr | ARCMSR_CCBPOST_FLAG_SGL_BSIZE;
} else {
reg->post_qbuffer[index] = cdb_phyaddr;
}
index++;
index %= ARCMSR_MAX_HBB_POSTQUEUE;/*if last index number set it to 0 */
reg->postq_index = index;
writel(ARCMSR_DRV2IOP_CDB_POSTED, reg->drv2iop_doorbell);
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *phbcmu = acb->pmuC;
uint32_t ccb_post_stamp, arc_cdb_size;
arc_cdb_size = (ccb->arc_cdb_size > 0x300) ? 0x300 : ccb->arc_cdb_size;
ccb_post_stamp = (cdb_phyaddr | ((arc_cdb_size - 1) >> 6) | 1);
if (acb->cdb_phyaddr_hi32) {
writel(acb->cdb_phyaddr_hi32, &phbcmu->inbound_queueport_high);
writel(ccb_post_stamp, &phbcmu->inbound_queueport_low);
} else {
writel(ccb_post_stamp, &phbcmu->inbound_queueport_low);
}
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *pmu = acb->pmuD;
u16 index_stripped;
u16 postq_index, toggle;
unsigned long flags;
struct InBound_SRB *pinbound_srb;
spin_lock_irqsave(&acb->postq_lock, flags);
postq_index = pmu->postq_index;
pinbound_srb = (struct InBound_SRB *)&(pmu->post_qbuffer[postq_index & 0xFF]);
pinbound_srb->addressHigh = dma_addr_hi32(cdb_phyaddr);
pinbound_srb->addressLow = dma_addr_lo32(cdb_phyaddr);
pinbound_srb->length = ccb->arc_cdb_size >> 2;
arcmsr_cdb->msgContext = dma_addr_lo32(cdb_phyaddr);
toggle = postq_index & 0x4000;
index_stripped = postq_index + 1;
index_stripped &= (ARCMSR_MAX_ARC1214_POSTQUEUE - 1);
pmu->postq_index = index_stripped ? (index_stripped | toggle) :
(toggle ^ 0x4000);
writel(postq_index, pmu->inboundlist_write_pointer);
spin_unlock_irqrestore(&acb->postq_lock, flags);
break;
}
}
}
static void arcmsr_hbaA_stop_bgrb(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
acb->acb_flags &= ~ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_STOP_BGRB, ®->inbound_msgaddr0);
if (!arcmsr_hbaA_wait_msgint_ready(acb)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'stop adapter background rebulid' timeout\n"
, acb->host->host_no);
}
}
static void arcmsr_hbaB_stop_bgrb(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
acb->acb_flags &= ~ACB_F_MSG_START_BGRB;
writel(ARCMSR_MESSAGE_STOP_BGRB, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'stop adapter background rebulid' timeout\n"
, acb->host->host_no);
}
}
static void arcmsr_hbaC_stop_bgrb(struct AdapterControlBlock *pACB)
{
struct MessageUnit_C __iomem *reg = pACB->pmuC;
pACB->acb_flags &= ~ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_STOP_BGRB, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
if (!arcmsr_hbaC_wait_msgint_ready(pACB)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'stop adapter background rebulid' timeout\n"
, pACB->host->host_no);
}
return;
}
static void arcmsr_hbaD_stop_bgrb(struct AdapterControlBlock *pACB)
{
struct MessageUnit_D *reg = pACB->pmuD;
pACB->acb_flags &= ~ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_STOP_BGRB, reg->inbound_msgaddr0);
if (!arcmsr_hbaD_wait_msgint_ready(pACB))
pr_notice("arcmsr%d: wait 'stop adapter background rebulid' "
"timeout\n", pACB->host->host_no);
}
static void arcmsr_stop_adapter_bgrb(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
arcmsr_hbaA_stop_bgrb(acb);
}
break;
case ACB_ADAPTER_TYPE_B: {
arcmsr_hbaB_stop_bgrb(acb);
}
break;
case ACB_ADAPTER_TYPE_C: {
arcmsr_hbaC_stop_bgrb(acb);
}
break;
case ACB_ADAPTER_TYPE_D:
arcmsr_hbaD_stop_bgrb(acb);
break;
}
}
static void arcmsr_free_ccb_pool(struct AdapterControlBlock *acb)
{
dma_free_coherent(&acb->pdev->dev, acb->uncache_size, acb->dma_coherent, acb->dma_coherent_handle);
}
static void arcmsr_iop_message_read(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
writel(ARCMSR_INBOUND_DRIVER_DATA_READ_OK, ®->inbound_doorbell);
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
writel(ARCMSR_DRV2IOP_DATA_READ_OK, reg->drv2iop_doorbell);
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
writel(ARCMSR_HBCMU_DRV2IOP_DATA_READ_OK, ®->inbound_doorbell);
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
writel(ARCMSR_ARC1214_DRV2IOP_DATA_OUT_READ,
reg->inbound_doorbell);
}
break;
}
}
static void arcmsr_iop_message_wrote(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
/*
** push inbound doorbell tell iop, driver data write ok
** and wait reply on next hwinterrupt for next Qbuffer post
*/
writel(ARCMSR_INBOUND_DRIVER_DATA_WRITE_OK, ®->inbound_doorbell);
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
/*
** push inbound doorbell tell iop, driver data write ok
** and wait reply on next hwinterrupt for next Qbuffer post
*/
writel(ARCMSR_DRV2IOP_DATA_WRITE_OK, reg->drv2iop_doorbell);
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
/*
** push inbound doorbell tell iop, driver data write ok
** and wait reply on next hwinterrupt for next Qbuffer post
*/
writel(ARCMSR_HBCMU_DRV2IOP_DATA_WRITE_OK, ®->inbound_doorbell);
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
writel(ARCMSR_ARC1214_DRV2IOP_DATA_IN_READY,
reg->inbound_doorbell);
}
break;
}
}
struct QBUFFER __iomem *arcmsr_get_iop_rqbuffer(struct AdapterControlBlock *acb)
{
struct QBUFFER __iomem *qbuffer = NULL;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
qbuffer = (struct QBUFFER __iomem *)®->message_rbuffer;
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
qbuffer = (struct QBUFFER __iomem *)reg->message_rbuffer;
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *phbcmu = acb->pmuC;
qbuffer = (struct QBUFFER __iomem *)&phbcmu->message_rbuffer;
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
qbuffer = (struct QBUFFER __iomem *)reg->message_rbuffer;
}
break;
}
return qbuffer;
}
static struct QBUFFER __iomem *arcmsr_get_iop_wqbuffer(struct AdapterControlBlock *acb)
{
struct QBUFFER __iomem *pqbuffer = NULL;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
pqbuffer = (struct QBUFFER __iomem *) ®->message_wbuffer;
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
pqbuffer = (struct QBUFFER __iomem *)reg->message_wbuffer;
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
pqbuffer = (struct QBUFFER __iomem *)®->message_wbuffer;
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
pqbuffer = (struct QBUFFER __iomem *)reg->message_wbuffer;
}
break;
}
return pqbuffer;
}
static uint32_t
arcmsr_Read_iop_rqbuffer_in_DWORD(struct AdapterControlBlock *acb,
struct QBUFFER __iomem *prbuffer)
{
uint8_t *pQbuffer;
uint8_t *buf1 = NULL;
uint32_t __iomem *iop_data;
uint32_t iop_len, data_len, *buf2 = NULL;
iop_data = (uint32_t __iomem *)prbuffer->data;
iop_len = readl(&prbuffer->data_len);
if (iop_len > 0) {
buf1 = kmalloc(128, GFP_ATOMIC);
buf2 = (uint32_t *)buf1;
if (buf1 == NULL)
return 0;
data_len = iop_len;
while (data_len >= 4) {
*buf2++ = readl(iop_data);
iop_data++;
data_len -= 4;
}
if (data_len)
*buf2 = readl(iop_data);
buf2 = (uint32_t *)buf1;
}
while (iop_len > 0) {
pQbuffer = &acb->rqbuffer[acb->rqbuf_putIndex];
*pQbuffer = *buf1;
acb->rqbuf_putIndex++;
/* if last, index number set it to 0 */
acb->rqbuf_putIndex %= ARCMSR_MAX_QBUFFER;
buf1++;
iop_len--;
}
kfree(buf2);
/* let IOP know data has been read */
arcmsr_iop_message_read(acb);
return 1;
}
uint32_t
arcmsr_Read_iop_rqbuffer_data(struct AdapterControlBlock *acb,
struct QBUFFER __iomem *prbuffer) {
uint8_t *pQbuffer;
uint8_t __iomem *iop_data;
uint32_t iop_len;
if (acb->adapter_type & (ACB_ADAPTER_TYPE_C | ACB_ADAPTER_TYPE_D))
return arcmsr_Read_iop_rqbuffer_in_DWORD(acb, prbuffer);
iop_data = (uint8_t __iomem *)prbuffer->data;
iop_len = readl(&prbuffer->data_len);
while (iop_len > 0) {
pQbuffer = &acb->rqbuffer[acb->rqbuf_putIndex];
*pQbuffer = readb(iop_data);
acb->rqbuf_putIndex++;
acb->rqbuf_putIndex %= ARCMSR_MAX_QBUFFER;
iop_data++;
iop_len--;
}
arcmsr_iop_message_read(acb);
return 1;
}
static void arcmsr_iop2drv_data_wrote_handle(struct AdapterControlBlock *acb)
{
unsigned long flags;
struct QBUFFER __iomem *prbuffer;
int32_t buf_empty_len;
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
prbuffer = arcmsr_get_iop_rqbuffer(acb);
buf_empty_len = (acb->rqbuf_putIndex - acb->rqbuf_getIndex - 1) &
(ARCMSR_MAX_QBUFFER - 1);
if (buf_empty_len >= readl(&prbuffer->data_len)) {
if (arcmsr_Read_iop_rqbuffer_data(acb, prbuffer) == 0)
acb->acb_flags |= ACB_F_IOPDATA_OVERFLOW;
} else
acb->acb_flags |= ACB_F_IOPDATA_OVERFLOW;
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
}
static void arcmsr_write_ioctldata2iop_in_DWORD(struct AdapterControlBlock *acb)
{
uint8_t *pQbuffer;
struct QBUFFER __iomem *pwbuffer;
uint8_t *buf1 = NULL;
uint32_t __iomem *iop_data;
uint32_t allxfer_len = 0, data_len, *buf2 = NULL, data;
if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_READED) {
buf1 = kmalloc(128, GFP_ATOMIC);
buf2 = (uint32_t *)buf1;
if (buf1 == NULL)
return;
acb->acb_flags &= (~ACB_F_MESSAGE_WQBUFFER_READED);
pwbuffer = arcmsr_get_iop_wqbuffer(acb);
iop_data = (uint32_t __iomem *)pwbuffer->data;
while ((acb->wqbuf_getIndex != acb->wqbuf_putIndex)
&& (allxfer_len < 124)) {
pQbuffer = &acb->wqbuffer[acb->wqbuf_getIndex];
*buf1 = *pQbuffer;
acb->wqbuf_getIndex++;
acb->wqbuf_getIndex %= ARCMSR_MAX_QBUFFER;
buf1++;
allxfer_len++;
}
data_len = allxfer_len;
buf1 = (uint8_t *)buf2;
while (data_len >= 4) {
data = *buf2++;
writel(data, iop_data);
iop_data++;
data_len -= 4;
}
if (data_len) {
data = *buf2;
writel(data, iop_data);
}
writel(allxfer_len, &pwbuffer->data_len);
kfree(buf1);
arcmsr_iop_message_wrote(acb);
}
}
void
arcmsr_write_ioctldata2iop(struct AdapterControlBlock *acb)
{
uint8_t *pQbuffer;
struct QBUFFER __iomem *pwbuffer;
uint8_t __iomem *iop_data;
int32_t allxfer_len = 0;
if (acb->adapter_type & (ACB_ADAPTER_TYPE_C | ACB_ADAPTER_TYPE_D)) {
arcmsr_write_ioctldata2iop_in_DWORD(acb);
return;
}
if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_READED) {
acb->acb_flags &= (~ACB_F_MESSAGE_WQBUFFER_READED);
pwbuffer = arcmsr_get_iop_wqbuffer(acb);
iop_data = (uint8_t __iomem *)pwbuffer->data;
while ((acb->wqbuf_getIndex != acb->wqbuf_putIndex)
&& (allxfer_len < 124)) {
pQbuffer = &acb->wqbuffer[acb->wqbuf_getIndex];
writeb(*pQbuffer, iop_data);
acb->wqbuf_getIndex++;
acb->wqbuf_getIndex %= ARCMSR_MAX_QBUFFER;
iop_data++;
allxfer_len++;
}
writel(allxfer_len, &pwbuffer->data_len);
arcmsr_iop_message_wrote(acb);
}
}
static void arcmsr_iop2drv_data_read_handle(struct AdapterControlBlock *acb)
{
unsigned long flags;
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_WQBUFFER_READED;
if (acb->wqbuf_getIndex != acb->wqbuf_putIndex)
arcmsr_write_ioctldata2iop(acb);
if (acb->wqbuf_getIndex == acb->wqbuf_putIndex)
acb->acb_flags |= ACB_F_MESSAGE_WQBUFFER_CLEARED;
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
}
static void arcmsr_hbaA_doorbell_isr(struct AdapterControlBlock *acb)
{
uint32_t outbound_doorbell;
struct MessageUnit_A __iomem *reg = acb->pmuA;
outbound_doorbell = readl(®->outbound_doorbell);
do {
writel(outbound_doorbell, ®->outbound_doorbell);
if (outbound_doorbell & ARCMSR_OUTBOUND_IOP331_DATA_WRITE_OK)
arcmsr_iop2drv_data_wrote_handle(acb);
if (outbound_doorbell & ARCMSR_OUTBOUND_IOP331_DATA_READ_OK)
arcmsr_iop2drv_data_read_handle(acb);
outbound_doorbell = readl(®->outbound_doorbell);
} while (outbound_doorbell & (ARCMSR_OUTBOUND_IOP331_DATA_WRITE_OK
| ARCMSR_OUTBOUND_IOP331_DATA_READ_OK));
}
static void arcmsr_hbaC_doorbell_isr(struct AdapterControlBlock *pACB)
{
uint32_t outbound_doorbell;
struct MessageUnit_C __iomem *reg = pACB->pmuC;
/*
*******************************************************************
** Maybe here we need to check wrqbuffer_lock is lock or not
** DOORBELL: din! don!
** check if there are any mail need to pack from firmware
*******************************************************************
*/
outbound_doorbell = readl(®->outbound_doorbell);
do {
writel(outbound_doorbell, ®->outbound_doorbell_clear);
readl(®->outbound_doorbell_clear);
if (outbound_doorbell & ARCMSR_HBCMU_IOP2DRV_DATA_WRITE_OK)
arcmsr_iop2drv_data_wrote_handle(pACB);
if (outbound_doorbell & ARCMSR_HBCMU_IOP2DRV_DATA_READ_OK)
arcmsr_iop2drv_data_read_handle(pACB);
if (outbound_doorbell & ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE)
arcmsr_hbaC_message_isr(pACB);
outbound_doorbell = readl(®->outbound_doorbell);
} while (outbound_doorbell & (ARCMSR_HBCMU_IOP2DRV_DATA_WRITE_OK
| ARCMSR_HBCMU_IOP2DRV_DATA_READ_OK
| ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE));
}
static void arcmsr_hbaD_doorbell_isr(struct AdapterControlBlock *pACB)
{
uint32_t outbound_doorbell;
struct MessageUnit_D *pmu = pACB->pmuD;
outbound_doorbell = readl(pmu->outbound_doorbell);
do {
writel(outbound_doorbell, pmu->outbound_doorbell);
if (outbound_doorbell & ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE)
arcmsr_hbaD_message_isr(pACB);
if (outbound_doorbell & ARCMSR_ARC1214_IOP2DRV_DATA_WRITE_OK)
arcmsr_iop2drv_data_wrote_handle(pACB);
if (outbound_doorbell & ARCMSR_ARC1214_IOP2DRV_DATA_READ_OK)
arcmsr_iop2drv_data_read_handle(pACB);
outbound_doorbell = readl(pmu->outbound_doorbell);
} while (outbound_doorbell & (ARCMSR_ARC1214_IOP2DRV_DATA_WRITE_OK
| ARCMSR_ARC1214_IOP2DRV_DATA_READ_OK
| ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE));
}
static void arcmsr_hbaA_postqueue_isr(struct AdapterControlBlock *acb)
{
uint32_t flag_ccb;
struct MessageUnit_A __iomem *reg = acb->pmuA;
struct ARCMSR_CDB *pARCMSR_CDB;
struct CommandControlBlock *pCCB;
bool error;
while ((flag_ccb = readl(®->outbound_queueport)) != 0xFFFFFFFF) {
pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset + (flag_ccb << 5));/*frame must be 32 bytes aligned*/
pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
}
}
static void arcmsr_hbaB_postqueue_isr(struct AdapterControlBlock *acb)
{
uint32_t index;
uint32_t flag_ccb;
struct MessageUnit_B *reg = acb->pmuB;
struct ARCMSR_CDB *pARCMSR_CDB;
struct CommandControlBlock *pCCB;
bool error;
index = reg->doneq_index;
while ((flag_ccb = reg->done_qbuffer[index]) != 0) {
reg->done_qbuffer[index] = 0;
pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset+(flag_ccb << 5));/*frame must be 32 bytes aligned*/
pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
index++;
index %= ARCMSR_MAX_HBB_POSTQUEUE;
reg->doneq_index = index;
}
}
static void arcmsr_hbaC_postqueue_isr(struct AdapterControlBlock *acb)
{
struct MessageUnit_C __iomem *phbcmu;
struct ARCMSR_CDB *arcmsr_cdb;
struct CommandControlBlock *ccb;
uint32_t flag_ccb, ccb_cdb_phy, throttling = 0;
int error;
phbcmu = acb->pmuC;
/* areca cdb command done */
/* Use correct offset and size for syncing */
while ((flag_ccb = readl(&phbcmu->outbound_queueport_low)) !=
0xFFFFFFFF) {
ccb_cdb_phy = (flag_ccb & 0xFFFFFFF0);
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset
+ ccb_cdb_phy);
ccb = container_of(arcmsr_cdb, struct CommandControlBlock,
arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1)
? true : false;
/* check if command done with no error */
arcmsr_drain_donequeue(acb, ccb, error);
throttling++;
if (throttling == ARCMSR_HBC_ISR_THROTTLING_LEVEL) {
writel(ARCMSR_HBCMU_DRV2IOP_POSTQUEUE_THROTTLING,
&phbcmu->inbound_doorbell);
throttling = 0;
}
}
}
static void arcmsr_hbaD_postqueue_isr(struct AdapterControlBlock *acb)
{
u32 outbound_write_pointer, doneq_index, index_stripped, toggle;
uint32_t addressLow, ccb_cdb_phy;
int error;
struct MessageUnit_D *pmu;
struct ARCMSR_CDB *arcmsr_cdb;
struct CommandControlBlock *ccb;
unsigned long flags;
spin_lock_irqsave(&acb->doneq_lock, flags);
pmu = acb->pmuD;
outbound_write_pointer = pmu->done_qbuffer[0].addressLow + 1;
doneq_index = pmu->doneq_index;
if ((doneq_index & 0xFFF) != (outbound_write_pointer & 0xFFF)) {
do {
toggle = doneq_index & 0x4000;
index_stripped = (doneq_index & 0xFFF) + 1;
index_stripped %= ARCMSR_MAX_ARC1214_DONEQUEUE;
pmu->doneq_index = index_stripped ? (index_stripped | toggle) :
((toggle ^ 0x4000) + 1);
doneq_index = pmu->doneq_index;
addressLow = pmu->done_qbuffer[doneq_index &
0xFFF].addressLow;
ccb_cdb_phy = (addressLow & 0xFFFFFFF0);
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset
+ ccb_cdb_phy);
ccb = container_of(arcmsr_cdb,
struct CommandControlBlock, arcmsr_cdb);
error = (addressLow & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1)
? true : false;
arcmsr_drain_donequeue(acb, ccb, error);
writel(doneq_index, pmu->outboundlist_read_pointer);
} while ((doneq_index & 0xFFF) !=
(outbound_write_pointer & 0xFFF));
}
writel(ARCMSR_ARC1214_OUTBOUND_LIST_INTERRUPT_CLEAR,
pmu->outboundlist_interrupt_cause);
readl(pmu->outboundlist_interrupt_cause);
spin_unlock_irqrestore(&acb->doneq_lock, flags);
}
/*
**********************************************************************************
** Handle a message interrupt
**
** The only message interrupt we expect is in response to a query for the current adapter config.
** We want this in order to compare the drivemap so that we can detect newly-attached drives.
**********************************************************************************
*/
static void arcmsr_hbaA_message_isr(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
/*clear interrupt and message state*/
writel(ARCMSR_MU_OUTBOUND_MESSAGE0_INT, ®->outbound_intstatus);
schedule_work(&acb->arcmsr_do_message_isr_bh);
}
static void arcmsr_hbaB_message_isr(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
/*clear interrupt and message state*/
writel(ARCMSR_MESSAGE_INT_CLEAR_PATTERN, reg->iop2drv_doorbell);
schedule_work(&acb->arcmsr_do_message_isr_bh);
}
/*
**********************************************************************************
** Handle a message interrupt
**
** The only message interrupt we expect is in response to a query for the
** current adapter config.
** We want this in order to compare the drivemap so that we can detect newly-attached drives.
**********************************************************************************
*/
static void arcmsr_hbaC_message_isr(struct AdapterControlBlock *acb)
{
struct MessageUnit_C __iomem *reg = acb->pmuC;
/*clear interrupt and message state*/
writel(ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE_DOORBELL_CLEAR, ®->outbound_doorbell_clear);
schedule_work(&acb->arcmsr_do_message_isr_bh);
}
static void arcmsr_hbaD_message_isr(struct AdapterControlBlock *acb)
{
struct MessageUnit_D *reg = acb->pmuD;
writel(ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE, reg->outbound_doorbell);
readl(reg->outbound_doorbell);
schedule_work(&acb->arcmsr_do_message_isr_bh);
}
static int arcmsr_hbaA_handle_isr(struct AdapterControlBlock *acb)
{
uint32_t outbound_intstatus;
struct MessageUnit_A __iomem *reg = acb->pmuA;
outbound_intstatus = readl(®->outbound_intstatus) &
acb->outbound_int_enable;
if (!(outbound_intstatus & ARCMSR_MU_OUTBOUND_HANDLE_INT))
return IRQ_NONE;
do {
writel(outbound_intstatus, ®->outbound_intstatus);
if (outbound_intstatus & ARCMSR_MU_OUTBOUND_DOORBELL_INT)
arcmsr_hbaA_doorbell_isr(acb);
if (outbound_intstatus & ARCMSR_MU_OUTBOUND_POSTQUEUE_INT)
arcmsr_hbaA_postqueue_isr(acb);
if (outbound_intstatus & ARCMSR_MU_OUTBOUND_MESSAGE0_INT)
arcmsr_hbaA_message_isr(acb);
outbound_intstatus = readl(®->outbound_intstatus) &
acb->outbound_int_enable;
} while (outbound_intstatus & (ARCMSR_MU_OUTBOUND_DOORBELL_INT
| ARCMSR_MU_OUTBOUND_POSTQUEUE_INT
| ARCMSR_MU_OUTBOUND_MESSAGE0_INT));
return IRQ_HANDLED;
}
static int arcmsr_hbaB_handle_isr(struct AdapterControlBlock *acb)
{
uint32_t outbound_doorbell;
struct MessageUnit_B *reg = acb->pmuB;
outbound_doorbell = readl(reg->iop2drv_doorbell) &
acb->outbound_int_enable;
if (!outbound_doorbell)
return IRQ_NONE;
do {
writel(~outbound_doorbell, reg->iop2drv_doorbell);
writel(ARCMSR_DRV2IOP_END_OF_INTERRUPT, reg->drv2iop_doorbell);
if (outbound_doorbell & ARCMSR_IOP2DRV_DATA_WRITE_OK)
arcmsr_iop2drv_data_wrote_handle(acb);
if (outbound_doorbell & ARCMSR_IOP2DRV_DATA_READ_OK)
arcmsr_iop2drv_data_read_handle(acb);
if (outbound_doorbell & ARCMSR_IOP2DRV_CDB_DONE)
arcmsr_hbaB_postqueue_isr(acb);
if (outbound_doorbell & ARCMSR_IOP2DRV_MESSAGE_CMD_DONE)
arcmsr_hbaB_message_isr(acb);
outbound_doorbell = readl(reg->iop2drv_doorbell) &
acb->outbound_int_enable;
} while (outbound_doorbell & (ARCMSR_IOP2DRV_DATA_WRITE_OK
| ARCMSR_IOP2DRV_DATA_READ_OK
| ARCMSR_IOP2DRV_CDB_DONE
| ARCMSR_IOP2DRV_MESSAGE_CMD_DONE));
return IRQ_HANDLED;
}
static int arcmsr_hbaC_handle_isr(struct AdapterControlBlock *pACB)
{
uint32_t host_interrupt_status;
struct MessageUnit_C __iomem *phbcmu = pACB->pmuC;
/*
*********************************************
** check outbound intstatus
*********************************************
*/
host_interrupt_status = readl(&phbcmu->host_int_status) &
(ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR |
ARCMSR_HBCMU_OUTBOUND_DOORBELL_ISR);
if (!host_interrupt_status)
return IRQ_NONE;
do {
if (host_interrupt_status & ARCMSR_HBCMU_OUTBOUND_DOORBELL_ISR)
arcmsr_hbaC_doorbell_isr(pACB);
/* MU post queue interrupts*/
if (host_interrupt_status & ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR)
arcmsr_hbaC_postqueue_isr(pACB);
host_interrupt_status = readl(&phbcmu->host_int_status);
} while (host_interrupt_status & (ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR |
ARCMSR_HBCMU_OUTBOUND_DOORBELL_ISR));
return IRQ_HANDLED;
}
static irqreturn_t arcmsr_hbaD_handle_isr(struct AdapterControlBlock *pACB)
{
u32 host_interrupt_status;
struct MessageUnit_D *pmu = pACB->pmuD;
host_interrupt_status = readl(pmu->host_int_status) &
(ARCMSR_ARC1214_OUTBOUND_POSTQUEUE_ISR |
ARCMSR_ARC1214_OUTBOUND_DOORBELL_ISR);
if (!host_interrupt_status)
return IRQ_NONE;
do {
/* MU post queue interrupts*/
if (host_interrupt_status &
ARCMSR_ARC1214_OUTBOUND_POSTQUEUE_ISR)
arcmsr_hbaD_postqueue_isr(pACB);
if (host_interrupt_status &
ARCMSR_ARC1214_OUTBOUND_DOORBELL_ISR)
arcmsr_hbaD_doorbell_isr(pACB);
host_interrupt_status = readl(pmu->host_int_status);
} while (host_interrupt_status &
(ARCMSR_ARC1214_OUTBOUND_POSTQUEUE_ISR |
ARCMSR_ARC1214_OUTBOUND_DOORBELL_ISR));
return IRQ_HANDLED;
}
static irqreturn_t arcmsr_interrupt(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:
return arcmsr_hbaA_handle_isr(acb);
break;
case ACB_ADAPTER_TYPE_B:
return arcmsr_hbaB_handle_isr(acb);
break;
case ACB_ADAPTER_TYPE_C:
return arcmsr_hbaC_handle_isr(acb);
case ACB_ADAPTER_TYPE_D:
return arcmsr_hbaD_handle_isr(acb);
default:
return IRQ_NONE;
}
}
static void arcmsr_iop_parking(struct AdapterControlBlock *acb)
{
if (acb) {
/* stop adapter background rebuild */
if (acb->acb_flags & ACB_F_MSG_START_BGRB) {
uint32_t intmask_org;
acb->acb_flags &= ~ACB_F_MSG_START_BGRB;
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
arcmsr_enable_outbound_ints(acb, intmask_org);
}
}
}
void arcmsr_clear_iop2drv_rqueue_buffer(struct AdapterControlBlock *acb)
{
uint32_t i;
if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) {
for (i = 0; i < 15; i++) {
if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) {
acb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
arcmsr_iop_message_read(acb);
mdelay(30);
} else if (acb->rqbuf_getIndex !=
acb->rqbuf_putIndex) {
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
mdelay(30);
} else
break;
}
}
}
static int arcmsr_iop_message_xfer(struct AdapterControlBlock *acb,
struct scsi_cmnd *cmd)
{
char *buffer;
unsigned short use_sg;
int retvalue = 0, transfer_len = 0;
unsigned long flags;
struct CMD_MESSAGE_FIELD *pcmdmessagefld;
uint32_t controlcode = (uint32_t)cmd->cmnd[5] << 24 |
(uint32_t)cmd->cmnd[6] << 16 |
(uint32_t)cmd->cmnd[7] << 8 |
(uint32_t)cmd->cmnd[8];
struct scatterlist *sg;
use_sg = scsi_sg_count(cmd);
sg = scsi_sglist(cmd);
buffer = kmap_atomic(sg_page(sg)) + sg->offset;
if (use_sg > 1) {
retvalue = ARCMSR_MESSAGE_FAIL;
goto message_out;
}
transfer_len += sg->length;
if (transfer_len > sizeof(struct CMD_MESSAGE_FIELD)) {
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: ARCMSR_MESSAGE_FAIL!\n", __func__);
goto message_out;
}
pcmdmessagefld = (struct CMD_MESSAGE_FIELD *)buffer;
switch (controlcode) {
case ARCMSR_MESSAGE_READ_RQBUFFER: {
unsigned char *ver_addr;
uint8_t *ptmpQbuffer;
uint32_t allxfer_len = 0;
ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);
if (!ver_addr) {
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: memory not enough!\n", __func__);
goto message_out;
}
ptmpQbuffer = ver_addr;
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
if (acb->rqbuf_getIndex != acb->rqbuf_putIndex) {
unsigned int tail = acb->rqbuf_getIndex;
unsigned int head = acb->rqbuf_putIndex;
unsigned int cnt_to_end = CIRC_CNT_TO_END(head, tail, ARCMSR_MAX_QBUFFER);
allxfer_len = CIRC_CNT(head, tail, ARCMSR_MAX_QBUFFER);
if (allxfer_len > ARCMSR_API_DATA_BUFLEN)
allxfer_len = ARCMSR_API_DATA_BUFLEN;
if (allxfer_len <= cnt_to_end)
memcpy(ptmpQbuffer, acb->rqbuffer + tail, allxfer_len);
else {
memcpy(ptmpQbuffer, acb->rqbuffer + tail, cnt_to_end);
memcpy(ptmpQbuffer + cnt_to_end, acb->rqbuffer, allxfer_len - cnt_to_end);
}
acb->rqbuf_getIndex = (acb->rqbuf_getIndex + allxfer_len) % ARCMSR_MAX_QBUFFER;
}
memcpy(pcmdmessagefld->messagedatabuffer, ver_addr,
allxfer_len);
if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) {
struct QBUFFER __iomem *prbuffer;
acb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW;
prbuffer = arcmsr_get_iop_rqbuffer(acb);
if (arcmsr_Read_iop_rqbuffer_data(acb, prbuffer) == 0)
acb->acb_flags |= ACB_F_IOPDATA_OVERFLOW;
}
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
kfree(ver_addr);
pcmdmessagefld->cmdmessage.Length = allxfer_len;
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_WRITE_WQBUFFER: {
unsigned char *ver_addr;
uint32_t user_len;
int32_t cnt2end;
uint8_t *pQbuffer, *ptmpuserbuffer;
ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);
if (!ver_addr) {
retvalue = ARCMSR_MESSAGE_FAIL;
goto message_out;
}
ptmpuserbuffer = ver_addr;
user_len = pcmdmessagefld->cmdmessage.Length;
if (user_len > ARCMSR_API_DATA_BUFLEN) {
retvalue = ARCMSR_MESSAGE_FAIL;
kfree(ver_addr);
goto message_out;
}
memcpy(ptmpuserbuffer,
pcmdmessagefld->messagedatabuffer, user_len);
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
if (acb->wqbuf_putIndex != acb->wqbuf_getIndex) {
struct SENSE_DATA *sensebuffer =
(struct SENSE_DATA *)cmd->sense_buffer;
arcmsr_write_ioctldata2iop(acb);
/* has error report sensedata */
sensebuffer->ErrorCode = SCSI_SENSE_CURRENT_ERRORS;
sensebuffer->SenseKey = ILLEGAL_REQUEST;
sensebuffer->AdditionalSenseLength = 0x0A;
sensebuffer->AdditionalSenseCode = 0x20;
sensebuffer->Valid = 1;
retvalue = ARCMSR_MESSAGE_FAIL;
} else {
pQbuffer = &acb->wqbuffer[acb->wqbuf_putIndex];
cnt2end = ARCMSR_MAX_QBUFFER - acb->wqbuf_putIndex;
if (user_len > cnt2end) {
memcpy(pQbuffer, ptmpuserbuffer, cnt2end);
ptmpuserbuffer += cnt2end;
user_len -= cnt2end;
acb->wqbuf_putIndex = 0;
pQbuffer = acb->wqbuffer;
}
memcpy(pQbuffer, ptmpuserbuffer, user_len);
acb->wqbuf_putIndex += user_len;
acb->wqbuf_putIndex %= ARCMSR_MAX_QBUFFER;
if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_CLEARED) {
acb->acb_flags &=
~ACB_F_MESSAGE_WQBUFFER_CLEARED;
arcmsr_write_ioctldata2iop(acb);
}
}
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
kfree(ver_addr);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_RQBUFFER: {
uint8_t *pQbuffer = acb->rqbuffer;
arcmsr_clear_iop2drv_rqueue_buffer(acb);
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_WQBUFFER: {
uint8_t *pQbuffer = acb->wqbuffer;
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->wqbuf_getIndex = 0;
acb->wqbuf_putIndex = 0;
memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_ALLQBUFFER: {
uint8_t *pQbuffer;
arcmsr_clear_iop2drv_rqueue_buffer(acb);
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
pQbuffer = acb->rqbuffer;
memset(pQbuffer, 0, sizeof(struct QBUFFER));
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->wqbuf_getIndex = 0;
acb->wqbuf_putIndex = 0;
pQbuffer = acb->wqbuffer;
memset(pQbuffer, 0, sizeof(struct QBUFFER));
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_RETURN_CODE_3F: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_3F;
break;
}
case ARCMSR_MESSAGE_SAY_HELLO: {
int8_t *hello_string = "Hello! I am ARCMSR";
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
memcpy(pcmdmessagefld->messagedatabuffer,
hello_string, (int16_t)strlen(hello_string));
break;
}
case ARCMSR_MESSAGE_SAY_GOODBYE: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
arcmsr_iop_parking(acb);
break;
}
case ARCMSR_MESSAGE_FLUSH_ADAPTER_CACHE: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
arcmsr_flush_adapter_cache(acb);
break;
}
default:
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: unknown controlcode!\n", __func__);
}
message_out:
if (use_sg) {
struct scatterlist *sg = scsi_sglist(cmd);
kunmap_atomic(buffer - sg->offset);
}
return retvalue;
}
static struct CommandControlBlock *arcmsr_get_freeccb(struct AdapterControlBlock *acb)
{
struct list_head *head = &acb->ccb_free_list;
struct CommandControlBlock *ccb = NULL;
unsigned long flags;
spin_lock_irqsave(&acb->ccblist_lock, flags);
if (!list_empty(head)) {
ccb = list_entry(head->next, struct CommandControlBlock, list);
list_del_init(&ccb->list);
}else{
spin_unlock_irqrestore(&acb->ccblist_lock, flags);
return NULL;
}
spin_unlock_irqrestore(&acb->ccblist_lock, flags);
return ccb;
}
static void arcmsr_handle_virtual_command(struct AdapterControlBlock *acb,
struct scsi_cmnd *cmd)
{
switch (cmd->cmnd[0]) {
case INQUIRY: {
unsigned char inqdata[36];
char *buffer;
struct scatterlist *sg;
if (cmd->device->lun) {
cmd->result = (DID_TIME_OUT << 16);
cmd->scsi_done(cmd);
return;
}
inqdata[0] = TYPE_PROCESSOR;
/* Periph Qualifier & Periph Dev Type */
inqdata[1] = 0;
/* rem media bit & Dev Type Modifier */
inqdata[2] = 0;
/* ISO, ECMA, & ANSI versions */
inqdata[4] = 31;
/* length of additional data */
strncpy(&inqdata[8], "Areca ", 8);
/* Vendor Identification */
strncpy(&inqdata[16], "RAID controller ", 16);
/* Product Identification */
strncpy(&inqdata[32], "R001", 4); /* Product Revision */
sg = scsi_sglist(cmd);
buffer = kmap_atomic(sg_page(sg)) + sg->offset;
memcpy(buffer, inqdata, sizeof(inqdata));
sg = scsi_sglist(cmd);
kunmap_atomic(buffer - sg->offset);
cmd->scsi_done(cmd);
}
break;
case WRITE_BUFFER:
case READ_BUFFER: {
if (arcmsr_iop_message_xfer(acb, cmd))
cmd->result = (DID_ERROR << 16);
cmd->scsi_done(cmd);
}
break;
default:
cmd->scsi_done(cmd);
}
}
static int arcmsr_queue_command_lck(struct scsi_cmnd *cmd,
void (* done)(struct scsi_cmnd *))
{
struct Scsi_Host *host = cmd->device->host;
struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata;
struct CommandControlBlock *ccb;
int target = cmd->device->id;
int lun = cmd->device->lun;
uint8_t scsicmd = cmd->cmnd[0];
cmd->scsi_done = done;
cmd->host_scribble = NULL;
cmd->result = 0;
if ((scsicmd == SYNCHRONIZE_CACHE) ||(scsicmd == SEND_DIAGNOSTIC)){
if(acb->devstate[target][lun] == ARECA_RAID_GONE) {
cmd->result = (DID_NO_CONNECT << 16);
}
cmd->scsi_done(cmd);
return 0;
}
if (target == 16) {
/* virtual device for iop message transfer */
arcmsr_handle_virtual_command(acb, cmd);
return 0;
}
ccb = arcmsr_get_freeccb(acb);
if (!ccb)
return SCSI_MLQUEUE_HOST_BUSY;
if (arcmsr_build_ccb( acb, ccb, cmd ) == FAILED) {
cmd->result = (DID_ERROR << 16) | (RESERVATION_CONFLICT << 1);
cmd->scsi_done(cmd);
return 0;
}
arcmsr_post_ccb(acb, ccb);
return 0;
}
static DEF_SCSI_QCMD(arcmsr_queue_command)
static bool arcmsr_hbaA_get_config(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
char *acb_firm_model = acb->firm_model;
char *acb_firm_version = acb->firm_version;
char *acb_device_map = acb->device_map;
char __iomem *iop_firm_model = (char __iomem *)(®->message_rwbuffer[15]);
char __iomem *iop_firm_version = (char __iomem *)(®->message_rwbuffer[17]);
char __iomem *iop_device_map = (char __iomem *)(®->message_rwbuffer[21]);
int count;
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG, ®->inbound_msgaddr0);
if (!arcmsr_hbaA_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: wait 'get adapter firmware \
miscellaneous data' timeout \n", acb->host->host_no);
return false;
}
count = 8;
while (count){
*acb_firm_model = readb(iop_firm_model);
acb_firm_model++;
iop_firm_model++;
count--;
}
count = 16;
while (count){
*acb_firm_version = readb(iop_firm_version);
acb_firm_version++;
iop_firm_version++;
count--;
}
count=16;
while(count){
*acb_device_map = readb(iop_device_map);
acb_device_map++;
iop_device_map++;
count--;
}
pr_notice("Areca RAID Controller%d: Model %s, F/W %s\n",
acb->host->host_no,
acb->firm_model,
acb->firm_version);
acb->signature = readl(®->message_rwbuffer[0]);
acb->firm_request_len = readl(®->message_rwbuffer[1]);
acb->firm_numbers_queue = readl(®->message_rwbuffer[2]);
acb->firm_sdram_size = readl(®->message_rwbuffer[3]);
acb->firm_hd_channels = readl(®->message_rwbuffer[4]);
acb->firm_cfg_version = readl(®->message_rwbuffer[25]); /*firm_cfg_version,25,100-103*/
return true;
}
static bool arcmsr_hbaB_get_config(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
char *acb_firm_model = acb->firm_model;
char *acb_firm_version = acb->firm_version;
char *acb_device_map = acb->device_map;
char __iomem *iop_firm_model;
/*firm_model,15,60-67*/
char __iomem *iop_firm_version;
/*firm_version,17,68-83*/
char __iomem *iop_device_map;
/*firm_version,21,84-99*/
int count;
iop_firm_model = (char __iomem *)(®->message_rwbuffer[15]); /*firm_model,15,60-67*/
iop_firm_version = (char __iomem *)(®->message_rwbuffer[17]); /*firm_version,17,68-83*/
iop_device_map = (char __iomem *)(®->message_rwbuffer[21]); /*firm_version,21,84-99*/
arcmsr_wait_firmware_ready(acb);
writel(ARCMSR_MESSAGE_START_DRIVER_MODE, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_ERR "arcmsr%d: can't set driver mode.\n", acb->host->host_no);
return false;
}
writel(ARCMSR_MESSAGE_GET_CONFIG, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: wait 'get adapter firmware \
miscellaneous data' timeout \n", acb->host->host_no);
return false;
}
count = 8;
while (count){
*acb_firm_model = readb(iop_firm_model);
acb_firm_model++;
iop_firm_model++;
count--;
}
count = 16;
while (count){
*acb_firm_version = readb(iop_firm_version);
acb_firm_version++;
iop_firm_version++;
count--;
}
count = 16;
while(count){
*acb_device_map = readb(iop_device_map);
acb_device_map++;
iop_device_map++;
count--;
}
pr_notice("Areca RAID Controller%d: Model %s, F/W %s\n",
acb->host->host_no,
acb->firm_model,
acb->firm_version);
acb->signature = readl(®->message_rwbuffer[0]);
/*firm_signature,1,00-03*/
acb->firm_request_len = readl(®->message_rwbuffer[1]);
/*firm_request_len,1,04-07*/
acb->firm_numbers_queue = readl(®->message_rwbuffer[2]);
/*firm_numbers_queue,2,08-11*/
acb->firm_sdram_size = readl(®->message_rwbuffer[3]);
/*firm_sdram_size,3,12-15*/
acb->firm_hd_channels = readl(®->message_rwbuffer[4]);
/*firm_ide_channels,4,16-19*/
acb->firm_cfg_version = readl(®->message_rwbuffer[25]); /*firm_cfg_version,25,100-103*/
/*firm_ide_channels,4,16-19*/
return true;
}
static bool arcmsr_hbaC_get_config(struct AdapterControlBlock *pACB)
{
uint32_t intmask_org, Index, firmware_state = 0;
struct MessageUnit_C __iomem *reg = pACB->pmuC;
char *acb_firm_model = pACB->firm_model;
char *acb_firm_version = pACB->firm_version;
char __iomem *iop_firm_model = (char __iomem *)(®->msgcode_rwbuffer[15]); /*firm_model,15,60-67*/
char __iomem *iop_firm_version = (char __iomem *)(®->msgcode_rwbuffer[17]); /*firm_version,17,68-83*/
int count;
/* disable all outbound interrupt */
intmask_org = readl(®->host_int_mask); /* disable outbound message0 int */
writel(intmask_org|ARCMSR_HBCMU_ALL_INTMASKENABLE, ®->host_int_mask);
/* wait firmware ready */
do {
firmware_state = readl(®->outbound_msgaddr1);
} while ((firmware_state & ARCMSR_HBCMU_MESSAGE_FIRMWARE_OK) == 0);
/* post "get config" instruction */
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
/* wait message ready */
for (Index = 0; Index < 2000; Index++) {
if (readl(®->outbound_doorbell) & ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE_DOORBELL_CLEAR, ®->outbound_doorbell_clear);/*clear interrupt*/
break;
}
udelay(10);
} /*max 1 seconds*/
if (Index >= 2000) {
printk(KERN_NOTICE "arcmsr%d: wait 'get adapter firmware \
miscellaneous data' timeout \n", pACB->host->host_no);
return false;
}
count = 8;
while (count) {
*acb_firm_model = readb(iop_firm_model);
acb_firm_model++;
iop_firm_model++;
count--;
}
count = 16;
while (count) {
*acb_firm_version = readb(iop_firm_version);
acb_firm_version++;
iop_firm_version++;
count--;
}
pr_notice("Areca RAID Controller%d: Model %s, F/W %s\n",
pACB->host->host_no,
pACB->firm_model,
pACB->firm_version);
pACB->firm_request_len = readl(®->msgcode_rwbuffer[1]); /*firm_request_len,1,04-07*/
pACB->firm_numbers_queue = readl(®->msgcode_rwbuffer[2]); /*firm_numbers_queue,2,08-11*/
pACB->firm_sdram_size = readl(®->msgcode_rwbuffer[3]); /*firm_sdram_size,3,12-15*/
pACB->firm_hd_channels = readl(®->msgcode_rwbuffer[4]); /*firm_ide_channels,4,16-19*/
pACB->firm_cfg_version = readl(®->msgcode_rwbuffer[25]); /*firm_cfg_version,25,100-103*/
/*all interrupt service will be enable at arcmsr_iop_init*/
return true;
}
static bool arcmsr_hbaD_get_config(struct AdapterControlBlock *acb)
{
char *acb_firm_model = acb->firm_model;
char *acb_firm_version = acb->firm_version;
char *acb_device_map = acb->device_map;
char __iomem *iop_firm_model;
char __iomem *iop_firm_version;
char __iomem *iop_device_map;
u32 count;
struct MessageUnit_D *reg = acb->pmuD;
iop_firm_model = (char __iomem *)(®->msgcode_rwbuffer[15]);
iop_firm_version = (char __iomem *)(®->msgcode_rwbuffer[17]);
iop_device_map = (char __iomem *)(®->msgcode_rwbuffer[21]);
if (readl(acb->pmuD->outbound_doorbell) &
ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE,
acb->pmuD->outbound_doorbell);/*clear interrupt*/
}
/* post "get config" instruction */
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG, reg->inbound_msgaddr0);
/* wait message ready */
if (!arcmsr_hbaD_wait_msgint_ready(acb)) {
pr_notice("arcmsr%d: wait get adapter firmware "
"miscellaneous data timeout\n", acb->host->host_no);
return false;
}
count = 8;
while (count) {
*acb_firm_model = readb(iop_firm_model);
acb_firm_model++;
iop_firm_model++;
count--;
}
count = 16;
while (count) {
*acb_firm_version = readb(iop_firm_version);
acb_firm_version++;
iop_firm_version++;
count--;
}
count = 16;
while (count) {
*acb_device_map = readb(iop_device_map);
acb_device_map++;
iop_device_map++;
count--;
}
acb->signature = readl(®->msgcode_rwbuffer[0]);
/*firm_signature,1,00-03*/
acb->firm_request_len = readl(®->msgcode_rwbuffer[1]);
/*firm_request_len,1,04-07*/
acb->firm_numbers_queue = readl(®->msgcode_rwbuffer[2]);
/*firm_numbers_queue,2,08-11*/
acb->firm_sdram_size = readl(®->msgcode_rwbuffer[3]);
/*firm_sdram_size,3,12-15*/
acb->firm_hd_channels = readl(®->msgcode_rwbuffer[4]);
/*firm_hd_channels,4,16-19*/
acb->firm_cfg_version = readl(®->msgcode_rwbuffer[25]);
pr_notice("Areca RAID Controller%d: Model %s, F/W %s\n",
acb->host->host_no,
acb->firm_model,
acb->firm_version);
return true;
}
static bool arcmsr_get_firmware_spec(struct AdapterControlBlock *acb)
{
bool rtn = false;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:
rtn = arcmsr_hbaA_get_config(acb);
break;
case ACB_ADAPTER_TYPE_B:
rtn = arcmsr_hbaB_get_config(acb);
break;
case ACB_ADAPTER_TYPE_C:
rtn = arcmsr_hbaC_get_config(acb);
break;
case ACB_ADAPTER_TYPE_D:
rtn = arcmsr_hbaD_get_config(acb);
break;
default:
break;
}
if (acb->firm_numbers_queue > ARCMSR_MAX_OUTSTANDING_CMD)
acb->maxOutstanding = ARCMSR_MAX_OUTSTANDING_CMD;
else
acb->maxOutstanding = acb->firm_numbers_queue - 1;
acb->host->can_queue = acb->maxOutstanding;
return rtn;
}
static int arcmsr_hbaA_polling_ccbdone(struct AdapterControlBlock *acb,
struct CommandControlBlock *poll_ccb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
struct CommandControlBlock *ccb;
struct ARCMSR_CDB *arcmsr_cdb;
uint32_t flag_ccb, outbound_intstatus, poll_ccb_done = 0, poll_count = 0;
int rtn;
bool error;
polling_hba_ccb_retry:
poll_count++;
outbound_intstatus = readl(®->outbound_intstatus) & acb->outbound_int_enable;
writel(outbound_intstatus, ®->outbound_intstatus);/*clear interrupt*/
while (1) {
if ((flag_ccb = readl(®->outbound_queueport)) == 0xFFFFFFFF) {
if (poll_ccb_done){
rtn = SUCCESS;
break;
}else {
msleep(25);
if (poll_count > 100){
rtn = FAILED;
break;
}
goto polling_hba_ccb_retry;
}
}
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset + (flag_ccb << 5));
ccb = container_of(arcmsr_cdb, struct CommandControlBlock, arcmsr_cdb);
poll_ccb_done |= (ccb == poll_ccb) ? 1 : 0;
if ((ccb->acb != acb) || (ccb->startdone != ARCMSR_CCB_START)) {
if ((ccb->startdone == ARCMSR_CCB_ABORTED) || (ccb == poll_ccb)) {
printk(KERN_NOTICE "arcmsr%d: scsi id = %d lun = %d ccb = '0x%p'"
" poll command abort successfully \n"
, acb->host->host_no
, ccb->pcmd->device->id
, (u32)ccb->pcmd->device->lun
, ccb);
ccb->pcmd->result = DID_ABORT << 16;
arcmsr_ccb_complete(ccb);
continue;
}
printk(KERN_NOTICE "arcmsr%d: polling get an illegal ccb"
" command done ccb = '0x%p'"
"ccboutstandingcount = %d \n"
, acb->host->host_no
, ccb
, atomic_read(&acb->ccboutstandingcount));
continue;
}
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_report_ccb_state(acb, ccb, error);
}
return rtn;
}
static int arcmsr_hbaB_polling_ccbdone(struct AdapterControlBlock *acb,
struct CommandControlBlock *poll_ccb)
{
struct MessageUnit_B *reg = acb->pmuB;
struct ARCMSR_CDB *arcmsr_cdb;
struct CommandControlBlock *ccb;
uint32_t flag_ccb, poll_ccb_done = 0, poll_count = 0;
int index, rtn;
bool error;
polling_hbb_ccb_retry:
poll_count++;
/* clear doorbell interrupt */
writel(ARCMSR_DOORBELL_INT_CLEAR_PATTERN, reg->iop2drv_doorbell);
while(1){
index = reg->doneq_index;
flag_ccb = reg->done_qbuffer[index];
if (flag_ccb == 0) {
if (poll_ccb_done){
rtn = SUCCESS;
break;
}else {
msleep(25);
if (poll_count > 100){
rtn = FAILED;
break;
}
goto polling_hbb_ccb_retry;
}
}
reg->done_qbuffer[index] = 0;
index++;
/*if last index number set it to 0 */
index %= ARCMSR_MAX_HBB_POSTQUEUE;
reg->doneq_index = index;
/* check if command done with no error*/
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset + (flag_ccb << 5));
ccb = container_of(arcmsr_cdb, struct CommandControlBlock, arcmsr_cdb);
poll_ccb_done |= (ccb == poll_ccb) ? 1 : 0;
if ((ccb->acb != acb) || (ccb->startdone != ARCMSR_CCB_START)) {
if ((ccb->startdone == ARCMSR_CCB_ABORTED) || (ccb == poll_ccb)) {
printk(KERN_NOTICE "arcmsr%d: scsi id = %d lun = %d ccb = '0x%p'"
" poll command abort successfully \n"
,acb->host->host_no
,ccb->pcmd->device->id
,(u32)ccb->pcmd->device->lun
,ccb);
ccb->pcmd->result = DID_ABORT << 16;
arcmsr_ccb_complete(ccb);
continue;
}
printk(KERN_NOTICE "arcmsr%d: polling get an illegal ccb"
" command done ccb = '0x%p'"
"ccboutstandingcount = %d \n"
, acb->host->host_no
, ccb
, atomic_read(&acb->ccboutstandingcount));
continue;
}
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_report_ccb_state(acb, ccb, error);
}
return rtn;
}
static int arcmsr_hbaC_polling_ccbdone(struct AdapterControlBlock *acb,
struct CommandControlBlock *poll_ccb)
{
struct MessageUnit_C __iomem *reg = acb->pmuC;
uint32_t flag_ccb, ccb_cdb_phy;
struct ARCMSR_CDB *arcmsr_cdb;
bool error;
struct CommandControlBlock *pCCB;
uint32_t poll_ccb_done = 0, poll_count = 0;
int rtn;
polling_hbc_ccb_retry:
poll_count++;
while (1) {
if ((readl(®->host_int_status) & ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR) == 0) {
if (poll_ccb_done) {
rtn = SUCCESS;
break;
} else {
msleep(25);
if (poll_count > 100) {
rtn = FAILED;
break;
}
goto polling_hbc_ccb_retry;
}
}
flag_ccb = readl(®->outbound_queueport_low);
ccb_cdb_phy = (flag_ccb & 0xFFFFFFF0);
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset + ccb_cdb_phy);/*frame must be 32 bytes aligned*/
pCCB = container_of(arcmsr_cdb, struct CommandControlBlock, arcmsr_cdb);
poll_ccb_done |= (pCCB == poll_ccb) ? 1 : 0;
/* check ifcommand done with no error*/
if ((pCCB->acb != acb) || (pCCB->startdone != ARCMSR_CCB_START)) {
if (pCCB->startdone == ARCMSR_CCB_ABORTED) {
printk(KERN_NOTICE "arcmsr%d: scsi id = %d lun = %d ccb = '0x%p'"
" poll command abort successfully \n"
, acb->host->host_no
, pCCB->pcmd->device->id
, (u32)pCCB->pcmd->device->lun
, pCCB);
pCCB->pcmd->result = DID_ABORT << 16;
arcmsr_ccb_complete(pCCB);
continue;
}
printk(KERN_NOTICE "arcmsr%d: polling get an illegal ccb"
" command done ccb = '0x%p'"
"ccboutstandingcount = %d \n"
, acb->host->host_no
, pCCB
, atomic_read(&acb->ccboutstandingcount));
continue;
}
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1) ? true : false;
arcmsr_report_ccb_state(acb, pCCB, error);
}
return rtn;
}
static int arcmsr_hbaD_polling_ccbdone(struct AdapterControlBlock *acb,
struct CommandControlBlock *poll_ccb)
{
bool error;
uint32_t poll_ccb_done = 0, poll_count = 0, flag_ccb, ccb_cdb_phy;
int rtn, doneq_index, index_stripped, outbound_write_pointer, toggle;
unsigned long flags;
struct ARCMSR_CDB *arcmsr_cdb;
struct CommandControlBlock *pCCB;
struct MessageUnit_D *pmu = acb->pmuD;
polling_hbaD_ccb_retry:
poll_count++;
while (1) {
spin_lock_irqsave(&acb->doneq_lock, flags);
outbound_write_pointer = pmu->done_qbuffer[0].addressLow + 1;
doneq_index = pmu->doneq_index;
if ((outbound_write_pointer & 0xFFF) == (doneq_index & 0xFFF)) {
spin_unlock_irqrestore(&acb->doneq_lock, flags);
if (poll_ccb_done) {
rtn = SUCCESS;
break;
} else {
msleep(25);
if (poll_count > 40) {
rtn = FAILED;
break;
}
goto polling_hbaD_ccb_retry;
}
}
toggle = doneq_index & 0x4000;
index_stripped = (doneq_index & 0xFFF) + 1;
index_stripped %= ARCMSR_MAX_ARC1214_DONEQUEUE;
pmu->doneq_index = index_stripped ? (index_stripped | toggle) :
((toggle ^ 0x4000) + 1);
doneq_index = pmu->doneq_index;
spin_unlock_irqrestore(&acb->doneq_lock, flags);
flag_ccb = pmu->done_qbuffer[doneq_index & 0xFFF].addressLow;
ccb_cdb_phy = (flag_ccb & 0xFFFFFFF0);
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset +
ccb_cdb_phy);
pCCB = container_of(arcmsr_cdb, struct CommandControlBlock,
arcmsr_cdb);
poll_ccb_done |= (pCCB == poll_ccb) ? 1 : 0;
if ((pCCB->acb != acb) ||
(pCCB->startdone != ARCMSR_CCB_START)) {
if (pCCB->startdone == ARCMSR_CCB_ABORTED) {
pr_notice("arcmsr%d: scsi id = %d "
"lun = %d ccb = '0x%p' poll command "
"abort successfully\n"
, acb->host->host_no
, pCCB->pcmd->device->id
, (u32)pCCB->pcmd->device->lun
, pCCB);
pCCB->pcmd->result = DID_ABORT << 16;
arcmsr_ccb_complete(pCCB);
continue;
}
pr_notice("arcmsr%d: polling an illegal "
"ccb command done ccb = '0x%p' "
"ccboutstandingcount = %d\n"
, acb->host->host_no
, pCCB
, atomic_read(&acb->ccboutstandingcount));
continue;
}
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1)
? true : false;
arcmsr_report_ccb_state(acb, pCCB, error);
}
return rtn;
}
static int arcmsr_polling_ccbdone(struct AdapterControlBlock *acb,
struct CommandControlBlock *poll_ccb)
{
int rtn = 0;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
rtn = arcmsr_hbaA_polling_ccbdone(acb, poll_ccb);
}
break;
case ACB_ADAPTER_TYPE_B: {
rtn = arcmsr_hbaB_polling_ccbdone(acb, poll_ccb);
}
break;
case ACB_ADAPTER_TYPE_C: {
rtn = arcmsr_hbaC_polling_ccbdone(acb, poll_ccb);
}
break;
case ACB_ADAPTER_TYPE_D:
rtn = arcmsr_hbaD_polling_ccbdone(acb, poll_ccb);
break;
}
return rtn;
}
static int arcmsr_iop_confirm(struct AdapterControlBlock *acb)
{
uint32_t cdb_phyaddr, cdb_phyaddr_hi32;
dma_addr_t dma_coherent_handle;
/*
********************************************************************
** here we need to tell iop 331 our freeccb.HighPart
** if freeccb.HighPart is not zero
********************************************************************
*/
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_B:
case ACB_ADAPTER_TYPE_D:
dma_coherent_handle = acb->dma_coherent_handle2;
break;
default:
dma_coherent_handle = acb->dma_coherent_handle;
break;
}
cdb_phyaddr = lower_32_bits(dma_coherent_handle);
cdb_phyaddr_hi32 = upper_32_bits(dma_coherent_handle);
acb->cdb_phyaddr_hi32 = cdb_phyaddr_hi32;
/*
***********************************************************************
** if adapter type B, set window of "post command Q"
***********************************************************************
*/
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
if (cdb_phyaddr_hi32 != 0) {
struct MessageUnit_A __iomem *reg = acb->pmuA;
writel(ARCMSR_SIGNATURE_SET_CONFIG, \
®->message_rwbuffer[0]);
writel(cdb_phyaddr_hi32, ®->message_rwbuffer[1]);
writel(ARCMSR_INBOUND_MESG0_SET_CONFIG, \
®->inbound_msgaddr0);
if (!arcmsr_hbaA_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: ""set ccb high \
part physical address timeout\n",
acb->host->host_no);
return 1;
}
}
}
break;
case ACB_ADAPTER_TYPE_B: {
uint32_t __iomem *rwbuffer;
struct MessageUnit_B *reg = acb->pmuB;
reg->postq_index = 0;
reg->doneq_index = 0;
writel(ARCMSR_MESSAGE_SET_POST_WINDOW, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: cannot set driver mode\n", \
acb->host->host_no);
return 1;
}
rwbuffer = reg->message_rwbuffer;
/* driver "set config" signature */
writel(ARCMSR_SIGNATURE_SET_CONFIG, rwbuffer++);
/* normal should be zero */
writel(cdb_phyaddr_hi32, rwbuffer++);
/* postQ size (256 + 8)*4 */
writel(cdb_phyaddr, rwbuffer++);
/* doneQ size (256 + 8)*4 */
writel(cdb_phyaddr + 1056, rwbuffer++);
/* ccb maxQ size must be --> [(256 + 8)*4]*/
writel(1056, rwbuffer);
writel(ARCMSR_MESSAGE_SET_CONFIG, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: 'set command Q window' \
timeout \n",acb->host->host_no);
return 1;
}
writel(ARCMSR_MESSAGE_START_DRIVER_MODE, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
pr_err("arcmsr%d: can't set driver mode.\n",
acb->host->host_no);
return 1;
}
}
break;
case ACB_ADAPTER_TYPE_C: {
if (cdb_phyaddr_hi32 != 0) {
struct MessageUnit_C __iomem *reg = acb->pmuC;
printk(KERN_NOTICE "arcmsr%d: cdb_phyaddr_hi32=0x%x\n",
acb->adapter_index, cdb_phyaddr_hi32);
writel(ARCMSR_SIGNATURE_SET_CONFIG, ®->msgcode_rwbuffer[0]);
writel(cdb_phyaddr_hi32, ®->msgcode_rwbuffer[1]);
writel(ARCMSR_INBOUND_MESG0_SET_CONFIG, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
if (!arcmsr_hbaC_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: 'set command Q window' \
timeout \n", acb->host->host_no);
return 1;
}
}
}
break;
case ACB_ADAPTER_TYPE_D: {
uint32_t __iomem *rwbuffer;
struct MessageUnit_D *reg = acb->pmuD;
reg->postq_index = 0;
reg->doneq_index = 0;
rwbuffer = reg->msgcode_rwbuffer;
writel(ARCMSR_SIGNATURE_SET_CONFIG, rwbuffer++);
writel(cdb_phyaddr_hi32, rwbuffer++);
writel(cdb_phyaddr, rwbuffer++);
writel(cdb_phyaddr + (ARCMSR_MAX_ARC1214_POSTQUEUE *
sizeof(struct InBound_SRB)), rwbuffer++);
writel(0x100, rwbuffer);
writel(ARCMSR_INBOUND_MESG0_SET_CONFIG, reg->inbound_msgaddr0);
if (!arcmsr_hbaD_wait_msgint_ready(acb)) {
pr_notice("arcmsr%d: 'set command Q window' timeout\n",
acb->host->host_no);
return 1;
}
}
break;
}
return 0;
}
static void arcmsr_wait_firmware_ready(struct AdapterControlBlock *acb)
{
uint32_t firmware_state = 0;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
do {
firmware_state = readl(®->outbound_msgaddr1);
} while ((firmware_state & ARCMSR_OUTBOUND_MESG1_FIRMWARE_OK) == 0);
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
do {
firmware_state = readl(reg->iop2drv_doorbell);
} while ((firmware_state & ARCMSR_MESSAGE_FIRMWARE_OK) == 0);
writel(ARCMSR_DRV2IOP_END_OF_INTERRUPT, reg->drv2iop_doorbell);
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
do {
firmware_state = readl(®->outbound_msgaddr1);
} while ((firmware_state & ARCMSR_HBCMU_MESSAGE_FIRMWARE_OK) == 0);
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
do {
firmware_state = readl(reg->outbound_msgaddr1);
} while ((firmware_state &
ARCMSR_ARC1214_MESSAGE_FIRMWARE_OK) == 0);
}
break;
}
}
static void arcmsr_hbaA_request_device_map(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
if (unlikely(atomic_read(&acb->rq_map_token) == 0) || ((acb->acb_flags & ACB_F_BUS_RESET) != 0 ) || ((acb->acb_flags & ACB_F_ABORT) != 0 )){
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
} else {
acb->fw_flag = FW_NORMAL;
if (atomic_read(&acb->ante_token_value) == atomic_read(&acb->rq_map_token)){
atomic_set(&acb->rq_map_token, 16);
}
atomic_set(&acb->ante_token_value, atomic_read(&acb->rq_map_token));
if (atomic_dec_and_test(&acb->rq_map_token)) {
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
}
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG, ®->inbound_msgaddr0);
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
}
return;
}
static void arcmsr_hbaB_request_device_map(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
if (unlikely(atomic_read(&acb->rq_map_token) == 0) || ((acb->acb_flags & ACB_F_BUS_RESET) != 0 ) || ((acb->acb_flags & ACB_F_ABORT) != 0 )){
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
} else {
acb->fw_flag = FW_NORMAL;
if (atomic_read(&acb->ante_token_value) == atomic_read(&acb->rq_map_token)) {
atomic_set(&acb->rq_map_token, 16);
}
atomic_set(&acb->ante_token_value, atomic_read(&acb->rq_map_token));
if (atomic_dec_and_test(&acb->rq_map_token)) {
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
}
writel(ARCMSR_MESSAGE_GET_CONFIG, reg->drv2iop_doorbell);
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
}
return;
}
static void arcmsr_hbaC_request_device_map(struct AdapterControlBlock *acb)
{
struct MessageUnit_C __iomem *reg = acb->pmuC;
if (unlikely(atomic_read(&acb->rq_map_token) == 0) || ((acb->acb_flags & ACB_F_BUS_RESET) != 0) || ((acb->acb_flags & ACB_F_ABORT) != 0)) {
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
} else {
acb->fw_flag = FW_NORMAL;
if (atomic_read(&acb->ante_token_value) == atomic_read(&acb->rq_map_token)) {
atomic_set(&acb->rq_map_token, 16);
}
atomic_set(&acb->ante_token_value, atomic_read(&acb->rq_map_token));
if (atomic_dec_and_test(&acb->rq_map_token)) {
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
}
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
}
return;
}
static void arcmsr_hbaD_request_device_map(struct AdapterControlBlock *acb)
{
struct MessageUnit_D *reg = acb->pmuD;
if (unlikely(atomic_read(&acb->rq_map_token) == 0) ||
((acb->acb_flags & ACB_F_BUS_RESET) != 0) ||
((acb->acb_flags & ACB_F_ABORT) != 0)) {
mod_timer(&acb->eternal_timer,
jiffies + msecs_to_jiffies(6 * HZ));
} else {
acb->fw_flag = FW_NORMAL;
if (atomic_read(&acb->ante_token_value) ==
atomic_read(&acb->rq_map_token)) {
atomic_set(&acb->rq_map_token, 16);
}
atomic_set(&acb->ante_token_value,
atomic_read(&acb->rq_map_token));
if (atomic_dec_and_test(&acb->rq_map_token)) {
mod_timer(&acb->eternal_timer, jiffies +
msecs_to_jiffies(6 * HZ));
return;
}
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG,
reg->inbound_msgaddr0);
mod_timer(&acb->eternal_timer, jiffies +
msecs_to_jiffies(6 * HZ));
}
}
static void arcmsr_request_device_map(unsigned long pacb)
{
struct AdapterControlBlock *acb = (struct AdapterControlBlock *)pacb;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
arcmsr_hbaA_request_device_map(acb);
}
break;
case ACB_ADAPTER_TYPE_B: {
arcmsr_hbaB_request_device_map(acb);
}
break;
case ACB_ADAPTER_TYPE_C: {
arcmsr_hbaC_request_device_map(acb);
}
break;
case ACB_ADAPTER_TYPE_D:
arcmsr_hbaD_request_device_map(acb);
break;
}
}
static void arcmsr_hbaA_start_bgrb(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
acb->acb_flags |= ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_START_BGRB, ®->inbound_msgaddr0);
if (!arcmsr_hbaA_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: wait 'start adapter background \
rebulid' timeout \n", acb->host->host_no);
}
}
static void arcmsr_hbaB_start_bgrb(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
acb->acb_flags |= ACB_F_MSG_START_BGRB;
writel(ARCMSR_MESSAGE_START_BGRB, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: wait 'start adapter background \
rebulid' timeout \n",acb->host->host_no);
}
}
static void arcmsr_hbaC_start_bgrb(struct AdapterControlBlock *pACB)
{
struct MessageUnit_C __iomem *phbcmu = pACB->pmuC;
pACB->acb_flags |= ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_START_BGRB, &phbcmu->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, &phbcmu->inbound_doorbell);
if (!arcmsr_hbaC_wait_msgint_ready(pACB)) {
printk(KERN_NOTICE "arcmsr%d: wait 'start adapter background \
rebulid' timeout \n", pACB->host->host_no);
}
return;
}
static void arcmsr_hbaD_start_bgrb(struct AdapterControlBlock *pACB)
{
struct MessageUnit_D *pmu = pACB->pmuD;
pACB->acb_flags |= ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_START_BGRB, pmu->inbound_msgaddr0);
if (!arcmsr_hbaD_wait_msgint_ready(pACB)) {
pr_notice("arcmsr%d: wait 'start adapter "
"background rebulid' timeout\n", pACB->host->host_no);
}
}
static void arcmsr_start_adapter_bgrb(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:
arcmsr_hbaA_start_bgrb(acb);
break;
case ACB_ADAPTER_TYPE_B:
arcmsr_hbaB_start_bgrb(acb);
break;
case ACB_ADAPTER_TYPE_C:
arcmsr_hbaC_start_bgrb(acb);
break;
case ACB_ADAPTER_TYPE_D:
arcmsr_hbaD_start_bgrb(acb);
break;
}
}
static void arcmsr_clear_doorbell_queue_buffer(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
uint32_t outbound_doorbell;
/* empty doorbell Qbuffer if door bell ringed */
outbound_doorbell = readl(®->outbound_doorbell);
/*clear doorbell interrupt */
writel(outbound_doorbell, ®->outbound_doorbell);
writel(ARCMSR_INBOUND_DRIVER_DATA_READ_OK, ®->inbound_doorbell);
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
/*clear interrupt and message state*/
writel(ARCMSR_MESSAGE_INT_CLEAR_PATTERN, reg->iop2drv_doorbell);
writel(ARCMSR_DRV2IOP_DATA_READ_OK, reg->drv2iop_doorbell);
/* let IOP know data has been read */
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
uint32_t outbound_doorbell, i;
/* empty doorbell Qbuffer if door bell ringed */
outbound_doorbell = readl(®->outbound_doorbell);
writel(outbound_doorbell, ®->outbound_doorbell_clear);
writel(ARCMSR_HBCMU_DRV2IOP_DATA_READ_OK, ®->inbound_doorbell);
for (i = 0; i < 200; i++) {
msleep(20);
outbound_doorbell = readl(®->outbound_doorbell);
if (outbound_doorbell &
ARCMSR_HBCMU_IOP2DRV_DATA_WRITE_OK) {
writel(outbound_doorbell,
®->outbound_doorbell_clear);
writel(ARCMSR_HBCMU_DRV2IOP_DATA_READ_OK,
®->inbound_doorbell);
} else
break;
}
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
uint32_t outbound_doorbell, i;
/* empty doorbell Qbuffer if door bell ringed */
outbound_doorbell = readl(reg->outbound_doorbell);
writel(outbound_doorbell, reg->outbound_doorbell);
writel(ARCMSR_ARC1214_DRV2IOP_DATA_OUT_READ,
reg->inbound_doorbell);
for (i = 0; i < 200; i++) {
msleep(20);
outbound_doorbell = readl(reg->outbound_doorbell);
if (outbound_doorbell &
ARCMSR_ARC1214_IOP2DRV_DATA_WRITE_OK) {
writel(outbound_doorbell,
reg->outbound_doorbell);
writel(ARCMSR_ARC1214_DRV2IOP_DATA_OUT_READ,
reg->inbound_doorbell);
} else
break;
}
}
break;
}
}
static void arcmsr_enable_eoi_mode(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:
return;
case ACB_ADAPTER_TYPE_B:
{
struct MessageUnit_B *reg = acb->pmuB;
writel(ARCMSR_MESSAGE_ACTIVE_EOI_MODE, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "ARCMSR IOP enables EOI_MODE TIMEOUT");
return;
}
}
break;
case ACB_ADAPTER_TYPE_C:
return;
}
return;
}
static void arcmsr_hardware_reset(struct AdapterControlBlock *acb)
{
uint8_t value[64];
int i, count = 0;
struct MessageUnit_A __iomem *pmuA = acb->pmuA;
struct MessageUnit_C __iomem *pmuC = acb->pmuC;
struct MessageUnit_D *pmuD = acb->pmuD;
/* backup pci config data */
printk(KERN_NOTICE "arcmsr%d: executing hw bus reset .....\n", acb->host->host_no);
for (i = 0; i < 64; i++) {
pci_read_config_byte(acb->pdev, i, &value[i]);
}
/* hardware reset signal */
if ((acb->dev_id == 0x1680)) {
writel(ARCMSR_ARC1680_BUS_RESET, &pmuA->reserved1[0]);
} else if ((acb->dev_id == 0x1880)) {
do {
count++;
writel(0xF, &pmuC->write_sequence);
writel(0x4, &pmuC->write_sequence);
writel(0xB, &pmuC->write_sequence);
writel(0x2, &pmuC->write_sequence);
writel(0x7, &pmuC->write_sequence);
writel(0xD, &pmuC->write_sequence);
} while (((readl(&pmuC->host_diagnostic) & ARCMSR_ARC1880_DiagWrite_ENABLE) == 0) && (count < 5));
writel(ARCMSR_ARC1880_RESET_ADAPTER, &pmuC->host_diagnostic);
} else if ((acb->dev_id == 0x1214)) {
writel(0x20, pmuD->reset_request);
} else {
pci_write_config_byte(acb->pdev, 0x84, 0x20);
}
msleep(2000);
/* write back pci config data */
for (i = 0; i < 64; i++) {
pci_write_config_byte(acb->pdev, i, value[i]);
}
msleep(1000);
return;
}
static void arcmsr_iop_init(struct AdapterControlBlock *acb)
{
uint32_t intmask_org;
/* disable all outbound interrupt */
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_wait_firmware_ready(acb);
arcmsr_iop_confirm(acb);
/*start background rebuild*/
arcmsr_start_adapter_bgrb(acb);
/* empty doorbell Qbuffer if door bell ringed */
arcmsr_clear_doorbell_queue_buffer(acb);
arcmsr_enable_eoi_mode(acb);
/* enable outbound Post Queue,outbound doorbell Interrupt */
arcmsr_enable_outbound_ints(acb, intmask_org);
acb->acb_flags |= ACB_F_IOP_INITED;
}
static uint8_t arcmsr_iop_reset(struct AdapterControlBlock *acb)
{
struct CommandControlBlock *ccb;
uint32_t intmask_org;
uint8_t rtnval = 0x00;
int i = 0;
unsigned long flags;
if (atomic_read(&acb->ccboutstandingcount) != 0) {
/* disable all outbound interrupt */
intmask_org = arcmsr_disable_outbound_ints(acb);
/* talk to iop 331 outstanding command aborted */
rtnval = arcmsr_abort_allcmd(acb);
/* clear all outbound posted Q */
arcmsr_done4abort_postqueue(acb);
for (i = 0; i < ARCMSR_MAX_FREECCB_NUM; i++) {
ccb = acb->pccb_pool[i];
if (ccb->startdone == ARCMSR_CCB_START) {
scsi_dma_unmap(ccb->pcmd);
ccb->startdone = ARCMSR_CCB_DONE;
ccb->ccb_flags = 0;
spin_lock_irqsave(&acb->ccblist_lock, flags);
list_add_tail(&ccb->list, &acb->ccb_free_list);
spin_unlock_irqrestore(&acb->ccblist_lock, flags);
}
}
atomic_set(&acb->ccboutstandingcount, 0);
/* enable all outbound interrupt */
arcmsr_enable_outbound_ints(acb, intmask_org);
return rtnval;
}
return rtnval;
}
static int arcmsr_bus_reset(struct scsi_cmnd *cmd)
{
struct AdapterControlBlock *acb;
uint32_t intmask_org, outbound_doorbell;
int retry_count = 0;
int rtn = FAILED;
acb = (struct AdapterControlBlock *) cmd->device->host->hostdata;
printk(KERN_ERR "arcmsr: executing bus reset eh.....num_resets = %d, num_aborts = %d \n", acb->num_resets, acb->num_aborts);
acb->num_resets++;
switch(acb->adapter_type){
case ACB_ADAPTER_TYPE_A:{
if (acb->acb_flags & ACB_F_BUS_RESET){
long timeout;
printk(KERN_ERR "arcmsr: there is an bus reset eh proceeding.......\n");
timeout = wait_event_timeout(wait_q, (acb->acb_flags & ACB_F_BUS_RESET) == 0, 220*HZ);
if (timeout) {
return SUCCESS;
}
}
acb->acb_flags |= ACB_F_BUS_RESET;
if (!arcmsr_iop_reset(acb)) {
struct MessageUnit_A __iomem *reg;
reg = acb->pmuA;
arcmsr_hardware_reset(acb);
acb->acb_flags &= ~ACB_F_IOP_INITED;
sleep_again:
ssleep(ARCMSR_SLEEPTIME);
if ((readl(®->outbound_msgaddr1) & ARCMSR_OUTBOUND_MESG1_FIRMWARE_OK) == 0) {
printk(KERN_ERR "arcmsr%d: waiting for hw bus reset return, retry=%d\n", acb->host->host_no, retry_count);
if (retry_count > ARCMSR_RETRYCOUNT) {
acb->fw_flag = FW_DEADLOCK;
printk(KERN_ERR "arcmsr%d: waiting for hw bus reset return, RETRY TERMINATED!!\n", acb->host->host_no);
return FAILED;
}
retry_count++;
goto sleep_again;
}
acb->acb_flags |= ACB_F_IOP_INITED;
/* disable all outbound interrupt */
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_get_firmware_spec(acb);
arcmsr_start_adapter_bgrb(acb);
/* clear Qbuffer if door bell ringed */
outbound_doorbell = readl(®->outbound_doorbell);
writel(outbound_doorbell, ®->outbound_doorbell); /*clear interrupt */
writel(ARCMSR_INBOUND_DRIVER_DATA_READ_OK, ®->inbound_doorbell);
/* enable outbound Post Queue,outbound doorbell Interrupt */
arcmsr_enable_outbound_ints(acb, intmask_org);
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
acb->acb_flags &= ~ACB_F_BUS_RESET;
rtn = SUCCESS;
printk(KERN_ERR "arcmsr: scsi bus reset eh returns with success\n");
} else {
acb->acb_flags &= ~ACB_F_BUS_RESET;
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6*HZ));
rtn = SUCCESS;
}
break;
}
case ACB_ADAPTER_TYPE_B:{
acb->acb_flags |= ACB_F_BUS_RESET;
if (!arcmsr_iop_reset(acb)) {
acb->acb_flags &= ~ACB_F_BUS_RESET;
rtn = FAILED;
} else {
acb->acb_flags &= ~ACB_F_BUS_RESET;
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
rtn = SUCCESS;
}
break;
}
case ACB_ADAPTER_TYPE_C:{
if (acb->acb_flags & ACB_F_BUS_RESET) {
long timeout;
printk(KERN_ERR "arcmsr: there is an bus reset eh proceeding.......\n");
timeout = wait_event_timeout(wait_q, (acb->acb_flags & ACB_F_BUS_RESET) == 0, 220*HZ);
if (timeout) {
return SUCCESS;
}
}
acb->acb_flags |= ACB_F_BUS_RESET;
if (!arcmsr_iop_reset(acb)) {
struct MessageUnit_C __iomem *reg;
reg = acb->pmuC;
arcmsr_hardware_reset(acb);
acb->acb_flags &= ~ACB_F_IOP_INITED;
sleep:
ssleep(ARCMSR_SLEEPTIME);
if ((readl(®->host_diagnostic) & 0x04) != 0) {
printk(KERN_ERR "arcmsr%d: waiting for hw bus reset return, retry=%d\n", acb->host->host_no, retry_count);
if (retry_count > ARCMSR_RETRYCOUNT) {
acb->fw_flag = FW_DEADLOCK;
printk(KERN_ERR "arcmsr%d: waiting for hw bus reset return, RETRY TERMINATED!!\n", acb->host->host_no);
return FAILED;
}
retry_count++;
goto sleep;
}
acb->acb_flags |= ACB_F_IOP_INITED;
/* disable all outbound interrupt */
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_get_firmware_spec(acb);
arcmsr_start_adapter_bgrb(acb);
/* clear Qbuffer if door bell ringed */
arcmsr_clear_doorbell_queue_buffer(acb);
/* enable outbound Post Queue,outbound doorbell Interrupt */
arcmsr_enable_outbound_ints(acb, intmask_org);
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
acb->acb_flags &= ~ACB_F_BUS_RESET;
rtn = SUCCESS;
printk(KERN_ERR "arcmsr: scsi bus reset eh returns with success\n");
} else {
acb->acb_flags &= ~ACB_F_BUS_RESET;
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6*HZ));
rtn = SUCCESS;
}
break;
}
case ACB_ADAPTER_TYPE_D: {
if (acb->acb_flags & ACB_F_BUS_RESET) {
long timeout;
pr_notice("arcmsr: there is an bus reset"
" eh proceeding.......\n");
timeout = wait_event_timeout(wait_q, (acb->acb_flags
& ACB_F_BUS_RESET) == 0, 220 * HZ);
if (timeout)
return SUCCESS;
}
acb->acb_flags |= ACB_F_BUS_RESET;
if (!arcmsr_iop_reset(acb)) {
struct MessageUnit_D *reg;
reg = acb->pmuD;
arcmsr_hardware_reset(acb);
acb->acb_flags &= ~ACB_F_IOP_INITED;
nap:
ssleep(ARCMSR_SLEEPTIME);
if ((readl(reg->sample_at_reset) & 0x80) != 0) {
pr_err("arcmsr%d: waiting for "
"hw bus reset return, retry=%d\n",
acb->host->host_no, retry_count);
if (retry_count > ARCMSR_RETRYCOUNT) {
acb->fw_flag = FW_DEADLOCK;
pr_err("arcmsr%d: waiting for hw bus"
" reset return, "
"RETRY TERMINATED!!\n",
acb->host->host_no);
return FAILED;
}
retry_count++;
goto nap;
}
acb->acb_flags |= ACB_F_IOP_INITED;
/* disable all outbound interrupt */
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_get_firmware_spec(acb);
arcmsr_start_adapter_bgrb(acb);
arcmsr_clear_doorbell_queue_buffer(acb);
arcmsr_enable_outbound_ints(acb, intmask_org);
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer,
jiffies + msecs_to_jiffies(6 * HZ));
acb->acb_flags &= ~ACB_F_BUS_RESET;
rtn = SUCCESS;
pr_err("arcmsr: scsi bus reset "
"eh returns with success\n");
} else {
acb->acb_flags &= ~ACB_F_BUS_RESET;
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer,
jiffies + msecs_to_jiffies(6 * HZ));
rtn = SUCCESS;
}
break;
}
}
return rtn;
}
static int arcmsr_abort_one_cmd(struct AdapterControlBlock *acb,
struct CommandControlBlock *ccb)
{
int rtn;
rtn = arcmsr_polling_ccbdone(acb, ccb);
return rtn;
}
static int arcmsr_abort(struct scsi_cmnd *cmd)
{
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *)cmd->device->host->hostdata;
int i = 0;
int rtn = FAILED;
uint32_t intmask_org;
printk(KERN_NOTICE
"arcmsr%d: abort device command of scsi id = %d lun = %d\n",
acb->host->host_no, cmd->device->id, (u32)cmd->device->lun);
acb->acb_flags |= ACB_F_ABORT;
acb->num_aborts++;
/*
************************************************
** the all interrupt service routine is locked
** we need to handle it as soon as possible and exit
************************************************
*/
if (!atomic_read(&acb->ccboutstandingcount)) {
acb->acb_flags &= ~ACB_F_ABORT;
return rtn;
}
intmask_org = arcmsr_disable_outbound_ints(acb);
for (i = 0; i < ARCMSR_MAX_FREECCB_NUM; i++) {
struct CommandControlBlock *ccb = acb->pccb_pool[i];
if (ccb->startdone == ARCMSR_CCB_START && ccb->pcmd == cmd) {
ccb->startdone = ARCMSR_CCB_ABORTED;
rtn = arcmsr_abort_one_cmd(acb, ccb);
break;
}
}
acb->acb_flags &= ~ACB_F_ABORT;
arcmsr_enable_outbound_ints(acb, intmask_org);
return rtn;
}
static const char *arcmsr_info(struct Scsi_Host *host)
{
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *) host->hostdata;
static char buf[256];
char *type;
int raid6 = 1;
switch (acb->pdev->device) {
case PCI_DEVICE_ID_ARECA_1110:
case PCI_DEVICE_ID_ARECA_1200:
case PCI_DEVICE_ID_ARECA_1202:
case PCI_DEVICE_ID_ARECA_1210:
raid6 = 0;
/*FALLTHRU*/
case PCI_DEVICE_ID_ARECA_1120:
case PCI_DEVICE_ID_ARECA_1130:
case PCI_DEVICE_ID_ARECA_1160:
case PCI_DEVICE_ID_ARECA_1170:
case PCI_DEVICE_ID_ARECA_1201:
case PCI_DEVICE_ID_ARECA_1203:
case PCI_DEVICE_ID_ARECA_1220:
case PCI_DEVICE_ID_ARECA_1230:
case PCI_DEVICE_ID_ARECA_1260:
case PCI_DEVICE_ID_ARECA_1270:
case PCI_DEVICE_ID_ARECA_1280:
type = "SATA";
break;
case PCI_DEVICE_ID_ARECA_1214:
case PCI_DEVICE_ID_ARECA_1380:
case PCI_DEVICE_ID_ARECA_1381:
case PCI_DEVICE_ID_ARECA_1680:
case PCI_DEVICE_ID_ARECA_1681:
case PCI_DEVICE_ID_ARECA_1880:
type = "SAS/SATA";
break;
default:
type = "unknown";
raid6 = 0;
break;
}
sprintf(buf, "Areca %s RAID Controller %s\narcmsr version %s\n",
type, raid6 ? "(RAID6 capable)" : "", ARCMSR_DRIVER_VERSION);
return buf;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5289_0 |
crossvul-cpp_data_bad_634_7 | /**************************************************
*
**************************************************
* This code was created by Peter Harvey @ CodeByDesign.
* Released under LGPL 28.JAN.99
*
* Contributions from...
* -----------------------------------------------
* Peter Harvey - pharvey@codebydesign.com
**************************************************/
#include <config.h>
#include <odbcinstext.h>
BOOL SQLWriteFileDSN( LPCSTR pszFileName,
LPCSTR pszAppName,
LPCSTR pszKeyName,
LPCSTR pszString )
{
HINI hIni;
char szFileName[ODBC_FILENAME_MAX+1];
if ( pszFileName[0] == '/' )
{
strncpy( szFileName, sizeof(szFileName) - 5, pszFileName );
}
else
{
char szPath[ODBC_FILENAME_MAX+1];
*szPath = '\0';
_odbcinst_FileINI( szPath );
snprintf( szFileName, sizeof(szFileName) - 5, "%s/%s", szPath, pszFileName );
}
if ( strlen( szFileName ) < 4 || strcmp( szFileName + strlen( szFileName ) - 4, ".dsn" ))
{
strcat( szFileName, ".dsn" );
}
#ifdef __OS2__
if ( iniOpen( &hIni, szFileName, "#;", '[', ']', '=', TRUE, 0L ) != INI_SUCCESS )
#else
if ( iniOpen( &hIni, szFileName, "#;", '[', ']', '=', TRUE ) != INI_SUCCESS )
#endif
{
inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_INVALID_PATH, "" );
return FALSE;
}
/* delete section */
if ( pszString == NULL && pszKeyName == NULL )
{
if ( iniObjectSeek( hIni, (char *)pszAppName ) == INI_SUCCESS )
{
iniObjectDelete( hIni );
}
}
/* delete entry */
else if ( pszString == NULL )
{
if ( iniPropertySeek( hIni, (char *)pszAppName, (char *)pszKeyName, "" ) == INI_SUCCESS )
{
iniPropertyDelete( hIni );
}
}
else
{
/* add section */
if ( iniObjectSeek( hIni, (char *)pszAppName ) != INI_SUCCESS )
{
iniObjectInsert( hIni, (char *)pszAppName );
}
/* update entry */
if ( iniPropertySeek( hIni, (char *)pszAppName, (char *)pszKeyName, "" ) == INI_SUCCESS )
{
iniObjectSeek( hIni, (char *)pszAppName );
iniPropertyUpdate( hIni, (char *)pszKeyName, (char *)pszString );
}
/* add entry */
else
{
iniObjectSeek( hIni, (char *)pszAppName );
iniPropertyInsert( hIni, (char *)pszKeyName, (char *)pszString );
}
}
if ( iniCommit( hIni ) != INI_SUCCESS )
{
iniClose( hIni );
inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_REQUEST_FAILED, "" );
return FALSE;
}
iniClose( hIni );
return TRUE;
}
BOOL INSTAPI SQLWriteFileDSNW(LPCWSTR lpszFileName,
LPCWSTR lpszAppName,
LPCWSTR lpszKeyName,
LPCWSTR lpszString)
{
BOOL ret;
char *file;
char *app;
char *key;
char *str;
file = lpszFileName ? _single_string_alloc_and_copy( lpszFileName ) : (char*)NULL;
app = lpszAppName ? _single_string_alloc_and_copy( lpszAppName ) : (char*)NULL;
key = lpszKeyName ? _single_string_alloc_and_copy( lpszKeyName ) : (char*)NULL;
str = lpszString ? _single_string_alloc_and_copy( lpszString ) : (char*)NULL;
ret = SQLWriteFileDSN( file, app, key, str );
if ( file )
free( file );
if ( app )
free( app );
if ( key )
free( key );
if ( str )
free( str );
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_634_7 |
crossvul-cpp_data_bad_340_8 | /*
* cryptoflex-tool.c: Tool for doing various Cryptoflex related stuff
*
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include "libopensc/sc-ossl-compat.h"
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include "libopensc/pkcs15.h"
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#include "util.h"
static const char *app_name = "cryptoflex-tool";
static char * opt_reader = NULL;
static int opt_wait = 0;
static int opt_key_num = 1, opt_pin_num = -1;
static int verbose = 0;
static int opt_exponent = 3;
static int opt_mod_length = 1024;
static int opt_key_count = 1;
static int opt_pin_attempts = 10;
static int opt_puk_attempts = 10;
static const char *opt_appdf = NULL, *opt_prkeyf = NULL, *opt_pubkeyf = NULL;
static u8 *pincode = NULL;
static const struct option options[] = {
{ "list-keys", 0, NULL, 'l' },
{ "create-key-files", 1, NULL, 'c' },
{ "create-pin-file", 1, NULL, 'P' },
{ "generate-key", 0, NULL, 'g' },
{ "read-key", 0, NULL, 'R' },
{ "verify-pin", 0, NULL, 'V' },
{ "key-num", 1, NULL, 'k' },
{ "app-df", 1, NULL, 'a' },
{ "prkey-file", 1, NULL, 'p' },
{ "pubkey-file", 1, NULL, 'u' },
{ "exponent", 1, NULL, 'e' },
{ "modulus-length", 1, NULL, 'm' },
{ "reader", 1, NULL, 'r' },
{ "wait", 0, NULL, 'w' },
{ "verbose", 0, NULL, 'v' },
{ NULL, 0, NULL, 0 }
};
static const char *option_help[] = {
"Lists all keys in a public key file",
"Creates new RSA key files for <arg> keys",
"Creates a new CHV<arg> file",
"Generates a new RSA key pair",
"Reads a public key from the card",
"Verifies CHV1 before issuing commands",
"Selects which key number to operate on [1]",
"Selects the DF to operate in",
"Private key file",
"Public key file",
"The RSA exponent to use in key generation [3]",
"Modulus length to use in key generation [1024]",
"Uses reader <arg>",
"Wait for card insertion",
"Verbose operation. Use several times to enable debug output.",
};
static sc_context_t *ctx = NULL;
static sc_card_t *card = NULL;
static char *getpin(const char *prompt)
{
char *buf, pass[20];
int i;
printf("%s", prompt);
fflush(stdout);
if (fgets(pass, 20, stdin) == NULL)
return NULL;
for (i = 0; i < 20; i++)
if (pass[i] == '\n')
pass[i] = 0;
if (strlen(pass) == 0)
return NULL;
buf = malloc(8);
if (buf == NULL)
return NULL;
if (strlen(pass) > 8) {
fprintf(stderr, "PIN code too long.\n");
free(buf);
return NULL;
}
memset(buf, 0, 8);
strlcpy(buf, pass, 8);
return buf;
}
static int verify_pin(int pin)
{
char prompt[50];
int r, tries_left = -1;
if (pincode == NULL) {
sprintf(prompt, "Please enter CHV%d: ", pin);
pincode = (u8 *) getpin(prompt);
if (pincode == NULL || strlen((char *) pincode) == 0)
return -1;
}
if (pin != 1 && pin != 2)
return -3;
r = sc_verify(card, SC_AC_CHV, pin, pincode, 8, &tries_left);
if (r) {
memset(pincode, 0, 8);
free(pincode);
pincode = NULL;
fprintf(stderr, "PIN code verification failed: %s\n", sc_strerror(r));
return -1;
}
return 0;
}
static int select_app_df(void)
{
sc_path_t path;
sc_file_t *file;
char str[80];
int r;
strcpy(str, "3F00");
if (opt_appdf != NULL)
strlcat(str, opt_appdf, sizeof str);
sc_format_path(str, &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select application DF: %s\n", sc_strerror(r));
return -1;
}
if (file->type != SC_FILE_TYPE_DF) {
fprintf(stderr, "Selected application DF is not a DF.\n");
return -1;
}
sc_file_free(file);
if (opt_pin_num >= 0)
return verify_pin(opt_pin_num);
else
return 0;
}
static void invert_buf(u8 *dest, const u8 *src, size_t c)
{
size_t i;
for (i = 0; i < c; i++)
dest[i] = src[c-1-i];
}
static BIGNUM * cf2bn(const u8 *buf, size_t bufsize, BIGNUM *num)
{
u8 tmp[512];
invert_buf(tmp, buf, bufsize);
return BN_bin2bn(tmp, bufsize, num);
}
static int bn2cf(const BIGNUM *num, u8 *buf)
{
u8 tmp[512];
int r;
r = BN_bn2bin(num, tmp);
if (r <= 0)
return r;
invert_buf(buf, tmp, r);
return r;
}
static int parse_public_key(const u8 *key, size_t keysize, RSA *rsa)
{
const u8 *p = key;
BIGNUM *n, *e;
int base;
base = (keysize - 7) / 5;
if (base != 32 && base != 48 && base != 64 && base != 128) {
fprintf(stderr, "Invalid public key.\n");
return -1;
}
p += 3;
n = BN_new();
if (n == NULL)
return -1;
cf2bn(p, 2 * base, n);
p += 2 * base;
p += base;
p += 2 * base;
e = BN_new();
if (e == NULL)
return -1;
cf2bn(p, 4, e);
if (RSA_set0_key(rsa, n, e, NULL) != 1)
return -1;
return 0;
}
static int gen_d(RSA *rsa)
{
BN_CTX *bnctx;
BIGNUM *r0, *r1, *r2;
const BIGNUM *rsa_p, *rsa_q, *rsa_n, *rsa_e, *rsa_d;
BIGNUM *rsa_n_new, *rsa_e_new, *rsa_d_new;
bnctx = BN_CTX_new();
if (bnctx == NULL)
return -1;
BN_CTX_start(bnctx);
r0 = BN_CTX_get(bnctx);
r1 = BN_CTX_get(bnctx);
r2 = BN_CTX_get(bnctx);
RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d);
RSA_get0_factors(rsa, &rsa_p, &rsa_q);
BN_sub(r1, rsa_p, BN_value_one());
BN_sub(r2, rsa_q, BN_value_one());
BN_mul(r0, r1, r2, bnctx);
if ((rsa_d_new = BN_mod_inverse(NULL, rsa_e, r0, bnctx)) == NULL) {
fprintf(stderr, "BN_mod_inverse() failed.\n");
return -1;
}
/* RSA_set0_key will free previous value, and replace with new value
* Thus the need to copy the contents of rsa_n and rsa_e
*/
rsa_n_new = BN_dup(rsa_n);
rsa_e_new = BN_dup(rsa_e);
if (RSA_set0_key(rsa, rsa_n_new, rsa_e_new, rsa_d_new) != 1)
return -1;
BN_CTX_end(bnctx);
BN_CTX_free(bnctx);
return 0;
}
static int parse_private_key(const u8 *key, size_t keysize, RSA *rsa)
{
const u8 *p = key;
BIGNUM *bn_p, *q, *dmp1, *dmq1, *iqmp;
int base;
base = (keysize - 3) / 5;
if (base != 32 && base != 48 && base != 64 && base != 128) {
fprintf(stderr, "Invalid private key.\n");
return -1;
}
p += 3;
bn_p = BN_new();
if (bn_p == NULL)
return -1;
cf2bn(p, base, bn_p);
p += base;
q = BN_new();
if (q == NULL)
return -1;
cf2bn(p, base, q);
p += base;
iqmp = BN_new();
if (iqmp == NULL)
return -1;
cf2bn(p, base, iqmp);
p += base;
dmp1 = BN_new();
if (dmp1 == NULL)
return -1;
cf2bn(p, base, dmp1);
p += base;
dmq1 = BN_new();
if (dmq1 == NULL)
return -1;
cf2bn(p, base, dmq1);
p += base;
if (RSA_set0_factors(rsa, bn_p, q) != 1)
return -1;
if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) != 1)
return -1;
if (gen_d(rsa))
return -1;
return 0;
}
static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = file->size;
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
static int read_private_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
const sc_acl_entry_t *e;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
e = sc_file_get_acl_entry(file, SC_AC_OP_READ);
if (e == NULL || e->method == SC_AC_NEVER)
return 10;
bufsize = file->size;
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_private_key(p, keysize, rsa);
}
static int read_key(void)
{
RSA *rsa = RSA_new();
u8 buf[1024], *p = buf;
u8 b64buf[2048];
int r;
if (rsa == NULL)
return -1;
r = read_public_key(rsa);
if (r)
return r;
r = i2d_RSA_PUBKEY(rsa, &p);
if (r <= 0) {
fprintf(stderr, "Error encoding public key.\n");
return -1;
}
r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64);
if (r < 0) {
fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r));
return -1;
}
printf("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n", b64buf);
r = read_private_key(rsa);
if (r == 10)
return 0;
else if (r)
return r;
p = buf;
r = i2d_RSAPrivateKey(rsa, &p);
if (r <= 0) {
fprintf(stderr, "Error encoding private key.\n");
return -1;
}
r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64);
if (r < 0) {
fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r));
return -1;
}
printf("-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n", b64buf);
return 0;
}
static int list_keys(void)
{
int r, idx = 0;
sc_path_t path;
u8 buf[2048], *p = buf;
size_t keysize, i;
int mod_lens[] = { 512, 768, 1024, 2048 };
size_t sizes[] = { 167, 247, 327, 647 };
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
do {
int mod_len = -1;
r = sc_read_binary(card, idx, buf, 3, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
idx += keysize;
for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++)
if (sizes[i] == keysize)
mod_len = mod_lens[i];
if (mod_len < 0)
printf("Key %d -- unknown modulus length\n", p[2] & 0x0F);
else
printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len);
} while (1);
return 0;
}
static int generate_key(void)
{
sc_apdu_t apdu;
u8 sbuf[4];
u8 p2;
int r;
switch (opt_mod_length) {
case 512:
p2 = 0x40;
break;
case 768:
p2 = 0x60;
break;
case 1024:
p2 = 0x80;
break;
case 2048:
p2 = 0x00;
break;
default:
fprintf(stderr, "Invalid modulus length.\n");
return 2;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, (u8) opt_key_num-1, p2);
apdu.cla = 0xF0;
apdu.lc = 4;
apdu.datalen = 4;
apdu.data = sbuf;
sbuf[0] = opt_exponent & 0xFF;
sbuf[1] = (opt_exponent >> 8) & 0xFF;
sbuf[2] = (opt_exponent >> 16) & 0xFF;
sbuf[3] = (opt_exponent >> 24) & 0xFF;
r = select_app_df();
if (r)
return 1;
if (verbose)
printf("Generating key...\n");
r = sc_transmit_apdu(card, &apdu);
if (r) {
fprintf(stderr, "APDU transmit failed: %s\n", sc_strerror(r));
if (r == SC_ERROR_TRANSMIT_FAILED)
fprintf(stderr, "Reader has timed out. It is still possible that the key generation has\n"
"succeeded.\n");
return 1;
}
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
printf("Key generation successful.\n");
return 0;
}
if (apdu.sw1 == 0x69 && apdu.sw2 == 0x82)
fprintf(stderr, "CHV1 not verified or invalid exponent value.\n");
else
fprintf(stderr, "Card returned SW1=%02X, SW2=%02X.\n", apdu.sw1, apdu.sw2);
return 1;
}
static int create_key_files(void)
{
sc_file_t *file;
int mod_lens[] = { 512, 768, 1024, 2048 };
int sizes[] = { 163, 243, 323, 643 };
int size = -1;
int r;
size_t i;
for (i = 0; i < sizeof(mod_lens) / sizeof(int); i++)
if (mod_lens[i] == opt_mod_length) {
size = sizes[i];
break;
}
if (size == -1) {
fprintf(stderr, "Invalid modulus length.\n");
return 1;
}
if (verbose)
printf("Creating key files for %d keys.\n", opt_key_count);
file = sc_file_new();
if (!file) {
fprintf(stderr, "out of memory.\n");
return 1;
}
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
file->id = 0x0012;
file->size = opt_key_count * size + 3;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1);
if (select_app_df()) {
sc_file_free(file);
return 1;
}
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "Unable to create private key file: %s\n", sc_strerror(r));
return 1;
}
file = sc_file_new();
if (!file) {
fprintf(stderr, "out of memory.\n");
return 1;
}
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
file->id = 0x1012;
file->size = opt_key_count * (size + 4) + 3;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1);
if (select_app_df()) {
sc_file_free(file);
return 1;
}
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "Unable to create public key file: %s\n", sc_strerror(r));
return 1;
}
if (verbose)
printf("Key files generated successfully.\n");
return 0;
}
static int read_rsa_privkey(RSA **rsa_out)
{
RSA *rsa = NULL;
BIO *in = NULL;
int r;
in = BIO_new(BIO_s_file());
if (opt_prkeyf == NULL) {
fprintf(stderr, "Private key file must be set.\n");
return 2;
}
r = BIO_read_filename(in, opt_prkeyf);
if (r <= 0) {
perror(opt_prkeyf);
return 2;
}
rsa = PEM_read_bio_RSAPrivateKey(in, NULL, NULL, NULL);
if (rsa == NULL) {
fprintf(stderr, "Unable to load private key.\n");
return 2;
}
BIO_free(in);
*rsa_out = rsa;
return 0;
}
static int encode_private_key(RSA *rsa, u8 *key, size_t *keysize)
{
u8 buf[1024], *p = buf;
u8 bnbuf[256];
int base = 0;
int r;
const BIGNUM *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp;
switch (RSA_bits(rsa)) {
case 512:
base = 32;
break;
case 768:
base = 48;
break;
case 1024:
base = 64;
break;
case 2048:
base = 128;
break;
}
if (base == 0) {
fprintf(stderr, "Key length invalid.\n");
return 2;
}
*p++ = (5 * base + 3) >> 8;
*p++ = (5 * base + 3) & 0xFF;
*p++ = opt_key_num;
RSA_get0_factors(rsa, &rsa_p, &rsa_q);
r = bn2cf(rsa_p, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_q, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
RSA_get0_crt_params(rsa, &rsa_dmp1, &rsa_dmq1, &rsa_iqmp);
r = bn2cf(rsa_iqmp, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_dmp1, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_dmq1, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
memcpy(key, buf, p - buf);
*keysize = p - buf;
return 0;
}
static int encode_public_key(RSA *rsa, u8 *key, size_t *keysize)
{
u8 buf[1024], *p = buf;
u8 bnbuf[256];
int base = 0;
int r;
const BIGNUM *rsa_n, *rsa_e;
switch (RSA_bits(rsa)) {
case 512:
base = 32;
break;
case 768:
base = 48;
break;
case 1024:
base = 64;
break;
case 2048:
base = 128;
break;
}
if (base == 0) {
fprintf(stderr, "Key length invalid.\n");
return 2;
}
*p++ = (5 * base + 7) >> 8;
*p++ = (5 * base + 7) & 0xFF;
*p++ = opt_key_num;
RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL);
r = bn2cf(rsa_n, bnbuf);
if (r != 2*base) {
fprintf(stderr, "Invalid public key.\n");
return 2;
}
memcpy(p, bnbuf, 2*base);
p += 2*base;
memset(p, 0, base);
p += base;
memset(bnbuf, 0, 2*base);
memcpy(p, bnbuf, 2*base);
p += 2*base;
r = bn2cf(rsa_e, bnbuf);
memcpy(p, bnbuf, 4);
p += 4;
memcpy(key, buf, p - buf);
*keysize = p - buf;
return 0;
}
static int update_public_key(const u8 *key, size_t keysize)
{
int r, idx = 0;
sc_path_t path;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
idx = keysize * (opt_key_num-1);
r = sc_update_binary(card, idx, key, keysize, 0);
if (r < 0) {
fprintf(stderr, "Unable to write public key: %s\n", sc_strerror(r));
return 2;
}
return 0;
}
static int update_private_key(const u8 *key, size_t keysize)
{
int r, idx = 0;
sc_path_t path;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
idx = keysize * (opt_key_num-1);
r = sc_update_binary(card, idx, key, keysize, 0);
if (r < 0) {
fprintf(stderr, "Unable to write private key: %s\n", sc_strerror(r));
return 2;
}
return 0;
}
static int store_key(void)
{
u8 prv[1024], pub[1024];
size_t prvsize, pubsize;
int r;
RSA *rsa;
r = read_rsa_privkey(&rsa);
if (r)
return r;
r = encode_private_key(rsa, prv, &prvsize);
if (r)
return r;
r = encode_public_key(rsa, pub, &pubsize);
if (r)
return r;
if (verbose)
printf("Storing private key...\n");
r = select_app_df();
if (r)
return r;
r = update_private_key(prv, prvsize);
if (r)
return r;
if (verbose)
printf("Storing public key...\n");
r = select_app_df();
if (r)
return r;
r = update_public_key(pub, pubsize);
if (r)
return r;
return 0;
}
static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id)
{
char prompt[40], *pin, *puk;
char buf[30], *p = buf;
sc_path_t file_id, path;
sc_file_t *file;
size_t len;
int r;
file_id = *inpath;
if (file_id.len < 2)
return -1;
if (chv == 1)
sc_format_path("I0000", &file_id);
else if (chv == 2)
sc_format_path("I0100", &file_id);
else
return -1;
r = sc_select_file(card, inpath, NULL);
if (r)
return -1;
r = sc_select_file(card, &file_id, NULL);
if (r == 0)
return 0;
sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id);
pin = getpin(prompt);
if (pin == NULL)
return -1;
sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id);
puk = getpin(prompt);
if (puk == NULL) {
free(pin);
return -1;
}
memset(p, 0xFF, 3);
p += 3;
memcpy(p, pin, 8);
p += 8;
*p++ = opt_pin_attempts;
*p++ = opt_pin_attempts;
memcpy(p, puk, 8);
p += 8;
*p++ = opt_puk_attempts;
*p++ = opt_puk_attempts;
len = p - buf;
free(pin);
free(puk);
file = sc_file_new();
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE);
if (inpath->len == 2 && inpath->value[0] == 0x3F &&
inpath->value[1] == 0x00)
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1);
else
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1);
file->size = len;
file->id = (file_id.value[0] << 8) | file_id.value[1];
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r));
return r;
}
path = *inpath;
sc_append_path(&path, &file_id);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r));
return r;
}
r = sc_update_binary(card, 0, (const u8 *) buf, len, 0);
if (r < 0) {
fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r));
return r;
}
return 0;
}
static int create_pin(void)
{
sc_path_t path;
char buf[80];
if (opt_pin_num != 1 && opt_pin_num != 2) {
fprintf(stderr, "Invalid PIN number. Possible values: 1, 2.\n");
return 2;
}
strcpy(buf, "3F00");
if (opt_appdf != NULL)
strlcat(buf, opt_appdf, sizeof buf);
sc_format_path(buf, &path);
return create_pin_file(&path, opt_pin_num, "");
}
int main(int argc, char *argv[])
{
int err = 0, r, c, long_optind = 0;
int action_count = 0;
int do_read_key = 0;
int do_generate_key = 0;
int do_create_key_files = 0;
int do_list_keys = 0;
int do_store_key = 0;
int do_create_pin_file = 0;
sc_context_param_t ctx_param;
while (1) {
c = getopt_long(argc, argv, "P:Vslgc:Rk:r:p:u:e:m:vwa:", options, &long_optind);
if (c == -1)
break;
if (c == '?')
util_print_usage_and_die(app_name, options, option_help, NULL);
switch (c) {
case 'l':
do_list_keys = 1;
action_count++;
break;
case 'P':
do_create_pin_file = 1;
opt_pin_num = atoi(optarg);
action_count++;
break;
case 'R':
do_read_key = 1;
action_count++;
break;
case 'g':
do_generate_key = 1;
action_count++;
break;
case 'c':
do_create_key_files = 1;
opt_key_count = atoi(optarg);
action_count++;
break;
case 's':
do_store_key = 1;
action_count++;
break;
case 'k':
opt_key_num = atoi(optarg);
if (opt_key_num < 1 || opt_key_num > 15) {
fprintf(stderr, "Key number invalid.\n");
exit(2);
}
break;
case 'V':
opt_pin_num = 1;
break;
case 'e':
opt_exponent = atoi(optarg);
break;
case 'm':
opt_mod_length = atoi(optarg);
break;
case 'p':
opt_prkeyf = optarg;
break;
case 'u':
opt_pubkeyf = optarg;
break;
case 'r':
opt_reader = optarg;
break;
case 'v':
verbose++;
break;
case 'w':
opt_wait = 1;
break;
case 'a':
opt_appdf = optarg;
break;
}
}
if (action_count == 0)
util_print_usage_and_die(app_name, options, option_help, NULL);
memset(&ctx_param, 0, sizeof(ctx_param));
ctx_param.ver = 0;
ctx_param.app_name = app_name;
r = sc_context_create(&ctx, &ctx_param);
if (r) {
fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r));
return 1;
}
if (verbose > 1) {
ctx->debug = verbose;
sc_ctx_log_to_file(ctx, "stderr");
}
err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose);
printf("Using card driver: %s\n", card->driver->name);
if (do_create_pin_file) {
if ((err = create_pin()) != 0)
goto end;
action_count--;
}
if (do_create_key_files) {
if ((err = create_key_files()) != 0)
goto end;
action_count--;
}
if (do_generate_key) {
if ((err = generate_key()) != 0)
goto end;
action_count--;
}
if (do_store_key) {
if ((err = store_key()) != 0)
goto end;
action_count--;
}
if (do_list_keys) {
if ((err = list_keys()) != 0)
goto end;
action_count--;
}
if (do_read_key) {
if ((err = read_key()) != 0)
goto end;
action_count--;
}
if (pincode != NULL) {
memset(pincode, 0, 8);
free(pincode);
}
end:
if (card) {
sc_unlock(card);
sc_disconnect_card(card);
}
if (ctx)
sc_release_context(ctx);
return err;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_340_8 |
crossvul-cpp_data_good_4063_2 | /*
* rre.c
*
* Routines to implement Rise-and-Run-length Encoding (RRE). This
* code is based on krw's original javatel rfbserver.
*/
/*
* OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>.
* Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge.
* All Rights Reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
#include <rfb/rfb.h>
/*
* cl->beforeEncBuf contains pixel data in the client's format.
* cl->afterEncBuf contains the RRE encoded version. If the RRE encoded version is
* larger than the raw data or if it exceeds cl->afterEncBufSize then
* raw encoding is used instead.
*/
static int subrectEncode8(rfbClientPtr cl, uint8_t *data, int w, int h);
static int subrectEncode16(rfbClientPtr cl, uint16_t *data, int w, int h);
static int subrectEncode32(rfbClientPtr cl, uint32_t *data, int w, int h);
static uint32_t getBgColour(char *data, int size, int bpp);
/*
* rfbSendRectEncodingRRE - send a given rectangle using RRE encoding.
*/
rfbBool
rfbSendRectEncodingRRE(rfbClientPtr cl,
int x,
int y,
int w,
int h)
{
rfbFramebufferUpdateRectHeader rect;
rfbRREHeader hdr;
int nSubrects;
int i;
char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y)
+ (x * (cl->scaledScreen->bitsPerPixel / 8)));
int maxRawSize = (cl->scaledScreen->width * cl->scaledScreen->height
* (cl->format.bitsPerPixel / 8));
if (cl->beforeEncBufSize < maxRawSize) {
cl->beforeEncBufSize = maxRawSize;
if (cl->beforeEncBuf == NULL)
cl->beforeEncBuf = (char *)malloc(cl->beforeEncBufSize);
else
cl->beforeEncBuf = (char *)realloc(cl->beforeEncBuf, cl->beforeEncBufSize);
}
if (cl->afterEncBufSize < maxRawSize) {
cl->afterEncBufSize = maxRawSize;
if (cl->afterEncBuf == NULL)
cl->afterEncBuf = (char *)malloc(cl->afterEncBufSize);
else
cl->afterEncBuf = (char *)realloc(cl->afterEncBuf, cl->afterEncBufSize);
}
(*cl->translateFn)(cl->translateLookupTable,
&(cl->screen->serverFormat),
&cl->format, fbptr, cl->beforeEncBuf,
cl->scaledScreen->paddedWidthInBytes, w, h);
switch (cl->format.bitsPerPixel) {
case 8:
nSubrects = subrectEncode8(cl, (uint8_t *)cl->beforeEncBuf, w, h);
break;
case 16:
nSubrects = subrectEncode16(cl, (uint16_t *)cl->beforeEncBuf, w, h);
break;
case 32:
nSubrects = subrectEncode32(cl, (uint32_t *)cl->beforeEncBuf, w, h);
break;
default:
rfbLog("getBgColour: bpp %d?\n",cl->format.bitsPerPixel);
return FALSE;
}
if (nSubrects < 0) {
/* RRE encoding was too large, use raw */
return rfbSendRectEncodingRaw(cl, x, y, w, h);
}
rfbStatRecordEncodingSent(cl, rfbEncodingRRE,
sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader + cl->afterEncBufLen,
sz_rfbFramebufferUpdateRectHeader + w * h * (cl->format.bitsPerPixel / 8));
if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader
> UPDATE_BUF_SIZE)
{
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
rect.r.x = Swap16IfLE(x);
rect.r.y = Swap16IfLE(y);
rect.r.w = Swap16IfLE(w);
rect.r.h = Swap16IfLE(h);
rect.encoding = Swap32IfLE(rfbEncodingRRE);
memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,
sz_rfbFramebufferUpdateRectHeader);
cl->ublen += sz_rfbFramebufferUpdateRectHeader;
hdr.nSubrects = Swap32IfLE(nSubrects);
memcpy(&cl->updateBuf[cl->ublen], (char *)&hdr, sz_rfbRREHeader);
cl->ublen += sz_rfbRREHeader;
for (i = 0; i < cl->afterEncBufLen;) {
int bytesToCopy = UPDATE_BUF_SIZE - cl->ublen;
if (i + bytesToCopy > cl->afterEncBufLen) {
bytesToCopy = cl->afterEncBufLen - i;
}
memcpy(&cl->updateBuf[cl->ublen], &cl->afterEncBuf[i], bytesToCopy);
cl->ublen += bytesToCopy;
i += bytesToCopy;
if (cl->ublen == UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
}
return TRUE;
}
/*
* subrectEncode() encodes the given multicoloured rectangle as a background
* colour overwritten by single-coloured rectangles. It returns the number
* of subrectangles in the encoded buffer, or -1 if subrect encoding won't
* fit in the buffer. It puts the encoded rectangles in cl->afterEncBuf. The
* single-colour rectangle partition is not optimal, but does find the biggest
* horizontal or vertical rectangle top-left anchored to each consecutive
* coordinate position.
*
* The coding scheme is simply [<bgcolour><subrect><subrect>...] where each
* <subrect> is [<colour><x><y><w><h>].
*/
#define DEFINE_SUBRECT_ENCODE(bpp) \
static int \
subrectEncode##bpp(rfbClientPtr client, uint##bpp##_t *data, int w, int h) { \
uint##bpp##_t cl; \
rfbRectangle subrect; \
int x,y; \
int i,j; \
int hx=0,hy,vx=0,vy; \
int hyflag; \
uint##bpp##_t *seg; \
uint##bpp##_t *line; \
int hw,hh,vw,vh; \
int thex,they,thew,theh; \
int numsubs = 0; \
int newLen; \
uint##bpp##_t bg = (uint##bpp##_t)getBgColour((char*)data,w*h,bpp); \
\
*((uint##bpp##_t*)client->afterEncBuf) = bg; \
\
client->afterEncBufLen = (bpp/8); \
\
for (y=0; y<h; y++) { \
line = data+(y*w); \
for (x=0; x<w; x++) { \
if (line[x] != bg) { \
cl = line[x]; \
hy = y-1; \
hyflag = 1; \
for (j=y; j<h; j++) { \
seg = data+(j*w); \
if (seg[x] != cl) {break;} \
i = x; \
while ((i < w) && (seg[i] == cl)) i += 1; \
i -= 1; \
if (j == y) vx = hx = i; \
if (i < vx) vx = i; \
if ((hyflag > 0) && (i >= hx)) {hy += 1;} else {hyflag = 0;} \
} \
vy = j-1; \
\
/* We now have two possible subrects: (x,y,hx,hy) and (x,y,vx,vy) \
* We'll choose the bigger of the two. \
*/ \
hw = hx-x+1; \
hh = hy-y+1; \
vw = vx-x+1; \
vh = vy-y+1; \
\
thex = x; \
they = y; \
\
if ((hw*hh) > (vw*vh)) { \
thew = hw; \
theh = hh; \
} else { \
thew = vw; \
theh = vh; \
} \
\
subrect.x = Swap16IfLE(thex); \
subrect.y = Swap16IfLE(they); \
subrect.w = Swap16IfLE(thew); \
subrect.h = Swap16IfLE(theh); \
\
newLen = client->afterEncBufLen + (bpp/8) + sz_rfbRectangle; \
if ((newLen > (w * h * (bpp/8))) || (newLen > client->afterEncBufSize)) \
return -1; \
\
numsubs += 1; \
*((uint##bpp##_t*)(client->afterEncBuf + client->afterEncBufLen)) = cl; \
client->afterEncBufLen += (bpp/8); \
memcpy(&client->afterEncBuf[client->afterEncBufLen],&subrect,sz_rfbRectangle); \
client->afterEncBufLen += sz_rfbRectangle; \
\
/* \
* Now mark the subrect as done. \
*/ \
for (j=they; j < (they+theh); j++) { \
for (i=thex; i < (thex+thew); i++) { \
data[j*w+i] = bg; \
} \
} \
} \
} \
} \
\
return numsubs; \
}
DEFINE_SUBRECT_ENCODE(8)
DEFINE_SUBRECT_ENCODE(16)
DEFINE_SUBRECT_ENCODE(32)
/*
* getBgColour() gets the most prevalent colour in a byte array.
*/
static uint32_t
getBgColour(char *data, int size, int bpp)
{
#define NUMCLRS 256
static int counts[NUMCLRS];
int i,j,k;
int maxcount = 0;
uint8_t maxclr = 0;
if (bpp != 8) {
if (bpp == 16) {
return ((uint16_t *)data)[0];
} else if (bpp == 32) {
return ((uint32_t *)data)[0];
} else {
rfbLog("getBgColour: bpp %d?\n",bpp);
return 0;
}
}
for (i=0; i<NUMCLRS; i++) {
counts[i] = 0;
}
for (j=0; j<size; j++) {
k = (int)(((uint8_t *)data)[j]);
if (k >= NUMCLRS) {
rfbErr("getBgColour: unusual colour = %d\n", k);
return 0;
}
counts[k] += 1;
if (counts[k] > maxcount) {
maxcount = counts[k];
maxclr = ((uint8_t *)data)[j];
}
}
return maxclr;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4063_2 |
crossvul-cpp_data_good_1359_0 | /**
* @file resolve.c
* @author Michal Vasko <mvasko@cesnet.cz>
* @brief libyang resolve functions
*
* Copyright (c) 2015 - 2018 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include "libyang.h"
#include "resolve.h"
#include "common.h"
#include "xpath.h"
#include "parser.h"
#include "parser_yang.h"
#include "xml_internal.h"
#include "hash_table.h"
#include "tree_internal.h"
#include "extensions.h"
#include "validation.h"
/* internal parsed predicate structure */
struct parsed_pred {
const struct lys_node *schema;
int len;
struct {
const char *mod_name;
int mod_name_len;
const char *name;
int nam_len;
const char *value;
int val_len;
} *pred;
};
int
parse_range_dec64(const char **str_num, uint8_t dig, int64_t *num)
{
const char *ptr;
int minus = 0;
int64_t ret = 0, prev_ret;
int8_t str_exp, str_dig = -1, trailing_zeros = 0;
ptr = *str_num;
if (ptr[0] == '-') {
minus = 1;
++ptr;
} else if (ptr[0] == '+') {
++ptr;
}
if (!isdigit(ptr[0])) {
/* there must be at least one */
return 1;
}
for (str_exp = 0; isdigit(ptr[0]) || ((ptr[0] == '.') && (str_dig < 0)); ++ptr) {
if (str_exp > 18) {
return 1;
}
if (ptr[0] == '.') {
if (ptr[1] == '.') {
/* it's the next interval */
break;
}
++str_dig;
} else {
prev_ret = ret;
if (minus) {
ret = ret * 10 - (ptr[0] - '0');
if (ret > prev_ret) {
return 1;
}
} else {
ret = ret * 10 + (ptr[0] - '0');
if (ret < prev_ret) {
return 1;
}
}
if (str_dig > -1) {
++str_dig;
if (ptr[0] == '0') {
/* possibly trailing zero */
trailing_zeros++;
} else {
trailing_zeros = 0;
}
}
++str_exp;
}
}
if (str_dig == 0) {
/* no digits after '.' */
return 1;
} else if (str_dig == -1) {
/* there are 0 numbers after the floating point */
str_dig = 0;
}
/* remove trailing zeros */
if (trailing_zeros) {
str_dig -= trailing_zeros;
str_exp -= trailing_zeros;
ret = ret / dec_pow(trailing_zeros);
}
/* it's parsed, now adjust the number based on fraction-digits, if needed */
if (str_dig < dig) {
if ((str_exp - 1) + (dig - str_dig) > 18) {
return 1;
}
prev_ret = ret;
ret *= dec_pow(dig - str_dig);
if ((minus && (ret > prev_ret)) || (!minus && (ret < prev_ret))) {
return 1;
}
}
if (str_dig > dig) {
return 1;
}
*str_num = ptr;
*num = ret;
return 0;
}
/**
* @brief Parse an identifier.
*
* ;; An identifier MUST NOT start with (('X'|'x') ('M'|'m') ('L'|'l'))
* identifier = (ALPHA / "_")
* *(ALPHA / DIGIT / "_" / "-" / ".")
*
* @param[in] id Identifier to use.
*
* @return Number of characters successfully parsed.
*/
unsigned int
parse_identifier(const char *id)
{
unsigned int parsed = 0;
assert(id);
if (!isalpha(id[0]) && (id[0] != '_')) {
return -parsed;
}
++parsed;
++id;
while (isalnum(id[0]) || (id[0] == '_') || (id[0] == '-') || (id[0] == '.')) {
++parsed;
++id;
}
return parsed;
}
/**
* @brief Parse a node-identifier.
*
* node-identifier = [module-name ":"] identifier
*
* @param[in] id Identifier to use.
* @param[out] mod_name Points to the module name, NULL if there is not any.
* @param[out] mod_name_len Length of the module name, 0 if there is not any.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] all_desc Whether the path starts with '/', only supported in extended paths.
* @param[in] extended Whether to accept an extended path (support for [prefix:]*, /[prefix:]*, /[prefix:]., prefix:#identifier).
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_node_identifier(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len,
int *all_desc, int extended)
{
int parsed = 0, ret, all_desc_local = 0, first_id_len;
const char *first_id;
assert(id);
assert((mod_name && mod_name_len) || (!mod_name && !mod_name_len));
assert((name && nam_len) || (!name && !nam_len));
if (mod_name) {
*mod_name = NULL;
*mod_name_len = 0;
}
if (name) {
*name = NULL;
*nam_len = 0;
}
if (extended) {
/* try to parse only the extended expressions */
if (id[parsed] == '/') {
if (all_desc) {
*all_desc = 1;
}
all_desc_local = 1;
} else {
if (all_desc) {
*all_desc = 0;
}
}
/* is there a prefix? */
ret = parse_identifier(id + all_desc_local);
if (ret > 0) {
if (id[all_desc_local + ret] != ':') {
/* this is not a prefix, so not an extended id */
goto standard_id;
}
if (mod_name) {
*mod_name = id + all_desc_local;
*mod_name_len = ret;
}
/* "/" and ":" */
ret += all_desc_local + 1;
} else {
ret = all_desc_local;
}
/* parse either "*" or "." */
if (*(id + ret) == '*') {
if (name) {
*name = id + ret;
*nam_len = 1;
}
++ret;
return ret;
} else if (*(id + ret) == '.') {
if (!all_desc_local) {
/* /. is redundant expression, we do not accept it */
return -ret;
}
if (name) {
*name = id + ret;
*nam_len = 1;
}
++ret;
return ret;
} else if (*(id + ret) == '#') {
if (all_desc_local || !ret) {
/* no prefix */
return 0;
}
parsed = ret + 1;
if ((ret = parse_identifier(id + parsed)) < 1) {
return -parsed + ret;
}
*name = id + parsed - 1;
*nam_len = ret + 1;
return parsed + ret;
}
/* else a standard id, parse it all again */
}
standard_id:
if ((ret = parse_identifier(id)) < 1) {
return ret;
}
first_id = id;
first_id_len = ret;
parsed += ret;
id += ret;
/* there is prefix */
if (id[0] == ':') {
++parsed;
++id;
/* there isn't */
} else {
if (name) {
*name = first_id;
*nam_len = first_id_len;
}
return parsed;
}
/* identifier (node name) */
if ((ret = parse_identifier(id)) < 1) {
return -parsed + ret;
}
if (mod_name) {
*mod_name = first_id;
*mod_name_len = first_id_len;
}
if (name) {
*name = id;
*nam_len = ret;
}
return parsed + ret;
}
/**
* @brief Parse a path-predicate (leafref).
*
* path-predicate = "[" *WSP path-equality-expr *WSP "]"
* path-equality-expr = node-identifier *WSP "=" *WSP path-key-expr
*
* @param[in] id Identifier to use.
* @param[out] prefix Points to the prefix, NULL if there is not any.
* @param[out] pref_len Length of the prefix, 0 if there is not any.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] path_key_expr Points to the path-key-expr.
* @param[out] pke_len Length of the path-key-expr.
* @param[out] has_predicate Flag to mark whether there is another predicate following.
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_path_predicate(const char *id, const char **prefix, int *pref_len, const char **name, int *nam_len,
const char **path_key_expr, int *pke_len, int *has_predicate)
{
const char *ptr;
int parsed = 0, ret;
assert(id);
if (prefix) {
*prefix = NULL;
}
if (pref_len) {
*pref_len = 0;
}
if (name) {
*name = NULL;
}
if (nam_len) {
*nam_len = 0;
}
if (path_key_expr) {
*path_key_expr = NULL;
}
if (pke_len) {
*pke_len = 0;
}
if (has_predicate) {
*has_predicate = 0;
}
if (id[0] != '[') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) {
return -parsed+ret;
}
parsed += ret;
id += ret;
while (isspace(id[0])) {
++parsed;
++id;
}
if (id[0] != '=') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
if ((ptr = strchr(id, ']')) == NULL) {
return -parsed;
}
--ptr;
while (isspace(ptr[0])) {
--ptr;
}
++ptr;
ret = ptr-id;
if (path_key_expr) {
*path_key_expr = id;
}
if (pke_len) {
*pke_len = ret;
}
parsed += ret;
id += ret;
while (isspace(id[0])) {
++parsed;
++id;
}
assert(id[0] == ']');
if (id[1] == '[') {
*has_predicate = 1;
}
return parsed+1;
}
/**
* @brief Parse a path-key-expr (leafref). First call parses "current()", all
* the ".." and the first node-identifier, other calls parse a single
* node-identifier each.
*
* path-key-expr = current-function-invocation *WSP "/" *WSP
* rel-path-keyexpr
* rel-path-keyexpr = 1*(".." *WSP "/" *WSP)
* *(node-identifier *WSP "/" *WSP)
* node-identifier
*
* @param[in] id Identifier to use.
* @param[out] prefix Points to the prefix, NULL if there is not any.
* @param[out] pref_len Length of the prefix, 0 if there is not any.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] parent_times Number of ".." in the path. Must be 0 on the first call,
* must not be changed between consecutive calls.
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_path_key_expr(const char *id, const char **prefix, int *pref_len, const char **name, int *nam_len,
int *parent_times)
{
int parsed = 0, ret, par_times = 0;
assert(id);
assert(parent_times);
if (prefix) {
*prefix = NULL;
}
if (pref_len) {
*pref_len = 0;
}
if (name) {
*name = NULL;
}
if (nam_len) {
*nam_len = 0;
}
if (!*parent_times) {
/* current-function-invocation *WSP "/" *WSP rel-path-keyexpr */
if (strncmp(id, "current()", 9)) {
return -parsed;
}
parsed += 9;
id += 9;
while (isspace(id[0])) {
++parsed;
++id;
}
if (id[0] != '/') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
/* rel-path-keyexpr */
if (strncmp(id, "..", 2)) {
return -parsed;
}
++par_times;
parsed += 2;
id += 2;
while (isspace(id[0])) {
++parsed;
++id;
}
}
/* 1*(".." *WSP "/" *WSP) *(node-identifier *WSP "/" *WSP) node-identifier
*
* first parent reference with whitespaces already parsed
*/
if (id[0] != '/') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
while (!strncmp(id, "..", 2) && !*parent_times) {
++par_times;
parsed += 2;
id += 2;
while (isspace(id[0])) {
++parsed;
++id;
}
if (id[0] != '/') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
}
if (!*parent_times) {
*parent_times = par_times;
}
/* all parent references must be parsed at this point */
if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) {
return -parsed + ret;
}
parsed += ret;
id += ret;
return parsed;
}
/**
* @brief Parse path-arg (leafref).
*
* path-arg = absolute-path / relative-path
* absolute-path = 1*("/" (node-identifier *path-predicate))
* relative-path = 1*(".." "/") descendant-path
*
* @param[in] mod Module of the context node to get correct prefix in case it is not explicitly specified
* @param[in] id Identifier to use.
* @param[out] prefix Points to the prefix, NULL if there is not any.
* @param[out] pref_len Length of the prefix, 0 if there is not any.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] parent_times Number of ".." in the path. Must be 0 on the first call,
* must not be changed between consecutive calls. -1 if the
* path is relative.
* @param[out] has_predicate Flag to mark whether there is a predicate specified.
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_path_arg(const struct lys_module *mod, const char *id, const char **prefix, int *pref_len,
const char **name, int *nam_len, int *parent_times, int *has_predicate)
{
int parsed = 0, ret, par_times = 0;
assert(id);
assert(parent_times);
if (prefix) {
*prefix = NULL;
}
if (pref_len) {
*pref_len = 0;
}
if (name) {
*name = NULL;
}
if (nam_len) {
*nam_len = 0;
}
if (has_predicate) {
*has_predicate = 0;
}
if (!*parent_times && !strncmp(id, "..", 2)) {
++par_times;
parsed += 2;
id += 2;
while (!strncmp(id, "/..", 3)) {
++par_times;
parsed += 3;
id += 3;
}
}
if (!*parent_times) {
if (par_times) {
*parent_times = par_times;
} else {
*parent_times = -1;
}
}
if (id[0] != '/') {
return -parsed;
}
/* skip '/' */
++parsed;
++id;
/* node-identifier ([prefix:]identifier) */
if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) {
return -parsed - ret;
}
if (prefix && !(*prefix)) {
/* actually we always need prefix even it is not specified */
*prefix = lys_main_module(mod)->name;
*pref_len = strlen(*prefix);
}
parsed += ret;
id += ret;
/* there is no predicate */
if ((id[0] == '/') || !id[0]) {
return parsed;
} else if (id[0] != '[') {
return -parsed;
}
if (has_predicate) {
*has_predicate = 1;
}
return parsed;
}
/**
* @brief Parse instance-identifier in JSON data format. That means that prefixes
* are actually model names.
*
* instance-identifier = 1*("/" (node-identifier *predicate))
*
* @param[in] id Identifier to use.
* @param[out] model Points to the model name.
* @param[out] mod_len Length of the model name.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] has_predicate Flag to mark whether there is a predicate specified.
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_instance_identifier(const char *id, const char **model, int *mod_len, const char **name, int *nam_len,
int *has_predicate)
{
int parsed = 0, ret;
assert(id && model && mod_len && name && nam_len);
if (has_predicate) {
*has_predicate = 0;
}
if (id[0] != '/') {
return -parsed;
}
++parsed;
++id;
if ((ret = parse_identifier(id)) < 1) {
return ret;
}
*name = id;
*nam_len = ret;
parsed += ret;
id += ret;
if (id[0] == ':') {
/* we have prefix */
*model = *name;
*mod_len = *nam_len;
++parsed;
++id;
if ((ret = parse_identifier(id)) < 1) {
return ret;
}
*name = id;
*nam_len = ret;
parsed += ret;
id += ret;
}
if (id[0] == '[' && has_predicate) {
*has_predicate = 1;
}
return parsed;
}
/**
* @brief Parse predicate (instance-identifier) in JSON data format. That means that prefixes
* (which are mandatory) are actually model names.
*
* predicate = "[" *WSP (predicate-expr / pos) *WSP "]"
* predicate-expr = (node-identifier / ".") *WSP "=" *WSP
* ((DQUOTE string DQUOTE) /
* (SQUOTE string SQUOTE))
* pos = non-negative-integer-value
*
* @param[in] id Identifier to use.
* @param[out] model Points to the model name.
* @param[out] mod_len Length of the model name.
* @param[out] name Points to the node name. Can be identifier (from node-identifier), "." or pos.
* @param[out] nam_len Length of the node name.
* @param[out] value Value the node-identifier must have (string from the grammar),
* NULL if there is not any.
* @param[out] val_len Length of the value, 0 if there is not any.
* @param[out] has_predicate Flag to mark whether there is a predicate specified.
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_predicate(const char *id, const char **model, int *mod_len, const char **name, int *nam_len,
const char **value, int *val_len, int *has_predicate)
{
const char *ptr;
int parsed = 0, ret;
char quote;
assert(id);
if (model) {
assert(mod_len);
*model = NULL;
*mod_len = 0;
}
if (name) {
assert(nam_len);
*name = NULL;
*nam_len = 0;
}
if (value) {
assert(val_len);
*value = NULL;
*val_len = 0;
}
if (has_predicate) {
*has_predicate = 0;
}
if (id[0] != '[') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
/* pos */
if (isdigit(id[0])) {
if (name) {
*name = id;
}
if (id[0] == '0') {
return -parsed;
}
while (isdigit(id[0])) {
++parsed;
++id;
}
if (nam_len) {
*nam_len = id-(*name);
}
/* "." or node-identifier */
} else {
if (id[0] == '.') {
if (name) {
*name = id;
}
if (nam_len) {
*nam_len = 1;
}
++parsed;
++id;
} else {
if ((ret = parse_node_identifier(id, model, mod_len, name, nam_len, NULL, 0)) < 1) {
return -parsed + ret;
}
parsed += ret;
id += ret;
}
while (isspace(id[0])) {
++parsed;
++id;
}
if (id[0] != '=') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
/* ((DQUOTE string DQUOTE) / (SQUOTE string SQUOTE)) */
if ((id[0] == '\"') || (id[0] == '\'')) {
quote = id[0];
++parsed;
++id;
if ((ptr = strchr(id, quote)) == NULL) {
return -parsed;
}
ret = ptr - id;
if (value) {
*value = id;
}
if (val_len) {
*val_len = ret;
}
parsed += ret + 1;
id += ret + 1;
} else {
return -parsed;
}
}
while (isspace(id[0])) {
++parsed;
++id;
}
if (id[0] != ']') {
return -parsed;
}
++parsed;
++id;
if ((id[0] == '[') && has_predicate) {
*has_predicate = 1;
}
return parsed;
}
/**
* @brief Parse schema-nodeid.
*
* schema-nodeid = absolute-schema-nodeid /
* descendant-schema-nodeid
* absolute-schema-nodeid = 1*("/" node-identifier)
* descendant-schema-nodeid = ["." "/"]
* node-identifier
* absolute-schema-nodeid
*
* @param[in] id Identifier to use.
* @param[out] mod_name Points to the module name, NULL if there is not any.
* @param[out] mod_name_len Length of the module name, 0 if there is not any.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] is_relative Flag to mark whether the nodeid is absolute or descendant. Must be -1
* on the first call, must not be changed between consecutive calls.
* @param[out] has_predicate Flag to mark whether there is a predicate specified. It cannot be
* based on the grammar, in those cases use NULL.
* @param[in] extended Whether to accept an extended path (support for /[prefix:]*, //[prefix:]*, //[prefix:].).
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
int
parse_schema_nodeid(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len,
int *is_relative, int *has_predicate, int *all_desc, int extended)
{
int parsed = 0, ret;
assert(id);
assert(is_relative);
if (has_predicate) {
*has_predicate = 0;
}
if (id[0] != '/') {
if (*is_relative != -1) {
return -parsed;
} else {
*is_relative = 1;
}
if (!strncmp(id, "./", 2)) {
parsed += 2;
id += 2;
}
} else {
if (*is_relative == -1) {
*is_relative = 0;
}
++parsed;
++id;
}
if ((ret = parse_node_identifier(id, mod_name, mod_name_len, name, nam_len, all_desc, extended)) < 1) {
return -parsed + ret;
}
parsed += ret;
id += ret;
if ((id[0] == '[') && has_predicate) {
*has_predicate = 1;
}
return parsed;
}
/**
* @brief Parse schema predicate (special format internally used).
*
* predicate = "[" *WSP predicate-expr *WSP "]"
* predicate-expr = "." / [prefix:]identifier / positive-integer / key-with-value
* key-with-value = identifier *WSP "=" *WSP
* ((DQUOTE string DQUOTE) /
* (SQUOTE string SQUOTE))
*
* @param[in] id Identifier to use.
* @param[out] mod_name Points to the list key module name.
* @param[out] mod_name_len Length of \p mod_name.
* @param[out] name Points to the list key name.
* @param[out] nam_len Length of \p name.
* @param[out] value Points to the key value. If specified, key-with-value is expected.
* @param[out] val_len Length of \p value.
* @param[out] has_predicate Flag to mark whether there is another predicate specified.
*/
int
parse_schema_json_predicate(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len,
const char **value, int *val_len, int *has_predicate)
{
const char *ptr;
int parsed = 0, ret;
char quote;
assert(id);
if (mod_name) {
*mod_name = NULL;
}
if (mod_name_len) {
*mod_name_len = 0;
}
if (name) {
*name = NULL;
}
if (nam_len) {
*nam_len = 0;
}
if (value) {
*value = NULL;
}
if (val_len) {
*val_len = 0;
}
if (has_predicate) {
*has_predicate = 0;
}
if (id[0] != '[') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
/* identifier */
if (id[0] == '.') {
ret = 1;
if (name) {
*name = id;
}
if (nam_len) {
*nam_len = ret;
}
} else if (isdigit(id[0])) {
if (id[0] == '0') {
return -parsed;
}
ret = 1;
while (isdigit(id[ret])) {
++ret;
}
if (name) {
*name = id;
}
if (nam_len) {
*nam_len = ret;
}
} else if ((ret = parse_node_identifier(id, mod_name, mod_name_len, name, nam_len, NULL, 0)) < 1) {
return -parsed + ret;
}
parsed += ret;
id += ret;
while (isspace(id[0])) {
++parsed;
++id;
}
/* there is value as well */
if (id[0] == '=') {
if (name && isdigit(**name)) {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
/* ((DQUOTE string DQUOTE) / (SQUOTE string SQUOTE)) */
if ((id[0] == '\"') || (id[0] == '\'')) {
quote = id[0];
++parsed;
++id;
if ((ptr = strchr(id, quote)) == NULL) {
return -parsed;
}
ret = ptr - id;
if (value) {
*value = id;
}
if (val_len) {
*val_len = ret;
}
parsed += ret + 1;
id += ret + 1;
} else {
return -parsed;
}
while (isspace(id[0])) {
++parsed;
++id;
}
}
if (id[0] != ']') {
return -parsed;
}
++parsed;
++id;
if ((id[0] == '[') && has_predicate) {
*has_predicate = 1;
}
return parsed;
}
#ifdef LY_ENABLED_CACHE
static int
resolve_hash_table_find_equal(void *val1_p, void *val2_p, int mod, void *UNUSED(cb_data))
{
struct lyd_node *val2, *elem2;
struct parsed_pred pp;
const char *str;
int i;
assert(!mod);
(void)mod;
pp = *((struct parsed_pred *)val1_p);
val2 = *((struct lyd_node **)val2_p);
if (val2->schema != pp.schema) {
return 0;
}
switch (val2->schema->nodetype) {
case LYS_CONTAINER:
case LYS_LEAF:
case LYS_ANYXML:
case LYS_ANYDATA:
return 1;
case LYS_LEAFLIST:
str = ((struct lyd_node_leaf_list *)val2)->value_str;
if (!strncmp(str, pp.pred[0].value, pp.pred[0].val_len) && !str[pp.pred[0].val_len]) {
return 1;
}
return 0;
case LYS_LIST:
assert(((struct lys_node_list *)val2->schema)->keys_size);
assert(((struct lys_node_list *)val2->schema)->keys_size == pp.len);
/* lists with keys, their equivalence is based on their keys */
elem2 = val2->child;
/* the exact data order is guaranteed */
for (i = 0; elem2 && (i < pp.len); ++i) {
/* module check */
if (pp.pred[i].mod_name) {
if (strncmp(lyd_node_module(elem2)->name, pp.pred[i].mod_name, pp.pred[i].mod_name_len)
|| lyd_node_module(elem2)->name[pp.pred[i].mod_name_len]) {
break;
}
} else {
if (lyd_node_module(elem2) != lys_node_module(pp.schema)) {
break;
}
}
/* name check */
if (strncmp(elem2->schema->name, pp.pred[i].name, pp.pred[i].nam_len) || elem2->schema->name[pp.pred[i].nam_len]) {
break;
}
/* value check */
str = ((struct lyd_node_leaf_list *)elem2)->value_str;
if (strncmp(str, pp.pred[i].value, pp.pred[i].val_len) || str[pp.pred[i].val_len]) {
break;
}
/* next key */
elem2 = elem2->next;
}
if (i == pp.len) {
return 1;
}
return 0;
default:
break;
}
LOGINT(val2->schema->module->ctx);
return 0;
}
static struct lyd_node *
resolve_json_data_node_hash(struct lyd_node *parent, struct parsed_pred pp)
{
values_equal_cb prev_cb;
struct lyd_node **ret = NULL;
uint32_t hash;
int i;
assert(parent && parent->hash);
/* set our value equivalence callback that does not require data nodes */
prev_cb = lyht_set_cb(parent->ht, resolve_hash_table_find_equal);
/* get the hash of the searched node */
hash = dict_hash_multi(0, lys_node_module(pp.schema)->name, strlen(lys_node_module(pp.schema)->name));
hash = dict_hash_multi(hash, pp.schema->name, strlen(pp.schema->name));
if (pp.schema->nodetype == LYS_LEAFLIST) {
assert((pp.len == 1) && (pp.pred[0].name[0] == '.') && (pp.pred[0].nam_len == 1));
/* leaf-list value in predicate */
hash = dict_hash_multi(hash, pp.pred[0].value, pp.pred[0].val_len);
} else if (pp.schema->nodetype == LYS_LIST) {
/* list keys in predicates */
for (i = 0; i < pp.len; ++i) {
hash = dict_hash_multi(hash, pp.pred[i].value, pp.pred[i].val_len);
}
}
hash = dict_hash_multi(hash, NULL, 0);
/* try to find the node */
i = lyht_find(parent->ht, &pp, hash, (void **)&ret);
assert(i || *ret);
/* restore the original callback */
lyht_set_cb(parent->ht, prev_cb);
return (i ? NULL : *ret);
}
#endif
/**
* @brief Resolve (find) a feature definition. Logs directly.
*
* @param[in] feat_name Feature name to resolve.
* @param[in] len Length of \p feat_name.
* @param[in] node Node with the if-feature expression.
* @param[out] feature Pointer to be set to point to the feature definition, if feature not found
* (return code 1), the pointer is untouched.
*
* @return 0 on success, 1 on forward reference, -1 on error.
*/
static int
resolve_feature(const char *feat_name, uint16_t len, const struct lys_node *node, struct lys_feature **feature)
{
char *str;
const char *mod_name, *name;
int mod_name_len, nam_len, i, j;
const struct lys_module *module;
assert(feature);
/* check prefix */
if ((i = parse_node_identifier(feat_name, &mod_name, &mod_name_len, &name, &nam_len, NULL, 0)) < 1) {
LOGVAL(node->module->ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, feat_name[-i], &feat_name[-i]);
return -1;
}
module = lyp_get_module(lys_node_module(node), NULL, 0, mod_name, mod_name_len, 0);
if (!module) {
/* identity refers unknown data model */
LOGVAL(node->module->ctx, LYE_INMOD_LEN, LY_VLOG_NONE, NULL, mod_name_len, mod_name);
return -1;
}
if (module != node->module && module == lys_node_module(node)) {
/* first, try to search directly in submodule where the feature was mentioned */
for (j = 0; j < node->module->features_size; j++) {
if (!strncmp(name, node->module->features[j].name, nam_len) && !node->module->features[j].name[nam_len]) {
/* check status */
if (lyp_check_status(node->flags, lys_node_module(node), node->name, node->module->features[j].flags,
node->module->features[j].module, node->module->features[j].name, NULL)) {
return -1;
}
*feature = &node->module->features[j];
return 0;
}
}
}
/* search in the identified module ... */
for (j = 0; j < module->features_size; j++) {
if (!strncmp(name, module->features[j].name, nam_len) && !module->features[j].name[nam_len]) {
/* check status */
if (lyp_check_status(node->flags, lys_node_module(node), node->name, module->features[j].flags,
module->features[j].module, module->features[j].name, NULL)) {
return -1;
}
*feature = &module->features[j];
return 0;
}
}
/* ... and all its submodules */
for (i = 0; i < module->inc_size && module->inc[i].submodule; i++) {
for (j = 0; j < module->inc[i].submodule->features_size; j++) {
if (!strncmp(name, module->inc[i].submodule->features[j].name, nam_len)
&& !module->inc[i].submodule->features[j].name[nam_len]) {
/* check status */
if (lyp_check_status(node->flags, lys_node_module(node), node->name,
module->inc[i].submodule->features[j].flags,
module->inc[i].submodule->features[j].module,
module->inc[i].submodule->features[j].name, NULL)) {
return -1;
}
*feature = &module->inc[i].submodule->features[j];
return 0;
}
}
}
/* not found */
str = strndup(feat_name, len);
LOGVAL(node->module->ctx, LYE_INRESOLV, LY_VLOG_NONE, NULL, "feature", str);
free(str);
return 1;
}
/*
* @return
* - 1 if enabled
* - 0 if disabled
*/
static int
resolve_feature_value(const struct lys_feature *feat)
{
int i;
for (i = 0; i < feat->iffeature_size; i++) {
if (!resolve_iffeature(&feat->iffeature[i])) {
return 0;
}
}
return feat->flags & LYS_FENABLED ? 1 : 0;
}
static int
resolve_iffeature_recursive(struct lys_iffeature *expr, int *index_e, int *index_f)
{
uint8_t op;
int a, b;
op = iff_getop(expr->expr, *index_e);
(*index_e)++;
switch (op) {
case LYS_IFF_F:
/* resolve feature */
return resolve_feature_value(expr->features[(*index_f)++]);
case LYS_IFF_NOT:
/* invert result */
return resolve_iffeature_recursive(expr, index_e, index_f) ? 0 : 1;
case LYS_IFF_AND:
case LYS_IFF_OR:
a = resolve_iffeature_recursive(expr, index_e, index_f);
b = resolve_iffeature_recursive(expr, index_e, index_f);
if (op == LYS_IFF_AND) {
return a && b;
} else { /* LYS_IFF_OR */
return a || b;
}
}
return 0;
}
int
resolve_iffeature(struct lys_iffeature *expr)
{
int index_e = 0, index_f = 0;
if (expr->expr) {
return resolve_iffeature_recursive(expr, &index_e, &index_f);
}
return 0;
}
struct iff_stack {
int size;
int index; /* first empty item */
uint8_t *stack;
};
static int
iff_stack_push(struct iff_stack *stack, uint8_t value)
{
if (stack->index == stack->size) {
stack->size += 4;
stack->stack = ly_realloc(stack->stack, stack->size * sizeof *stack->stack);
LY_CHECK_ERR_RETURN(!stack->stack, LOGMEM(NULL); stack->size = 0, EXIT_FAILURE);
}
stack->stack[stack->index++] = value;
return EXIT_SUCCESS;
}
static uint8_t
iff_stack_pop(struct iff_stack *stack)
{
stack->index--;
return stack->stack[stack->index];
}
static void
iff_stack_clean(struct iff_stack *stack)
{
stack->size = 0;
free(stack->stack);
}
static void
iff_setop(uint8_t *list, uint8_t op, int pos)
{
uint8_t *item;
uint8_t mask = 3;
assert(pos >= 0);
assert(op <= 3); /* max 2 bits */
item = &list[pos / 4];
mask = mask << 2 * (pos % 4);
*item = (*item) & ~mask;
*item = (*item) | (op << 2 * (pos % 4));
}
uint8_t
iff_getop(uint8_t *list, int pos)
{
uint8_t *item;
uint8_t mask = 3, result;
assert(pos >= 0);
item = &list[pos / 4];
result = (*item) & (mask << 2 * (pos % 4));
return result >> 2 * (pos % 4);
}
#define LYS_IFF_LP 0x04 /* ( */
#define LYS_IFF_RP 0x08 /* ) */
/* internal structure for passing data for UNRES_IFFEAT */
struct unres_iffeat_data {
struct lys_node *node;
const char *fname;
int infeature;
};
void
resolve_iffeature_getsizes(struct lys_iffeature *iffeat, unsigned int *expr_size, unsigned int *feat_size)
{
unsigned int e = 0, f = 0, r = 0;
uint8_t op;
assert(iffeat);
if (!iffeat->expr) {
goto result;
}
do {
op = iff_getop(iffeat->expr, e++);
switch (op) {
case LYS_IFF_NOT:
if (!r) {
r += 1;
}
break;
case LYS_IFF_AND:
case LYS_IFF_OR:
if (!r) {
r += 2;
} else {
r += 1;
}
break;
case LYS_IFF_F:
f++;
if (r) {
r--;
}
break;
}
} while(r);
result:
if (expr_size) {
*expr_size = e;
}
if (feat_size) {
*feat_size = f;
}
}
int
resolve_iffeature_compile(struct lys_iffeature *iffeat_expr, const char *value, struct lys_node *node,
int infeature, struct unres_schema *unres)
{
const char *c = value;
int r, rc = EXIT_FAILURE;
int i, j, last_not, checkversion = 0;
unsigned int f_size = 0, expr_size = 0, f_exp = 1;
uint8_t op;
struct iff_stack stack = {0, 0, NULL};
struct unres_iffeat_data *iff_data;
struct ly_ctx *ctx = node->module->ctx;
assert(c);
if (isspace(c[0])) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, c[0], c);
return EXIT_FAILURE;
}
/* pre-parse the expression to get sizes for arrays, also do some syntax checks of the expression */
for (i = j = last_not = 0; c[i]; i++) {
if (c[i] == '(') {
checkversion = 1;
j++;
continue;
} else if (c[i] == ')') {
j--;
continue;
} else if (isspace(c[i])) {
continue;
}
if (!strncmp(&c[i], "not", r = 3) || !strncmp(&c[i], "and", r = 3) || !strncmp(&c[i], "or", r = 2)) {
if (c[i + r] == '\0') {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature");
return EXIT_FAILURE;
} else if (!isspace(c[i + r])) {
/* feature name starting with the not/and/or */
last_not = 0;
f_size++;
} else if (c[i] == 'n') { /* not operation */
if (last_not) {
/* double not */
expr_size = expr_size - 2;
last_not = 0;
} else {
last_not = 1;
}
} else { /* and, or */
f_exp++;
/* not a not operation */
last_not = 0;
}
i += r;
} else {
f_size++;
last_not = 0;
}
expr_size++;
while (!isspace(c[i])) {
if (!c[i] || c[i] == ')') {
i--;
break;
}
i++;
}
}
if (j || f_exp != f_size) {
/* not matching count of ( and ) */
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature");
return EXIT_FAILURE;
}
if (checkversion || expr_size > 1) {
/* check that we have 1.1 module */
if (node->module->version != LYS_VERSION_1_1) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "YANG 1.1 if-feature expression found in 1.0 module.");
return EXIT_FAILURE;
}
}
/* allocate the memory */
iffeat_expr->expr = calloc((j = (expr_size / 4) + ((expr_size % 4) ? 1 : 0)), sizeof *iffeat_expr->expr);
iffeat_expr->features = calloc(f_size, sizeof *iffeat_expr->features);
stack.stack = malloc(expr_size * sizeof *stack.stack);
LY_CHECK_ERR_GOTO(!stack.stack || !iffeat_expr->expr || !iffeat_expr->features, LOGMEM(ctx), error);
stack.size = expr_size;
f_size--; expr_size--; /* used as indexes from now */
for (i--; i >= 0; i--) {
if (c[i] == ')') {
/* push it on stack */
iff_stack_push(&stack, LYS_IFF_RP);
continue;
} else if (c[i] == '(') {
/* pop from the stack into result all operators until ) */
while((op = iff_stack_pop(&stack)) != LYS_IFF_RP) {
iff_setop(iffeat_expr->expr, op, expr_size--);
}
continue;
} else if (isspace(c[i])) {
continue;
}
/* end operator or operand -> find beginning and get what is it */
j = i + 1;
while (i >= 0 && !isspace(c[i]) && c[i] != '(') {
i--;
}
i++; /* get back by one step */
if (!strncmp(&c[i], "not", 3) && isspace(c[i + 3])) {
if (stack.index && stack.stack[stack.index - 1] == LYS_IFF_NOT) {
/* double not */
iff_stack_pop(&stack);
} else {
/* not has the highest priority, so do not pop from the stack
* as in case of AND and OR */
iff_stack_push(&stack, LYS_IFF_NOT);
}
} else if (!strncmp(&c[i], "and", 3) && isspace(c[i + 3])) {
/* as for OR - pop from the stack all operators with the same or higher
* priority and store them to the result, then push the AND to the stack */
while (stack.index && stack.stack[stack.index - 1] <= LYS_IFF_AND) {
op = iff_stack_pop(&stack);
iff_setop(iffeat_expr->expr, op, expr_size--);
}
iff_stack_push(&stack, LYS_IFF_AND);
} else if (!strncmp(&c[i], "or", 2) && isspace(c[i + 2])) {
while (stack.index && stack.stack[stack.index - 1] <= LYS_IFF_OR) {
op = iff_stack_pop(&stack);
iff_setop(iffeat_expr->expr, op, expr_size--);
}
iff_stack_push(&stack, LYS_IFF_OR);
} else {
/* feature name, length is j - i */
/* add it to the result */
iff_setop(iffeat_expr->expr, LYS_IFF_F, expr_size--);
/* now get the link to the feature definition. Since it can be
* forward referenced, we have to keep the feature name in auxiliary
* structure passed into unres */
iff_data = malloc(sizeof *iff_data);
LY_CHECK_ERR_GOTO(!iff_data, LOGMEM(ctx), error);
iff_data->node = node;
iff_data->fname = lydict_insert(node->module->ctx, &c[i], j - i);
iff_data->infeature = infeature;
r = unres_schema_add_node(node->module, unres, &iffeat_expr->features[f_size], UNRES_IFFEAT,
(struct lys_node *)iff_data);
f_size--;
if (r == -1) {
lydict_remove(node->module->ctx, iff_data->fname);
free(iff_data);
goto error;
}
}
}
while (stack.index) {
op = iff_stack_pop(&stack);
iff_setop(iffeat_expr->expr, op, expr_size--);
}
if (++expr_size || ++f_size) {
/* not all expected operators and operands found */
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature");
rc = EXIT_FAILURE;
} else {
rc = EXIT_SUCCESS;
}
error:
/* cleanup */
iff_stack_clean(&stack);
return rc;
}
/**
* @brief Resolve (find) a data node based on a schema-nodeid.
*
* Used for resolving unique statements - so id is expected to be relative and local (without reference to a different
* module).
*
*/
struct lyd_node *
resolve_data_descendant_schema_nodeid(const char *nodeid, struct lyd_node *start)
{
char *str, *token, *p;
struct lyd_node *result = NULL, *iter;
const struct lys_node *schema = NULL;
assert(nodeid && start);
if (nodeid[0] == '/') {
return NULL;
}
str = p = strdup(nodeid);
LY_CHECK_ERR_RETURN(!str, LOGMEM(start->schema->module->ctx), NULL);
while (p) {
token = p;
p = strchr(p, '/');
if (p) {
*p = '\0';
p++;
}
if (p) {
/* inner node */
if (resolve_descendant_schema_nodeid(token, schema ? schema->child : start->schema,
LYS_CONTAINER | LYS_CHOICE | LYS_CASE | LYS_LEAF, 0, &schema)
|| !schema) {
result = NULL;
break;
}
if (schema->nodetype & (LYS_CHOICE | LYS_CASE)) {
continue;
}
} else {
/* final node */
if (resolve_descendant_schema_nodeid(token, schema ? schema->child : start->schema, LYS_LEAF, 0, &schema)
|| !schema) {
result = NULL;
break;
}
}
LY_TREE_FOR(result ? result->child : start, iter) {
if (iter->schema == schema) {
/* move in data tree according to returned schema */
result = iter;
break;
}
}
if (!iter) {
/* instance not found */
result = NULL;
break;
}
}
free(str);
return result;
}
int
schema_nodeid_siblingcheck(const struct lys_node *sibling, const struct lys_module *cur_module, const char *mod_name,
int mod_name_len, const char *name, int nam_len)
{
const struct lys_module *prefix_mod;
/* handle special names */
if (name[0] == '*') {
return 2;
} else if (name[0] == '.') {
return 3;
}
/* name check */
if (strncmp(name, sibling->name, nam_len) || sibling->name[nam_len]) {
return 1;
}
/* module check */
if (mod_name) {
prefix_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0);
if (!prefix_mod) {
return -1;
}
} else {
prefix_mod = cur_module;
}
if (prefix_mod != lys_node_module(sibling)) {
return 1;
}
/* match */
return 0;
}
/* keys do not have to be ordered and do not have to be all of them */
static int
resolve_extended_schema_nodeid_predicate(const char *nodeid, const struct lys_node *node,
const struct lys_module *cur_module, int *nodeid_end)
{
int mod_len, nam_len, has_predicate, r, i;
const char *model, *name;
struct lys_node_list *list;
if (!(node->nodetype & (LYS_LIST | LYS_LEAFLIST))) {
return 1;
}
list = (struct lys_node_list *)node;
do {
r = parse_schema_json_predicate(nodeid, &model, &mod_len, &name, &nam_len, NULL, NULL, &has_predicate);
if (r < 1) {
LOGVAL(cur_module->ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, nodeid[r], &nodeid[r]);
return -1;
}
nodeid += r;
if (node->nodetype == LYS_LEAFLIST) {
/* just check syntax */
if (model || !name || (name[0] != '.') || has_predicate) {
return 1;
}
break;
} else {
/* check the key */
for (i = 0; i < list->keys_size; ++i) {
if (strncmp(list->keys[i]->name, name, nam_len) || list->keys[i]->name[nam_len]) {
continue;
}
if (model) {
if (strncmp(lys_node_module((struct lys_node *)list->keys[i])->name, model, mod_len)
|| lys_node_module((struct lys_node *)list->keys[i])->name[mod_len]) {
continue;
}
} else {
if (lys_node_module((struct lys_node *)list->keys[i]) != cur_module) {
continue;
}
}
/* match */
break;
}
if (i == list->keys_size) {
return 1;
}
}
} while (has_predicate);
if (!nodeid[0]) {
*nodeid_end = 1;
}
return 0;
}
/* start_parent - relative, module - absolute, -1 error (logged), EXIT_SUCCESS ok
*/
int
resolve_schema_nodeid(const char *nodeid, const struct lys_node *start_parent, const struct lys_module *cur_module,
struct ly_set **ret, int extended, int no_node_error)
{
const char *name, *mod_name, *id, *backup_mod_name = NULL, *yang_data_name = NULL;
const struct lys_node *sibling, *next, *elem;
struct lys_node_augment *last_aug;
int r, nam_len, mod_name_len = 0, is_relative = -1, all_desc, has_predicate, nodeid_end = 0;
int yang_data_name_len, backup_mod_name_len = 0;
/* resolved import module from the start module, it must match the next node-name-match sibling */
const struct lys_module *start_mod, *aux_mod = NULL;
char *str;
struct ly_ctx *ctx;
assert(nodeid && (start_parent || cur_module) && ret);
*ret = NULL;
if (!cur_module) {
cur_module = lys_node_module(start_parent);
}
ctx = cur_module->ctx;
id = nodeid;
r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1);
if (r < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]);
return -1;
}
if (name[0] == '#') {
if (is_relative) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name);
return -1;
}
yang_data_name = name + 1;
yang_data_name_len = nam_len - 1;
backup_mod_name = mod_name;
backup_mod_name_len = mod_name_len;
id += r;
} else {
is_relative = -1;
}
r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate,
(extended ? &all_desc : NULL), extended);
if (r < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]);
return -1;
}
id += r;
if (backup_mod_name) {
mod_name = backup_mod_name;
mod_name_len = backup_mod_name_len;
}
if (is_relative && !start_parent) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_STR, nodeid, "Starting node must be provided for relative paths.");
return -1;
}
/* descendant-schema-nodeid */
if (is_relative) {
cur_module = start_mod = lys_node_module(start_parent);
/* absolute-schema-nodeid */
} else {
start_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0);
if (!start_mod) {
str = strndup(mod_name, mod_name_len);
LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str);
free(str);
return -1;
}
start_parent = NULL;
if (yang_data_name) {
start_parent = lyp_get_yang_data_template(start_mod, yang_data_name, yang_data_name_len);
if (!start_parent) {
str = strndup(nodeid, (yang_data_name + yang_data_name_len) - nodeid);
LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str);
free(str);
return -1;
}
}
}
while (1) {
sibling = NULL;
last_aug = NULL;
if (start_parent) {
if (mod_name && (strncmp(mod_name, cur_module->name, mod_name_len)
|| (mod_name_len != (signed)strlen(cur_module->name)))) {
/* we are getting into another module (augment) */
aux_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0);
if (!aux_mod) {
str = strndup(mod_name, mod_name_len);
LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str);
free(str);
return -1;
}
} else {
/* there is no mod_name, so why are we checking augments again?
* because this module may be not implemented and it augments something in another module and
* there is another augment augmenting that previous one */
aux_mod = cur_module;
}
/* look into augments */
if (!extended) {
get_next_augment:
last_aug = lys_getnext_target_aug(last_aug, aux_mod, start_parent);
}
}
while ((sibling = lys_getnext(sibling, (last_aug ? (struct lys_node *)last_aug : start_parent), start_mod,
LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_WITHINOUT | LYS_GETNEXT_PARENTUSES | LYS_GETNEXT_NOSTATECHECK))) {
r = schema_nodeid_siblingcheck(sibling, cur_module, mod_name, mod_name_len, name, nam_len);
/* resolve predicate */
if (extended && ((r == 0) || (r == 2) || (r == 3)) && has_predicate) {
r = resolve_extended_schema_nodeid_predicate(id, sibling, cur_module, &nodeid_end);
if (r == 1) {
continue;
} else if (r == -1) {
return -1;
}
} else if (!id[0]) {
nodeid_end = 1;
}
if (r == 0) {
/* one matching result */
if (nodeid_end) {
*ret = ly_set_new();
LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1);
ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST);
} else {
if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
return -1;
}
start_parent = sibling;
}
break;
} else if (r == 1) {
continue;
} else if (r == 2) {
/* "*" */
if (!*ret) {
*ret = ly_set_new();
LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1);
}
ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST);
if (all_desc) {
LY_TREE_DFS_BEGIN(sibling, next, elem) {
if (elem != sibling) {
ly_set_add(*ret, (void *)elem, LY_SET_OPT_USEASLIST);
}
LY_TREE_DFS_END(sibling, next, elem);
}
}
} else if (r == 3) {
/* "." */
if (!*ret) {
*ret = ly_set_new();
LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1);
ly_set_add(*ret, (void *)start_parent, LY_SET_OPT_USEASLIST);
}
ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST);
if (all_desc) {
LY_TREE_DFS_BEGIN(sibling, next, elem) {
if (elem != sibling) {
ly_set_add(*ret, (void *)elem, LY_SET_OPT_USEASLIST);
}
LY_TREE_DFS_END(sibling, next, elem);
}
}
} else {
LOGINT(ctx);
return -1;
}
}
/* skip predicate */
if (extended && has_predicate) {
while (id[0] == '[') {
id = strchr(id, ']');
if (!id) {
LOGINT(ctx);
return -1;
}
++id;
}
}
if (nodeid_end && ((r == 0) || (r == 2) || (r == 3))) {
return EXIT_SUCCESS;
}
/* no match */
if (!sibling) {
if (last_aug) {
/* it still could be in another augment */
goto get_next_augment;
}
if (no_node_error) {
str = strndup(nodeid, (name - nodeid) + nam_len);
LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str);
free(str);
return -1;
}
*ret = NULL;
return EXIT_SUCCESS;
}
r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate,
(extended ? &all_desc : NULL), extended);
if (r < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]);
return -1;
}
id += r;
}
/* cannot get here */
LOGINT(ctx);
return -1;
}
/* unique, refine,
* >0 - unexpected char on position (ret - 1),
* 0 - ok (but ret can still be NULL),
* -1 - error,
* -2 - violated no_innerlist */
int
resolve_descendant_schema_nodeid(const char *nodeid, const struct lys_node *start, int ret_nodetype,
int no_innerlist, const struct lys_node **ret)
{
const char *name, *mod_name, *id;
const struct lys_node *sibling, *start_parent;
int r, nam_len, mod_name_len, is_relative = -1;
/* resolved import module from the start module, it must match the next node-name-match sibling */
const struct lys_module *module;
assert(nodeid && ret);
assert(!(ret_nodetype & (LYS_USES | LYS_AUGMENT | LYS_GROUPING)));
if (!start) {
/* leaf not found */
return 0;
}
id = nodeid;
module = lys_node_module(start);
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) {
return ((id - nodeid) - r) + 1;
}
id += r;
if (!is_relative) {
return -1;
}
start_parent = lys_parent(start);
while ((start_parent->nodetype == LYS_USES) && lys_parent(start_parent)) {
start_parent = lys_parent(start_parent);
}
while (1) {
sibling = NULL;
while ((sibling = lys_getnext(sibling, start_parent, module,
LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_PARENTUSES | LYS_GETNEXT_NOSTATECHECK))) {
r = schema_nodeid_siblingcheck(sibling, module, mod_name, mod_name_len, name, nam_len);
if (r == 0) {
if (!id[0]) {
if (!(sibling->nodetype & ret_nodetype)) {
/* wrong node type, too bad */
continue;
}
*ret = sibling;
return EXIT_SUCCESS;
}
start_parent = sibling;
break;
} else if (r == 1) {
continue;
} else {
return -1;
}
}
/* no match */
if (!sibling) {
*ret = NULL;
return EXIT_SUCCESS;
} else if (no_innerlist && sibling->nodetype == LYS_LIST) {
*ret = NULL;
return -2;
}
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) {
return ((id - nodeid) - r) + 1;
}
id += r;
}
/* cannot get here */
LOGINT(module->ctx);
return -1;
}
/* choice default */
int
resolve_choice_default_schema_nodeid(const char *nodeid, const struct lys_node *start, const struct lys_node **ret)
{
/* cannot actually be a path */
if (strchr(nodeid, '/')) {
return -1;
}
return resolve_descendant_schema_nodeid(nodeid, start, LYS_NO_RPC_NOTIF_NODE, 0, ret);
}
/* uses, -1 error, EXIT_SUCCESS ok (but ret can still be NULL), >0 unexpected char on ret - 1 */
static int
resolve_uses_schema_nodeid(const char *nodeid, const struct lys_node *start, const struct lys_node_grp **ret)
{
const struct lys_module *module;
const char *mod_prefix, *name;
int i, mod_prefix_len, nam_len;
/* parse the identifier, it must be parsed on one call */
if (((i = parse_node_identifier(nodeid, &mod_prefix, &mod_prefix_len, &name, &nam_len, NULL, 0)) < 1) || nodeid[i]) {
return -i + 1;
}
module = lyp_get_module(start->module, mod_prefix, mod_prefix_len, NULL, 0, 0);
if (!module) {
return -1;
}
if (module != lys_main_module(start->module)) {
start = module->data;
}
*ret = lys_find_grouping_up(name, (struct lys_node *)start);
return EXIT_SUCCESS;
}
int
resolve_absolute_schema_nodeid(const char *nodeid, const struct lys_module *module, int ret_nodetype,
const struct lys_node **ret)
{
const char *name, *mod_name, *id;
const struct lys_node *sibling, *start_parent;
int r, nam_len, mod_name_len, is_relative = -1;
const struct lys_module *abs_start_mod;
assert(nodeid && module && ret);
assert(!(ret_nodetype & (LYS_USES | LYS_AUGMENT)) && ((ret_nodetype == LYS_GROUPING) || !(ret_nodetype & LYS_GROUPING)));
id = nodeid;
start_parent = NULL;
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) {
return ((id - nodeid) - r) + 1;
}
id += r;
if (is_relative) {
return -1;
}
abs_start_mod = lyp_get_module(module, NULL, 0, mod_name, mod_name_len, 0);
if (!abs_start_mod) {
return -1;
}
while (1) {
sibling = NULL;
while ((sibling = lys_getnext(sibling, start_parent, abs_start_mod, LYS_GETNEXT_WITHCHOICE
| LYS_GETNEXT_WITHCASE | LYS_GETNEXT_WITHINOUT | LYS_GETNEXT_WITHGROUPING | LYS_GETNEXT_NOSTATECHECK))) {
r = schema_nodeid_siblingcheck(sibling, module, mod_name, mod_name_len, name, nam_len);
if (r == 0) {
if (!id[0]) {
if (!(sibling->nodetype & ret_nodetype)) {
/* wrong node type, too bad */
continue;
}
*ret = sibling;
return EXIT_SUCCESS;
}
start_parent = sibling;
break;
} else if (r == 1) {
continue;
} else {
return -1;
}
}
/* no match */
if (!sibling) {
*ret = NULL;
return EXIT_SUCCESS;
}
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) {
return ((id - nodeid) - r) + 1;
}
id += r;
}
/* cannot get here */
LOGINT(module->ctx);
return -1;
}
static int
resolve_json_schema_list_predicate(const char *predicate, const struct lys_node_list *list, int *parsed)
{
const char *mod_name, *name;
int mod_name_len, nam_len, has_predicate, i;
struct lys_node *key;
if (((i = parse_schema_json_predicate(predicate, &mod_name, &mod_name_len, &name, &nam_len, NULL, NULL, &has_predicate)) < 1)
|| !strncmp(name, ".", nam_len)) {
LOGVAL(list->module->ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, predicate[-i], &predicate[-i]);
return -1;
}
predicate += i;
*parsed += i;
if (!isdigit(name[0])) {
for (i = 0; i < list->keys_size; ++i) {
key = (struct lys_node *)list->keys[i];
if (!strncmp(key->name, name, nam_len) && !key->name[nam_len]) {
break;
}
}
if (i == list->keys_size) {
LOGVAL(list->module->ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, name);
return -1;
}
}
/* more predicates? */
if (has_predicate) {
return resolve_json_schema_list_predicate(predicate, list, parsed);
}
return 0;
}
/* cannot return LYS_GROUPING, LYS_AUGMENT, LYS_USES, logs directly */
const struct lys_node *
resolve_json_nodeid(const char *nodeid, struct ly_ctx *ctx, const struct lys_node *start, int output)
{
char *str;
const char *name, *mod_name, *id, *backup_mod_name = NULL, *yang_data_name = NULL;
const struct lys_node *sibling, *start_parent, *parent;
int r, nam_len, mod_name_len, is_relative = -1, has_predicate;
int yang_data_name_len, backup_mod_name_len;
/* resolved import module from the start module, it must match the next node-name-match sibling */
const struct lys_module *prefix_mod, *module, *prev_mod;
assert(nodeid && (ctx || start));
if (!ctx) {
ctx = start->module->ctx;
}
id = nodeid;
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
return NULL;
}
if (name[0] == '#') {
if (is_relative) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name);
return NULL;
}
yang_data_name = name + 1;
yang_data_name_len = nam_len - 1;
backup_mod_name = mod_name;
backup_mod_name_len = mod_name_len;
id += r;
} else {
is_relative = -1;
}
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
return NULL;
}
id += r;
if (backup_mod_name) {
mod_name = backup_mod_name;
mod_name_len = backup_mod_name_len;
}
if (is_relative) {
assert(start);
start_parent = start;
while (start_parent && (start_parent->nodetype == LYS_USES)) {
start_parent = lys_parent(start_parent);
}
module = start->module;
} else {
if (!mod_name) {
str = strndup(nodeid, (name + nam_len) - nodeid);
LOGVAL(ctx, LYE_PATH_MISSMOD, LY_VLOG_STR, nodeid);
free(str);
return NULL;
}
str = strndup(mod_name, mod_name_len);
module = ly_ctx_get_module(ctx, str, NULL, 1);
free(str);
if (!module) {
str = strndup(nodeid, (mod_name + mod_name_len) - nodeid);
LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str);
free(str);
return NULL;
}
start_parent = NULL;
if (yang_data_name) {
start_parent = lyp_get_yang_data_template(module, yang_data_name, yang_data_name_len);
if (!start_parent) {
str = strndup(nodeid, (yang_data_name + yang_data_name_len) - nodeid);
LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str);
free(str);
return NULL;
}
}
/* now it's as if there was no module name */
mod_name = NULL;
mod_name_len = 0;
}
prev_mod = module;
while (1) {
sibling = NULL;
while ((sibling = lys_getnext(sibling, start_parent, module, 0))) {
/* name match */
if (sibling->name && !strncmp(name, sibling->name, nam_len) && !sibling->name[nam_len]) {
/* output check */
for (parent = lys_parent(sibling); parent && !(parent->nodetype & (LYS_INPUT | LYS_OUTPUT)); parent = lys_parent(parent));
if (parent) {
if (output && (parent->nodetype == LYS_INPUT)) {
continue;
} else if (!output && (parent->nodetype == LYS_OUTPUT)) {
continue;
}
}
/* module check */
if (mod_name) {
/* will also find an augment module */
prefix_mod = ly_ctx_nget_module(ctx, mod_name, mod_name_len, NULL, 1);
if (!prefix_mod) {
str = strndup(nodeid, (mod_name + mod_name_len) - nodeid);
LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str);
free(str);
return NULL;
}
} else {
prefix_mod = prev_mod;
}
if (prefix_mod != lys_node_module(sibling)) {
continue;
}
/* do we have some predicates on it? */
if (has_predicate) {
r = 0;
if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST)) {
if ((r = parse_schema_json_predicate(id, NULL, NULL, NULL, NULL, NULL, NULL, &has_predicate)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
return NULL;
}
} else if (sibling->nodetype == LYS_LIST) {
if (resolve_json_schema_list_predicate(id, (const struct lys_node_list *)sibling, &r)) {
return NULL;
}
} else {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id);
return NULL;
}
id += r;
}
/* the result node? */
if (!id[0]) {
return sibling;
}
/* move down the tree, if possible */
if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id);
return NULL;
}
start_parent = sibling;
/* update prev mod */
prev_mod = (start_parent->child ? lys_node_module(start_parent->child) : module);
break;
}
}
/* no match */
if (!sibling) {
str = strndup(nodeid, (name + nam_len) - nodeid);
LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str);
free(str);
return NULL;
}
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
return NULL;
}
id += r;
}
/* cannot get here */
LOGINT(ctx);
return NULL;
}
static int
resolve_partial_json_data_list_predicate(struct parsed_pred pp, struct lyd_node *node, int position)
{
uint16_t i;
struct lyd_node_leaf_list *key;
struct lys_node_list *slist;
struct ly_ctx *ctx;
assert(node);
assert(node->schema->nodetype == LYS_LIST);
assert(pp.len);
ctx = node->schema->module->ctx;
slist = (struct lys_node_list *)node->schema;
/* is the predicate a number? */
if (isdigit(pp.pred[0].name[0])) {
if (position == atoi(pp.pred[0].name)) {
/* match */
return 0;
} else {
/* not a match */
return 1;
}
}
key = (struct lyd_node_leaf_list *)node->child;
if (!key) {
/* it is not a position, so we need a key for it to be a match */
return 1;
}
/* go through all the keys */
for (i = 0; i < slist->keys_size; ++i) {
if (strncmp(key->schema->name, pp.pred[i].name, pp.pred[i].nam_len) || key->schema->name[pp.pred[i].nam_len]) {
LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name);
return -1;
}
if (pp.pred[i].mod_name) {
/* specific module, check that the found key is from that module */
if (strncmp(lyd_node_module((struct lyd_node *)key)->name, pp.pred[i].mod_name, pp.pred[i].mod_name_len)
|| lyd_node_module((struct lyd_node *)key)->name[pp.pred[i].mod_name_len]) {
LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name);
return -1;
}
/* but if the module is the same as the parent, it should have been omitted */
if (lyd_node_module((struct lyd_node *)key) == lyd_node_module(node)) {
LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name);
return -1;
}
} else {
/* no module, so it must be the same as the list (parent) */
if (lyd_node_module((struct lyd_node *)key) != lyd_node_module(node)) {
LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name);
return -1;
}
}
/* value does not match */
if (strncmp(key->value_str, pp.pred[i].value, pp.pred[i].val_len) || key->value_str[pp.pred[i].val_len]) {
return 1;
}
key = (struct lyd_node_leaf_list *)key->next;
}
return 0;
}
/**
* @brief get the closest parent of the node (or the node itself) identified by the nodeid (path)
*
* @param[in] nodeid Node data path to find
* @param[in] llist_value If the \p nodeid identifies leaf-list, this is expected value of the leaf-list instance.
* @param[in] options Bitmask of options flags, see @ref pathoptions.
* @param[out] parsed Number of characters processed in \p id
* @return The closes parent (or the node itself) from the path
*/
struct lyd_node *
resolve_partial_json_data_nodeid(const char *nodeid, const char *llist_value, struct lyd_node *start, int options,
int *parsed)
{
const char *id, *mod_name, *name, *data_val, *llval;
int r, ret, mod_name_len, nam_len, is_relative = -1, list_instance_position;
int has_predicate, last_parsed = 0, llval_len;
struct lyd_node *sibling, *last_match = NULL;
struct lyd_node_leaf_list *llist;
const struct lys_module *prev_mod;
struct ly_ctx *ctx;
const struct lys_node *ssibling, *sparent;
struct lys_node_list *slist;
struct parsed_pred pp;
assert(nodeid && start && parsed);
memset(&pp, 0, sizeof pp);
ctx = start->schema->module->ctx;
id = nodeid;
/* parse first nodeid in case it is yang-data extension */
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
goto error;
}
if (name[0] == '#') {
if (is_relative) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name);
goto error;
}
id += r;
last_parsed = r;
} else {
is_relative = -1;
}
/* parse first nodeid */
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
goto error;
}
id += r;
/* add it to parsed only after the data node was actually found */
last_parsed += r;
if (is_relative) {
prev_mod = lyd_node_module(start);
start = (start->schema->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_RPC | LYS_ACTION | LYS_NOTIF)) ? start->child : NULL;
} else {
for (; start->parent; start = start->parent);
prev_mod = lyd_node_module(start);
}
if (!start) {
/* there are no siblings to search */
return NULL;
}
/* do not duplicate code, use predicate parsing from the loop */
goto parse_predicates;
while (1) {
/* find the correct schema node first */
ssibling = NULL;
sparent = (start && start->parent) ? start->parent->schema : NULL;
while ((ssibling = lys_getnext(ssibling, sparent, prev_mod, 0))) {
/* skip invalid input/output nodes */
if (sparent && (sparent->nodetype & (LYS_RPC | LYS_ACTION))) {
if (options & LYD_PATH_OPT_OUTPUT) {
if (lys_parent(ssibling)->nodetype == LYS_INPUT) {
continue;
}
} else {
if (lys_parent(ssibling)->nodetype == LYS_OUTPUT) {
continue;
}
}
}
if (!schema_nodeid_siblingcheck(ssibling, prev_mod, mod_name, mod_name_len, name, nam_len)) {
break;
}
}
if (!ssibling) {
/* there is not even such a schema node */
free(pp.pred);
return last_match;
}
pp.schema = ssibling;
/* unify leaf-list value - it is possible to specify last-node value as both a predicate or parameter if
* is a leaf-list, unify both cases and the value will in both cases be in the predicate structure */
if (!id[0] && !pp.len && (ssibling->nodetype == LYS_LEAFLIST)) {
pp.len = 1;
pp.pred = calloc(1, sizeof *pp.pred);
LY_CHECK_ERR_GOTO(!pp.pred, LOGMEM(ctx), error);
pp.pred[0].name = ".";
pp.pred[0].nam_len = 1;
pp.pred[0].value = (llist_value ? llist_value : "");
pp.pred[0].val_len = strlen(pp.pred[0].value);
}
if (ssibling->nodetype & (LYS_LEAFLIST | LYS_LEAF)) {
/* check leaf/leaf-list predicate */
if (pp.len > 1) {
LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL);
goto error;
} else if (pp.len) {
if ((pp.pred[0].name[0] != '.') || (pp.pred[0].nam_len != 1)) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, pp.pred[0].name[0], pp.pred[0].name);
goto error;
}
if ((((struct lys_node_leaf *)ssibling)->type.base == LY_TYPE_IDENT) && !strnchr(pp.pred[0].value, ':', pp.pred[0].val_len)) {
LOGVAL(ctx, LYE_PATH_INIDENTREF, LY_VLOG_LYS, ssibling, pp.pred[0].val_len, pp.pred[0].value);
goto error;
}
}
} else if (ssibling->nodetype == LYS_LIST) {
/* list should have predicates for all the keys or position */
slist = (struct lys_node_list *)ssibling;
if (!pp.len) {
/* none match */
return last_match;
} else if (!isdigit(pp.pred[0].name[0])) {
/* list predicate is not a position, so there must be all the keys */
if (pp.len > slist->keys_size) {
LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL);
goto error;
} else if (pp.len < slist->keys_size) {
LOGVAL(ctx, LYE_PATH_MISSKEY, LY_VLOG_NONE, NULL, slist->keys[pp.len]->name);
goto error;
}
/* check that all identityrefs have module name, otherwise the hash of the list instance will never match!! */
for (r = 0; r < pp.len; ++r) {
if ((slist->keys[r]->type.base == LY_TYPE_IDENT) && !strnchr(pp.pred[r].value, ':', pp.pred[r].val_len)) {
LOGVAL(ctx, LYE_PATH_INIDENTREF, LY_VLOG_LYS, slist->keys[r], pp.pred[r].val_len, pp.pred[r].value);
goto error;
}
}
}
} else if (pp.pred) {
/* no other nodes allow predicates */
LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL);
goto error;
}
#ifdef LY_ENABLED_CACHE
/* we will not be matching keyless lists or state leaf-lists this way */
if (start->parent && start->parent->ht && ((pp.schema->nodetype != LYS_LIST) || ((struct lys_node_list *)pp.schema)->keys_size)
&& ((pp.schema->nodetype != LYS_LEAFLIST) || (pp.schema->flags & LYS_CONFIG_W))) {
sibling = resolve_json_data_node_hash(start->parent, pp);
} else
#endif
{
list_instance_position = 0;
LY_TREE_FOR(start, sibling) {
/* RPC/action data check, return simply invalid argument, because the data tree is invalid */
if (lys_parent(sibling->schema)) {
if (options & LYD_PATH_OPT_OUTPUT) {
if (lys_parent(sibling->schema)->nodetype == LYS_INPUT) {
LOGERR(ctx, LY_EINVAL, "Provided data tree includes some RPC input nodes (%s).", sibling->schema->name);
goto error;
}
} else {
if (lys_parent(sibling->schema)->nodetype == LYS_OUTPUT) {
LOGERR(ctx, LY_EINVAL, "Provided data tree includes some RPC output nodes (%s).", sibling->schema->name);
goto error;
}
}
}
if (sibling->schema != ssibling) {
/* wrong schema node */
continue;
}
/* leaf-list, did we find it with the correct value or not? */
if (ssibling->nodetype == LYS_LEAFLIST) {
if (ssibling->flags & LYS_CONFIG_R) {
/* state leaf-lists will never match */
continue;
}
llist = (struct lyd_node_leaf_list *)sibling;
/* get the expected leaf-list value */
llval = NULL;
llval_len = 0;
if (pp.pred) {
/* it was already checked that it is correct */
llval = pp.pred[0].value;
llval_len = pp.pred[0].val_len;
}
/* make value canonical (remove module name prefix) unless it was specified with it */
if (llval && !strchr(llval, ':') && (llist->value_type & LY_TYPE_IDENT)
&& !strncmp(llist->value_str, lyd_node_module(sibling)->name, strlen(lyd_node_module(sibling)->name))
&& (llist->value_str[strlen(lyd_node_module(sibling)->name)] == ':')) {
data_val = llist->value_str + strlen(lyd_node_module(sibling)->name) + 1;
} else {
data_val = llist->value_str;
}
if ((!llval && data_val && data_val[0]) || (llval && (strncmp(llval, data_val, llval_len)
|| data_val[llval_len]))) {
continue;
}
} else if (ssibling->nodetype == LYS_LIST) {
/* list, we likely need predicates'n'stuff then, but if without a predicate, we are always creating it */
++list_instance_position;
ret = resolve_partial_json_data_list_predicate(pp, sibling, list_instance_position);
if (ret == -1) {
goto error;
} else if (ret == 1) {
/* this list instance does not match */
continue;
}
}
break;
}
}
/* no match, return last match */
if (!sibling) {
free(pp.pred);
return last_match;
}
/* we found a next matching node */
*parsed += last_parsed;
last_match = sibling;
prev_mod = lyd_node_module(sibling);
/* the result node? */
if (!id[0]) {
free(pp.pred);
return last_match;
}
/* move down the tree, if possible, and continue */
if (ssibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
/* there can be no children even through expected, error */
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id);
goto error;
} else if (!sibling->child) {
/* there could be some children, but are not, return what we found so far */
free(pp.pred);
return last_match;
}
start = sibling->child;
/* parse nodeid */
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
goto error;
}
id += r;
last_parsed = r;
parse_predicates:
/* parse all the predicates */
free(pp.pred);
pp.schema = NULL;
pp.len = 0;
pp.pred = NULL;
while (has_predicate) {
++pp.len;
pp.pred = ly_realloc(pp.pred, pp.len * sizeof *pp.pred);
LY_CHECK_ERR_GOTO(!pp.pred, LOGMEM(ctx), error);
if ((r = parse_schema_json_predicate(id, &pp.pred[pp.len - 1].mod_name, &pp.pred[pp.len - 1].mod_name_len,
&pp.pred[pp.len - 1].name, &pp.pred[pp.len - 1].nam_len, &pp.pred[pp.len - 1].value,
&pp.pred[pp.len - 1].val_len, &has_predicate)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id);
goto error;
}
id += r;
last_parsed += r;
}
}
error:
*parsed = -1;
free(pp.pred);
return NULL;
}
/**
* @brief Resolves length or range intervals. Does not log.
* Syntax is assumed to be correct, *ret MUST be NULL.
*
* @param[in] ctx Context for errors.
* @param[in] str_restr Restriction as a string.
* @param[in] type Type of the restriction.
* @param[out] ret Final interval structure that starts with
* the interval of the initial type, continues with intervals
* of any superior types derived from the initial one, and
* finishes with intervals from our \p type.
*
* @return EXIT_SUCCESS on succes, -1 on error.
*/
int
resolve_len_ran_interval(struct ly_ctx *ctx, const char *str_restr, struct lys_type *type, struct len_ran_intv **ret)
{
/* 0 - unsigned, 1 - signed, 2 - floating point */
int kind;
int64_t local_smin = 0, local_smax = 0, local_fmin, local_fmax;
uint64_t local_umin, local_umax = 0;
uint8_t local_fdig = 0;
const char *seg_ptr, *ptr;
struct len_ran_intv *local_intv = NULL, *tmp_local_intv = NULL, *tmp_intv, *intv = NULL;
switch (type->base) {
case LY_TYPE_BINARY:
kind = 0;
local_umin = 0;
local_umax = 18446744073709551615UL;
if (!str_restr && type->info.binary.length) {
str_restr = type->info.binary.length->expr;
}
break;
case LY_TYPE_DEC64:
kind = 2;
local_fmin = __INT64_C(-9223372036854775807) - __INT64_C(1);
local_fmax = __INT64_C(9223372036854775807);
local_fdig = type->info.dec64.dig;
if (!str_restr && type->info.dec64.range) {
str_restr = type->info.dec64.range->expr;
}
break;
case LY_TYPE_INT8:
kind = 1;
local_smin = __INT64_C(-128);
local_smax = __INT64_C(127);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_INT16:
kind = 1;
local_smin = __INT64_C(-32768);
local_smax = __INT64_C(32767);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_INT32:
kind = 1;
local_smin = __INT64_C(-2147483648);
local_smax = __INT64_C(2147483647);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_INT64:
kind = 1;
local_smin = __INT64_C(-9223372036854775807) - __INT64_C(1);
local_smax = __INT64_C(9223372036854775807);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_UINT8:
kind = 0;
local_umin = __UINT64_C(0);
local_umax = __UINT64_C(255);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_UINT16:
kind = 0;
local_umin = __UINT64_C(0);
local_umax = __UINT64_C(65535);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_UINT32:
kind = 0;
local_umin = __UINT64_C(0);
local_umax = __UINT64_C(4294967295);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_UINT64:
kind = 0;
local_umin = __UINT64_C(0);
local_umax = __UINT64_C(18446744073709551615);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_STRING:
kind = 0;
local_umin = __UINT64_C(0);
local_umax = __UINT64_C(18446744073709551615);
if (!str_restr && type->info.str.length) {
str_restr = type->info.str.length->expr;
}
break;
default:
return -1;
}
/* process superior types */
if (type->der) {
if (resolve_len_ran_interval(ctx, NULL, &type->der->type, &intv)) {
return -1;
}
assert(!intv || (intv->kind == kind));
}
if (!str_restr) {
/* we do not have any restriction, return superior ones */
*ret = intv;
return EXIT_SUCCESS;
}
/* adjust local min and max */
if (intv) {
tmp_intv = intv;
if (kind == 0) {
local_umin = tmp_intv->value.uval.min;
} else if (kind == 1) {
local_smin = tmp_intv->value.sval.min;
} else if (kind == 2) {
local_fmin = tmp_intv->value.fval.min;
}
while (tmp_intv->next) {
tmp_intv = tmp_intv->next;
}
if (kind == 0) {
local_umax = tmp_intv->value.uval.max;
} else if (kind == 1) {
local_smax = tmp_intv->value.sval.max;
} else if (kind == 2) {
local_fmax = tmp_intv->value.fval.max;
}
}
/* finally parse our restriction */
seg_ptr = str_restr;
tmp_intv = NULL;
while (1) {
if (!tmp_local_intv) {
assert(!local_intv);
local_intv = malloc(sizeof *local_intv);
tmp_local_intv = local_intv;
} else {
tmp_local_intv->next = malloc(sizeof *tmp_local_intv);
tmp_local_intv = tmp_local_intv->next;
}
LY_CHECK_ERR_GOTO(!tmp_local_intv, LOGMEM(ctx), error);
tmp_local_intv->kind = kind;
tmp_local_intv->type = type;
tmp_local_intv->next = NULL;
/* min */
ptr = seg_ptr;
while (isspace(ptr[0])) {
++ptr;
}
if (isdigit(ptr[0]) || (ptr[0] == '+') || (ptr[0] == '-')) {
if (kind == 0) {
tmp_local_intv->value.uval.min = strtoll(ptr, (char **)&ptr, 10);
} else if (kind == 1) {
tmp_local_intv->value.sval.min = strtoll(ptr, (char **)&ptr, 10);
} else if (kind == 2) {
if (parse_range_dec64(&ptr, local_fdig, &tmp_local_intv->value.fval.min)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, ptr, "range");
goto error;
}
}
} else if (!strncmp(ptr, "min", 3)) {
if (kind == 0) {
tmp_local_intv->value.uval.min = local_umin;
} else if (kind == 1) {
tmp_local_intv->value.sval.min = local_smin;
} else if (kind == 2) {
tmp_local_intv->value.fval.min = local_fmin;
}
ptr += 3;
} else if (!strncmp(ptr, "max", 3)) {
if (kind == 0) {
tmp_local_intv->value.uval.min = local_umax;
} else if (kind == 1) {
tmp_local_intv->value.sval.min = local_smax;
} else if (kind == 2) {
tmp_local_intv->value.fval.min = local_fmax;
}
ptr += 3;
} else {
goto error;
}
while (isspace(ptr[0])) {
ptr++;
}
/* no interval or interval */
if ((ptr[0] == '|') || !ptr[0]) {
if (kind == 0) {
tmp_local_intv->value.uval.max = tmp_local_intv->value.uval.min;
} else if (kind == 1) {
tmp_local_intv->value.sval.max = tmp_local_intv->value.sval.min;
} else if (kind == 2) {
tmp_local_intv->value.fval.max = tmp_local_intv->value.fval.min;
}
} else if (!strncmp(ptr, "..", 2)) {
/* skip ".." */
ptr += 2;
while (isspace(ptr[0])) {
++ptr;
}
/* max */
if (isdigit(ptr[0]) || (ptr[0] == '+') || (ptr[0] == '-')) {
if (kind == 0) {
tmp_local_intv->value.uval.max = strtoll(ptr, (char **)&ptr, 10);
} else if (kind == 1) {
tmp_local_intv->value.sval.max = strtoll(ptr, (char **)&ptr, 10);
} else if (kind == 2) {
if (parse_range_dec64(&ptr, local_fdig, &tmp_local_intv->value.fval.max)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, ptr, "range");
goto error;
}
}
} else if (!strncmp(ptr, "max", 3)) {
if (kind == 0) {
tmp_local_intv->value.uval.max = local_umax;
} else if (kind == 1) {
tmp_local_intv->value.sval.max = local_smax;
} else if (kind == 2) {
tmp_local_intv->value.fval.max = local_fmax;
}
} else {
goto error;
}
} else {
goto error;
}
/* check min and max in correct order*/
if (kind == 0) {
/* current segment */
if (tmp_local_intv->value.uval.min > tmp_local_intv->value.uval.max) {
goto error;
}
if (tmp_local_intv->value.uval.min < local_umin || tmp_local_intv->value.uval.max > local_umax) {
goto error;
}
/* segments sholud be ascending order */
if (tmp_intv && (tmp_intv->value.uval.max >= tmp_local_intv->value.uval.min)) {
goto error;
}
} else if (kind == 1) {
if (tmp_local_intv->value.sval.min > tmp_local_intv->value.sval.max) {
goto error;
}
if (tmp_local_intv->value.sval.min < local_smin || tmp_local_intv->value.sval.max > local_smax) {
goto error;
}
if (tmp_intv && (tmp_intv->value.sval.max >= tmp_local_intv->value.sval.min)) {
goto error;
}
} else if (kind == 2) {
if (tmp_local_intv->value.fval.min > tmp_local_intv->value.fval.max) {
goto error;
}
if (tmp_local_intv->value.fval.min < local_fmin || tmp_local_intv->value.fval.max > local_fmax) {
goto error;
}
if (tmp_intv && (tmp_intv->value.fval.max >= tmp_local_intv->value.fval.min)) {
/* fraction-digits value is always the same (it cannot be changed in derived types) */
goto error;
}
}
/* next segment (next OR) */
seg_ptr = strchr(seg_ptr, '|');
if (!seg_ptr) {
break;
}
seg_ptr++;
tmp_intv = tmp_local_intv;
}
/* check local restrictions against superior ones */
if (intv) {
tmp_intv = intv;
tmp_local_intv = local_intv;
while (tmp_local_intv && tmp_intv) {
/* reuse local variables */
if (kind == 0) {
local_umin = tmp_local_intv->value.uval.min;
local_umax = tmp_local_intv->value.uval.max;
/* it must be in this interval */
if ((local_umin >= tmp_intv->value.uval.min) && (local_umin <= tmp_intv->value.uval.max)) {
/* this interval is covered, next one */
if (local_umax <= tmp_intv->value.uval.max) {
tmp_local_intv = tmp_local_intv->next;
continue;
/* ascending order of restrictions -> fail */
} else {
goto error;
}
}
} else if (kind == 1) {
local_smin = tmp_local_intv->value.sval.min;
local_smax = tmp_local_intv->value.sval.max;
if ((local_smin >= tmp_intv->value.sval.min) && (local_smin <= tmp_intv->value.sval.max)) {
if (local_smax <= tmp_intv->value.sval.max) {
tmp_local_intv = tmp_local_intv->next;
continue;
} else {
goto error;
}
}
} else if (kind == 2) {
local_fmin = tmp_local_intv->value.fval.min;
local_fmax = tmp_local_intv->value.fval.max;
if ((dec64cmp(local_fmin, local_fdig, tmp_intv->value.fval.min, local_fdig) > -1)
&& (dec64cmp(local_fmin, local_fdig, tmp_intv->value.fval.max, local_fdig) < 1)) {
if (dec64cmp(local_fmax, local_fdig, tmp_intv->value.fval.max, local_fdig) < 1) {
tmp_local_intv = tmp_local_intv->next;
continue;
} else {
goto error;
}
}
}
tmp_intv = tmp_intv->next;
}
/* some interval left uncovered -> fail */
if (tmp_local_intv) {
goto error;
}
}
/* append the local intervals to all the intervals of the superior types, return it all */
if (intv) {
for (tmp_intv = intv; tmp_intv->next; tmp_intv = tmp_intv->next);
tmp_intv->next = local_intv;
} else {
intv = local_intv;
}
*ret = intv;
return EXIT_SUCCESS;
error:
while (intv) {
tmp_intv = intv->next;
free(intv);
intv = tmp_intv;
}
while (local_intv) {
tmp_local_intv = local_intv->next;
free(local_intv);
local_intv = tmp_local_intv;
}
return -1;
}
/**
* @brief Resolve a typedef, return only resolved typedefs if derived. If leafref, it must be
* resolved for this function to return it. Does not log.
*
* @param[in] name Typedef name.
* @param[in] mod_name Typedef name module name.
* @param[in] module Main module.
* @param[in] parent Parent of the resolved type definition.
* @param[out] ret Pointer to the resolved typedef. Can be NULL.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
int
resolve_superior_type(const char *name, const char *mod_name, const struct lys_module *module,
const struct lys_node *parent, struct lys_tpdf **ret)
{
int i, j;
struct lys_tpdf *tpdf, *match;
int tpdf_size;
if (!mod_name) {
/* no prefix, try built-in types */
for (i = 1; i < LY_DATA_TYPE_COUNT; i++) {
if (!strcmp(ly_types[i]->name, name)) {
if (ret) {
*ret = ly_types[i];
}
return EXIT_SUCCESS;
}
}
} else {
if (!strcmp(mod_name, module->name)) {
/* prefix refers to the current module, ignore it */
mod_name = NULL;
}
}
if (!mod_name && parent) {
/* search in local typedefs */
while (parent) {
switch (parent->nodetype) {
case LYS_CONTAINER:
tpdf_size = ((struct lys_node_container *)parent)->tpdf_size;
tpdf = ((struct lys_node_container *)parent)->tpdf;
break;
case LYS_LIST:
tpdf_size = ((struct lys_node_list *)parent)->tpdf_size;
tpdf = ((struct lys_node_list *)parent)->tpdf;
break;
case LYS_GROUPING:
tpdf_size = ((struct lys_node_grp *)parent)->tpdf_size;
tpdf = ((struct lys_node_grp *)parent)->tpdf;
break;
case LYS_RPC:
case LYS_ACTION:
tpdf_size = ((struct lys_node_rpc_action *)parent)->tpdf_size;
tpdf = ((struct lys_node_rpc_action *)parent)->tpdf;
break;
case LYS_NOTIF:
tpdf_size = ((struct lys_node_notif *)parent)->tpdf_size;
tpdf = ((struct lys_node_notif *)parent)->tpdf;
break;
case LYS_INPUT:
case LYS_OUTPUT:
tpdf_size = ((struct lys_node_inout *)parent)->tpdf_size;
tpdf = ((struct lys_node_inout *)parent)->tpdf;
break;
default:
parent = lys_parent(parent);
continue;
}
for (i = 0; i < tpdf_size; i++) {
if (!strcmp(tpdf[i].name, name) && tpdf[i].type.base > 0) {
match = &tpdf[i];
goto check_leafref;
}
}
parent = lys_parent(parent);
}
} else {
/* get module where to search */
module = lyp_get_module(module, NULL, 0, mod_name, 0, 0);
if (!module) {
return -1;
}
}
/* search in top level typedefs */
for (i = 0; i < module->tpdf_size; i++) {
if (!strcmp(module->tpdf[i].name, name) && module->tpdf[i].type.base > 0) {
match = &module->tpdf[i];
goto check_leafref;
}
}
/* search in submodules */
for (i = 0; i < module->inc_size && module->inc[i].submodule; i++) {
for (j = 0; j < module->inc[i].submodule->tpdf_size; j++) {
if (!strcmp(module->inc[i].submodule->tpdf[j].name, name) && module->inc[i].submodule->tpdf[j].type.base > 0) {
match = &module->inc[i].submodule->tpdf[j];
goto check_leafref;
}
}
}
return EXIT_FAILURE;
check_leafref:
if (ret) {
*ret = match;
}
if (match->type.base == LY_TYPE_LEAFREF) {
while (!match->type.info.lref.path) {
match = match->type.der;
assert(match);
}
}
return EXIT_SUCCESS;
}
/**
* @brief Check the default \p value of the \p type. Logs directly.
*
* @param[in] type Type definition to use.
* @param[in] value Default value to check.
* @param[in] module Type module.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
check_default(struct lys_type *type, const char **value, struct lys_module *module, int tpdf)
{
struct lys_tpdf *base_tpdf = NULL;
struct lyd_node_leaf_list node;
const char *dflt = NULL;
char *s;
int ret = EXIT_SUCCESS, r;
struct ly_ctx *ctx = module->ctx;
assert(value);
memset(&node, 0, sizeof node);
if (type->base <= LY_TYPE_DER) {
/* the type was not resolved yet, nothing to do for now */
ret = EXIT_FAILURE;
goto cleanup;
} else if (!tpdf && !module->implemented) {
/* do not check defaults in not implemented module's data */
goto cleanup;
} else if (tpdf && !module->implemented && type->base == LY_TYPE_IDENT) {
/* identityrefs are checked when instantiated in data instead of typedef,
* but in typedef the value has to be modified to include the prefix */
if (*value) {
if (strchr(*value, ':')) {
dflt = transform_schema2json(module, *value);
} else {
/* default prefix of the module where the typedef is defined */
if (asprintf(&s, "%s:%s", lys_main_module(module)->name, *value) == -1) {
LOGMEM(ctx);
ret = -1;
goto cleanup;
}
dflt = lydict_insert_zc(ctx, s);
}
lydict_remove(ctx, *value);
*value = dflt;
dflt = NULL;
}
goto cleanup;
} else if (type->base == LY_TYPE_LEAFREF && tpdf) {
/* leafref in typedef cannot be checked */
goto cleanup;
}
dflt = lydict_insert(ctx, *value, 0);
if (!dflt) {
/* we do not have a new default value, so is there any to check even, in some base type? */
for (base_tpdf = type->der; base_tpdf->type.der; base_tpdf = base_tpdf->type.der) {
if (base_tpdf->dflt) {
dflt = lydict_insert(ctx, base_tpdf->dflt, 0);
break;
}
}
if (!dflt) {
/* no default value, nothing to check, all is well */
goto cleanup;
}
/* so there is a default value in a base type, but can the default value be no longer valid (did we define some new restrictions)? */
switch (type->base) {
case LY_TYPE_IDENT:
if (lys_main_module(base_tpdf->type.parent->module)->implemented) {
goto cleanup;
} else {
/* check the default value from typedef, but use also the typedef's module
* due to possible searching in imported modules which is expected in
* typedef's module instead of module where the typedef is used */
module = base_tpdf->module;
}
break;
case LY_TYPE_INST:
case LY_TYPE_LEAFREF:
case LY_TYPE_BOOL:
case LY_TYPE_EMPTY:
/* these have no restrictions, so we would do the exact same work as the unres in the base typedef */
goto cleanup;
case LY_TYPE_BITS:
/* the default value must match the restricted list of values, if the type was restricted */
if (type->info.bits.count) {
break;
}
goto cleanup;
case LY_TYPE_ENUM:
/* the default value must match the restricted list of values, if the type was restricted */
if (type->info.enums.count) {
break;
}
goto cleanup;
case LY_TYPE_DEC64:
if (type->info.dec64.range) {
break;
}
goto cleanup;
case LY_TYPE_BINARY:
if (type->info.binary.length) {
break;
}
goto cleanup;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
if (type->info.num.range) {
break;
}
goto cleanup;
case LY_TYPE_STRING:
if (type->info.str.length || type->info.str.patterns) {
break;
}
goto cleanup;
case LY_TYPE_UNION:
/* way too much trouble learning whether we need to check the default again, so just do it */
break;
default:
LOGINT(ctx);
ret = -1;
goto cleanup;
}
} else if (type->base == LY_TYPE_EMPTY) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "default", type->parent->name);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The \"empty\" data type cannot have a default value.");
ret = -1;
goto cleanup;
}
/* dummy leaf */
memset(&node, 0, sizeof node);
node.value_str = lydict_insert(ctx, dflt, 0);
node.value_type = type->base;
if (tpdf) {
node.schema = calloc(1, sizeof (struct lys_node_leaf));
if (!node.schema) {
LOGMEM(ctx);
ret = -1;
goto cleanup;
}
r = asprintf((char **)&node.schema->name, "typedef-%s-default", ((struct lys_tpdf *)type->parent)->name);
if (r == -1) {
LOGMEM(ctx);
ret = -1;
goto cleanup;
}
node.schema->module = module;
memcpy(&((struct lys_node_leaf *)node.schema)->type, type, sizeof *type);
} else {
node.schema = (struct lys_node *)type->parent;
}
if (type->base == LY_TYPE_LEAFREF) {
if (!type->info.lref.target) {
ret = EXIT_FAILURE;
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Default value \"%s\" cannot be checked in an unresolved leafref.",
dflt);
goto cleanup;
}
ret = check_default(&type->info.lref.target->type, &dflt, module, 0);
if (!ret) {
/* adopt possibly changed default value to its canonical form */
if (*value) {
lydict_remove(ctx, *value);
*value = dflt;
dflt = NULL;
}
}
} else {
if (!lyp_parse_value(type, &node.value_str, NULL, &node, NULL, module, 1, 1, 0)) {
/* possible forward reference */
ret = EXIT_FAILURE;
if (base_tpdf) {
/* default value is defined in some base typedef */
if ((type->base == LY_TYPE_BITS && type->der->type.der) ||
(type->base == LY_TYPE_ENUM && type->der->type.der)) {
/* we have refined bits/enums */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"Invalid value \"%s\" of the default statement inherited to \"%s\" from \"%s\" base type.",
dflt, type->parent->name, base_tpdf->name);
}
}
} else {
/* success - adopt canonical form from the node into the default value */
if (!ly_strequal(dflt, node.value_str, 1)) {
/* this can happen only if we have non-inherited default value,
* inherited default values are already in canonical form */
assert(ly_strequal(dflt, *value, 1));
lydict_remove(ctx, *value);
*value = node.value_str;
node.value_str = NULL;
}
}
}
cleanup:
lyd_free_value(node.value, node.value_type, node.value_flags, type, NULL, NULL, NULL);
lydict_remove(ctx, node.value_str);
if (tpdf && node.schema) {
free((char *)node.schema->name);
free(node.schema);
}
lydict_remove(ctx, dflt);
return ret;
}
/**
* @brief Check a key for mandatory attributes. Logs directly.
*
* @param[in] key The key to check.
* @param[in] flags What flags to check.
* @param[in] list The list of all the keys.
* @param[in] index Index of the key in the key list.
* @param[in] name The name of the keys.
* @param[in] len The name length.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
static int
check_key(struct lys_node_list *list, int index, const char *name, int len)
{
struct lys_node_leaf *key = list->keys[index];
char *dup = NULL;
int j;
struct ly_ctx *ctx = list->module->ctx;
/* existence */
if (!key) {
if (name[len] != '\0') {
dup = strdup(name);
LY_CHECK_ERR_RETURN(!dup, LOGMEM(ctx), -1);
dup[len] = '\0';
name = dup;
}
LOGVAL(ctx, LYE_KEY_MISS, LY_VLOG_LYS, list, name);
free(dup);
return -1;
}
/* uniqueness */
for (j = index - 1; j >= 0; j--) {
if (key == list->keys[j]) {
LOGVAL(ctx, LYE_KEY_DUP, LY_VLOG_LYS, list, key->name);
return -1;
}
}
/* key is a leaf */
if (key->nodetype != LYS_LEAF) {
LOGVAL(ctx, LYE_KEY_NLEAF, LY_VLOG_LYS, list, key->name);
return -1;
}
/* type of the leaf is not built-in empty */
if (key->type.base == LY_TYPE_EMPTY && key->module->version < LYS_VERSION_1_1) {
LOGVAL(ctx, LYE_KEY_TYPE, LY_VLOG_LYS, list, key->name);
return -1;
}
/* config attribute is the same as of the list */
if ((key->flags & LYS_CONFIG_MASK) && (list->flags & LYS_CONFIG_MASK)
&& ((list->flags & LYS_CONFIG_MASK) != (key->flags & LYS_CONFIG_MASK))) {
LOGVAL(ctx, LYE_KEY_CONFIG, LY_VLOG_LYS, list, key->name);
return -1;
}
/* key is not placed from augment */
if (key->parent->nodetype == LYS_AUGMENT) {
LOGVAL(ctx, LYE_KEY_MISS, LY_VLOG_LYS, key, key->name);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Key inserted from augment.");
return -1;
}
/* key is not when/if-feature -conditional */
j = 0;
if (key->when || (key->iffeature_size && (j = 1))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, key, j ? "if-feature" : "when", "leaf");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Key definition cannot depend on a \"%s\" condition.",
j ? "if-feature" : "when");
return -1;
}
return EXIT_SUCCESS;
}
/**
* @brief Resolve (test the target exists) unique. Logs directly.
*
* @param[in] parent The parent node of the unique structure.
* @param[in] uniq_str_path One path from the unique string.
*
* @return EXIT_SUCCESS on succes, EXIT_FAILURE on forward reference, -1 on error.
*/
int
resolve_unique(struct lys_node *parent, const char *uniq_str_path, uint8_t *trg_type)
{
int rc;
const struct lys_node *leaf = NULL;
struct ly_ctx *ctx = parent->module->ctx;
rc = resolve_descendant_schema_nodeid(uniq_str_path, *lys_child(parent, LYS_LEAF), LYS_LEAF, 1, &leaf);
if (rc || !leaf) {
if (rc) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique");
if (rc > 0) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_PREV, NULL, uniq_str_path[rc - 1], &uniq_str_path[rc - 1]);
} else if (rc == -2) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Unique argument references list.");
}
rc = -1;
} else {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Target leaf not found.");
rc = EXIT_FAILURE;
}
goto error;
}
if (leaf->nodetype != LYS_LEAF) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Target is not a leaf.");
return -1;
}
/* check status */
if (parent->nodetype != LYS_EXT && lyp_check_status(parent->flags, parent->module, parent->name,
leaf->flags, leaf->module, leaf->name, leaf)) {
return -1;
}
/* check that all unique's targets are of the same config type */
if (*trg_type) {
if (((*trg_type == 1) && (leaf->flags & LYS_CONFIG_R)) || ((*trg_type == 2) && (leaf->flags & LYS_CONFIG_W))) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"Leaf \"%s\" referenced in unique statement is config %s, but previous referenced leaf is config %s.",
uniq_str_path, *trg_type == 1 ? "false" : "true", *trg_type == 1 ? "true" : "false");
return -1;
}
} else {
/* first unique */
if (leaf->flags & LYS_CONFIG_W) {
*trg_type = 1;
} else {
*trg_type = 2;
}
}
/* set leaf's unique flag */
((struct lys_node_leaf *)leaf)->flags |= LYS_UNIQUE;
return EXIT_SUCCESS;
error:
return rc;
}
void
unres_data_del(struct unres_data *unres, uint32_t i)
{
/* there are items after the one deleted */
if (i+1 < unres->count) {
/* we only move the data, memory is left allocated, why bother */
memmove(&unres->node[i], &unres->node[i+1], (unres->count-(i+1)) * sizeof *unres->node);
/* deleting the last item */
} else if (i == 0) {
free(unres->node);
unres->node = NULL;
}
/* if there are no items after and it is not the last one, just move the counter */
--unres->count;
}
/**
* @brief Resolve (find) a data node from a specific module. Does not log.
*
* @param[in] mod Module to search in.
* @param[in] name Name of the data node.
* @param[in] nam_len Length of the name.
* @param[in] start Data node to start the search from.
* @param[in,out] parents Resolved nodes. If there are some parents,
* they are replaced (!!) with the resolvents.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_data(const struct lys_module *mod, const char *name, int nam_len, struct lyd_node *start, struct unres_data *parents)
{
struct lyd_node *node;
int flag;
uint32_t i;
if (!parents->count) {
parents->count = 1;
parents->node = malloc(sizeof *parents->node);
LY_CHECK_ERR_RETURN(!parents->node, LOGMEM(mod->ctx), -1);
parents->node[0] = NULL;
}
for (i = 0; i < parents->count;) {
if (parents->node[i] && (parents->node[i]->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
/* skip */
++i;
continue;
}
flag = 0;
LY_TREE_FOR(parents->node[i] ? parents->node[i]->child : start, node) {
if (lyd_node_module(node) == mod && !strncmp(node->schema->name, name, nam_len)
&& node->schema->name[nam_len] == '\0') {
/* matching target */
if (!flag) {
/* put node instead of the current parent */
parents->node[i] = node;
flag = 1;
} else {
/* multiple matching, so create a new node */
++parents->count;
parents->node = ly_realloc(parents->node, parents->count * sizeof *parents->node);
LY_CHECK_ERR_RETURN(!parents->node, LOGMEM(mod->ctx), EXIT_FAILURE);
parents->node[parents->count-1] = node;
++i;
}
}
}
if (!flag) {
/* remove item from the parents list */
unres_data_del(parents, i);
} else {
++i;
}
}
return parents->count ? EXIT_SUCCESS : EXIT_FAILURE;
}
static int
resolve_schema_leafref_valid_dep_flag(const struct lys_node *op_node, const struct lys_module *local_mod,
const struct lys_node *first_node, int abs_path)
{
int dep1, dep2;
const struct lys_node *node;
if (!op_node) {
/* leafref pointing to a different module */
if (local_mod != lys_node_module(first_node)) {
return 1;
}
} else if (lys_parent(op_node)) {
/* inner operation (notif/action) */
if (abs_path) {
return 1;
} else {
/* compare depth of both nodes */
for (dep1 = 0, node = op_node; lys_parent(node); node = lys_parent(node));
for (dep2 = 0, node = first_node; lys_parent(node); node = lys_parent(node));
if ((dep2 > dep1) || ((dep2 == dep1) && (op_node != first_node))) {
return 1;
}
}
} else {
/* top-level operation (notif/rpc) */
if (op_node != first_node) {
return 1;
}
}
return 0;
}
/**
* @brief Resolve a path (leafref) predicate in JSON schema context. Logs directly.
*
* @param[in] path Path to use.
* @param[in] context_node Predicate context node (where the predicate is placed).
* @param[in] parent Path context node (where the path begins/is placed).
* @param[in] op_node Optional node if the leafref is in an operation (action/rpc/notif).
*
* @return 0 on forward reference, otherwise the number
* of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
resolve_schema_leafref_predicate(const char *path, const struct lys_node *context_node, struct lys_node *parent)
{
const struct lys_module *trg_mod;
const struct lys_node *src_node, *dst_node;
const char *path_key_expr, *source, *sour_pref, *dest, *dest_pref;
int pke_len, sour_len, sour_pref_len, dest_len, dest_pref_len, pke_parsed, parsed = 0;
int has_predicate, dest_parent_times, i, rc;
struct ly_ctx *ctx = context_node->module->ctx;
do {
if ((i = parse_path_predicate(path, &sour_pref, &sour_pref_len, &source, &sour_len, &path_key_expr,
&pke_len, &has_predicate)) < 1) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, path[-i], path-i);
return -parsed+i;
}
parsed += i;
path += i;
/* source (must be leaf) */
if (sour_pref) {
trg_mod = lyp_get_module(lys_node_module(parent), NULL, 0, sour_pref, sour_pref_len, 0);
} else {
trg_mod = lys_node_module(parent);
}
rc = lys_getnext_data(trg_mod, context_node, source, sour_len, LYS_LEAF | LYS_LEAFLIST, LYS_GETNEXT_NOSTATECHECK,
&src_node);
if (rc) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path-parsed);
return 0;
}
/* destination */
dest_parent_times = 0;
pke_parsed = 0;
if ((i = parse_path_key_expr(path_key_expr, &dest_pref, &dest_pref_len, &dest, &dest_len,
&dest_parent_times)) < 1) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, path_key_expr[-i], path_key_expr-i);
return -parsed;
}
pke_parsed += i;
for (i = 0, dst_node = parent; i < dest_parent_times; ++i) {
if (!dst_node) {
/* we went too much into parents, there is no parent anymore */
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path_key_expr);
return 0;
}
if (dst_node->parent && (dst_node->parent->nodetype == LYS_AUGMENT)
&& !((struct lys_node_augment *)dst_node->parent)->target) {
/* we are in an unresolved augment, cannot evaluate */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, dst_node->parent,
"Cannot resolve leafref predicate \"%s\" because it is in an unresolved augment.", path_key_expr);
return 0;
}
/* path is supposed to be evaluated in data tree, so we have to skip
* all schema nodes that cannot be instantiated in data tree */
for (dst_node = lys_parent(dst_node);
dst_node && !(dst_node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_ACTION | LYS_NOTIF | LYS_RPC));
dst_node = lys_parent(dst_node));
}
while (1) {
if (dest_pref) {
trg_mod = lyp_get_module(lys_node_module(parent), NULL, 0, dest_pref, dest_pref_len, 0);
} else {
trg_mod = lys_node_module(parent);
}
rc = lys_getnext_data(trg_mod, dst_node, dest, dest_len, LYS_CONTAINER | LYS_LIST | LYS_LEAF,
LYS_GETNEXT_NOSTATECHECK, &dst_node);
if (rc) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path_key_expr);
return 0;
}
if (pke_len == pke_parsed) {
break;
}
if ((i = parse_path_key_expr(path_key_expr + pke_parsed, &dest_pref, &dest_pref_len, &dest, &dest_len,
&dest_parent_times)) < 1) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent,
(path_key_expr + pke_parsed)[-i], (path_key_expr + pke_parsed)-i);
return -parsed;
}
pke_parsed += i;
}
/* check source - dest match */
if (dst_node->nodetype != src_node->nodetype) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path - parsed);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Destination node is not a %s, but a %s.",
strnodetype(src_node->nodetype), strnodetype(dst_node->nodetype));
return -parsed;
}
} while (has_predicate);
return parsed;
}
static int
check_leafref_features(struct lys_type *type)
{
struct lys_node *iter;
struct ly_set *src_parents, *trg_parents, *features;
struct lys_node_augment *aug;
struct ly_ctx *ctx = ((struct lys_tpdf *)type->parent)->module->ctx;
unsigned int i, j, size, x;
int ret = EXIT_SUCCESS;
assert(type->parent);
src_parents = ly_set_new();
trg_parents = ly_set_new();
features = ly_set_new();
/* get parents chain of source (leafref) */
for (iter = (struct lys_node *)type->parent; iter; iter = lys_parent(iter)) {
if (iter->nodetype & (LYS_INPUT | LYS_OUTPUT)) {
continue;
}
if (iter->parent && (iter->parent->nodetype == LYS_AUGMENT)) {
aug = (struct lys_node_augment *)iter->parent;
if ((aug->module->implemented && (aug->flags & LYS_NOTAPPLIED)) || !aug->target) {
/* unresolved augment, wait until it's resolved */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, aug,
"Cannot check leafref \"%s\" if-feature consistency because of an unresolved augment.", type->info.lref.path);
ret = EXIT_FAILURE;
goto cleanup;
}
/* also add this augment */
ly_set_add(src_parents, aug, LY_SET_OPT_USEASLIST);
}
ly_set_add(src_parents, iter, LY_SET_OPT_USEASLIST);
}
/* get parents chain of target */
for (iter = (struct lys_node *)type->info.lref.target; iter; iter = lys_parent(iter)) {
if (iter->nodetype & (LYS_INPUT | LYS_OUTPUT)) {
continue;
}
if (iter->parent && (iter->parent->nodetype == LYS_AUGMENT)) {
aug = (struct lys_node_augment *)iter->parent;
if ((aug->module->implemented && (aug->flags & LYS_NOTAPPLIED)) || !aug->target) {
/* unresolved augment, wait until it's resolved */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, aug,
"Cannot check leafref \"%s\" if-feature consistency because of an unresolved augment.", type->info.lref.path);
ret = EXIT_FAILURE;
goto cleanup;
}
}
ly_set_add(trg_parents, iter, LY_SET_OPT_USEASLIST);
}
/* compare the features used in if-feature statements in the rest of both
* chains of parents. The set of features used for target must be a subset
* of features used for the leafref. This is not a perfect, we should compare
* the truth tables but it could require too much resources, so we simplify that */
for (i = 0; i < src_parents->number; i++) {
iter = src_parents->set.s[i]; /* shortcut */
if (!iter->iffeature_size) {
continue;
}
for (j = 0; j < iter->iffeature_size; j++) {
resolve_iffeature_getsizes(&iter->iffeature[j], NULL, &size);
for (; size; size--) {
if (!iter->iffeature[j].features[size - 1]) {
/* not yet resolved feature, postpone this check */
ret = EXIT_FAILURE;
goto cleanup;
}
ly_set_add(features, iter->iffeature[j].features[size - 1], 0);
}
}
}
x = features->number;
for (i = 0; i < trg_parents->number; i++) {
iter = trg_parents->set.s[i]; /* shortcut */
if (!iter->iffeature_size) {
continue;
}
for (j = 0; j < iter->iffeature_size; j++) {
resolve_iffeature_getsizes(&iter->iffeature[j], NULL, &size);
for (; size; size--) {
if (!iter->iffeature[j].features[size - 1]) {
/* not yet resolved feature, postpone this check */
ret = EXIT_FAILURE;
goto cleanup;
}
if ((unsigned)ly_set_add(features, iter->iffeature[j].features[size - 1], 0) >= x) {
/* the feature is not present in features set of target's parents chain */
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, type->parent, "leafref", type->info.lref.path);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"Leafref is not conditional based on \"%s\" feature as its target.",
iter->iffeature[j].features[size - 1]->name);
ret = -1;
goto cleanup;
}
}
}
}
cleanup:
ly_set_free(features);
ly_set_free(src_parents);
ly_set_free(trg_parents);
return ret;
}
/**
* @brief Resolve a path (leafref) in JSON schema context. Logs directly.
*
* @param[in] path Path to use.
* @param[in] parent_node Parent of the leafref.
* @param[out] ret Pointer to the resolved schema node. Can be NULL.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_schema_leafref(struct lys_type *type, struct lys_node *parent, struct unres_schema *unres)
{
const struct lys_node *node, *op_node = NULL, *tmp_parent;
struct lys_node_augment *last_aug;
const struct lys_module *tmp_mod, *cur_module;
const char *id, *prefix, *name;
int pref_len, nam_len, parent_times, has_predicate;
int i, first_iter;
struct ly_ctx *ctx = parent->module->ctx;
if (!type->info.lref.target) {
first_iter = 1;
parent_times = 0;
id = type->info.lref.path;
/* find operation schema we are in */
for (op_node = lys_parent(parent);
op_node && !(op_node->nodetype & (LYS_ACTION | LYS_NOTIF | LYS_RPC));
op_node = lys_parent(op_node));
cur_module = lys_node_module(parent);
do {
if ((i = parse_path_arg(cur_module, id, &prefix, &pref_len, &name, &nam_len, &parent_times, &has_predicate)) < 1) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, id[-i], &id[-i]);
return -1;
}
id += i;
/* get the current module */
tmp_mod = prefix ? lyp_get_module(cur_module, NULL, 0, prefix, pref_len, 0) : cur_module;
if (!tmp_mod) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path);
return EXIT_FAILURE;
}
last_aug = NULL;
if (first_iter) {
if (parent_times == -1) {
/* use module data */
node = NULL;
} else if (parent_times > 0) {
/* we are looking for the right parent */
for (i = 0, node = parent; i < parent_times; i++) {
if (node->parent && (node->parent->nodetype == LYS_AUGMENT)
&& !((struct lys_node_augment *)node->parent)->target) {
/* we are in an unresolved augment, cannot evaluate */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, node->parent,
"Cannot resolve leafref \"%s\" because it is in an unresolved augment.", type->info.lref.path);
return EXIT_FAILURE;
}
/* path is supposed to be evaluated in data tree, so we have to skip
* all schema nodes that cannot be instantiated in data tree */
for (node = lys_parent(node);
node && !(node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_ACTION | LYS_NOTIF | LYS_RPC));
node = lys_parent(node));
if (!node) {
if (i == parent_times - 1) {
/* top-level */
break;
}
/* higher than top-level */
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path);
return EXIT_FAILURE;
}
}
} else {
LOGINT(ctx);
return -1;
}
}
/* find the next node (either in unconnected augment or as a schema sibling, node is NULL for top-level node -
* - useless to search for that in augments) */
if (!tmp_mod->implemented && node) {
get_next_augment:
last_aug = lys_getnext_target_aug(last_aug, tmp_mod, node);
}
tmp_parent = (last_aug ? (struct lys_node *)last_aug : node);
node = NULL;
while ((node = lys_getnext(node, tmp_parent, tmp_mod, LYS_GETNEXT_NOSTATECHECK))) {
if (lys_node_module(node) != lys_main_module(tmp_mod)) {
continue;
}
if (strncmp(node->name, name, nam_len) || node->name[nam_len]) {
continue;
}
/* match */
break;
}
if (!node) {
if (last_aug) {
/* restore the correct augment target */
node = last_aug->target;
goto get_next_augment;
}
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path);
return EXIT_FAILURE;
}
if (first_iter) {
/* set external dependency flag, we can decide based on the first found node */
if (resolve_schema_leafref_valid_dep_flag(op_node, cur_module, node, (parent_times == -1 ? 1 : 0))) {
parent->flags |= LYS_LEAFREF_DEP;
}
first_iter = 0;
}
if (has_predicate) {
/* we have predicate, so the current result must be list */
if (node->nodetype != LYS_LIST) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path);
return -1;
}
i = resolve_schema_leafref_predicate(id, node, parent);
if (!i) {
return EXIT_FAILURE;
} else if (i < 0) {
return -1;
}
id += i;
has_predicate = 0;
}
} while (id[0]);
/* the target must be leaf or leaf-list (in YANG 1.1 only) */
if ((node->nodetype != LYS_LEAF) && (node->nodetype != LYS_LEAFLIST)) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Leafref target \"%s\" is not a leaf nor a leaf-list.", type->info.lref.path);
return -1;
}
/* check status */
if (lyp_check_status(parent->flags, parent->module, parent->name,
node->flags, node->module, node->name, node)) {
return -1;
}
/* assign */
type->info.lref.target = (struct lys_node_leaf *)node;
}
/* as the last thing traverse this leafref and make targets on the path implemented */
if (lys_node_module(parent)->implemented) {
/* make all the modules in the path implemented */
for (node = (struct lys_node *)type->info.lref.target; node; node = lys_parent(node)) {
if (!lys_node_module(node)->implemented) {
lys_node_module(node)->implemented = 1;
if (unres_schema_add_node(lys_node_module(node), unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) {
return -1;
}
}
}
/* store the backlink from leafref target */
if (lys_leaf_add_leafref_target(type->info.lref.target, (struct lys_node *)type->parent)) {
return -1;
}
}
/* check if leafref and its target are under common if-features */
return check_leafref_features(type);
}
/**
* @brief Compare 2 data node values.
*
* Comparison performed on canonical forms, the first value
* is first transformed into canonical form.
*
* @param[in] node Leaf/leaf-list with these values.
* @param[in] noncan_val Non-canonical value.
* @param[in] noncan_val_len Length of \p noncal_val.
* @param[in] can_val Canonical value.
* @return 1 if equal, 0 if not, -1 on error (logged).
*/
static int
valequal(struct lys_node *node, const char *noncan_val, int noncan_val_len, const char *can_val)
{
int ret;
struct lyd_node_leaf_list leaf;
struct lys_node_leaf *sleaf = (struct lys_node_leaf*)node;
/* dummy leaf */
memset(&leaf, 0, sizeof leaf);
leaf.value_str = lydict_insert(node->module->ctx, noncan_val, noncan_val_len);
repeat:
leaf.value_type = sleaf->type.base;
leaf.schema = node;
if (leaf.value_type == LY_TYPE_LEAFREF) {
if (!sleaf->type.info.lref.target) {
/* it should either be unresolved leafref (leaf.value_type are ORed flags) or it will be resolved */
LOGINT(node->module->ctx);
ret = -1;
goto finish;
}
sleaf = sleaf->type.info.lref.target;
goto repeat;
} else {
if (!lyp_parse_value(&sleaf->type, &leaf.value_str, NULL, &leaf, NULL, NULL, 0, 0, 0)) {
ret = -1;
goto finish;
}
}
if (!strcmp(leaf.value_str, can_val)) {
ret = 1;
} else {
ret = 0;
}
finish:
lydict_remove(node->module->ctx, leaf.value_str);
return ret;
}
/**
* @brief Resolve instance-identifier predicate in JSON data format.
* Does not log.
*
* @param[in] prev_mod Previous module to use in case there is no prefix.
* @param[in] pred Predicate to use.
* @param[in,out] node Node matching the restriction without
* the predicate. If it does not satisfy the predicate,
* it is set to NULL.
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
resolve_instid_predicate(const struct lys_module *prev_mod, const char *pred, struct lyd_node **node, int cur_idx)
{
/* ... /node[key=value] ... */
struct lyd_node_leaf_list *key;
struct lys_node_leaf **list_keys = NULL;
struct lys_node_list *slist = NULL;
const char *model, *name, *value;
int mod_len, nam_len, val_len, i, has_predicate, parsed;
struct ly_ctx *ctx = prev_mod->ctx;
assert(pred && node && *node);
parsed = 0;
do {
if ((i = parse_predicate(pred + parsed, &model, &mod_len, &name, &nam_len, &value, &val_len, &has_predicate)) < 1) {
return -parsed + i;
}
parsed += i;
if (!(*node)) {
/* just parse it all */
continue;
}
/* target */
if (name[0] == '.') {
/* leaf-list value */
if ((*node)->schema->nodetype != LYS_LEAFLIST) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects leaf-list, but have %s \"%s\".",
strnodetype((*node)->schema->nodetype), (*node)->schema->name);
parsed = -1;
goto cleanup;
}
/* check the value */
if (!valequal((*node)->schema, value, val_len, ((struct lyd_node_leaf_list *)*node)->value_str)) {
*node = NULL;
goto cleanup;
}
} else if (isdigit(name[0])) {
assert(!value);
/* keyless list position */
if ((*node)->schema->nodetype != LYS_LIST) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list, but have %s \"%s\".",
strnodetype((*node)->schema->nodetype), (*node)->schema->name);
parsed = -1;
goto cleanup;
}
if (((struct lys_node_list *)(*node)->schema)->keys) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list without keys, but have list \"%s\".",
(*node)->schema->name);
parsed = -1;
goto cleanup;
}
/* check the index */
if (atoi(name) != cur_idx) {
*node = NULL;
goto cleanup;
}
} else {
/* list key value */
if ((*node)->schema->nodetype != LYS_LIST) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list, but have %s \"%s\".",
strnodetype((*node)->schema->nodetype), (*node)->schema->name);
parsed = -1;
goto cleanup;
}
slist = (struct lys_node_list *)(*node)->schema;
/* prepare key array */
if (!list_keys) {
list_keys = malloc(slist->keys_size * sizeof *list_keys);
LY_CHECK_ERR_RETURN(!list_keys, LOGMEM(ctx), -1);
for (i = 0; i < slist->keys_size; ++i) {
list_keys[i] = slist->keys[i];
}
}
/* find the schema key leaf */
for (i = 0; i < slist->keys_size; ++i) {
if (list_keys[i] && !strncmp(list_keys[i]->name, name, nam_len) && !list_keys[i]->name[nam_len]) {
break;
}
}
if (i == slist->keys_size) {
/* this list has no such key */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list with the key \"%.*s\","
" but list \"%s\" does not define it.", nam_len, name, slist->name);
parsed = -1;
goto cleanup;
}
/* check module */
if (model) {
if (strncmp(list_keys[i]->module->name, model, mod_len) || list_keys[i]->module->name[mod_len]) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects key \"%s\" from module \"%.*s\", not \"%s\".",
list_keys[i]->name, model, mod_len, list_keys[i]->module->name);
parsed = -1;
goto cleanup;
}
} else {
if (list_keys[i]->module != prev_mod) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects key \"%s\" from module \"%s\", not \"%s\".",
list_keys[i]->name, prev_mod->name, list_keys[i]->module->name);
parsed = -1;
goto cleanup;
}
}
/* find the actual data key */
for (key = (struct lyd_node_leaf_list *)(*node)->child; key; key = (struct lyd_node_leaf_list *)key->next) {
if (key->schema == (struct lys_node *)list_keys[i]) {
break;
}
}
if (!key) {
/* list instance is missing a key? definitely should not happen */
LOGINT(ctx);
parsed = -1;
goto cleanup;
}
/* check the value */
if (!valequal(key->schema, value, val_len, key->value_str)) {
*node = NULL;
/* we still want to parse the whole predicate */
continue;
}
/* everything is fine, mark this key as resolved */
list_keys[i] = NULL;
}
} while (has_predicate);
/* check that all list keys were specified */
if (*node && list_keys) {
for (i = 0; i < slist->keys_size; ++i) {
if (list_keys[i]) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier is missing list key \"%s\".", list_keys[i]->name);
parsed = -1;
goto cleanup;
}
}
}
cleanup:
free(list_keys);
return parsed;
}
static int
check_xpath(struct lys_node *node, int check_place)
{
struct lys_node *parent;
struct lyxp_set set;
enum int_log_opts prev_ilo;
if (check_place) {
parent = node;
while (parent) {
if (parent->nodetype == LYS_GROUPING) {
/* unresolved grouping, skip for now (will be checked later) */
return EXIT_SUCCESS;
}
if (parent->nodetype == LYS_AUGMENT) {
if (!((struct lys_node_augment *)parent)->target) {
/* unresolved augment, skip for now (will be checked later) */
return EXIT_FAILURE;
} else {
parent = ((struct lys_node_augment *)parent)->target;
continue;
}
}
parent = parent->parent;
}
}
memset(&set, 0, sizeof set);
/* produce just warnings */
ly_ilo_change(NULL, ILO_ERR2WRN, &prev_ilo, NULL);
lyxp_node_atomize(node, &set, 1);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (set.val.snodes) {
free(set.val.snodes);
}
return EXIT_SUCCESS;
}
static int
check_leafref_config(struct lys_node_leaf *leaf, struct lys_type *type)
{
unsigned int i;
if (type->base == LY_TYPE_LEAFREF) {
if ((leaf->flags & LYS_CONFIG_W) && type->info.lref.target && type->info.lref.req != -1 &&
(type->info.lref.target->flags & LYS_CONFIG_R)) {
LOGVAL(leaf->module->ctx, LYE_SPEC, LY_VLOG_LYS, leaf, "The leafref %s is config but refers to a non-config %s.",
strnodetype(leaf->nodetype), strnodetype(type->info.lref.target->nodetype));
return -1;
}
/* we can skip the test in case the leafref is not yet resolved. In that case the test is done in the time
* of leafref resolving (lys_leaf_add_leafref_target()) */
} else if (type->base == LY_TYPE_UNION) {
for (i = 0; i < type->info.uni.count; i++) {
if (check_leafref_config(leaf, &type->info.uni.types[i])) {
return -1;
}
}
}
return 0;
}
/**
* @brief Passes config flag down to children, skips nodes without config flags.
* Logs.
*
* @param[in] node Siblings and their children to have flags changed.
* @param[in] clear Flag to clear all config flags if parent is LYS_NOTIF, LYS_INPUT, LYS_OUTPUT, LYS_RPC.
* @param[in] flags Flags to assign to all the nodes.
* @param[in,out] unres List of unresolved items.
*
* @return 0 on success, -1 on error.
*/
int
inherit_config_flag(struct lys_node *node, int flags, int clear)
{
struct lys_node_leaf *leaf;
struct ly_ctx *ctx;
if (!node) {
return 0;
}
assert(!(flags ^ (flags & LYS_CONFIG_MASK)));
ctx = node->module->ctx;
LY_TREE_FOR(node, node) {
if (clear) {
node->flags &= ~LYS_CONFIG_MASK;
node->flags &= ~LYS_CONFIG_SET;
} else {
if (node->flags & LYS_CONFIG_SET) {
/* skip nodes with an explicit config value */
if ((flags & LYS_CONFIG_R) && (node->flags & LYS_CONFIG_W)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, node, "true", "config");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "State nodes cannot have configuration nodes as children.");
return -1;
}
continue;
}
if (!(node->nodetype & (LYS_USES | LYS_GROUPING))) {
node->flags = (node->flags & ~LYS_CONFIG_MASK) | flags;
/* check that configuration lists have keys */
if ((node->nodetype == LYS_LIST) && (node->flags & LYS_CONFIG_W)
&& !((struct lys_node_list *)node)->keys_size) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, node, "key", "list");
return -1;
}
}
}
if (!(node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
if (inherit_config_flag(node->child, flags, clear)) {
return -1;
}
} else if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST)) {
leaf = (struct lys_node_leaf *)node;
if (check_leafref_config(leaf, &leaf->type)) {
return -1;
}
}
}
return 0;
}
/**
* @brief Resolve augment target. Logs directly.
*
* @param[in] aug Augment to use.
* @param[in] uses Parent where to start the search in. If set, uses augment, if not, standalone augment.
* @param[in,out] unres List of unresolved items.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_augment(struct lys_node_augment *aug, struct lys_node *uses, struct unres_schema *unres)
{
int rc;
struct lys_node *sub;
struct lys_module *mod;
struct ly_set *set;
struct ly_ctx *ctx;
assert(aug);
mod = lys_main_module(aug->module);
ctx = mod->ctx;
/* set it as not applied for now */
aug->flags |= LYS_NOTAPPLIED;
/* it can already be resolved in case we returned EXIT_FAILURE from if block below */
if (!aug->target) {
/* resolve target node */
rc = resolve_schema_nodeid(aug->target_name, uses, (uses ? NULL : lys_node_module((struct lys_node *)aug)), &set, 0, 0);
if (rc == -1) {
LOGVAL(ctx, LYE_PATH, LY_VLOG_LYS, aug);
return -1;
}
if (!set) {
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, aug, "augment", aug->target_name);
return EXIT_FAILURE;
}
aug->target = set->set.s[0];
ly_set_free(set);
}
/* make this module implemented if the target module is (if the target is in an unimplemented module,
* it is fine because when we will be making that module implemented, its augment will be applied
* and that augment target module made implemented, recursively) */
if (mod->implemented && !lys_node_module(aug->target)->implemented) {
lys_node_module(aug->target)->implemented = 1;
if (unres_schema_add_node(lys_node_module(aug->target), unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) {
return -1;
}
}
/* check for mandatory nodes - if the target node is in another module
* the added nodes cannot be mandatory
*/
if (!aug->parent && (lys_node_module((struct lys_node *)aug) != lys_node_module(aug->target))
&& (rc = lyp_check_mandatory_augment(aug, aug->target))) {
return rc;
}
/* check augment target type and then augment nodes type */
if (aug->target->nodetype & (LYS_CONTAINER | LYS_LIST)) {
LY_TREE_FOR(aug->child, sub) {
if (!(sub->nodetype & (LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_USES
| LYS_CHOICE | LYS_ACTION | LYS_NOTIF))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".",
strnodetype(aug->target->nodetype), strnodetype(sub->nodetype));
return -1;
}
}
} else if (aug->target->nodetype & (LYS_CASE | LYS_INPUT | LYS_OUTPUT | LYS_NOTIF)) {
LY_TREE_FOR(aug->child, sub) {
if (!(sub->nodetype & (LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_USES | LYS_CHOICE))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".",
strnodetype(aug->target->nodetype), strnodetype(sub->nodetype));
return -1;
}
}
} else if (aug->target->nodetype == LYS_CHOICE) {
LY_TREE_FOR(aug->child, sub) {
if (!(sub->nodetype & (LYS_CASE | LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".",
strnodetype(aug->target->nodetype), strnodetype(sub->nodetype));
return -1;
}
}
} else {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, aug, aug->target_name, "target-node");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Invalid augment target node type \"%s\".", strnodetype(aug->target->nodetype));
return -1;
}
/* check identifier uniqueness as in lys_node_addchild() */
LY_TREE_FOR(aug->child, sub) {
if (lys_check_id(sub, aug->target, NULL)) {
return -1;
}
}
if (!aug->child) {
/* empty augment, nothing to connect, but it is techincally applied */
LOGWRN(ctx, "Augment \"%s\" without children.", aug->target_name);
aug->flags &= ~LYS_NOTAPPLIED;
} else if ((aug->parent || mod->implemented) && apply_aug(aug, unres)) {
/* we try to connect the augment only in case the module is implemented or
* the augment applies on the used grouping, anyway we failed here */
return -1;
}
return EXIT_SUCCESS;
}
static int
resolve_extension(struct unres_ext *info, struct lys_ext_instance **ext, struct unres_schema *unres)
{
enum LY_VLOG_ELEM vlog_type;
void *vlog_node;
unsigned int i, j;
struct lys_ext *e;
char *ext_name, *ext_prefix, *tmp;
struct lyxml_elem *next_yin, *yin;
const struct lys_module *mod;
struct lys_ext_instance *tmp_ext;
struct ly_ctx *ctx = NULL;
LYEXT_TYPE etype;
switch (info->parent_type) {
case LYEXT_PAR_NODE:
vlog_node = info->parent;
vlog_type = LY_VLOG_LYS;
break;
case LYEXT_PAR_MODULE:
case LYEXT_PAR_IMPORT:
case LYEXT_PAR_INCLUDE:
vlog_node = NULL;
vlog_type = LY_VLOG_LYS;
break;
default:
vlog_node = NULL;
vlog_type = LY_VLOG_NONE;
break;
}
if (info->datatype == LYS_IN_YIN) {
/* YIN */
/* get the module where the extension is supposed to be defined */
mod = lyp_get_import_module_ns(info->mod, info->data.yin->ns->value);
if (!mod) {
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, info->data.yin->name);
return EXIT_FAILURE;
}
ctx = mod->ctx;
/* find the extension definition */
e = NULL;
for (i = 0; i < mod->extensions_size; i++) {
if (ly_strequal(mod->extensions[i].name, info->data.yin->name, 1)) {
e = &mod->extensions[i];
break;
}
}
/* try submodules */
for (j = 0; !e && j < mod->inc_size; j++) {
for (i = 0; i < mod->inc[j].submodule->extensions_size; i++) {
if (ly_strequal(mod->inc[j].submodule->extensions[i].name, info->data.yin->name, 1)) {
e = &mod->inc[j].submodule->extensions[i];
break;
}
}
}
if (!e) {
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, info->data.yin->name);
return EXIT_FAILURE;
}
/* we have the extension definition, so now it cannot be forward referenced and error is always fatal */
if (e->plugin && e->plugin->check_position) {
/* common part - we have plugin with position checking function, use it first */
if ((*e->plugin->check_position)(info->parent, info->parent_type, info->substmt)) {
/* extension is not allowed here */
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, e->name);
return -1;
}
}
/* extension type-specific part - allocation */
if (e->plugin) {
etype = e->plugin->type;
} else {
/* default type */
etype = LYEXT_FLAG;
}
switch (etype) {
case LYEXT_FLAG:
(*ext) = calloc(1, sizeof(struct lys_ext_instance));
break;
case LYEXT_COMPLEX:
(*ext) = calloc(1, ((struct lyext_plugin_complex*)e->plugin)->instance_size);
break;
case LYEXT_ERR:
/* we never should be here */
LOGINT(ctx);
return -1;
}
LY_CHECK_ERR_RETURN(!*ext, LOGMEM(ctx), -1);
/* common part for all extension types */
(*ext)->def = e;
(*ext)->parent = info->parent;
(*ext)->parent_type = info->parent_type;
(*ext)->insubstmt = info->substmt;
(*ext)->insubstmt_index = info->substmt_index;
(*ext)->ext_type = e->plugin ? e->plugin->type : LYEXT_FLAG;
(*ext)->flags |= e->plugin ? e->plugin->flags : 0;
if (e->argument) {
if (!(e->flags & LYS_YINELEM)) {
(*ext)->arg_value = lyxml_get_attr(info->data.yin, e->argument, NULL);
if (!(*ext)->arg_value) {
LOGVAL(ctx, LYE_MISSARG, LY_VLOG_NONE, NULL, e->argument, info->data.yin->name);
return -1;
}
(*ext)->arg_value = lydict_insert(mod->ctx, (*ext)->arg_value, 0);
} else {
LY_TREE_FOR_SAFE(info->data.yin->child, next_yin, yin) {
if (ly_strequal(yin->name, e->argument, 1)) {
(*ext)->arg_value = lydict_insert(mod->ctx, yin->content, 0);
lyxml_free(mod->ctx, yin);
break;
}
}
}
}
if ((*ext)->flags & LYEXT_OPT_VALID &&
(info->parent_type == LYEXT_PAR_NODE || info->parent_type == LYEXT_PAR_TPDF)) {
((struct lys_node *)info->parent)->flags |= LYS_VALID_EXT;
}
(*ext)->nodetype = LYS_EXT;
(*ext)->module = info->mod;
/* extension type-specific part - parsing content */
switch (etype) {
case LYEXT_FLAG:
LY_TREE_FOR_SAFE(info->data.yin->child, next_yin, yin) {
if (!yin->ns) {
/* garbage */
lyxml_free(mod->ctx, yin);
continue;
} else if (!strcmp(yin->ns->value, LY_NSYIN)) {
/* standard YANG statements are not expected here */
LOGVAL(ctx, LYE_INCHILDSTMT, vlog_type, vlog_node, yin->name, info->data.yin->name);
return -1;
} else if (yin->ns == info->data.yin->ns &&
(e->flags & LYS_YINELEM) && ly_strequal(yin->name, e->argument, 1)) {
/* we have the extension's argument */
if ((*ext)->arg_value) {
LOGVAL(ctx, LYE_TOOMANY, vlog_type, vlog_node, yin->name, info->data.yin->name);
return -1;
}
(*ext)->arg_value = yin->content;
yin->content = NULL;
lyxml_free(mod->ctx, yin);
} else {
/* extension instance */
if (lyp_yin_parse_subnode_ext(info->mod, *ext, LYEXT_PAR_EXTINST, yin,
LYEXT_SUBSTMT_SELF, 0, unres)) {
return -1;
}
continue;
}
}
break;
case LYEXT_COMPLEX:
((struct lys_ext_instance_complex*)(*ext))->substmt = ((struct lyext_plugin_complex*)e->plugin)->substmt;
if (lyp_yin_parse_complex_ext(info->mod, (struct lys_ext_instance_complex*)(*ext), info->data.yin, unres)) {
/* TODO memory cleanup */
return -1;
}
break;
default:
break;
}
/* TODO - lyext_check_result_clb, other than LYEXT_FLAG plugins */
} else {
/* YANG */
ext_prefix = (char *)(*ext)->def;
tmp = strchr(ext_prefix, ':');
if (!tmp) {
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix);
goto error;
}
ext_name = tmp + 1;
/* get the module where the extension is supposed to be defined */
mod = lyp_get_module(info->mod, ext_prefix, tmp - ext_prefix, NULL, 0, 0);
if (!mod) {
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix);
return EXIT_FAILURE;
}
ctx = mod->ctx;
/* find the extension definition */
e = NULL;
for (i = 0; i < mod->extensions_size; i++) {
if (ly_strequal(mod->extensions[i].name, ext_name, 0)) {
e = &mod->extensions[i];
break;
}
}
/* try submodules */
for (j = 0; !e && j < mod->inc_size; j++) {
for (i = 0; i < mod->inc[j].submodule->extensions_size; i++) {
if (ly_strequal(mod->inc[j].submodule->extensions[i].name, ext_name, 0)) {
e = &mod->inc[j].submodule->extensions[i];
break;
}
}
}
if (!e) {
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix);
return EXIT_FAILURE;
}
(*ext)->flags &= ~LYEXT_OPT_YANG;
(*ext)->def = NULL;
/* we have the extension definition, so now it cannot be forward referenced and error is always fatal */
if (e->plugin && e->plugin->check_position) {
/* common part - we have plugin with position checking function, use it first */
if ((*e->plugin->check_position)(info->parent, info->parent_type, info->substmt)) {
/* extension is not allowed here */
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, e->name);
goto error;
}
}
/* extension common part */
(*ext)->def = e;
(*ext)->parent = info->parent;
(*ext)->ext_type = e->plugin ? e->plugin->type : LYEXT_FLAG;
(*ext)->flags |= e->plugin ? e->plugin->flags : 0;
if (e->argument && !(*ext)->arg_value) {
LOGVAL(ctx, LYE_MISSARG, LY_VLOG_NONE, NULL, e->argument, ext_name);
goto error;
}
if ((*ext)->flags & LYEXT_OPT_VALID &&
(info->parent_type == LYEXT_PAR_NODE || info->parent_type == LYEXT_PAR_TPDF)) {
((struct lys_node *)info->parent)->flags |= LYS_VALID_EXT;
}
(*ext)->module = info->mod;
(*ext)->nodetype = LYS_EXT;
/* extension type-specific part */
if (e->plugin) {
etype = e->plugin->type;
} else {
/* default type */
etype = LYEXT_FLAG;
}
switch (etype) {
case LYEXT_FLAG:
/* nothing change */
break;
case LYEXT_COMPLEX:
tmp_ext = realloc(*ext, ((struct lyext_plugin_complex*)e->plugin)->instance_size);
LY_CHECK_ERR_GOTO(!tmp_ext, LOGMEM(ctx), error);
memset((char *)tmp_ext + offsetof(struct lys_ext_instance_complex, content), 0,
((struct lyext_plugin_complex*)e->plugin)->instance_size - offsetof(struct lys_ext_instance_complex, content));
(*ext) = tmp_ext;
((struct lys_ext_instance_complex*)(*ext))->substmt = ((struct lyext_plugin_complex*)e->plugin)->substmt;
if (info->data.yang) {
*tmp = ':';
if (yang_parse_ext_substatement(info->mod, unres, info->data.yang->ext_substmt, ext_prefix,
(struct lys_ext_instance_complex*)(*ext))) {
goto error;
}
if (yang_fill_extcomplex_module(info->mod->ctx, (struct lys_ext_instance_complex*)(*ext), ext_prefix,
info->data.yang->ext_modules, info->mod->implemented)) {
goto error;
}
}
if (lyp_mand_check_ext((struct lys_ext_instance_complex*)(*ext), ext_prefix)) {
goto error;
}
break;
case LYEXT_ERR:
/* we never should be here */
LOGINT(ctx);
goto error;
}
if (yang_check_ext_instance(info->mod, &(*ext)->ext, (*ext)->ext_size, *ext, unres)) {
goto error;
}
free(ext_prefix);
}
return EXIT_SUCCESS;
error:
free(ext_prefix);
return -1;
}
/**
* @brief Resolve (find) choice default case. Does not log.
*
* @param[in] choic Choice to use.
* @param[in] dflt Name of the default case.
*
* @return Pointer to the default node or NULL.
*/
static struct lys_node *
resolve_choice_dflt(struct lys_node_choice *choic, const char *dflt)
{
struct lys_node *child, *ret;
LY_TREE_FOR(choic->child, child) {
if (child->nodetype == LYS_USES) {
ret = resolve_choice_dflt((struct lys_node_choice *)child, dflt);
if (ret) {
return ret;
}
}
if (ly_strequal(child->name, dflt, 1) && (child->nodetype & (LYS_ANYDATA | LYS_CASE
| LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_CHOICE))) {
return child;
}
}
return NULL;
}
/**
* @brief Resolve uses, apply augments, refines. Logs directly.
*
* @param[in] uses Uses to use.
* @param[in,out] unres List of unresolved items.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
static int
resolve_uses(struct lys_node_uses *uses, struct unres_schema *unres)
{
struct ly_ctx *ctx = uses->module->ctx; /* shortcut */
struct lys_node *node = NULL, *next, *iter, **refine_nodes = NULL;
struct lys_node *node_aux, *parent, *tmp;
struct lys_node_leaflist *llist;
struct lys_node_leaf *leaf;
struct lys_refine *rfn;
struct lys_restr *must, **old_must;
struct lys_iffeature *iff, **old_iff;
int i, j, k, rc;
uint8_t size, *old_size;
unsigned int usize, usize1, usize2;
assert(uses->grp);
/* check that the grouping is resolved (no unresolved uses inside) */
assert(!uses->grp->unres_count);
/* copy the data nodes from grouping into the uses context */
LY_TREE_FOR(uses->grp->child, node_aux) {
if (node_aux->nodetype & LYS_GROUPING) {
/* do not instantiate groupings from groupings */
continue;
}
node = lys_node_dup(uses->module, (struct lys_node *)uses, node_aux, unres, 0);
if (!node) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, uses->grp->name, "uses");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Copying data from grouping failed.");
goto fail;
}
/* test the name of siblings */
LY_TREE_FOR((uses->parent) ? *lys_child(uses->parent, LYS_USES) : lys_main_module(uses->module)->data, tmp) {
if (!(tmp->nodetype & (LYS_USES | LYS_GROUPING | LYS_CASE)) && ly_strequal(tmp->name, node_aux->name, 1)) {
goto fail;
}
}
}
/* we managed to copy the grouping, the rest must be possible to resolve */
if (uses->refine_size) {
refine_nodes = malloc(uses->refine_size * sizeof *refine_nodes);
LY_CHECK_ERR_GOTO(!refine_nodes, LOGMEM(ctx), fail);
}
/* apply refines */
for (i = 0; i < uses->refine_size; i++) {
rfn = &uses->refine[i];
rc = resolve_descendant_schema_nodeid(rfn->target_name, uses->child,
LYS_NO_RPC_NOTIF_NODE | LYS_ACTION | LYS_NOTIF,
0, (const struct lys_node **)&node);
if (rc || !node) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->target_name, "refine");
goto fail;
}
if (rfn->target_type && !(node->nodetype & rfn->target_type)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->target_name, "refine");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Refine substatements not applicable to the target-node.");
goto fail;
}
refine_nodes[i] = node;
/* description on any nodetype */
if (rfn->dsc) {
lydict_remove(ctx, node->dsc);
node->dsc = lydict_insert(ctx, rfn->dsc, 0);
}
/* reference on any nodetype */
if (rfn->ref) {
lydict_remove(ctx, node->ref);
node->ref = lydict_insert(ctx, rfn->ref, 0);
}
/* config on any nodetype,
* in case of notification or rpc/action, the config is not applicable (there is no config status) */
if ((rfn->flags & LYS_CONFIG_MASK) && (node->flags & LYS_CONFIG_MASK)) {
node->flags &= ~LYS_CONFIG_MASK;
node->flags |= (rfn->flags & LYS_CONFIG_MASK);
}
/* default value ... */
if (rfn->dflt_size) {
if (node->nodetype == LYS_LEAF) {
/* leaf */
leaf = (struct lys_node_leaf *)node;
/* replace default value */
lydict_remove(ctx, leaf->dflt);
leaf->dflt = lydict_insert(ctx, rfn->dflt[0], 0);
/* check the default value */
if (unres_schema_add_node(leaf->module, unres, &leaf->type, UNRES_TYPE_DFLT,
(struct lys_node *)(&leaf->dflt)) == -1) {
goto fail;
}
} else if (node->nodetype == LYS_LEAFLIST) {
/* leaf-list */
llist = (struct lys_node_leaflist *)node;
/* remove complete set of defaults in target */
for (j = 0; j < llist->dflt_size; j++) {
lydict_remove(ctx, llist->dflt[j]);
}
free(llist->dflt);
/* copy the default set from refine */
llist->dflt = malloc(rfn->dflt_size * sizeof *llist->dflt);
LY_CHECK_ERR_GOTO(!llist->dflt, LOGMEM(ctx), fail);
llist->dflt_size = rfn->dflt_size;
for (j = 0; j < llist->dflt_size; j++) {
llist->dflt[j] = lydict_insert(ctx, rfn->dflt[j], 0);
}
/* check default value */
for (j = 0; j < llist->dflt_size; j++) {
if (unres_schema_add_node(llist->module, unres, &llist->type, UNRES_TYPE_DFLT,
(struct lys_node *)(&llist->dflt[j])) == -1) {
goto fail;
}
}
}
}
/* mandatory on leaf, anyxml or choice */
if (rfn->flags & LYS_MAND_MASK) {
/* remove current value */
node->flags &= ~LYS_MAND_MASK;
/* set new value */
node->flags |= (rfn->flags & LYS_MAND_MASK);
if (rfn->flags & LYS_MAND_TRUE) {
/* check if node has default value */
if ((node->nodetype & LYS_LEAF) && ((struct lys_node_leaf *)node)->dflt) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses,
"The \"mandatory\" statement is forbidden on leaf with \"default\".");
goto fail;
}
if ((node->nodetype & LYS_CHOICE) && ((struct lys_node_choice *)node)->dflt) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses,
"The \"mandatory\" statement is forbidden on choices with \"default\".");
goto fail;
}
}
}
/* presence on container */
if ((node->nodetype & LYS_CONTAINER) && rfn->mod.presence) {
lydict_remove(ctx, ((struct lys_node_container *)node)->presence);
((struct lys_node_container *)node)->presence = lydict_insert(ctx, rfn->mod.presence, 0);
}
/* min/max-elements on list or leaf-list */
if (node->nodetype == LYS_LIST) {
if (rfn->flags & LYS_RFN_MINSET) {
((struct lys_node_list *)node)->min = rfn->mod.list.min;
}
if (rfn->flags & LYS_RFN_MAXSET) {
((struct lys_node_list *)node)->max = rfn->mod.list.max;
}
} else if (node->nodetype == LYS_LEAFLIST) {
if (rfn->flags & LYS_RFN_MINSET) {
((struct lys_node_leaflist *)node)->min = rfn->mod.list.min;
}
if (rfn->flags & LYS_RFN_MAXSET) {
((struct lys_node_leaflist *)node)->max = rfn->mod.list.max;
}
}
/* must in leaf, leaf-list, list, container or anyxml */
if (rfn->must_size) {
switch (node->nodetype) {
case LYS_LEAF:
old_size = &((struct lys_node_leaf *)node)->must_size;
old_must = &((struct lys_node_leaf *)node)->must;
break;
case LYS_LEAFLIST:
old_size = &((struct lys_node_leaflist *)node)->must_size;
old_must = &((struct lys_node_leaflist *)node)->must;
break;
case LYS_LIST:
old_size = &((struct lys_node_list *)node)->must_size;
old_must = &((struct lys_node_list *)node)->must;
break;
case LYS_CONTAINER:
old_size = &((struct lys_node_container *)node)->must_size;
old_must = &((struct lys_node_container *)node)->must;
break;
case LYS_ANYXML:
case LYS_ANYDATA:
old_size = &((struct lys_node_anydata *)node)->must_size;
old_must = &((struct lys_node_anydata *)node)->must;
break;
default:
LOGINT(ctx);
goto fail;
}
size = *old_size + rfn->must_size;
must = realloc(*old_must, size * sizeof *rfn->must);
LY_CHECK_ERR_GOTO(!must, LOGMEM(ctx), fail);
for (k = 0, j = *old_size; k < rfn->must_size; k++, j++) {
must[j].ext_size = rfn->must[k].ext_size;
lys_ext_dup(ctx, rfn->module, rfn->must[k].ext, rfn->must[k].ext_size, &rfn->must[k], LYEXT_PAR_RESTR,
&must[j].ext, 0, unres);
must[j].expr = lydict_insert(ctx, rfn->must[k].expr, 0);
must[j].dsc = lydict_insert(ctx, rfn->must[k].dsc, 0);
must[j].ref = lydict_insert(ctx, rfn->must[k].ref, 0);
must[j].eapptag = lydict_insert(ctx, rfn->must[k].eapptag, 0);
must[j].emsg = lydict_insert(ctx, rfn->must[k].emsg, 0);
must[j].flags = rfn->must[k].flags;
}
*old_must = must;
*old_size = size;
/* check XPath dependencies again */
if (unres_schema_add_node(node->module, unres, node, UNRES_XPATH, NULL) == -1) {
goto fail;
}
}
/* if-feature in leaf, leaf-list, list, container or anyxml */
if (rfn->iffeature_size) {
old_size = &node->iffeature_size;
old_iff = &node->iffeature;
size = *old_size + rfn->iffeature_size;
iff = realloc(*old_iff, size * sizeof *rfn->iffeature);
LY_CHECK_ERR_GOTO(!iff, LOGMEM(ctx), fail);
*old_iff = iff;
for (k = 0, j = *old_size; k < rfn->iffeature_size; k++, j++) {
resolve_iffeature_getsizes(&rfn->iffeature[k], &usize1, &usize2);
if (usize1) {
/* there is something to duplicate */
/* duplicate compiled expression */
usize = (usize1 / 4) + (usize1 % 4) ? 1 : 0;
iff[j].expr = malloc(usize * sizeof *iff[j].expr);
LY_CHECK_ERR_GOTO(!iff[j].expr, LOGMEM(ctx), fail);
memcpy(iff[j].expr, rfn->iffeature[k].expr, usize * sizeof *iff[j].expr);
/* duplicate list of feature pointers */
iff[j].features = malloc(usize2 * sizeof *iff[k].features);
LY_CHECK_ERR_GOTO(!iff[j].expr, LOGMEM(ctx), fail);
memcpy(iff[j].features, rfn->iffeature[k].features, usize2 * sizeof *iff[j].features);
/* duplicate extensions */
iff[j].ext_size = rfn->iffeature[k].ext_size;
lys_ext_dup(ctx, rfn->module, rfn->iffeature[k].ext, rfn->iffeature[k].ext_size,
&rfn->iffeature[k], LYEXT_PAR_IFFEATURE, &iff[j].ext, 0, unres);
}
(*old_size)++;
}
assert(*old_size == size);
}
}
/* apply augments */
for (i = 0; i < uses->augment_size; i++) {
rc = resolve_augment(&uses->augment[i], (struct lys_node *)uses, unres);
if (rc) {
goto fail;
}
}
/* check refines */
for (i = 0; i < uses->refine_size; i++) {
node = refine_nodes[i];
rfn = &uses->refine[i];
/* config on any nodetype */
if ((rfn->flags & LYS_CONFIG_MASK) && (node->flags & LYS_CONFIG_MASK)) {
for (parent = lys_parent(node); parent && parent->nodetype == LYS_USES; parent = lys_parent(parent));
if (parent && parent->nodetype != LYS_GROUPING && (parent->flags & LYS_CONFIG_MASK) &&
((parent->flags & LYS_CONFIG_MASK) != (rfn->flags & LYS_CONFIG_MASK)) &&
(rfn->flags & LYS_CONFIG_W)) {
/* setting config true under config false is prohibited */
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, "config", "refine");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"changing config from 'false' to 'true' is prohibited while "
"the target's parent is still config 'false'.");
goto fail;
}
/* inherit config change to the target children */
LY_TREE_DFS_BEGIN(node->child, next, iter) {
if (rfn->flags & LYS_CONFIG_W) {
if (iter->flags & LYS_CONFIG_SET) {
/* config is set explicitely, go to next sibling */
next = NULL;
goto nextsibling;
}
} else { /* LYS_CONFIG_R */
if ((iter->flags & LYS_CONFIG_SET) && (iter->flags & LYS_CONFIG_W)) {
/* error - we would have config data under status data */
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, "config", "refine");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"changing config from 'true' to 'false' is prohibited while the target "
"has still a children with explicit config 'true'.");
goto fail;
}
}
/* change config */
iter->flags &= ~LYS_CONFIG_MASK;
iter->flags |= (rfn->flags & LYS_CONFIG_MASK);
/* select next iter - modified LY_TREE_DFS_END */
if (iter->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
next = NULL;
} else {
next = iter->child;
}
nextsibling:
if (!next) {
/* try siblings */
next = iter->next;
}
while (!next) {
/* parent is already processed, go to its sibling */
iter = lys_parent(iter);
/* no siblings, go back through parents */
if (iter == node) {
/* we are done, no next element to process */
break;
}
next = iter->next;
}
}
}
/* default value */
if (rfn->dflt_size) {
if (node->nodetype == LYS_CHOICE) {
/* choice */
((struct lys_node_choice *)node)->dflt = resolve_choice_dflt((struct lys_node_choice *)node,
rfn->dflt[0]);
if (!((struct lys_node_choice *)node)->dflt) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->dflt[0], "default");
goto fail;
}
if (lyp_check_mandatory_choice(node)) {
goto fail;
}
}
}
/* min/max-elements on list or leaf-list */
if (node->nodetype == LYS_LIST && ((struct lys_node_list *)node)->max) {
if (((struct lys_node_list *)node)->min > ((struct lys_node_list *)node)->max) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "Invalid value \"%d\" of \"%s\".", rfn->mod.list.min, "min-elements");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"min-elements\" is bigger than \"max-elements\".");
goto fail;
}
} else if (node->nodetype == LYS_LEAFLIST && ((struct lys_node_leaflist *)node)->max) {
if (((struct lys_node_leaflist *)node)->min > ((struct lys_node_leaflist *)node)->max) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "Invalid value \"%d\" of \"%s\".", rfn->mod.list.min, "min-elements");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"min-elements\" is bigger than \"max-elements\".");
goto fail;
}
}
/* additional checks */
/* default value with mandatory/min-elements */
if (node->nodetype == LYS_LEAFLIST) {
llist = (struct lys_node_leaflist *)node;
if (llist->dflt_size && llist->min) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, uses, rfn->dflt_size ? "default" : "min-elements", "refine");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement.");
goto fail;
}
} else if (node->nodetype == LYS_LEAF) {
leaf = (struct lys_node_leaf *)node;
if (leaf->dflt && (leaf->flags & LYS_MAND_TRUE)) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, uses, rfn->dflt_size ? "default" : "mandatory", "refine");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"The \"mandatory\" statement is forbidden on leafs with the \"default\" statement.");
goto fail;
}
}
/* check for mandatory node in default case, first find the closest parent choice to the changed node */
if ((rfn->flags & LYS_MAND_TRUE) || rfn->mod.list.min) {
for (parent = node->parent;
parent && !(parent->nodetype & (LYS_CHOICE | LYS_GROUPING | LYS_ACTION | LYS_USES));
parent = parent->parent) {
if (parent->nodetype == LYS_CONTAINER && ((struct lys_node_container *)parent)->presence) {
/* stop also on presence containers */
break;
}
}
/* and if it is a choice with the default case, check it for presence of a mandatory node in it */
if (parent && parent->nodetype == LYS_CHOICE && ((struct lys_node_choice *)parent)->dflt) {
if (lyp_check_mandatory_choice(parent)) {
goto fail;
}
}
}
}
free(refine_nodes);
return EXIT_SUCCESS;
fail:
LY_TREE_FOR_SAFE(uses->child, next, iter) {
lys_node_free(iter, NULL, 0);
}
free(refine_nodes);
return -1;
}
void
resolve_identity_backlink_update(struct lys_ident *der, struct lys_ident *base)
{
int i;
assert(der && base);
if (!base->der) {
/* create a set for backlinks if it does not exist */
base->der = ly_set_new();
}
/* store backlink */
ly_set_add(base->der, der, LY_SET_OPT_USEASLIST);
/* do it recursively */
for (i = 0; i < base->base_size; i++) {
resolve_identity_backlink_update(der, base->base[i]);
}
}
/**
* @brief Resolve base identity recursively. Does not log.
*
* @param[in] module Main module.
* @param[in] ident Identity to use.
* @param[in] basename Base name of the identity.
* @param[out] ret Pointer to the resolved identity. Can be NULL.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on crucial error.
*/
static int
resolve_base_ident_sub(const struct lys_module *module, struct lys_ident *ident, const char *basename,
struct unres_schema *unres, struct lys_ident **ret)
{
uint32_t i, j;
struct lys_ident *base = NULL;
struct ly_ctx *ctx = module->ctx;
assert(ret);
/* search module */
for (i = 0; i < module->ident_size; i++) {
if (!strcmp(basename, module->ident[i].name)) {
if (!ident) {
/* just search for type, so do not modify anything, just return
* the base identity pointer */
*ret = &module->ident[i];
return EXIT_SUCCESS;
}
base = &module->ident[i];
goto matchfound;
}
}
/* search submodules */
for (j = 0; j < module->inc_size && module->inc[j].submodule; j++) {
for (i = 0; i < module->inc[j].submodule->ident_size; i++) {
if (!strcmp(basename, module->inc[j].submodule->ident[i].name)) {
if (!ident) {
*ret = &module->inc[j].submodule->ident[i];
return EXIT_SUCCESS;
}
base = &module->inc[j].submodule->ident[i];
goto matchfound;
}
}
}
matchfound:
/* we found it somewhere */
if (base) {
/* is it already completely resolved? */
for (i = 0; i < unres->count; i++) {
if ((unres->item[i] == base) && (unres->type[i] == UNRES_IDENT)) {
/* identity found, but not yet resolved, so do not return it in *res and try it again later */
/* simple check for circular reference,
* the complete check is done as a side effect of using only completely
* resolved identities (previous check of unres content) */
if (ly_strequal((const char *)unres->str_snode[i], ident->name, 1)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, basename, "base");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Circular reference of \"%s\" identity.", basename);
return -1;
}
return EXIT_FAILURE;
}
}
/* checks done, store the result */
*ret = base;
return EXIT_SUCCESS;
}
/* base not found (maybe a forward reference) */
return EXIT_FAILURE;
}
/**
* @brief Resolve base identity. Logs directly.
*
* @param[in] module Main module.
* @param[in] ident Identity to use.
* @param[in] basename Base name of the identity.
* @param[in] parent Either "type" or "identity".
* @param[in,out] type Type structure where we want to resolve identity. Can be NULL.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_base_ident(const struct lys_module *module, struct lys_ident *ident, const char *basename, const char *parent,
struct lys_type *type, struct unres_schema *unres)
{
const char *name;
int mod_name_len = 0, rc;
struct lys_ident *target, **ret;
uint16_t flags;
struct lys_module *mod;
struct ly_ctx *ctx = module->ctx;
assert((ident && !type) || (!ident && type));
if (!type) {
/* have ident to resolve */
ret = ⌖
flags = ident->flags;
mod = ident->module;
} else {
/* have type to fill */
++type->info.ident.count;
type->info.ident.ref = ly_realloc(type->info.ident.ref, type->info.ident.count * sizeof *type->info.ident.ref);
LY_CHECK_ERR_RETURN(!type->info.ident.ref, LOGMEM(ctx), -1);
ret = &type->info.ident.ref[type->info.ident.count - 1];
flags = type->parent->flags;
mod = type->parent->module;
}
*ret = NULL;
/* search for the base identity */
name = strchr(basename, ':');
if (name) {
/* set name to correct position after colon */
mod_name_len = name - basename;
name++;
if (!strncmp(basename, module->name, mod_name_len) && !module->name[mod_name_len]) {
/* prefix refers to the current module, ignore it */
mod_name_len = 0;
}
} else {
name = basename;
}
/* get module where to search */
module = lyp_get_module(module, NULL, 0, mod_name_len ? basename : NULL, mod_name_len, 0);
if (!module) {
/* identity refers unknown data model */
LOGVAL(ctx, LYE_INMOD, LY_VLOG_NONE, NULL, basename);
return -1;
}
/* search in the identified module ... */
rc = resolve_base_ident_sub(module, ident, name, unres, ret);
if (!rc) {
assert(*ret);
/* check status */
if (lyp_check_status(flags, mod, ident ? ident->name : "of type",
(*ret)->flags, (*ret)->module, (*ret)->name, NULL)) {
rc = -1;
} else if (ident) {
ident->base[ident->base_size++] = *ret;
if (lys_main_module(mod)->implemented) {
/* in case of the implemented identity, maintain backlinks to it
* from the base identities to make it available when resolving
* data with the identity values (not implemented identity is not
* allowed as an identityref value). */
resolve_identity_backlink_update(ident, *ret);
}
}
} else if (rc == EXIT_FAILURE) {
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_NONE, NULL, parent, basename);
if (type) {
--type->info.ident.count;
}
}
return rc;
}
/*
* 1 - true (der is derived from base)
* 0 - false (der is not derived from base)
*/
static int
search_base_identity(struct lys_ident *der, struct lys_ident *base)
{
int i;
if (der == base) {
return 1;
} else {
for(i = 0; i < der->base_size; i++) {
if (search_base_identity(der->base[i], base) == 1) {
return 1;
}
}
}
return 0;
}
/**
* @brief Resolve JSON data format identityref. Logs directly.
*
* @param[in] type Identityref type.
* @param[in] ident_name Identityref name.
* @param[in] node Node where the identityref is being resolved
* @param[in] dflt flag if we are resolving default value in the schema
*
* @return Pointer to the identity resolvent, NULL on error.
*/
struct lys_ident *
resolve_identref(struct lys_type *type, const char *ident_name, struct lyd_node *node, struct lys_module *mod, int dflt)
{
const char *mod_name, *name;
char *str;
int mod_name_len, nam_len, rc;
int need_implemented = 0;
unsigned int i, j;
struct lys_ident *der, *cur;
struct lys_module *imod = NULL, *m, *tmod;
struct ly_ctx *ctx;
assert(type && ident_name && mod);
ctx = mod->ctx;
if (!type || (!type->info.ident.count && !type->der) || !ident_name) {
return NULL;
}
rc = parse_node_identifier(ident_name, &mod_name, &mod_name_len, &name, &nam_len, NULL, 0);
if (rc < 1) {
LOGVAL(ctx, LYE_INCHAR, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, ident_name[-rc], &ident_name[-rc]);
return NULL;
} else if (rc < (signed)strlen(ident_name)) {
LOGVAL(ctx, LYE_INCHAR, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, ident_name[rc], &ident_name[rc]);
return NULL;
}
m = lys_main_module(mod); /* shortcut */
if (!mod_name || (!strncmp(mod_name, m->name, mod_name_len) && !m->name[mod_name_len])) {
/* identity is defined in the same module as node */
imod = m;
} else if (dflt) {
/* solving identityref in default definition in schema -
* find the identity's module in the imported modules list to have a correct revision */
for (i = 0; i < mod->imp_size; i++) {
if (!strncmp(mod_name, mod->imp[i].module->name, mod_name_len) && !mod->imp[i].module->name[mod_name_len]) {
imod = mod->imp[i].module;
break;
}
}
/* We may need to pull it from the module that the typedef came from */
if (!imod && type && type->der) {
tmod = type->der->module;
for (i = 0; i < tmod->imp_size; i++) {
if (!strncmp(mod_name, tmod->imp[i].module->name, mod_name_len) && !tmod->imp[i].module->name[mod_name_len]) {
imod = tmod->imp[i].module;
break;
}
}
}
} else {
/* solving identityref in data - get the module from the context */
for (i = 0; i < (unsigned)mod->ctx->models.used; ++i) {
imod = mod->ctx->models.list[i];
if (!strncmp(mod_name, imod->name, mod_name_len) && !imod->name[mod_name_len]) {
break;
}
imod = NULL;
}
if (!imod && mod->ctx->models.parsing_sub_modules_count) {
/* we are currently parsing some module and checking XPath or a default value,
* so take this module into account */
for (i = 0; i < mod->ctx->models.parsing_sub_modules_count; i++) {
imod = mod->ctx->models.parsing_sub_modules[i];
if (imod->type) {
/* skip submodules */
continue;
}
if (!strncmp(mod_name, imod->name, mod_name_len) && !imod->name[mod_name_len]) {
break;
}
imod = NULL;
}
}
}
if (!dflt && (!imod || !imod->implemented) && ctx->data_clb) {
/* the needed module was not found, but it may have been expected so call the data callback */
if (imod) {
ctx->data_clb(ctx, imod->name, imod->ns, LY_MODCLB_NOT_IMPLEMENTED, ctx->data_clb_data);
} else if (mod_name) {
str = strndup(mod_name, mod_name_len);
imod = (struct lys_module *)ctx->data_clb(ctx, str, NULL, 0, ctx->data_clb_data);
free(str);
}
}
if (!imod) {
goto fail;
}
if (m != imod || lys_main_module(type->parent->module) != mod) {
/* the type is not referencing the same schema,
* THEN, we may need to make the module with the identity implemented, but only if it really
* contains the identity */
if (!imod->implemented) {
cur = NULL;
/* get the identity in the module */
for (i = 0; i < imod->ident_size; i++) {
if (!strcmp(name, imod->ident[i].name)) {
cur = &imod->ident[i];
break;
}
}
if (!cur) {
/* go through includes */
for (j = 0; j < imod->inc_size; j++) {
for (i = 0; i < imod->inc[j].submodule->ident_size; i++) {
if (!strcmp(name, imod->inc[j].submodule->ident[i].name)) {
cur = &imod->inc[j].submodule->ident[i];
break;
}
}
}
if (!cur) {
goto fail;
}
}
/* check that identity is derived from one of the type's base */
while (type->der) {
for (i = 0; i < type->info.ident.count; i++) {
if (search_base_identity(cur, type->info.ident.ref[i])) {
/* cur's base matches the type's base */
need_implemented = 1;
goto match;
}
}
type = &type->der->type;
}
/* matching base not found */
LOGVAL(ctx, LYE_SPEC, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, "Identity used as identityref value is not implemented.");
goto fail;
}
}
/* go through all the derived types of all the bases */
while (type->der) {
for (i = 0; i < type->info.ident.count; ++i) {
cur = type->info.ident.ref[i];
if (cur->der) {
/* there are some derived identities */
for (j = 0; j < cur->der->number; j++) {
der = (struct lys_ident *)cur->der->set.g[j]; /* shortcut */
if (!strcmp(der->name, name) && lys_main_module(der->module) == imod) {
/* we have match */
cur = der;
goto match;
}
}
}
}
type = &type->der->type;
}
fail:
LOGVAL(ctx, LYE_INRESOLV, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, "identityref", ident_name);
return NULL;
match:
for (i = 0; i < cur->iffeature_size; i++) {
if (!resolve_iffeature(&cur->iffeature[i])) {
if (node) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, node, cur->name, node->schema->name);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Identity \"%s\" is disabled by its if-feature condition.", cur->name);
return NULL;
}
}
if (need_implemented) {
if (dflt) {
/* later try to make the module implemented */
LOGVRB("Making \"%s\" module implemented because of identityref default value \"%s\" used in the implemented \"%s\" module",
imod->name, cur->name, mod->name);
/* to be more effective we should use UNRES_MOD_IMPLEMENT but that would require changing prototype of
* several functions with little gain */
if (lys_set_implemented(imod)) {
LOGERR(ctx, ly_errno, "Setting the module \"%s\" implemented because of used default identity \"%s\" failed.",
imod->name, cur->name);
goto fail;
}
} else {
/* just say that it was found, but in a non-implemented module */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Identity found, but in a non-implemented module \"%s\".",
lys_main_module(cur->module)->name);
goto fail;
}
}
return cur;
}
/**
* @brief Resolve unresolved uses. Logs directly.
*
* @param[in] uses Uses to use.
* @param[in] unres Specific unres item.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_unres_schema_uses(struct lys_node_uses *uses, struct unres_schema *unres)
{
int rc;
struct lys_node *par_grp;
struct ly_ctx *ctx = uses->module->ctx;
/* HACK: when a grouping has uses inside, all such uses have to be resolved before the grouping itself is used
* in some uses. When we see such a uses, the grouping's unres counter is used to store number of so far
* unresolved uses. The grouping cannot be used unless this counter is decreased back to 0. To remember
* that the uses already increased grouping's counter, the LYS_USESGRP flag is used. */
for (par_grp = lys_parent((struct lys_node *)uses); par_grp && (par_grp->nodetype != LYS_GROUPING); par_grp = lys_parent(par_grp));
if (par_grp && ly_strequal(par_grp->name, uses->name, 1)) {
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name);
return -1;
}
if (!uses->grp) {
rc = resolve_uses_schema_nodeid(uses->name, (const struct lys_node *)uses, (const struct lys_node_grp **)&uses->grp);
if (rc == -1) {
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name);
return -1;
} else if (rc > 0) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, uses, uses->name[rc - 1], &uses->name[rc - 1]);
return -1;
} else if (!uses->grp) {
if (par_grp && !(uses->flags & LYS_USESGRP)) {
if (++((struct lys_node_grp *)par_grp)->unres_count == 0) {
LOGERR(ctx, LY_EINT, "Too many unresolved items (uses) inside a grouping.");
return -1;
}
uses->flags |= LYS_USESGRP;
}
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name);
return EXIT_FAILURE;
}
}
if (uses->grp->unres_count) {
if (par_grp && !(uses->flags & LYS_USESGRP)) {
if (++((struct lys_node_grp *)par_grp)->unres_count == 0) {
LOGERR(ctx, LY_EINT, "Too many unresolved items (uses) inside a grouping.");
return -1;
}
uses->flags |= LYS_USESGRP;
} else {
/* instantiate grouping only when it is completely resolved */
uses->grp = NULL;
}
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name);
return EXIT_FAILURE;
}
rc = resolve_uses(uses, unres);
if (!rc) {
/* decrease unres count only if not first try */
if (par_grp && (uses->flags & LYS_USESGRP)) {
assert(((struct lys_node_grp *)par_grp)->unres_count);
((struct lys_node_grp *)par_grp)->unres_count--;
uses->flags &= ~LYS_USESGRP;
}
/* check status */
if (lyp_check_status(uses->flags, uses->module, "of uses",
uses->grp->flags, uses->grp->module, uses->grp->name,
(struct lys_node *)uses)) {
return -1;
}
return EXIT_SUCCESS;
}
return rc;
}
/**
* @brief Resolve list keys. Logs directly.
*
* @param[in] list List to use.
* @param[in] keys_str Keys node value.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_list_keys(struct lys_node_list *list, const char *keys_str)
{
int i, len, rc;
const char *value;
char *s = NULL;
struct ly_ctx *ctx = list->module->ctx;
for (i = 0; i < list->keys_size; ++i) {
assert(keys_str);
if (!list->child) {
/* no child, possible forward reference */
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, list, "list keys", keys_str);
return EXIT_FAILURE;
}
/* get the key name */
if ((value = strpbrk(keys_str, " \t\n"))) {
len = value - keys_str;
while (isspace(value[0])) {
value++;
}
} else {
len = strlen(keys_str);
}
rc = lys_getnext_data(lys_node_module((struct lys_node *)list), (struct lys_node *)list, keys_str, len, LYS_LEAF,
LYS_GETNEXT_NOSTATECHECK, (const struct lys_node **)&list->keys[i]);
if (rc) {
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, list, "list key", keys_str);
return EXIT_FAILURE;
}
if (check_key(list, i, keys_str, len)) {
/* check_key logs */
return -1;
}
/* check status */
if (lyp_check_status(list->flags, list->module, list->name,
list->keys[i]->flags, list->keys[i]->module, list->keys[i]->name,
(struct lys_node *)list->keys[i])) {
return -1;
}
/* default value - is ignored, keep it but print a warning */
if (list->keys[i]->dflt) {
/* log is not hidden only in case this resolving fails and in such a case
* we cannot get here
*/
assert(log_opt == ILO_STORE);
log_opt = ILO_LOG;
LOGWRN(ctx, "Default value \"%s\" in the list key \"%s\" is ignored. (%s)", list->keys[i]->dflt,
list->keys[i]->name, s = lys_path((struct lys_node*)list, LYS_PATH_FIRST_PREFIX));
log_opt = ILO_STORE;
free(s);
}
/* prepare for next iteration */
while (value && isspace(value[0])) {
value++;
}
keys_str = value;
}
return EXIT_SUCCESS;
}
/**
* @brief Resolve (check) all must conditions of \p node.
* Logs directly.
*
* @param[in] node Data node with optional must statements.
* @param[in] inout_parent If set, must in input or output parent of node->schema will be resolved.
*
* @return EXIT_SUCCESS on pass, EXIT_FAILURE on fail, -1 on error.
*/
static int
resolve_must(struct lyd_node *node, int inout_parent, int ignore_fail)
{
uint8_t i, must_size;
struct lys_node *schema;
struct lys_restr *must;
struct lyxp_set set;
struct ly_ctx *ctx = node->schema->module->ctx;
assert(node);
memset(&set, 0, sizeof set);
if (inout_parent) {
for (schema = lys_parent(node->schema);
schema && (schema->nodetype & (LYS_CHOICE | LYS_CASE | LYS_USES));
schema = lys_parent(schema));
if (!schema || !(schema->nodetype & (LYS_INPUT | LYS_OUTPUT))) {
LOGINT(ctx);
return -1;
}
must_size = ((struct lys_node_inout *)schema)->must_size;
must = ((struct lys_node_inout *)schema)->must;
/* context node is the RPC/action */
node = node->parent;
if (!(node->schema->nodetype & (LYS_RPC | LYS_ACTION))) {
LOGINT(ctx);
return -1;
}
} else {
switch (node->schema->nodetype) {
case LYS_CONTAINER:
must_size = ((struct lys_node_container *)node->schema)->must_size;
must = ((struct lys_node_container *)node->schema)->must;
break;
case LYS_LEAF:
must_size = ((struct lys_node_leaf *)node->schema)->must_size;
must = ((struct lys_node_leaf *)node->schema)->must;
break;
case LYS_LEAFLIST:
must_size = ((struct lys_node_leaflist *)node->schema)->must_size;
must = ((struct lys_node_leaflist *)node->schema)->must;
break;
case LYS_LIST:
must_size = ((struct lys_node_list *)node->schema)->must_size;
must = ((struct lys_node_list *)node->schema)->must;
break;
case LYS_ANYXML:
case LYS_ANYDATA:
must_size = ((struct lys_node_anydata *)node->schema)->must_size;
must = ((struct lys_node_anydata *)node->schema)->must;
break;
case LYS_NOTIF:
must_size = ((struct lys_node_notif *)node->schema)->must_size;
must = ((struct lys_node_notif *)node->schema)->must;
break;
default:
must_size = 0;
break;
}
}
for (i = 0; i < must_size; ++i) {
if (lyxp_eval(must[i].expr, node, LYXP_NODE_ELEM, lyd_node_module(node), &set, LYXP_MUST)) {
return -1;
}
lyxp_set_cast(&set, LYXP_SET_BOOLEAN, node, lyd_node_module(node), LYXP_MUST);
if (!set.val.bool) {
if ((ignore_fail == 1) || ((must[i].flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) && (ignore_fail == 2))) {
LOGVRB("Must condition \"%s\" not satisfied, but it is not required.", must[i].expr);
} else {
LOGVAL(ctx, LYE_NOMUST, LY_VLOG_LYD, node, must[i].expr);
if (must[i].emsg) {
ly_vlog_str(ctx, LY_VLOG_PREV, must[i].emsg);
}
if (must[i].eapptag) {
ly_err_last_set_apptag(ctx, must[i].eapptag);
}
return 1;
}
}
}
return EXIT_SUCCESS;
}
/**
* @brief Resolve (find) when condition schema context node. Does not log.
*
* @param[in] schema Schema node with the when condition.
* @param[out] ctx_snode When schema context node.
* @param[out] ctx_snode_type Schema context node type.
*/
void
resolve_when_ctx_snode(const struct lys_node *schema, struct lys_node **ctx_snode, enum lyxp_node_type *ctx_snode_type)
{
const struct lys_node *sparent;
/* find a not schema-only node */
*ctx_snode_type = LYXP_NODE_ELEM;
while (schema->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE | LYS_AUGMENT | LYS_INPUT | LYS_OUTPUT)) {
if (schema->nodetype == LYS_AUGMENT) {
sparent = ((struct lys_node_augment *)schema)->target;
} else {
sparent = schema->parent;
}
if (!sparent) {
/* context node is the document root (fake root in our case) */
if (schema->flags & LYS_CONFIG_W) {
*ctx_snode_type = LYXP_NODE_ROOT_CONFIG;
} else {
*ctx_snode_type = LYXP_NODE_ROOT;
}
/* we need the first top-level sibling, but no uses or groupings */
schema = lys_getnext(NULL, NULL, lys_node_module(schema), LYS_GETNEXT_NOSTATECHECK);
break;
}
schema = sparent;
}
*ctx_snode = (struct lys_node *)schema;
}
/**
* @brief Resolve (find) when condition context node. Does not log.
*
* @param[in] node Data node, whose conditional definition is being decided.
* @param[in] schema Schema node with the when condition.
* @param[out] ctx_node Context node.
* @param[out] ctx_node_type Context node type.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
static int
resolve_when_ctx_node(struct lyd_node *node, struct lys_node *schema, struct lyd_node **ctx_node,
enum lyxp_node_type *ctx_node_type)
{
struct lyd_node *parent;
struct lys_node *sparent;
enum lyxp_node_type node_type;
uint16_t i, data_depth, schema_depth;
resolve_when_ctx_snode(schema, &schema, &node_type);
if (node_type == LYXP_NODE_ELEM) {
/* standard element context node */
for (parent = node, data_depth = 0; parent; parent = parent->parent, ++data_depth);
for (sparent = schema, schema_depth = 0;
sparent;
sparent = (sparent->nodetype == LYS_AUGMENT ? ((struct lys_node_augment *)sparent)->target : sparent->parent)) {
if (sparent->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_ANYDATA | LYS_NOTIF | LYS_RPC)) {
++schema_depth;
}
}
if (data_depth < schema_depth) {
return -1;
}
/* find the corresponding data node */
for (i = 0; i < data_depth - schema_depth; ++i) {
node = node->parent;
}
if (node->schema != schema) {
return -1;
}
} else {
/* root context node */
while (node->parent) {
node = node->parent;
}
while (node->prev->next) {
node = node->prev;
}
}
*ctx_node = node;
*ctx_node_type = node_type;
return EXIT_SUCCESS;
}
/**
* @brief Temporarily unlink nodes as per YANG 1.1 RFC section 7.21.5 for when XPath evaluation.
* The context node is adjusted if needed.
*
* @param[in] snode Schema node, whose children instances need to be unlinked.
* @param[in,out] node Data siblings where to look for the children of \p snode. If it is unlinked,
* it is moved to point to another sibling still in the original tree.
* @param[in,out] ctx_node When context node, adjusted if needed.
* @param[in] ctx_node_type Context node type, just for information to detect invalid situations.
* @param[out] unlinked_nodes Unlinked siblings. Can be safely appended to \p node afterwards.
* Ordering may change, but there will be no semantic change.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
static int
resolve_when_unlink_nodes(struct lys_node *snode, struct lyd_node **node, struct lyd_node **ctx_node,
enum lyxp_node_type ctx_node_type, struct lyd_node **unlinked_nodes)
{
struct lyd_node *next, *elem;
const struct lys_node *slast;
struct ly_ctx *ctx = snode->module->ctx;
switch (snode->nodetype) {
case LYS_AUGMENT:
case LYS_USES:
case LYS_CHOICE:
case LYS_CASE:
slast = NULL;
while ((slast = lys_getnext(slast, snode, NULL, LYS_GETNEXT_PARENTUSES))) {
if (slast->nodetype & (LYS_ACTION | LYS_NOTIF)) {
continue;
}
if (resolve_when_unlink_nodes((struct lys_node *)slast, node, ctx_node, ctx_node_type, unlinked_nodes)) {
return -1;
}
}
break;
case LYS_CONTAINER:
case LYS_LIST:
case LYS_LEAF:
case LYS_LEAFLIST:
case LYS_ANYXML:
case LYS_ANYDATA:
LY_TREE_FOR_SAFE(lyd_first_sibling(*node), next, elem) {
if (elem->schema == snode) {
if (elem == *ctx_node) {
/* We are going to unlink our context node! This normally cannot happen,
* but we use normal top-level data nodes for faking a document root node,
* so if this is the context node, we just use the next top-level node.
* Additionally, it can even happen that there are no top-level data nodes left,
* all were unlinked, so in this case we pass NULL as the context node/data tree,
* lyxp_eval() can handle this special situation.
*/
if (ctx_node_type == LYXP_NODE_ELEM) {
LOGINT(ctx);
return -1;
}
if (elem->prev == elem) {
/* unlinking last top-level element, use an empty data tree */
*ctx_node = NULL;
} else {
/* in this case just use the previous/last top-level data node */
*ctx_node = elem->prev;
}
} else if (elem == *node) {
/* We are going to unlink the currently processed node. This does not matter that
* much, but we would lose access to the original data tree, so just move our
* pointer somewhere still inside it.
*/
if ((*node)->prev != *node) {
*node = (*node)->prev;
} else {
/* the processed node with sibings were all unlinked, oh well */
*node = NULL;
}
}
/* temporarily unlink the node */
lyd_unlink_internal(elem, 0);
if (*unlinked_nodes) {
if (lyd_insert_after((*unlinked_nodes)->prev, elem)) {
LOGINT(ctx);
return -1;
}
} else {
*unlinked_nodes = elem;
}
if (snode->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_ANYDATA)) {
/* there can be only one instance */
break;
}
}
}
break;
default:
LOGINT(ctx);
return -1;
}
return EXIT_SUCCESS;
}
/**
* @brief Relink the unlinked nodes back.
*
* @param[in] node Data node to link the nodes back to. It can actually be the adjusted context node,
* we simply need a sibling from the original data tree.
* @param[in] unlinked_nodes Unlinked nodes to relink to \p node.
* @param[in] ctx_node_type Context node type to distinguish between \p node being the parent
* or the sibling of \p unlinked_nodes.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
static int
resolve_when_relink_nodes(struct lyd_node *node, struct lyd_node *unlinked_nodes, enum lyxp_node_type ctx_node_type)
{
struct lyd_node *elem;
LY_TREE_FOR_SAFE(unlinked_nodes, unlinked_nodes, elem) {
lyd_unlink_internal(elem, 0);
if (ctx_node_type == LYXP_NODE_ELEM) {
if (lyd_insert_common(node, NULL, elem, 0)) {
return -1;
}
} else {
if (lyd_insert_nextto(node, elem, 0, 0)) {
return -1;
}
}
}
return EXIT_SUCCESS;
}
int
resolve_applies_must(const struct lyd_node *node)
{
int ret = 0;
uint8_t must_size;
struct lys_node *schema, *iter;
assert(node);
schema = node->schema;
/* their own must */
switch (schema->nodetype) {
case LYS_CONTAINER:
must_size = ((struct lys_node_container *)schema)->must_size;
break;
case LYS_LEAF:
must_size = ((struct lys_node_leaf *)schema)->must_size;
break;
case LYS_LEAFLIST:
must_size = ((struct lys_node_leaflist *)schema)->must_size;
break;
case LYS_LIST:
must_size = ((struct lys_node_list *)schema)->must_size;
break;
case LYS_ANYXML:
case LYS_ANYDATA:
must_size = ((struct lys_node_anydata *)schema)->must_size;
break;
case LYS_NOTIF:
must_size = ((struct lys_node_notif *)schema)->must_size;
break;
default:
must_size = 0;
break;
}
if (must_size) {
++ret;
}
/* schema may be a direct data child of input/output with must (but it must be first, it needs to be evaluated only once) */
if (!node->prev->next) {
for (iter = lys_parent(schema); iter && (iter->nodetype & (LYS_CHOICE | LYS_CASE | LYS_USES)); iter = lys_parent(iter));
if (iter && (iter->nodetype & (LYS_INPUT | LYS_OUTPUT))) {
ret += 0x2;
}
}
return ret;
}
static struct lys_when *
snode_get_when(const struct lys_node *schema)
{
switch (schema->nodetype) {
case LYS_CONTAINER:
return ((struct lys_node_container *)schema)->when;
case LYS_CHOICE:
return ((struct lys_node_choice *)schema)->when;
case LYS_LEAF:
return ((struct lys_node_leaf *)schema)->when;
case LYS_LEAFLIST:
return ((struct lys_node_leaflist *)schema)->when;
case LYS_LIST:
return ((struct lys_node_list *)schema)->when;
case LYS_ANYDATA:
case LYS_ANYXML:
return ((struct lys_node_anydata *)schema)->when;
case LYS_CASE:
return ((struct lys_node_case *)schema)->when;
case LYS_USES:
return ((struct lys_node_uses *)schema)->when;
case LYS_AUGMENT:
return ((struct lys_node_augment *)schema)->when;
default:
return NULL;
}
}
int
resolve_applies_when(const struct lys_node *schema, int mode, const struct lys_node *stop)
{
const struct lys_node *parent;
assert(schema);
if (!(schema->nodetype & (LYS_NOTIF | LYS_RPC)) && snode_get_when(schema)) {
return 1;
}
parent = schema;
goto check_augment;
while (parent) {
/* stop conditions */
if (!mode) {
/* stop on node that can be instantiated in data tree */
if (!(parent->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE))) {
break;
}
} else {
/* stop on the specified node */
if (parent == stop) {
break;
}
}
if (snode_get_when(parent)) {
return 1;
}
check_augment:
if (parent->parent && (parent->parent->nodetype == LYS_AUGMENT) && snode_get_when(parent->parent)) {
return 1;
}
parent = lys_parent(parent);
}
return 0;
}
/**
* @brief Resolve (check) all when conditions relevant for \p node.
* Logs directly.
*
* @param[in] node Data node, whose conditional reference, if such, is being decided.
* @param[in] ignore_fail 1 if when does not have to be satisfied, 2 if it does not have to be satisfied
* only when requiring external dependencies.
*
* @return
* -1 - error, ly_errno is set
* 0 - all "when" statements true
* 0, ly_vecode = LYVE_NOWHEN - some "when" statement false, returned in failed_when
* 1, ly_vecode = LYVE_INWHEN - nodes needed to resolve are conditional and not yet resolved (under another "when")
*/
int
resolve_when(struct lyd_node *node, int ignore_fail, struct lys_when **failed_when)
{
struct lyd_node *ctx_node = NULL, *unlinked_nodes, *tmp_node;
struct lys_node *sparent;
struct lyxp_set set;
enum lyxp_node_type ctx_node_type;
struct ly_ctx *ctx = node->schema->module->ctx;
int rc = 0;
assert(node);
memset(&set, 0, sizeof set);
if (!(node->schema->nodetype & (LYS_NOTIF | LYS_RPC | LYS_ACTION)) && snode_get_when(node->schema)) {
/* make the node dummy for the evaluation */
node->validity |= LYD_VAL_INUSE;
rc = lyxp_eval(snode_get_when(node->schema)->cond, node, LYXP_NODE_ELEM, lyd_node_module(node),
&set, LYXP_WHEN);
node->validity &= ~LYD_VAL_INUSE;
if (rc) {
if (rc == 1) {
LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(node->schema)->cond);
}
goto cleanup;
}
/* set boolean result of the condition */
lyxp_set_cast(&set, LYXP_SET_BOOLEAN, node, lyd_node_module(node), LYXP_WHEN);
if (!set.val.bool) {
node->when_status |= LYD_WHEN_FALSE;
if ((ignore_fail == 1) || ((snode_get_when(node->schema)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP))
&& (ignore_fail == 2))) {
LOGVRB("When condition \"%s\" is not satisfied, but it is not required.", snode_get_when(node->schema)->cond);
} else {
LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(node->schema)->cond);
if (failed_when) {
*failed_when = snode_get_when(node->schema);
}
goto cleanup;
}
}
/* free xpath set content */
lyxp_set_cast(&set, LYXP_SET_EMPTY, node, lyd_node_module(node), 0);
}
sparent = node->schema;
goto check_augment;
/* check when in every schema node that affects node */
while (sparent && (sparent->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE))) {
if (snode_get_when(sparent)) {
if (!ctx_node) {
rc = resolve_when_ctx_node(node, sparent, &ctx_node, &ctx_node_type);
if (rc) {
LOGINT(ctx);
goto cleanup;
}
}
unlinked_nodes = NULL;
/* we do not want our node pointer to change */
tmp_node = node;
rc = resolve_when_unlink_nodes(sparent, &tmp_node, &ctx_node, ctx_node_type, &unlinked_nodes);
if (rc) {
goto cleanup;
}
rc = lyxp_eval(snode_get_when(sparent)->cond, ctx_node, ctx_node_type, lys_node_module(sparent),
&set, LYXP_WHEN);
if (unlinked_nodes && ctx_node) {
if (resolve_when_relink_nodes(ctx_node, unlinked_nodes, ctx_node_type)) {
rc = -1;
goto cleanup;
}
}
if (rc) {
if (rc == 1) {
LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(sparent)->cond);
}
goto cleanup;
}
lyxp_set_cast(&set, LYXP_SET_BOOLEAN, ctx_node, lys_node_module(sparent), LYXP_WHEN);
if (!set.val.bool) {
if ((ignore_fail == 1) || ((snode_get_when(sparent)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP))
&& (ignore_fail == 2))) {
LOGVRB("When condition \"%s\" is not satisfied, but it is not required.", snode_get_when(sparent)->cond);
} else {
node->when_status |= LYD_WHEN_FALSE;
LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(sparent)->cond);
if (failed_when) {
*failed_when = snode_get_when(sparent);
}
goto cleanup;
}
}
/* free xpath set content */
lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node, lys_node_module(sparent), 0);
}
check_augment:
if ((sparent->parent && (sparent->parent->nodetype == LYS_AUGMENT) && snode_get_when(sparent->parent))) {
if (!ctx_node) {
rc = resolve_when_ctx_node(node, sparent->parent, &ctx_node, &ctx_node_type);
if (rc) {
LOGINT(ctx);
goto cleanup;
}
}
unlinked_nodes = NULL;
tmp_node = node;
rc = resolve_when_unlink_nodes(sparent->parent, &tmp_node, &ctx_node, ctx_node_type, &unlinked_nodes);
if (rc) {
goto cleanup;
}
rc = lyxp_eval(snode_get_when(sparent->parent)->cond, ctx_node, ctx_node_type,
lys_node_module(sparent->parent), &set, LYXP_WHEN);
/* reconnect nodes, if ctx_node is NULL then all the nodes were unlinked, but linked together,
* so the tree did not actually change and there is nothing for us to do
*/
if (unlinked_nodes && ctx_node) {
if (resolve_when_relink_nodes(ctx_node, unlinked_nodes, ctx_node_type)) {
rc = -1;
goto cleanup;
}
}
if (rc) {
if (rc == 1) {
LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(sparent->parent)->cond);
}
goto cleanup;
}
lyxp_set_cast(&set, LYXP_SET_BOOLEAN, ctx_node, lys_node_module(sparent->parent), LYXP_WHEN);
if (!set.val.bool) {
node->when_status |= LYD_WHEN_FALSE;
if ((ignore_fail == 1) || ((snode_get_when(sparent->parent)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP))
&& (ignore_fail == 2))) {
LOGVRB("When condition \"%s\" is not satisfied, but it is not required.",
snode_get_when(sparent->parent)->cond);
} else {
LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(sparent->parent)->cond);
if (failed_when) {
*failed_when = snode_get_when(sparent->parent);
}
goto cleanup;
}
}
/* free xpath set content */
lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node, lys_node_module(sparent->parent), 0);
}
sparent = lys_parent(sparent);
}
node->when_status |= LYD_WHEN_TRUE;
cleanup:
/* free xpath set content */
lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node ? ctx_node : node, NULL, 0);
return rc;
}
static int
check_type_union_leafref(struct lys_type *type)
{
uint8_t i;
if ((type->base == LY_TYPE_UNION) && type->info.uni.count) {
/* go through unions and look for leafref */
for (i = 0; i < type->info.uni.count; ++i) {
switch (type->info.uni.types[i].base) {
case LY_TYPE_LEAFREF:
return 1;
case LY_TYPE_UNION:
if (check_type_union_leafref(&type->info.uni.types[i])) {
return 1;
}
break;
default:
break;
}
}
return 0;
}
/* just inherit the flag value */
return type->der->has_union_leafref;
}
/**
* @brief Resolve a single unres schema item. Logs indirectly.
*
* @param[in] mod Main module.
* @param[in] item Item to resolve. Type determined by \p type.
* @param[in] type Type of the unresolved item.
* @param[in] str_snode String, a schema node, or NULL.
* @param[in] unres Unres schema structure to use.
* @param[in] final_fail Whether we are just printing errors of the failed unres items.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_unres_schema_item(struct lys_module *mod, void *item, enum UNRES_ITEM type, void *str_snode,
struct unres_schema *unres)
{
/* has_str - whether the str_snode is a string in a dictionary that needs to be freed */
int rc = -1, has_str = 0, parent_type = 0, i, k;
unsigned int j;
struct ly_ctx * ctx = mod->ctx;
struct lys_node *root, *next, *node, *par_grp;
const char *expr;
uint8_t *u;
struct ly_set *refs, *procs;
struct lys_feature *ref, *feat;
struct lys_ident *ident;
struct lys_type *stype;
struct lys_node_choice *choic;
struct lyxml_elem *yin;
struct yang_type *yang;
struct unres_list_uniq *unique_info;
struct unres_iffeat_data *iff_data;
struct unres_ext *ext_data;
struct lys_ext_instance *ext, **extlist;
struct lyext_plugin *eplugin;
switch (type) {
case UNRES_IDENT:
expr = str_snode;
has_str = 1;
ident = item;
rc = resolve_base_ident(mod, ident, expr, "identity", NULL, unres);
break;
case UNRES_TYPE_IDENTREF:
expr = str_snode;
has_str = 1;
stype = item;
rc = resolve_base_ident(mod, NULL, expr, "type", stype, unres);
break;
case UNRES_TYPE_LEAFREF:
node = str_snode;
stype = item;
rc = resolve_schema_leafref(stype, node, unres);
break;
case UNRES_TYPE_DER_EXT:
parent_type++;
/* falls through */
case UNRES_TYPE_DER_TPDF:
parent_type++;
/* falls through */
case UNRES_TYPE_DER:
/* parent */
node = str_snode;
stype = item;
/* HACK type->der is temporarily unparsed type statement */
yin = (struct lyxml_elem *)stype->der;
stype->der = NULL;
if (yin->flags & LY_YANG_STRUCTURE_FLAG) {
yang = (struct yang_type *)yin;
rc = yang_check_type(mod, node, yang, stype, parent_type, unres);
if (rc) {
/* may try again later */
stype->der = (struct lys_tpdf *)yang;
} else {
/* we need to always be able to free this, it's safe only in this case */
lydict_remove(ctx, yang->name);
free(yang);
}
} else {
rc = fill_yin_type(mod, node, yin, stype, parent_type, unres);
if (!rc || rc == -1) {
/* we need to always be able to free this, it's safe only in this case */
lyxml_free(ctx, yin);
} else {
/* may try again later, put all back how it was */
stype->der = (struct lys_tpdf *)yin;
}
}
if (rc == EXIT_SUCCESS) {
/* it does not make sense to have leaf-list of empty type */
if (!parent_type && node->nodetype == LYS_LEAFLIST && stype->base == LY_TYPE_EMPTY) {
LOGWRN(ctx, "The leaf-list \"%s\" is of \"empty\" type, which does not make sense.", node->name);
}
if ((type == UNRES_TYPE_DER_TPDF) && (stype->base == LY_TYPE_UNION)) {
/* fill typedef union leafref flag */
((struct lys_tpdf *)stype->parent)->has_union_leafref = check_type_union_leafref(stype);
} else if ((type == UNRES_TYPE_DER) && stype->der->has_union_leafref) {
/* copy the type in case it has union leafref flag */
if (lys_copy_union_leafrefs(mod, node, stype, NULL, unres)) {
LOGERR(ctx, LY_EINT, "Failed to duplicate type.");
return -1;
}
}
} else if (rc == EXIT_FAILURE && !(stype->value_flags & LY_VALUE_UNRESGRP)) {
/* forward reference - in case the type is in grouping, we have to make the grouping unusable
* by uses statement until the type is resolved. We do that the same way as uses statements inside
* grouping. The grouping cannot be used unless the unres counter is 0.
* To remember that the grouping already increased the counter, the LYTYPE_GRP is used as value
* of the type's base member. */
for (par_grp = node; par_grp && (par_grp->nodetype != LYS_GROUPING); par_grp = lys_parent(par_grp));
if (par_grp) {
if (++((struct lys_node_grp *)par_grp)->unres_count == 0) {
LOGERR(ctx, LY_EINT, "Too many unresolved items (type) inside a grouping.");
return -1;
}
stype->value_flags |= LY_VALUE_UNRESGRP;
}
}
break;
case UNRES_IFFEAT:
iff_data = str_snode;
rc = resolve_feature(iff_data->fname, strlen(iff_data->fname), iff_data->node, item);
if (!rc) {
/* success */
if (iff_data->infeature) {
/* store backlink into the target feature to allow reverse changes in case of changing feature status */
feat = *((struct lys_feature **)item);
if (!feat->depfeatures) {
feat->depfeatures = ly_set_new();
}
ly_set_add(feat->depfeatures, iff_data->node, LY_SET_OPT_USEASLIST);
}
/* cleanup temporary data */
lydict_remove(ctx, iff_data->fname);
free(iff_data);
}
break;
case UNRES_FEATURE:
feat = (struct lys_feature *)item;
if (feat->iffeature_size) {
refs = ly_set_new();
procs = ly_set_new();
ly_set_add(procs, feat, 0);
while (procs->number) {
ref = procs->set.g[procs->number - 1];
ly_set_rm_index(procs, procs->number - 1);
for (i = 0; i < ref->iffeature_size; i++) {
resolve_iffeature_getsizes(&ref->iffeature[i], NULL, &j);
for (; j > 0 ; j--) {
if (ref->iffeature[i].features[j - 1]) {
if (ref->iffeature[i].features[j - 1] == feat) {
LOGVAL(ctx, LYE_CIRC_FEATURES, LY_VLOG_NONE, NULL, feat->name);
goto featurecheckdone;
}
if (ref->iffeature[i].features[j - 1]->iffeature_size) {
k = refs->number;
if (ly_set_add(refs, ref->iffeature[i].features[j - 1], 0) == k) {
/* not yet seen feature, add it for processing */
ly_set_add(procs, ref->iffeature[i].features[j - 1], 0);
}
}
} else {
/* forward reference */
rc = EXIT_FAILURE;
goto featurecheckdone;
}
}
}
}
rc = EXIT_SUCCESS;
featurecheckdone:
ly_set_free(refs);
ly_set_free(procs);
}
break;
case UNRES_USES:
rc = resolve_unres_schema_uses(item, unres);
break;
case UNRES_TYPEDEF_DFLT:
parent_type++;
/* falls through */
case UNRES_TYPE_DFLT:
stype = item;
rc = check_default(stype, (const char **)str_snode, mod, parent_type);
if ((rc == EXIT_FAILURE) && !parent_type && (stype->base == LY_TYPE_LEAFREF)) {
for (par_grp = (struct lys_node *)stype->parent;
par_grp && (par_grp->nodetype != LYS_GROUPING);
par_grp = lys_parent(par_grp));
if (par_grp) {
/* checking default value in a grouping finished with forward reference means we cannot check the value */
rc = EXIT_SUCCESS;
}
}
break;
case UNRES_CHOICE_DFLT:
expr = str_snode;
has_str = 1;
choic = item;
if (!choic->dflt) {
choic->dflt = resolve_choice_dflt(choic, expr);
}
if (choic->dflt) {
rc = lyp_check_mandatory_choice((struct lys_node *)choic);
} else {
rc = EXIT_FAILURE;
}
break;
case UNRES_LIST_KEYS:
rc = resolve_list_keys(item, ((struct lys_node_list *)item)->keys_str);
break;
case UNRES_LIST_UNIQ:
unique_info = (struct unres_list_uniq *)item;
rc = resolve_unique(unique_info->list, unique_info->expr, unique_info->trg_type);
break;
case UNRES_AUGMENT:
rc = resolve_augment(item, NULL, unres);
break;
case UNRES_XPATH:
node = (struct lys_node *)item;
rc = check_xpath(node, 1);
break;
case UNRES_MOD_IMPLEMENT:
rc = lys_make_implemented_r(mod, unres);
break;
case UNRES_EXT:
ext_data = (struct unres_ext *)str_snode;
extlist = &(*(struct lys_ext_instance ***)item)[ext_data->ext_index];
rc = resolve_extension(ext_data, extlist, unres);
if (!rc) {
/* success */
/* is there a callback to be done to finalize the extension? */
eplugin = extlist[0]->def->plugin;
if (eplugin) {
if (eplugin->check_result || (eplugin->flags & LYEXT_OPT_INHERIT)) {
u = malloc(sizeof *u);
LY_CHECK_ERR_RETURN(!u, LOGMEM(ctx), -1);
(*u) = ext_data->ext_index;
if (unres_schema_add_node(mod, unres, item, UNRES_EXT_FINALIZE, (struct lys_node *)u) == -1) {
/* something really bad happend since the extension finalization is not actually
* being resolved while adding into unres, so something more serious with the unres
* list itself must happened */
return -1;
}
}
}
}
if (!rc || rc == -1) {
/* cleanup on success or fatal error */
if (ext_data->datatype == LYS_IN_YIN) {
/* YIN */
lyxml_free(ctx, ext_data->data.yin);
} else {
/* YANG */
yang_free_ext_data(ext_data->data.yang);
}
free(ext_data);
}
break;
case UNRES_EXT_FINALIZE:
u = (uint8_t *)str_snode;
ext = (*(struct lys_ext_instance ***)item)[*u];
free(u);
eplugin = ext->def->plugin;
/* inherit */
if ((eplugin->flags & LYEXT_OPT_INHERIT) && (ext->parent_type == LYEXT_PAR_NODE)) {
root = (struct lys_node *)ext->parent;
if (!(root->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
LY_TREE_DFS_BEGIN(root->child, next, node) {
/* first, check if the node already contain instance of the same extension,
* in such a case we won't inherit. In case the node was actually defined as
* augment data, we are supposed to check the same way also the augment node itself */
if (lys_ext_instance_presence(ext->def, node->ext, node->ext_size) != -1) {
goto inherit_dfs_sibling;
} else if (node->parent != root && node->parent->nodetype == LYS_AUGMENT &&
lys_ext_instance_presence(ext->def, node->parent->ext, node->parent->ext_size) != -1) {
goto inherit_dfs_sibling;
}
if (eplugin->check_inherit) {
/* we have a callback to check the inheritance, use it */
switch ((rc = (*eplugin->check_inherit)(ext, node))) {
case 0:
/* yes - continue with the inheriting code */
break;
case 1:
/* no - continue with the node's sibling */
goto inherit_dfs_sibling;
case 2:
/* no, but continue with the children, just skip the inheriting code for this node */
goto inherit_dfs_child;
default:
LOGERR(ctx, LY_EINT, "Plugin's (%s:%s) check_inherit callback returns invalid value (%d),",
ext->def->module->name, ext->def->name, rc);
}
}
/* inherit the extension */
extlist = realloc(node->ext, (node->ext_size + 1) * sizeof *node->ext);
LY_CHECK_ERR_RETURN(!extlist, LOGMEM(ctx), -1);
extlist[node->ext_size] = malloc(sizeof **extlist);
LY_CHECK_ERR_RETURN(!extlist[node->ext_size], LOGMEM(ctx); node->ext = extlist, -1);
memcpy(extlist[node->ext_size], ext, sizeof *ext);
extlist[node->ext_size]->flags |= LYEXT_OPT_INHERIT;
node->ext = extlist;
node->ext_size++;
inherit_dfs_child:
/* modification of - select element for the next run - children first */
if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
next = NULL;
} else {
next = node->child;
}
if (!next) {
inherit_dfs_sibling:
/* no children, try siblings */
next = node->next;
}
while (!next) {
/* go to the parent */
node = lys_parent(node);
/* we are done if we are back in the root (the starter's parent */
if (node == root) {
break;
}
/* parent is already processed, go to its sibling */
next = node->next;
}
}
}
}
/* final check */
if (eplugin->check_result) {
if ((*eplugin->check_result)(ext)) {
LOGERR(ctx, LY_EPLUGIN, "Resolving extension failed.");
return -1;
}
}
rc = 0;
break;
default:
LOGINT(ctx);
break;
}
if (has_str && !rc) {
/* the string is no more needed in case of success.
* In case of forward reference, we will try to resolve the string later */
lydict_remove(ctx, str_snode);
}
return rc;
}
/* logs directly */
static void
print_unres_schema_item_fail(void *item, enum UNRES_ITEM type, void *str_node)
{
struct lyxml_elem *xml;
struct lyxml_attr *attr;
struct unres_iffeat_data *iff_data;
const char *name = NULL;
struct unres_ext *extinfo;
switch (type) {
case UNRES_IDENT:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "identity", (char *)str_node);
break;
case UNRES_TYPE_IDENTREF:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "identityref", (char *)str_node);
break;
case UNRES_TYPE_LEAFREF:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "leafref",
((struct lys_type *)item)->info.lref.path);
break;
case UNRES_TYPE_DER_EXT:
case UNRES_TYPE_DER_TPDF:
case UNRES_TYPE_DER:
xml = (struct lyxml_elem *)((struct lys_type *)item)->der;
if (xml->flags & LY_YANG_STRUCTURE_FLAG) {
name = ((struct yang_type *)xml)->name;
} else {
LY_TREE_FOR(xml->attr, attr) {
if ((attr->type == LYXML_ATTR_STD) && !strcmp(attr->name, "name")) {
name = attr->value;
break;
}
}
assert(attr);
}
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "derived type", name);
break;
case UNRES_IFFEAT:
iff_data = str_node;
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "if-feature", iff_data->fname);
break;
case UNRES_FEATURE:
LOGVRB("There are unresolved if-features for \"%s\" feature circular dependency check, it will be attempted later",
((struct lys_feature *)item)->name);
break;
case UNRES_USES:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "uses", ((struct lys_node_uses *)item)->name);
break;
case UNRES_TYPEDEF_DFLT:
case UNRES_TYPE_DFLT:
if (*(char **)str_node) {
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "type default", *(char **)str_node);
} /* else no default value in the type itself, but we are checking some restrictions against
* possible default value of some base type. The failure is caused by not resolved base type,
* so it was already reported */
break;
case UNRES_CHOICE_DFLT:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "choice default", (char *)str_node);
break;
case UNRES_LIST_KEYS:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "list keys", (char *)str_node);
break;
case UNRES_LIST_UNIQ:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "list unique", (char *)str_node);
break;
case UNRES_AUGMENT:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "augment target",
((struct lys_node_augment *)item)->target_name);
break;
case UNRES_XPATH:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "XPath expressions of",
((struct lys_node *)item)->name);
break;
case UNRES_EXT:
extinfo = (struct unres_ext *)str_node;
name = extinfo->datatype == LYS_IN_YIN ? extinfo->data.yin->name : NULL; /* TODO YANG extension */
LOGVRB("Resolving extension \"%s\" failed, it will be attempted later.", name);
break;
default:
LOGINT(NULL);
break;
}
}
static int
resolve_unres_schema_types(struct unres_schema *unres, enum UNRES_ITEM types, struct ly_ctx *ctx, int forward_ref,
int print_all_errors, uint32_t *resolved)
{
uint32_t i, unres_count, res_count;
int ret = 0, rc;
struct ly_err_item *prev_eitem;
enum int_log_opts prev_ilo;
LY_ERR prev_ly_errno;
/* if there can be no forward references, every failure is final, so we can print it directly */
if (forward_ref) {
prev_ly_errno = ly_errno;
ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem);
}
do {
unres_count = 0;
res_count = 0;
for (i = 0; i < unres->count; ++i) {
/* UNRES_TYPE_LEAFREF must be resolved (for storing leafref target pointers);
* if-features are resolved here to make sure that we will have all if-features for
* later check of feature circular dependency */
if (unres->type[i] & types) {
++unres_count;
rc = resolve_unres_schema_item(unres->module[i], unres->item[i], unres->type[i], unres->str_snode[i], unres);
if (unres->type[i] == UNRES_EXT_FINALIZE) {
/* to avoid double free */
unres->type[i] = UNRES_RESOLVED;
}
if (!rc || (unres->type[i] == UNRES_XPATH)) {
/* invalid XPath can never cause an error, only a warning */
if (unres->type[i] == UNRES_LIST_UNIQ) {
/* free the allocated structure */
free(unres->item[i]);
}
unres->type[i] = UNRES_RESOLVED;
++(*resolved);
++res_count;
} else if ((rc == EXIT_FAILURE) && forward_ref) {
/* forward reference, erase errors */
ly_err_free_next(ctx, prev_eitem);
} else if (print_all_errors) {
/* just so that we quit the loop */
++res_count;
ret = -1;
} else {
if (forward_ref) {
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 1);
}
return -1;
}
}
}
} while (res_count && (res_count < unres_count));
if (res_count < unres_count) {
assert(forward_ref);
/* just print the errors (but we must free the ones we have and get them again :-/ ) */
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0);
for (i = 0; i < unres->count; ++i) {
if (unres->type[i] & types) {
resolve_unres_schema_item(unres->module[i], unres->item[i], unres->type[i], unres->str_snode[i], unres);
}
}
return -1;
}
if (forward_ref) {
/* restore log */
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0);
ly_errno = prev_ly_errno;
}
return ret;
}
/**
* @brief Resolve every unres schema item in the structure. Logs directly.
*
* @param[in] mod Main module.
* @param[in] unres Unres schema structure to use.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
int
resolve_unres_schema(struct lys_module *mod, struct unres_schema *unres)
{
uint32_t resolved = 0;
assert(unres);
LOGVRB("Resolving \"%s\" unresolved schema nodes and their constraints...", mod->name);
/* UNRES_TYPE_LEAFREF must be resolved (for storing leafref target pointers);
* if-features are resolved here to make sure that we will have all if-features for
* later check of feature circular dependency */
if (resolve_unres_schema_types(unres, UNRES_USES | UNRES_IFFEAT | UNRES_TYPE_DER | UNRES_TYPE_DER_TPDF | UNRES_TYPE_DER_TPDF
| UNRES_TYPE_LEAFREF | UNRES_MOD_IMPLEMENT | UNRES_AUGMENT | UNRES_CHOICE_DFLT | UNRES_IDENT,
mod->ctx, 1, 0, &resolved)) {
return -1;
}
/* another batch of resolved items */
if (resolve_unres_schema_types(unres, UNRES_TYPE_IDENTREF | UNRES_FEATURE | UNRES_TYPEDEF_DFLT | UNRES_TYPE_DFLT
| UNRES_LIST_KEYS | UNRES_LIST_UNIQ | UNRES_EXT, mod->ctx, 1, 0, &resolved)) {
return -1;
}
/* print xpath warnings and finalize extensions, keep it last to provide the complete schema tree information to the plugin's checkers */
if (resolve_unres_schema_types(unres, UNRES_XPATH | UNRES_EXT_FINALIZE, mod->ctx, 0, 1, &resolved)) {
return -1;
}
LOGVRB("All \"%s\" schema nodes and constraints resolved.", mod->name);
unres->count = 0;
return EXIT_SUCCESS;
}
/**
* @brief Try to resolve an unres schema item with a string argument. Logs indirectly.
*
* @param[in] mod Main module.
* @param[in] unres Unres schema structure to use.
* @param[in] item Item to resolve. Type determined by \p type.
* @param[in] type Type of the unresolved item.
* @param[in] str String argument.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on storing the item in unres, -1 on error.
*/
int
unres_schema_add_str(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type,
const char *str)
{
int rc;
const char *dictstr;
dictstr = lydict_insert(mod->ctx, str, 0);
rc = unres_schema_add_node(mod, unres, item, type, (struct lys_node *)dictstr);
if (rc < 0) {
lydict_remove(mod->ctx, dictstr);
}
return rc;
}
/**
* @brief Try to resolve an unres schema item with a schema node argument. Logs indirectly.
*
* @param[in] mod Main module.
* @param[in] unres Unres schema structure to use.
* @param[in] item Item to resolve. Type determined by \p type.
* @param[in] type Type of the unresolved item. UNRES_TYPE_DER is handled specially!
* @param[in] snode Schema node argument.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on storing the item in unres, -1 on error.
*/
int
unres_schema_add_node(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type,
struct lys_node *snode)
{
int rc;
uint32_t u;
enum int_log_opts prev_ilo;
struct ly_err_item *prev_eitem;
LY_ERR prev_ly_errno;
struct lyxml_elem *yin;
struct ly_ctx *ctx = mod->ctx;
assert(unres && (item || (type == UNRES_MOD_IMPLEMENT)) && ((type != UNRES_LEAFREF) && (type != UNRES_INSTID)
&& (type != UNRES_WHEN) && (type != UNRES_MUST)));
/* check for duplicities in unres */
for (u = 0; u < unres->count; u++) {
if (unres->type[u] == type && unres->item[u] == item &&
unres->str_snode[u] == snode && unres->module[u] == mod) {
/* duplication can happen when the node contains multiple statements of the same type to check,
* this can happen for example when refinement is being applied, so we just postpone the processing
* and do not duplicate the information */
return EXIT_FAILURE;
}
}
if ((type == UNRES_EXT_FINALIZE) || (type == UNRES_XPATH) || (type == UNRES_MOD_IMPLEMENT)) {
/* extension finalization is not even tried when adding the item into the inres list,
* xpath is not tried because it would hide some potential warnings,
* implementing module must be deferred because some other nodes can be added that will need to be traversed
* and their targets made implemented */
rc = EXIT_FAILURE;
} else {
prev_ly_errno = ly_errno;
ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem);
rc = resolve_unres_schema_item(mod, item, type, snode, unres);
if (rc != EXIT_FAILURE) {
ly_ilo_restore(ctx, prev_ilo, prev_eitem, rc == -1 ? 1 : 0);
if (rc != -1) {
ly_errno = prev_ly_errno;
}
if (type == UNRES_LIST_UNIQ) {
/* free the allocated structure */
free(item);
} else if (rc == -1 && type == UNRES_IFFEAT) {
/* free the allocated resources */
free(*((char **)item));
}
return rc;
} else {
/* erase info about validation errors */
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0);
ly_errno = prev_ly_errno;
}
print_unres_schema_item_fail(item, type, snode);
/* HACK unlinking is performed here so that we do not do any (NS) copying in vain */
if (type == UNRES_TYPE_DER || type == UNRES_TYPE_DER_TPDF) {
yin = (struct lyxml_elem *)((struct lys_type *)item)->der;
if (!(yin->flags & LY_YANG_STRUCTURE_FLAG)) {
lyxml_unlink_elem(mod->ctx, yin, 1);
((struct lys_type *)item)->der = (struct lys_tpdf *)yin;
}
}
}
unres->count++;
unres->item = ly_realloc(unres->item, unres->count*sizeof *unres->item);
LY_CHECK_ERR_RETURN(!unres->item, LOGMEM(ctx), -1);
unres->item[unres->count-1] = item;
unres->type = ly_realloc(unres->type, unres->count*sizeof *unres->type);
LY_CHECK_ERR_RETURN(!unres->type, LOGMEM(ctx), -1);
unres->type[unres->count-1] = type;
unres->str_snode = ly_realloc(unres->str_snode, unres->count*sizeof *unres->str_snode);
LY_CHECK_ERR_RETURN(!unres->str_snode, LOGMEM(ctx), -1);
unres->str_snode[unres->count-1] = snode;
unres->module = ly_realloc(unres->module, unres->count*sizeof *unres->module);
LY_CHECK_ERR_RETURN(!unres->module, LOGMEM(ctx), -1);
unres->module[unres->count-1] = mod;
return rc;
}
/**
* @brief Duplicate an unres schema item. Logs indirectly.
*
* @param[in] mod Main module.
* @param[in] unres Unres schema structure to use.
* @param[in] item Old item to be resolved.
* @param[in] type Type of the old unresolved item.
* @param[in] new_item New item to use in the duplicate.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE if item is not in unres, -1 on error.
*/
int
unres_schema_dup(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type, void *new_item)
{
int i;
struct unres_list_uniq aux_uniq;
struct unres_iffeat_data *iff_data;
assert(item && new_item && ((type != UNRES_LEAFREF) && (type != UNRES_INSTID) && (type != UNRES_WHEN)));
/* hack for UNRES_LIST_UNIQ, which stores multiple items behind its item */
if (type == UNRES_LIST_UNIQ) {
aux_uniq.list = item;
aux_uniq.expr = ((struct unres_list_uniq *)new_item)->expr;
item = &aux_uniq;
}
i = unres_schema_find(unres, -1, item, type);
if (i == -1) {
if (type == UNRES_LIST_UNIQ) {
free(new_item);
}
return EXIT_FAILURE;
}
if ((type == UNRES_TYPE_LEAFREF) || (type == UNRES_USES) || (type == UNRES_TYPE_DFLT) ||
(type == UNRES_FEATURE) || (type == UNRES_LIST_UNIQ)) {
if (unres_schema_add_node(mod, unres, new_item, type, unres->str_snode[i]) == -1) {
LOGINT(mod->ctx);
return -1;
}
} else if (type == UNRES_IFFEAT) {
/* duplicate unres_iffeature_data */
iff_data = malloc(sizeof *iff_data);
LY_CHECK_ERR_RETURN(!iff_data, LOGMEM(mod->ctx), -1);
iff_data->fname = lydict_insert(mod->ctx, ((struct unres_iffeat_data *)unres->str_snode[i])->fname, 0);
iff_data->node = ((struct unres_iffeat_data *)unres->str_snode[i])->node;
if (unres_schema_add_node(mod, unres, new_item, type, (struct lys_node *)iff_data) == -1) {
LOGINT(mod->ctx);
return -1;
}
} else {
if (unres_schema_add_str(mod, unres, new_item, type, unres->str_snode[i]) == -1) {
LOGINT(mod->ctx);
return -1;
}
}
return EXIT_SUCCESS;
}
/* does not log */
int
unres_schema_find(struct unres_schema *unres, int start_on_backwards, void *item, enum UNRES_ITEM type)
{
int i;
struct unres_list_uniq *aux_uniq1, *aux_uniq2;
if (!unres->count) {
return -1;
}
if (start_on_backwards >= 0) {
i = start_on_backwards;
} else {
i = unres->count - 1;
}
for (; i > -1; i--) {
if (unres->type[i] != type) {
continue;
}
if (type != UNRES_LIST_UNIQ) {
if (unres->item[i] == item) {
break;
}
} else {
aux_uniq1 = (struct unres_list_uniq *)unres->item[i];
aux_uniq2 = (struct unres_list_uniq *)item;
if ((aux_uniq1->list == aux_uniq2->list) && ly_strequal(aux_uniq1->expr, aux_uniq2->expr, 0)) {
break;
}
}
}
return i;
}
static void
unres_schema_free_item(struct ly_ctx *ctx, struct unres_schema *unres, uint32_t i)
{
struct lyxml_elem *yin;
struct yang_type *yang;
struct unres_iffeat_data *iff_data;
switch (unres->type[i]) {
case UNRES_TYPE_DER_TPDF:
case UNRES_TYPE_DER:
yin = (struct lyxml_elem *)((struct lys_type *)unres->item[i])->der;
if (yin->flags & LY_YANG_STRUCTURE_FLAG) {
yang =(struct yang_type *)yin;
((struct lys_type *)unres->item[i])->base = yang->base;
lydict_remove(ctx, yang->name);
free(yang);
if (((struct lys_type *)unres->item[i])->base == LY_TYPE_UNION) {
yang_free_type_union(ctx, (struct lys_type *)unres->item[i]);
}
} else {
lyxml_free(ctx, yin);
}
break;
case UNRES_IFFEAT:
iff_data = (struct unres_iffeat_data *)unres->str_snode[i];
lydict_remove(ctx, iff_data->fname);
free(unres->str_snode[i]);
break;
case UNRES_IDENT:
case UNRES_TYPE_IDENTREF:
case UNRES_CHOICE_DFLT:
case UNRES_LIST_KEYS:
lydict_remove(ctx, (const char *)unres->str_snode[i]);
break;
case UNRES_LIST_UNIQ:
free(unres->item[i]);
break;
case UNRES_EXT:
free(unres->str_snode[i]);
break;
case UNRES_EXT_FINALIZE:
free(unres->str_snode[i]);
default:
break;
}
unres->type[i] = UNRES_RESOLVED;
}
void
unres_schema_free(struct lys_module *module, struct unres_schema **unres, int all)
{
uint32_t i;
unsigned int unresolved = 0;
if (!unres || !(*unres)) {
return;
}
assert(module || ((*unres)->count == 0));
for (i = 0; i < (*unres)->count; ++i) {
if (!all && ((*unres)->module[i] != module)) {
if ((*unres)->type[i] != UNRES_RESOLVED) {
unresolved++;
}
continue;
}
/* free heap memory for the specific item */
unres_schema_free_item(module->ctx, *unres, i);
}
/* free it all */
if (!module || all || (!unresolved && !module->type)) {
free((*unres)->item);
free((*unres)->type);
free((*unres)->str_snode);
free((*unres)->module);
free((*unres));
(*unres) = NULL;
}
}
/* check whether instance-identifier points outside its data subtree (for operation it is any node
* outside the operation subtree, otherwise it is a node from a foreign model) */
static int
check_instid_ext_dep(const struct lys_node *sleaf, const char *json_instid)
{
const struct lys_node *op_node, *first_node;
enum int_log_opts prev_ilo;
char *buf, *tmp;
if (!json_instid || !json_instid[0]) {
/* no/empty value */
return 0;
}
for (op_node = lys_parent(sleaf);
op_node && !(op_node->nodetype & (LYS_NOTIF | LYS_RPC | LYS_ACTION));
op_node = lys_parent(op_node));
if (op_node && lys_parent(op_node)) {
/* nested operation - any absolute path is external */
return 1;
}
/* get the first node from the instid */
tmp = strchr(json_instid + 1, '/');
buf = strndup(json_instid, tmp ? (size_t)(tmp - json_instid) : strlen(json_instid));
if (!buf) {
/* so that we do not have to bother with logging, say it is not external */
return 0;
}
/* find the first schema node, do not log */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
first_node = ly_ctx_get_node(NULL, sleaf, buf, 0);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
free(buf);
if (!first_node) {
/* unknown path, say it is external */
return 1;
}
/* based on the first schema node in the path we can decide whether it points to an external tree or not */
if (op_node) {
if (op_node != first_node) {
/* it is a top-level operation, so we're good if it points somewhere inside it */
return 1;
}
} else {
if (lys_node_module(sleaf) != lys_node_module(first_node)) {
/* modules differ */
return 1;
}
}
return 0;
}
/**
* @brief Resolve instance-identifier in JSON data format. Logs directly.
*
* @param[in] data Data node where the path is used
* @param[in] path Instance-identifier node value.
* @param[in,out] ret Resolved instance or NULL.
*
* @return 0 on success (even if unresolved and \p ret is NULL), -1 on error.
*/
static int
resolve_instid(struct lyd_node *data, const char *path, int req_inst, struct lyd_node **ret)
{
int i = 0, j, parsed, cur_idx;
const struct lys_module *mod, *prev_mod = NULL;
struct ly_ctx *ctx = data->schema->module->ctx;
struct lyd_node *root, *node;
const char *model = NULL, *name;
char *str;
int mod_len, name_len, has_predicate;
struct unres_data node_match;
memset(&node_match, 0, sizeof node_match);
*ret = NULL;
/* we need root to resolve absolute path */
for (root = data; root->parent; root = root->parent);
/* we're still parsing it and the pointer is not correct yet */
if (root->prev) {
for (; root->prev->next; root = root->prev);
}
/* search for the instance node */
while (path[i]) {
j = parse_instance_identifier(&path[i], &model, &mod_len, &name, &name_len, &has_predicate);
if (j <= 0) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYD, data, path[i-j], &path[i-j]);
goto error;
}
i += j;
if (model) {
str = strndup(model, mod_len);
if (!str) {
LOGMEM(ctx);
goto error;
}
mod = ly_ctx_get_module(ctx, str, NULL, 1);
if (ctx->data_clb) {
if (!mod) {
mod = ctx->data_clb(ctx, str, NULL, 0, ctx->data_clb_data);
} else if (!mod->implemented) {
mod = ctx->data_clb(ctx, mod->name, mod->ns, LY_MODCLB_NOT_IMPLEMENTED, ctx->data_clb_data);
}
}
free(str);
if (!mod || !mod->implemented || mod->disabled) {
break;
}
} else if (!prev_mod) {
/* first iteration and we are missing module name */
LOGVAL(ctx, LYE_INELEM_LEN, LY_VLOG_LYD, data, name_len, name);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Instance-identifier is missing prefix in the first node.");
goto error;
} else {
mod = prev_mod;
}
if (resolve_data(mod, name, name_len, root, &node_match)) {
/* no instance exists */
break;
}
if (has_predicate) {
/* we have predicate, so the current results must be list or leaf-list */
parsed = j = 0;
/* index of the current node (for lists with position predicates) */
cur_idx = 1;
while (j < (signed)node_match.count) {
node = node_match.node[j];
parsed = resolve_instid_predicate(mod, &path[i], &node, cur_idx);
if (parsed < 1) {
LOGVAL(ctx, LYE_INPRED, LY_VLOG_LYD, data, &path[i - parsed]);
goto error;
}
if (!node) {
/* current node does not satisfy the predicate */
unres_data_del(&node_match, j);
} else {
++j;
}
++cur_idx;
}
i += parsed;
} else if (node_match.count) {
/* check that we are not addressing lists */
for (j = 0; (unsigned)j < node_match.count; ++j) {
if (node_match.node[j]->schema->nodetype == LYS_LIST) {
unres_data_del(&node_match, j--);
}
}
if (!node_match.count) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYD, data, "Instance identifier is missing list keys.");
}
}
prev_mod = mod;
}
if (!node_match.count) {
/* no instance exists */
if (req_inst > -1) {
LOGVAL(ctx, LYE_NOREQINS, LY_VLOG_LYD, data, path);
return EXIT_FAILURE;
}
LOGVRB("There is no instance of \"%s\", but it is not required.", path);
return EXIT_SUCCESS;
} else if (node_match.count > 1) {
/* instance identifier must resolve to a single node */
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, data, path, "data tree");
goto error;
} else {
/* we have required result, remember it and cleanup */
*ret = node_match.node[0];
free(node_match.node);
return EXIT_SUCCESS;
}
error:
/* cleanup */
free(node_match.node);
return -1;
}
static int
resolve_leafref(struct lyd_node_leaf_list *leaf, const char *path, int req_inst, struct lyd_node **ret)
{
struct lyxp_set xp_set;
uint32_t i;
memset(&xp_set, 0, sizeof xp_set);
*ret = NULL;
/* syntax was already checked, so just evaluate the path using standard XPath */
if (lyxp_eval(path, (struct lyd_node *)leaf, LYXP_NODE_ELEM, lyd_node_module((struct lyd_node *)leaf), &xp_set, 0) != EXIT_SUCCESS) {
return -1;
}
if (xp_set.type == LYXP_SET_NODE_SET) {
for (i = 0; i < xp_set.used; ++i) {
if ((xp_set.val.nodes[i].type != LYXP_NODE_ELEM) || !(xp_set.val.nodes[i].node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
continue;
}
/* not that the value is already in canonical form since the parsers does the conversion,
* so we can simply compare just the values */
if (ly_strequal(leaf->value_str, ((struct lyd_node_leaf_list *)xp_set.val.nodes[i].node)->value_str, 1)) {
/* we have the match */
*ret = xp_set.val.nodes[i].node;
break;
}
}
}
lyxp_set_cast(&xp_set, LYXP_SET_EMPTY, (struct lyd_node *)leaf, NULL, 0);
if (!*ret) {
/* reference not found */
if (req_inst > -1) {
LOGVAL(leaf->schema->module->ctx, LYE_NOLEAFREF, LY_VLOG_LYD, leaf, path, leaf->value_str);
return EXIT_FAILURE;
} else {
LOGVRB("There is no leafref \"%s\" with the value \"%s\", but it is not required.", path, leaf->value_str);
}
}
return EXIT_SUCCESS;
}
/* ignore fail because we are parsing edit-config, get, or get-config - but only if the union includes leafref or instid */
int
resolve_union(struct lyd_node_leaf_list *leaf, struct lys_type *type, int store, int ignore_fail,
struct lys_type **resolved_type)
{
struct ly_ctx *ctx = leaf->schema->module->ctx;
struct lys_type *t;
struct lyd_node *ret;
enum int_log_opts prev_ilo;
int found, success = 0, ext_dep, req_inst;
const char *json_val = NULL;
assert(type->base == LY_TYPE_UNION);
if ((leaf->value_type == LY_TYPE_UNION) || ((leaf->value_type == LY_TYPE_INST) && (leaf->value_flags & LY_VALUE_UNRES))) {
/* either NULL or instid previously converted to JSON */
json_val = lydict_insert(ctx, leaf->value.string, 0);
}
if (store) {
lyd_free_value(leaf->value, leaf->value_type, leaf->value_flags, &((struct lys_node_leaf *)leaf->schema)->type,
NULL, NULL, NULL);
memset(&leaf->value, 0, sizeof leaf->value);
}
/* turn logging off, we are going to try to validate the value with all the types in order */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, 0);
t = NULL;
found = 0;
while ((t = lyp_get_next_union_type(type, t, &found))) {
found = 0;
switch (t->base) {
case LY_TYPE_LEAFREF:
if ((ignore_fail == 1) || ((leaf->schema->flags & LYS_LEAFREF_DEP) && (ignore_fail == 2))) {
req_inst = -1;
} else {
req_inst = t->info.lref.req;
}
if (!resolve_leafref(leaf, t->info.lref.path, req_inst, &ret)) {
if (store) {
if (ret && !(leaf->schema->flags & LYS_LEAFREF_DEP)) {
/* valid resolved */
leaf->value.leafref = ret;
leaf->value_type = LY_TYPE_LEAFREF;
} else {
/* valid unresolved */
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!lyp_parse_value(t, &leaf->value_str, NULL, leaf, NULL, NULL, 1, 0, 0)) {
return -1;
}
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
}
}
success = 1;
}
break;
case LY_TYPE_INST:
ext_dep = check_instid_ext_dep(leaf->schema, (json_val ? json_val : leaf->value_str));
if ((ignore_fail == 1) || (ext_dep && (ignore_fail == 2))) {
req_inst = -1;
} else {
req_inst = t->info.inst.req;
}
if (!resolve_instid((struct lyd_node *)leaf, (json_val ? json_val : leaf->value_str), req_inst, &ret)) {
if (store) {
if (ret && !ext_dep) {
/* valid resolved */
leaf->value.instance = ret;
leaf->value_type = LY_TYPE_INST;
if (json_val) {
lydict_remove(leaf->schema->module->ctx, leaf->value_str);
leaf->value_str = json_val;
json_val = NULL;
}
} else {
/* valid unresolved */
if (json_val) {
/* put the JSON val back */
leaf->value.string = json_val;
json_val = NULL;
} else {
leaf->value.instance = NULL;
}
leaf->value_type = LY_TYPE_INST;
leaf->value_flags |= LY_VALUE_UNRES;
}
}
success = 1;
}
break;
default:
if (lyp_parse_value(t, &leaf->value_str, NULL, leaf, NULL, NULL, store, 0, 0)) {
success = 1;
}
break;
}
if (success) {
break;
}
/* erase possible present and invalid value data */
if (store) {
lyd_free_value(leaf->value, leaf->value_type, leaf->value_flags, t, NULL, NULL, NULL);
memset(&leaf->value, 0, sizeof leaf->value);
}
}
/* turn logging back on */
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (json_val) {
if (!success) {
/* put the value back for now */
assert(leaf->value_type == LY_TYPE_UNION);
leaf->value.string = json_val;
} else {
/* value was ultimately useless, but we could not have known */
lydict_remove(leaf->schema->module->ctx, json_val);
}
}
if (success) {
if (resolved_type) {
*resolved_type = t;
}
} else if (!ignore_fail || !type->info.uni.has_ptr_type) {
/* not found and it is required */
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, leaf, leaf->value_str ? leaf->value_str : "", leaf->schema->name);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* @brief Resolve a single unres data item. Logs directly.
*
* @param[in] node Data node to resolve.
* @param[in] type Type of the unresolved item.
* @param[in] ignore_fail 0 - no, 1 - yes, 2 - yes, but only for external dependencies.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
int
resolve_unres_data_item(struct lyd_node *node, enum UNRES_ITEM type, int ignore_fail, struct lys_when **failed_when)
{
int rc, req_inst, ext_dep;
struct lyd_node_leaf_list *leaf;
struct lyd_node *ret;
struct lys_node_leaf *sleaf;
leaf = (struct lyd_node_leaf_list *)node;
sleaf = (struct lys_node_leaf *)leaf->schema;
switch (type) {
case UNRES_LEAFREF:
assert(sleaf->type.base == LY_TYPE_LEAFREF);
assert(leaf->validity & LYD_VAL_LEAFREF);
if ((ignore_fail == 1) || ((leaf->schema->flags & LYS_LEAFREF_DEP) && (ignore_fail == 2))) {
req_inst = -1;
} else {
req_inst = sleaf->type.info.lref.req;
}
rc = resolve_leafref(leaf, sleaf->type.info.lref.path, req_inst, &ret);
if (!rc) {
if (ret && !(leaf->schema->flags & LYS_LEAFREF_DEP)) {
/* valid resolved */
if (leaf->value_type == LY_TYPE_BITS) {
free(leaf->value.bit);
}
leaf->value.leafref = ret;
leaf->value_type = LY_TYPE_LEAFREF;
leaf->value_flags &= ~LY_VALUE_UNRES;
} else {
/* valid unresolved */
if (!(leaf->value_flags & LY_VALUE_UNRES)) {
if (!lyp_parse_value(&sleaf->type, &leaf->value_str, NULL, leaf, NULL, NULL, 1, 0, 0)) {
return -1;
}
}
}
leaf->validity &= ~LYD_VAL_LEAFREF;
} else {
return rc;
}
break;
case UNRES_INSTID:
assert(sleaf->type.base == LY_TYPE_INST);
ext_dep = check_instid_ext_dep(leaf->schema, leaf->value_str);
if (ext_dep == -1) {
return -1;
}
if ((ignore_fail == 1) || (ext_dep && (ignore_fail == 2))) {
req_inst = -1;
} else {
req_inst = sleaf->type.info.inst.req;
}
rc = resolve_instid(node, leaf->value_str, req_inst, &ret);
if (!rc) {
if (ret && !ext_dep) {
/* valid resolved */
leaf->value.instance = ret;
leaf->value_type = LY_TYPE_INST;
leaf->value_flags &= ~LY_VALUE_UNRES;
} else {
/* valid unresolved */
leaf->value.instance = NULL;
leaf->value_type = LY_TYPE_INST;
leaf->value_flags |= LY_VALUE_UNRES;
}
} else {
return rc;
}
break;
case UNRES_UNION:
assert(sleaf->type.base == LY_TYPE_UNION);
return resolve_union(leaf, &sleaf->type, 1, ignore_fail, NULL);
case UNRES_WHEN:
if ((rc = resolve_when(node, ignore_fail, failed_when))) {
return rc;
}
break;
case UNRES_MUST:
if ((rc = resolve_must(node, 0, ignore_fail))) {
return rc;
}
break;
case UNRES_MUST_INOUT:
if ((rc = resolve_must(node, 1, ignore_fail))) {
return rc;
}
break;
case UNRES_UNIQ_LEAVES:
if (lyv_data_unique(node)) {
return -1;
}
break;
default:
LOGINT(NULL);
return -1;
}
return EXIT_SUCCESS;
}
/**
* @brief add data unres item
*
* @param[in] unres Unres data structure to use.
* @param[in] node Data node to use.
*
* @return 0 on success, -1 on error.
*/
int
unres_data_add(struct unres_data *unres, struct lyd_node *node, enum UNRES_ITEM type)
{
assert(unres && node);
assert((type == UNRES_LEAFREF) || (type == UNRES_INSTID) || (type == UNRES_WHEN) || (type == UNRES_MUST)
|| (type == UNRES_MUST_INOUT) || (type == UNRES_UNION) || (type == UNRES_UNIQ_LEAVES));
unres->count++;
unres->node = ly_realloc(unres->node, unres->count * sizeof *unres->node);
LY_CHECK_ERR_RETURN(!unres->node, LOGMEM(NULL), -1);
unres->node[unres->count - 1] = node;
unres->type = ly_realloc(unres->type, unres->count * sizeof *unres->type);
LY_CHECK_ERR_RETURN(!unres->type, LOGMEM(NULL), -1);
unres->type[unres->count - 1] = type;
return 0;
}
static void
resolve_unres_data_autodel_diff(struct unres_data *unres, uint32_t unres_i)
{
struct lyd_node *next, *child, *parent;
uint32_t i;
for (i = 0; i < unres->diff_idx; ++i) {
if (unres->diff->type[i] == LYD_DIFF_DELETED) {
/* only leaf(-list) default could be removed and there is nothing to be checked in that case */
continue;
}
if (unres->diff->second[i] == unres->node[unres_i]) {
/* 1) default value was supposed to be created, but is disabled by when
* -> remove it from diff altogether
*/
unres_data_diff_rem(unres, i);
/* if diff type is CREATED, the value was just a pointer, it can be freed normally (unlike in 4) */
return;
} else {
parent = unres->diff->second[i]->parent;
while (parent && (parent != unres->node[unres_i])) {
parent = parent->parent;
}
if (parent) {
/* 2) default value was supposed to be created but is disabled by when in some parent
* -> remove this default subtree and add the rest into diff as deleted instead in 4)
*/
unres_data_diff_rem(unres, i);
break;
}
LY_TREE_DFS_BEGIN(unres->diff->second[i]->parent, next, child) {
if (child == unres->node[unres_i]) {
/* 3) some default child of a default value was supposed to be created but has false when
* -> the subtree will be freed later and automatically disconnected from the diff parent node
*/
return;
}
LY_TREE_DFS_END(unres->diff->second[i]->parent, next, child);
}
}
}
/* 4) it does not overlap with created default values in any way
* -> just add it into diff as deleted
*/
unres_data_diff_new(unres, unres->node[unres_i], unres->node[unres_i]->parent, 0);
lyd_unlink(unres->node[unres_i]);
/* should not be freed anymore */
unres->node[unres_i] = NULL;
}
/**
* @brief Resolve every unres data item in the structure. Logs directly.
*
* If options include #LYD_OPT_TRUSTED, the data are considered trusted (must conditions are not expected,
* unresolved leafrefs/instids are accepted, when conditions are normally resolved because at least some implicit
* non-presence containers may need to be deleted).
*
* If options includes #LYD_OPT_WHENAUTODEL, the non-default nodes with false when conditions are auto-deleted.
*
* @param[in] ctx Context used.
* @param[in] unres Unres data structure to use.
* @param[in,out] root Root node of the data tree, can be changed due to autodeletion.
* @param[in] options Data options as described above.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
int
resolve_unres_data(struct ly_ctx *ctx, struct unres_data *unres, struct lyd_node **root, int options)
{
uint32_t i, j, first, resolved, del_items, stmt_count;
uint8_t prev_when_status;
int rc, progress, ignore_fail;
enum int_log_opts prev_ilo;
struct ly_err_item *prev_eitem;
LY_ERR prev_ly_errno = ly_errno;
struct lyd_node *parent;
struct lys_when *when;
assert(root);
assert(unres);
if (!unres->count) {
return EXIT_SUCCESS;
}
if (options & (LYD_OPT_NOTIF_FILTER | LYD_OPT_GET | LYD_OPT_GETCONFIG | LYD_OPT_EDIT)) {
ignore_fail = 1;
} else if (options & LYD_OPT_NOEXTDEPS) {
ignore_fail = 2;
} else {
ignore_fail = 0;
}
LOGVRB("Resolving unresolved data nodes and their constraints...");
if (!ignore_fail) {
/* remember logging state only if errors are generated and valid */
ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem);
}
/*
* when-stmt first
*/
first = 1;
stmt_count = 0;
resolved = 0;
del_items = 0;
do {
if (!ignore_fail) {
ly_err_free_next(ctx, prev_eitem);
}
progress = 0;
for (i = 0; i < unres->count; i++) {
if (unres->type[i] != UNRES_WHEN) {
continue;
}
if (first) {
/* count when-stmt nodes in unres list */
stmt_count++;
}
/* resolve when condition only when all parent when conditions are already resolved */
for (parent = unres->node[i]->parent;
parent && LYD_WHEN_DONE(parent->when_status);
parent = parent->parent) {
if (!parent->parent && (parent->when_status & LYD_WHEN_FALSE)) {
/* the parent node was already unlinked, do not resolve this node,
* it will be removed anyway, so just mark it as resolved
*/
unres->node[i]->when_status |= LYD_WHEN_FALSE;
unres->type[i] = UNRES_RESOLVED;
resolved++;
break;
}
}
if (parent) {
continue;
}
prev_when_status = unres->node[i]->when_status;
rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, &when);
if (!rc) {
/* finish with error/delete the node only if when was changed from true to false, an external
* dependency was not required, or it was not provided (the flag would not be passed down otherwise,
* checked in upper functions) */
if ((unres->node[i]->when_status & LYD_WHEN_FALSE)
&& (!(when->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) || !(options & LYD_OPT_NOEXTDEPS))) {
if ((!(prev_when_status & LYD_WHEN_TRUE) || !(options & LYD_OPT_WHENAUTODEL)) && !unres->node[i]->dflt) {
/* false when condition */
goto error;
} /* follows else */
/* auto-delete */
LOGVRB("Auto-deleting node \"%s\" due to when condition (%s)", ly_errpath(ctx), when->cond);
/* only unlink now, the subtree can contain another nodes stored in the unres list */
/* if it has parent non-presence containers that would be empty, we should actually
* remove the container
*/
for (parent = unres->node[i];
parent->parent && parent->parent->schema->nodetype == LYS_CONTAINER;
parent = parent->parent) {
if (((struct lys_node_container *)parent->parent->schema)->presence) {
/* presence container */
break;
}
if (parent->next || parent->prev != parent) {
/* non empty (the child we are in and we are going to remove is not the only child) */
break;
}
}
unres->node[i] = parent;
if (*root && *root == unres->node[i]) {
*root = (*root)->next;
}
lyd_unlink(unres->node[i]);
unres->type[i] = UNRES_DELETE;
del_items++;
/* update the rest of unres items */
for (j = 0; j < unres->count; j++) {
if (unres->type[j] == UNRES_RESOLVED || unres->type[j] == UNRES_DELETE) {
continue;
}
/* test if the node is in subtree to be deleted */
for (parent = unres->node[j]; parent; parent = parent->parent) {
if (parent == unres->node[i]) {
/* yes, it is */
unres->type[j] = UNRES_RESOLVED;
resolved++;
break;
}
}
}
} else {
unres->type[i] = UNRES_RESOLVED;
}
if (!ignore_fail) {
ly_err_free_next(ctx, prev_eitem);
}
resolved++;
progress = 1;
} else if (rc == -1) {
goto error;
} /* else forward reference */
}
first = 0;
} while (progress && resolved < stmt_count);
/* do we have some unresolved when-stmt? */
if (stmt_count > resolved) {
goto error;
}
for (i = 0; del_items && i < unres->count; i++) {
/* we had some when-stmt resulted to false, so now we have to sanitize the unres list */
if (unres->type[i] != UNRES_DELETE) {
continue;
}
if (!unres->node[i]) {
unres->type[i] = UNRES_RESOLVED;
del_items--;
continue;
}
if (unres->store_diff) {
resolve_unres_data_autodel_diff(unres, i);
}
/* really remove the complete subtree */
lyd_free(unres->node[i]);
unres->type[i] = UNRES_RESOLVED;
del_items--;
}
/*
* now leafrefs
*/
if (options & LYD_OPT_TRUSTED) {
/* we want to attempt to resolve leafrefs */
assert(!ignore_fail);
ignore_fail = 1;
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0);
ly_errno = prev_ly_errno;
}
first = 1;
stmt_count = 0;
resolved = 0;
do {
progress = 0;
for (i = 0; i < unres->count; i++) {
if (unres->type[i] != UNRES_LEAFREF) {
continue;
}
if (first) {
/* count leafref nodes in unres list */
stmt_count++;
}
rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, NULL);
if (!rc) {
unres->type[i] = UNRES_RESOLVED;
if (!ignore_fail) {
ly_err_free_next(ctx, prev_eitem);
}
resolved++;
progress = 1;
} else if (rc == -1) {
goto error;
} /* else forward reference */
}
first = 0;
} while (progress && resolved < stmt_count);
/* do we have some unresolved leafrefs? */
if (stmt_count > resolved) {
goto error;
}
if (!ignore_fail) {
/* log normally now, throw away irrelevant errors */
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0);
ly_errno = prev_ly_errno;
}
/*
* rest
*/
for (i = 0; i < unres->count; ++i) {
if (unres->type[i] == UNRES_RESOLVED) {
continue;
}
assert(!(options & LYD_OPT_TRUSTED) || ((unres->type[i] != UNRES_MUST) && (unres->type[i] != UNRES_MUST_INOUT)));
rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, NULL);
if (rc) {
/* since when was already resolved, a forward reference is an error */
return -1;
}
unres->type[i] = UNRES_RESOLVED;
}
LOGVRB("All data nodes and constraints resolved.");
unres->count = 0;
return EXIT_SUCCESS;
error:
if (!ignore_fail) {
/* print all the new errors */
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 1);
/* do not restore ly_errno, it was udpated properly */
}
return -1;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1359_0 |
crossvul-cpp_data_bad_345_4 | /*
* PKCS15 emulation layer for EstEID card.
*
* Copyright (C) 2004, Martin Paljak <martin@martinpaljak.net>
* Copyright (C) 2004, Bud P. Bruegger <bud@comune.grosseto.it>
* Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it>
* Copyright (C) 2003, Olaf Kirch <okir@suse.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#include "internal.h"
#include "opensc.h"
#include "pkcs15.h"
#include "esteid.h"
int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *);
static void
set_string (char **strp, const char *value)
{
if (*strp)
free (*strp);
*strp = value ? strdup (value) : NULL;
}
int
select_esteid_df (sc_card_t * card)
{
int r;
sc_path_t tmppath;
sc_format_path ("3F00EEEE", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "esteid select DF failed");
return r;
}
static int
sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
unsigned char buff[128];
int r, i;
size_t field_length = 0, modulus_length = 0;
sc_path_t tmppath;
set_string (&p15card->tokeninfo->label, "ID-kaart");
set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus");
/* Select application directory */
sc_format_path ("3f00eeee5044", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed");
/* read the serial (document number) */
r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed");
buff[r] = '\0';
set_string (&p15card->tokeninfo->serial_number, (const char *) buff);
p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION
| SC_PKCS15_TOKEN_EID_COMPLIANT
| SC_PKCS15_TOKEN_READONLY;
/* add certificates */
for (i = 0; i < 2; i++) {
static const char *esteid_cert_names[2] = {
"Isikutuvastus",
"Allkirjastamine"};
static char const *esteid_cert_paths[2] = {
"3f00eeeeaace",
"3f00eeeeddce"};
static int esteid_cert_ids[2] = {1, 2};
struct sc_pkcs15_cert_info cert_info;
struct sc_pkcs15_object cert_obj;
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id.value[0] = esteid_cert_ids[i];
cert_info.id.len = 1;
sc_format_path(esteid_cert_paths[i], &cert_info.path);
strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
if (r < 0)
return SC_ERROR_INTERNAL;
if (i == 0) {
sc_pkcs15_cert_t *cert = NULL;
r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert);
if (r < 0)
return SC_ERROR_INTERNAL;
if (cert->key->algorithm == SC_ALGORITHM_EC)
field_length = cert->key->u.ec.params.field_length;
else
modulus_length = cert->key->u.rsa.modulus.len * 8;
if (r == SC_SUCCESS) {
static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }};
u8 *cn_name = NULL;
size_t cn_len = 0;
sc_pkcs15_get_name_from_dn(card->ctx, cert->subject,
cert->subject_len, &cn_oid, &cn_name, &cn_len);
if (cn_len > 0) {
char *token_name = malloc(cn_len+1);
if (token_name) {
memcpy(token_name, cn_name, cn_len);
token_name[cn_len] = '\0';
set_string(&p15card->tokeninfo->label, (const char*)token_name);
free(token_name);
}
}
free(cn_name);
sc_pkcs15_free_certificate(cert);
}
}
}
/* the file with key pin info (tries left) */
sc_format_path ("3f000016", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
if (r < 0)
return SC_ERROR_INTERNAL;
/* add pins */
for (i = 0; i < 3; i++) {
unsigned char tries_left;
static const char *esteid_pin_names[3] = {
"PIN1",
"PIN2",
"PUK" };
static const int esteid_pin_min[3] = {4, 5, 8};
static const int esteid_pin_ref[3] = {1, 2, 0};
static const int esteid_pin_authid[3] = {1, 2, 3};
static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN};
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
/* read the number of tries left for the PIN */
r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
if (r < 0)
return SC_ERROR_INTERNAL;
tries_left = buff[5];
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = esteid_pin_authid[i];
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = esteid_pin_ref[i];
pin_info.attrs.pin.flags = esteid_pin_flags[i];
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = esteid_pin_min[i];
pin_info.attrs.pin.stored_length = 12;
pin_info.attrs.pin.max_length = 12;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = (int)tries_left;
pin_info.max_tries = 3;
strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label));
pin_obj.flags = esteid_pin_flags[i];
/* Link normal PINs with PUK */
if (i < 2) {
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 3;
}
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
/* add private keys */
for (i = 0; i < 2; i++) {
static int prkey_pin[2] = {1, 2};
static const char *prkey_name[2] = {
"Isikutuvastus",
"Allkirjastamine"};
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
memset(&prkey_info, 0, sizeof(prkey_info));
memset(&prkey_obj, 0, sizeof(prkey_obj));
prkey_info.id.len = 1;
prkey_info.id.value[0] = prkey_pin[i];
prkey_info.native = 1;
prkey_info.key_reference = i + 1;
prkey_info.field_length = field_length;
prkey_info.modulus_length = modulus_length;
if (i == 1)
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
else if(field_length > 0) // ECC has sign and derive usage
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE;
else
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT;
strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label));
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = prkey_pin[i];
prkey_obj.user_consent = 0;
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
if(field_length > 0)
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info);
else
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
return SC_SUCCESS;
}
static int esteid_detect_card(sc_pkcs15_card_t *p15card)
{
if (is_esteid_card(p15card->card))
return SC_SUCCESS;
else
return SC_ERROR_WRONG_CARD;
}
int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)
return sc_pkcs15emu_esteid_init(p15card);
else {
int r = esteid_detect_card(p15card);
if (r)
return SC_ERROR_WRONG_CARD;
return sc_pkcs15emu_esteid_init(p15card);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_345_4 |
crossvul-cpp_data_good_5593_0 | /*
* Kernel-based Virtual Machine driver for Linux
*
* derived from drivers/kvm/kvm_main.c
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright (C) 2008 Qumranet, Inc.
* Copyright IBM Corporation, 2008
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Avi Kivity <avi@qumranet.com>
* Yaniv Kamay <yaniv@qumranet.com>
* Amit Shah <amit.shah@qumranet.com>
* Ben-Ami Yassour <benami@il.ibm.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include <linux/kvm_host.h>
#include "irq.h"
#include "mmu.h"
#include "i8254.h"
#include "tss.h"
#include "kvm_cache_regs.h"
#include "x86.h"
#include "cpuid.h"
#include <linux/clocksource.h>
#include <linux/interrupt.h>
#include <linux/kvm.h>
#include <linux/fs.h>
#include <linux/vmalloc.h>
#include <linux/module.h>
#include <linux/mman.h>
#include <linux/highmem.h>
#include <linux/iommu.h>
#include <linux/intel-iommu.h>
#include <linux/cpufreq.h>
#include <linux/user-return-notifier.h>
#include <linux/srcu.h>
#include <linux/slab.h>
#include <linux/perf_event.h>
#include <linux/uaccess.h>
#include <linux/hash.h>
#include <linux/pci.h>
#include <linux/timekeeper_internal.h>
#include <linux/pvclock_gtod.h>
#include <trace/events/kvm.h>
#define CREATE_TRACE_POINTS
#include "trace.h"
#include <asm/debugreg.h>
#include <asm/msr.h>
#include <asm/desc.h>
#include <asm/mtrr.h>
#include <asm/mce.h>
#include <asm/i387.h>
#include <asm/fpu-internal.h> /* Ugh! */
#include <asm/xcr.h>
#include <asm/pvclock.h>
#include <asm/div64.h>
#define MAX_IO_MSRS 256
#define KVM_MAX_MCE_BANKS 32
#define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
#define emul_to_vcpu(ctxt) \
container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
/* EFER defaults:
* - enable syscall per default because its emulated by KVM
* - enable LME and LMA per default on 64 bit KVM
*/
#ifdef CONFIG_X86_64
static
u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
#else
static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
#endif
#define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
#define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
static void update_cr8_intercept(struct kvm_vcpu *vcpu);
static void process_nmi(struct kvm_vcpu *vcpu);
struct kvm_x86_ops *kvm_x86_ops;
EXPORT_SYMBOL_GPL(kvm_x86_ops);
static bool ignore_msrs = 0;
module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
bool kvm_has_tsc_control;
EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
u32 kvm_max_guest_tsc_khz;
EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
/* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
static u32 tsc_tolerance_ppm = 250;
module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
#define KVM_NR_SHARED_MSRS 16
struct kvm_shared_msrs_global {
int nr;
u32 msrs[KVM_NR_SHARED_MSRS];
};
struct kvm_shared_msrs {
struct user_return_notifier urn;
bool registered;
struct kvm_shared_msr_values {
u64 host;
u64 curr;
} values[KVM_NR_SHARED_MSRS];
};
static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
static struct kvm_shared_msrs __percpu *shared_msrs;
struct kvm_stats_debugfs_item debugfs_entries[] = {
{ "pf_fixed", VCPU_STAT(pf_fixed) },
{ "pf_guest", VCPU_STAT(pf_guest) },
{ "tlb_flush", VCPU_STAT(tlb_flush) },
{ "invlpg", VCPU_STAT(invlpg) },
{ "exits", VCPU_STAT(exits) },
{ "io_exits", VCPU_STAT(io_exits) },
{ "mmio_exits", VCPU_STAT(mmio_exits) },
{ "signal_exits", VCPU_STAT(signal_exits) },
{ "irq_window", VCPU_STAT(irq_window_exits) },
{ "nmi_window", VCPU_STAT(nmi_window_exits) },
{ "halt_exits", VCPU_STAT(halt_exits) },
{ "halt_wakeup", VCPU_STAT(halt_wakeup) },
{ "hypercalls", VCPU_STAT(hypercalls) },
{ "request_irq", VCPU_STAT(request_irq_exits) },
{ "irq_exits", VCPU_STAT(irq_exits) },
{ "host_state_reload", VCPU_STAT(host_state_reload) },
{ "efer_reload", VCPU_STAT(efer_reload) },
{ "fpu_reload", VCPU_STAT(fpu_reload) },
{ "insn_emulation", VCPU_STAT(insn_emulation) },
{ "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
{ "irq_injections", VCPU_STAT(irq_injections) },
{ "nmi_injections", VCPU_STAT(nmi_injections) },
{ "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
{ "mmu_pte_write", VM_STAT(mmu_pte_write) },
{ "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
{ "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
{ "mmu_flooded", VM_STAT(mmu_flooded) },
{ "mmu_recycled", VM_STAT(mmu_recycled) },
{ "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
{ "mmu_unsync", VM_STAT(mmu_unsync) },
{ "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
{ "largepages", VM_STAT(lpages) },
{ NULL }
};
u64 __read_mostly host_xcr0;
static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
static int kvm_vcpu_reset(struct kvm_vcpu *vcpu);
static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
{
int i;
for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
vcpu->arch.apf.gfns[i] = ~0;
}
static void kvm_on_user_return(struct user_return_notifier *urn)
{
unsigned slot;
struct kvm_shared_msrs *locals
= container_of(urn, struct kvm_shared_msrs, urn);
struct kvm_shared_msr_values *values;
for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
values = &locals->values[slot];
if (values->host != values->curr) {
wrmsrl(shared_msrs_global.msrs[slot], values->host);
values->curr = values->host;
}
}
locals->registered = false;
user_return_notifier_unregister(urn);
}
static void shared_msr_update(unsigned slot, u32 msr)
{
u64 value;
unsigned int cpu = smp_processor_id();
struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
/* only read, and nobody should modify it at this time,
* so don't need lock */
if (slot >= shared_msrs_global.nr) {
printk(KERN_ERR "kvm: invalid MSR slot!");
return;
}
rdmsrl_safe(msr, &value);
smsr->values[slot].host = value;
smsr->values[slot].curr = value;
}
void kvm_define_shared_msr(unsigned slot, u32 msr)
{
if (slot >= shared_msrs_global.nr)
shared_msrs_global.nr = slot + 1;
shared_msrs_global.msrs[slot] = msr;
/* we need ensured the shared_msr_global have been updated */
smp_wmb();
}
EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
static void kvm_shared_msr_cpu_online(void)
{
unsigned i;
for (i = 0; i < shared_msrs_global.nr; ++i)
shared_msr_update(i, shared_msrs_global.msrs[i]);
}
void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
{
unsigned int cpu = smp_processor_id();
struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
if (((value ^ smsr->values[slot].curr) & mask) == 0)
return;
smsr->values[slot].curr = value;
wrmsrl(shared_msrs_global.msrs[slot], value);
if (!smsr->registered) {
smsr->urn.on_user_return = kvm_on_user_return;
user_return_notifier_register(&smsr->urn);
smsr->registered = true;
}
}
EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
static void drop_user_return_notifiers(void *ignore)
{
unsigned int cpu = smp_processor_id();
struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
if (smsr->registered)
kvm_on_user_return(&smsr->urn);
}
u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
{
return vcpu->arch.apic_base;
}
EXPORT_SYMBOL_GPL(kvm_get_apic_base);
void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
{
/* TODO: reserve bits check */
kvm_lapic_set_base(vcpu, data);
}
EXPORT_SYMBOL_GPL(kvm_set_apic_base);
#define EXCPT_BENIGN 0
#define EXCPT_CONTRIBUTORY 1
#define EXCPT_PF 2
static int exception_class(int vector)
{
switch (vector) {
case PF_VECTOR:
return EXCPT_PF;
case DE_VECTOR:
case TS_VECTOR:
case NP_VECTOR:
case SS_VECTOR:
case GP_VECTOR:
return EXCPT_CONTRIBUTORY;
default:
break;
}
return EXCPT_BENIGN;
}
static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
unsigned nr, bool has_error, u32 error_code,
bool reinject)
{
u32 prev_nr;
int class1, class2;
kvm_make_request(KVM_REQ_EVENT, vcpu);
if (!vcpu->arch.exception.pending) {
queue:
vcpu->arch.exception.pending = true;
vcpu->arch.exception.has_error_code = has_error;
vcpu->arch.exception.nr = nr;
vcpu->arch.exception.error_code = error_code;
vcpu->arch.exception.reinject = reinject;
return;
}
/* to check exception */
prev_nr = vcpu->arch.exception.nr;
if (prev_nr == DF_VECTOR) {
/* triple fault -> shutdown */
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
class1 = exception_class(prev_nr);
class2 = exception_class(nr);
if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
|| (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
/* generate double fault per SDM Table 5-5 */
vcpu->arch.exception.pending = true;
vcpu->arch.exception.has_error_code = true;
vcpu->arch.exception.nr = DF_VECTOR;
vcpu->arch.exception.error_code = 0;
} else
/* replace previous exception with a new one in a hope
that instruction re-execution will regenerate lost
exception */
goto queue;
}
void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
{
kvm_multiple_exception(vcpu, nr, false, 0, false);
}
EXPORT_SYMBOL_GPL(kvm_queue_exception);
void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
{
kvm_multiple_exception(vcpu, nr, false, 0, true);
}
EXPORT_SYMBOL_GPL(kvm_requeue_exception);
void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
{
if (err)
kvm_inject_gp(vcpu, 0);
else
kvm_x86_ops->skip_emulated_instruction(vcpu);
}
EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
{
++vcpu->stat.pf_guest;
vcpu->arch.cr2 = fault->address;
kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
}
EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
{
if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
else
vcpu->arch.mmu.inject_page_fault(vcpu, fault);
}
void kvm_inject_nmi(struct kvm_vcpu *vcpu)
{
atomic_inc(&vcpu->arch.nmi_queued);
kvm_make_request(KVM_REQ_NMI, vcpu);
}
EXPORT_SYMBOL_GPL(kvm_inject_nmi);
void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
{
kvm_multiple_exception(vcpu, nr, true, error_code, false);
}
EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
{
kvm_multiple_exception(vcpu, nr, true, error_code, true);
}
EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
/*
* Checks if cpl <= required_cpl; if true, return true. Otherwise queue
* a #GP and return false.
*/
bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
{
if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
return true;
kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
return false;
}
EXPORT_SYMBOL_GPL(kvm_require_cpl);
/*
* This function will be used to read from the physical memory of the currently
* running guest. The difference to kvm_read_guest_page is that this function
* can read from guest physical or from the guest's guest physical memory.
*/
int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
gfn_t ngfn, void *data, int offset, int len,
u32 access)
{
gfn_t real_gfn;
gpa_t ngpa;
ngpa = gfn_to_gpa(ngfn);
real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
if (real_gfn == UNMAPPED_GVA)
return -EFAULT;
real_gfn = gpa_to_gfn(real_gfn);
return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
}
EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
void *data, int offset, int len, u32 access)
{
return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
data, offset, len, access);
}
/*
* Load the pae pdptrs. Return true is they are all valid.
*/
int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
{
gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
int i;
int ret;
u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
offset * sizeof(u64), sizeof(pdpte),
PFERR_USER_MASK|PFERR_WRITE_MASK);
if (ret < 0) {
ret = 0;
goto out;
}
for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
if (is_present_gpte(pdpte[i]) &&
(pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
ret = 0;
goto out;
}
}
ret = 1;
memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_avail);
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_dirty);
out:
return ret;
}
EXPORT_SYMBOL_GPL(load_pdptrs);
static bool pdptrs_changed(struct kvm_vcpu *vcpu)
{
u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
bool changed = true;
int offset;
gfn_t gfn;
int r;
if (is_long_mode(vcpu) || !is_pae(vcpu))
return false;
if (!test_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_avail))
return true;
gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
PFERR_USER_MASK | PFERR_WRITE_MASK);
if (r < 0)
goto out;
changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
out:
return changed;
}
int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
{
unsigned long old_cr0 = kvm_read_cr0(vcpu);
unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
X86_CR0_CD | X86_CR0_NW;
cr0 |= X86_CR0_ET;
#ifdef CONFIG_X86_64
if (cr0 & 0xffffffff00000000UL)
return 1;
#endif
cr0 &= ~CR0_RESERVED_BITS;
if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
return 1;
if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
return 1;
if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
#ifdef CONFIG_X86_64
if ((vcpu->arch.efer & EFER_LME)) {
int cs_db, cs_l;
if (!is_pae(vcpu))
return 1;
kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
if (cs_l)
return 1;
} else
#endif
if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
kvm_read_cr3(vcpu)))
return 1;
}
if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
return 1;
kvm_x86_ops->set_cr0(vcpu, cr0);
if ((cr0 ^ old_cr0) & X86_CR0_PG) {
kvm_clear_async_pf_completion_queue(vcpu);
kvm_async_pf_hash_reset(vcpu);
}
if ((cr0 ^ old_cr0) & update_bits)
kvm_mmu_reset_context(vcpu);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr0);
void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
{
(void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
}
EXPORT_SYMBOL_GPL(kvm_lmsw);
int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
{
u64 xcr0;
/* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
if (index != XCR_XFEATURE_ENABLED_MASK)
return 1;
xcr0 = xcr;
if (kvm_x86_ops->get_cpl(vcpu) != 0)
return 1;
if (!(xcr0 & XSTATE_FP))
return 1;
if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
return 1;
if (xcr0 & ~host_xcr0)
return 1;
vcpu->arch.xcr0 = xcr0;
vcpu->guest_xcr0_loaded = 0;
return 0;
}
int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
{
if (__kvm_set_xcr(vcpu, index, xcr)) {
kvm_inject_gp(vcpu, 0);
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_xcr);
int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
{
unsigned long old_cr4 = kvm_read_cr4(vcpu);
unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
X86_CR4_PAE | X86_CR4_SMEP;
if (cr4 & CR4_RESERVED_BITS)
return 1;
if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
return 1;
if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
return 1;
if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
return 1;
if (is_long_mode(vcpu)) {
if (!(cr4 & X86_CR4_PAE))
return 1;
} else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
&& ((cr4 ^ old_cr4) & pdptr_bits)
&& !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
kvm_read_cr3(vcpu)))
return 1;
if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
if (!guest_cpuid_has_pcid(vcpu))
return 1;
/* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
return 1;
}
if (kvm_x86_ops->set_cr4(vcpu, cr4))
return 1;
if (((cr4 ^ old_cr4) & pdptr_bits) ||
(!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
kvm_mmu_reset_context(vcpu);
if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
kvm_update_cpuid(vcpu);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr4);
int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
{
if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
kvm_mmu_sync_roots(vcpu);
kvm_mmu_flush_tlb(vcpu);
return 0;
}
if (is_long_mode(vcpu)) {
if (kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)) {
if (cr3 & CR3_PCID_ENABLED_RESERVED_BITS)
return 1;
} else
if (cr3 & CR3_L_MODE_RESERVED_BITS)
return 1;
} else {
if (is_pae(vcpu)) {
if (cr3 & CR3_PAE_RESERVED_BITS)
return 1;
if (is_paging(vcpu) &&
!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
return 1;
}
/*
* We don't check reserved bits in nonpae mode, because
* this isn't enforced, and VMware depends on this.
*/
}
/*
* Does the new cr3 value map to physical memory? (Note, we
* catch an invalid cr3 even in real-mode, because it would
* cause trouble later on when we turn on paging anyway.)
*
* A real CPU would silently accept an invalid cr3 and would
* attempt to use it - with largely undefined (and often hard
* to debug) behavior on the guest side.
*/
if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
return 1;
vcpu->arch.cr3 = cr3;
__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
vcpu->arch.mmu.new_cr3(vcpu);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr3);
int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
{
if (cr8 & CR8_RESERVED_BITS)
return 1;
if (irqchip_in_kernel(vcpu->kvm))
kvm_lapic_set_tpr(vcpu, cr8);
else
vcpu->arch.cr8 = cr8;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr8);
unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
{
if (irqchip_in_kernel(vcpu->kvm))
return kvm_lapic_get_cr8(vcpu);
else
return vcpu->arch.cr8;
}
EXPORT_SYMBOL_GPL(kvm_get_cr8);
static void kvm_update_dr7(struct kvm_vcpu *vcpu)
{
unsigned long dr7;
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
dr7 = vcpu->arch.guest_debug_dr7;
else
dr7 = vcpu->arch.dr7;
kvm_x86_ops->set_dr7(vcpu, dr7);
vcpu->arch.switch_db_regs = (dr7 & DR7_BP_EN_MASK);
}
static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
{
switch (dr) {
case 0 ... 3:
vcpu->arch.db[dr] = val;
if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
vcpu->arch.eff_db[dr] = val;
break;
case 4:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1; /* #UD */
/* fall through */
case 6:
if (val & 0xffffffff00000000ULL)
return -1; /* #GP */
vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
break;
case 5:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1; /* #UD */
/* fall through */
default: /* 7 */
if (val & 0xffffffff00000000ULL)
return -1; /* #GP */
vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
kvm_update_dr7(vcpu);
break;
}
return 0;
}
int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
{
int res;
res = __kvm_set_dr(vcpu, dr, val);
if (res > 0)
kvm_queue_exception(vcpu, UD_VECTOR);
else if (res < 0)
kvm_inject_gp(vcpu, 0);
return res;
}
EXPORT_SYMBOL_GPL(kvm_set_dr);
static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
{
switch (dr) {
case 0 ... 3:
*val = vcpu->arch.db[dr];
break;
case 4:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1;
/* fall through */
case 6:
*val = vcpu->arch.dr6;
break;
case 5:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1;
/* fall through */
default: /* 7 */
*val = vcpu->arch.dr7;
break;
}
return 0;
}
int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
{
if (_kvm_get_dr(vcpu, dr, val)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_get_dr);
bool kvm_rdpmc(struct kvm_vcpu *vcpu)
{
u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
u64 data;
int err;
err = kvm_pmu_read_pmc(vcpu, ecx, &data);
if (err)
return err;
kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
return err;
}
EXPORT_SYMBOL_GPL(kvm_rdpmc);
/*
* List of msr numbers which we expose to userspace through KVM_GET_MSRS
* and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
*
* This list is modified at module load time to reflect the
* capabilities of the host cpu. This capabilities test skips MSRs that are
* kvm-specific. Those are put in the beginning of the list.
*/
#define KVM_SAVE_MSRS_BEGIN 10
static u32 msrs_to_save[] = {
MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
MSR_KVM_PV_EOI_EN,
MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
MSR_STAR,
#ifdef CONFIG_X86_64
MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
#endif
MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
};
static unsigned num_msrs_to_save;
static const u32 emulated_msrs[] = {
MSR_IA32_TSC_ADJUST,
MSR_IA32_TSCDEADLINE,
MSR_IA32_MISC_ENABLE,
MSR_IA32_MCG_STATUS,
MSR_IA32_MCG_CTL,
};
static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
{
u64 old_efer = vcpu->arch.efer;
if (efer & efer_reserved_bits)
return 1;
if (is_paging(vcpu)
&& (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
return 1;
if (efer & EFER_FFXSR) {
struct kvm_cpuid_entry2 *feat;
feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
return 1;
}
if (efer & EFER_SVME) {
struct kvm_cpuid_entry2 *feat;
feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
return 1;
}
efer &= ~EFER_LMA;
efer |= vcpu->arch.efer & EFER_LMA;
kvm_x86_ops->set_efer(vcpu, efer);
/* Update reserved bits */
if ((efer ^ old_efer) & EFER_NX)
kvm_mmu_reset_context(vcpu);
return 0;
}
void kvm_enable_efer_bits(u64 mask)
{
efer_reserved_bits &= ~mask;
}
EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
/*
* Writes msr value into into the appropriate "register".
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
{
return kvm_x86_ops->set_msr(vcpu, msr);
}
/*
* Adapt set_msr() to msr_io()'s calling convention
*/
static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
{
struct msr_data msr;
msr.data = *data;
msr.index = index;
msr.host_initiated = true;
return kvm_set_msr(vcpu, &msr);
}
#ifdef CONFIG_X86_64
struct pvclock_gtod_data {
seqcount_t seq;
struct { /* extract of a clocksource struct */
int vclock_mode;
cycle_t cycle_last;
cycle_t mask;
u32 mult;
u32 shift;
} clock;
/* open coded 'struct timespec' */
u64 monotonic_time_snsec;
time_t monotonic_time_sec;
};
static struct pvclock_gtod_data pvclock_gtod_data;
static void update_pvclock_gtod(struct timekeeper *tk)
{
struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
write_seqcount_begin(&vdata->seq);
/* copy pvclock gtod data */
vdata->clock.vclock_mode = tk->clock->archdata.vclock_mode;
vdata->clock.cycle_last = tk->clock->cycle_last;
vdata->clock.mask = tk->clock->mask;
vdata->clock.mult = tk->mult;
vdata->clock.shift = tk->shift;
vdata->monotonic_time_sec = tk->xtime_sec
+ tk->wall_to_monotonic.tv_sec;
vdata->monotonic_time_snsec = tk->xtime_nsec
+ (tk->wall_to_monotonic.tv_nsec
<< tk->shift);
while (vdata->monotonic_time_snsec >=
(((u64)NSEC_PER_SEC) << tk->shift)) {
vdata->monotonic_time_snsec -=
((u64)NSEC_PER_SEC) << tk->shift;
vdata->monotonic_time_sec++;
}
write_seqcount_end(&vdata->seq);
}
#endif
static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
{
int version;
int r;
struct pvclock_wall_clock wc;
struct timespec boot;
if (!wall_clock)
return;
r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
if (r)
return;
if (version & 1)
++version; /* first time write, random junk */
++version;
kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
/*
* The guest calculates current wall clock time by adding
* system time (updated by kvm_guest_time_update below) to the
* wall clock specified here. guest system time equals host
* system time for us, thus we must fill in host boot time here.
*/
getboottime(&boot);
if (kvm->arch.kvmclock_offset) {
struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
boot = timespec_sub(boot, ts);
}
wc.sec = boot.tv_sec;
wc.nsec = boot.tv_nsec;
wc.version = version;
kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
version++;
kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
}
static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
{
uint32_t quotient, remainder;
/* Don't try to replace with do_div(), this one calculates
* "(dividend << 32) / divisor" */
__asm__ ( "divl %4"
: "=a" (quotient), "=d" (remainder)
: "0" (0), "1" (dividend), "r" (divisor) );
return quotient;
}
static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
s8 *pshift, u32 *pmultiplier)
{
uint64_t scaled64;
int32_t shift = 0;
uint64_t tps64;
uint32_t tps32;
tps64 = base_khz * 1000LL;
scaled64 = scaled_khz * 1000LL;
while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
tps64 >>= 1;
shift--;
}
tps32 = (uint32_t)tps64;
while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
scaled64 >>= 1;
else
tps32 <<= 1;
shift++;
}
*pshift = shift;
*pmultiplier = div_frac(scaled64, tps32);
pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
__func__, base_khz, scaled_khz, shift, *pmultiplier);
}
static inline u64 get_kernel_ns(void)
{
struct timespec ts;
WARN_ON(preemptible());
ktime_get_ts(&ts);
monotonic_to_bootbased(&ts);
return timespec_to_ns(&ts);
}
#ifdef CONFIG_X86_64
static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
#endif
static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
unsigned long max_tsc_khz;
static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
{
return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
vcpu->arch.virtual_tsc_shift);
}
static u32 adjust_tsc_khz(u32 khz, s32 ppm)
{
u64 v = (u64)khz * (1000000 + ppm);
do_div(v, 1000000);
return v;
}
static void kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
{
u32 thresh_lo, thresh_hi;
int use_scaling = 0;
/* Compute a scale to convert nanoseconds in TSC cycles */
kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
&vcpu->arch.virtual_tsc_shift,
&vcpu->arch.virtual_tsc_mult);
vcpu->arch.virtual_tsc_khz = this_tsc_khz;
/*
* Compute the variation in TSC rate which is acceptable
* within the range of tolerance and decide if the
* rate being applied is within that bounds of the hardware
* rate. If so, no scaling or compensation need be done.
*/
thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
use_scaling = 1;
}
kvm_x86_ops->set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
}
static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
{
u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
vcpu->arch.virtual_tsc_mult,
vcpu->arch.virtual_tsc_shift);
tsc += vcpu->arch.this_tsc_write;
return tsc;
}
void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
{
#ifdef CONFIG_X86_64
bool vcpus_matched;
bool do_request = false;
struct kvm_arch *ka = &vcpu->kvm->arch;
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
atomic_read(&vcpu->kvm->online_vcpus));
if (vcpus_matched && gtod->clock.vclock_mode == VCLOCK_TSC)
if (!ka->use_master_clock)
do_request = 1;
if (!vcpus_matched && ka->use_master_clock)
do_request = 1;
if (do_request)
kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
atomic_read(&vcpu->kvm->online_vcpus),
ka->use_master_clock, gtod->clock.vclock_mode);
#endif
}
static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
{
u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
}
void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
{
struct kvm *kvm = vcpu->kvm;
u64 offset, ns, elapsed;
unsigned long flags;
s64 usdiff;
bool matched;
u64 data = msr->data;
raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
ns = get_kernel_ns();
elapsed = ns - kvm->arch.last_tsc_nsec;
/* n.b - signed multiplication and division required */
usdiff = data - kvm->arch.last_tsc_write;
#ifdef CONFIG_X86_64
usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
#else
/* do_div() only does unsigned */
asm("idivl %2; xor %%edx, %%edx"
: "=A"(usdiff)
: "A"(usdiff * 1000), "rm"(vcpu->arch.virtual_tsc_khz));
#endif
do_div(elapsed, 1000);
usdiff -= elapsed;
if (usdiff < 0)
usdiff = -usdiff;
/*
* Special case: TSC write with a small delta (1 second) of virtual
* cycle time against real time is interpreted as an attempt to
* synchronize the CPU.
*
* For a reliable TSC, we can match TSC offsets, and for an unstable
* TSC, we add elapsed time in this computation. We could let the
* compensation code attempt to catch up if we fall behind, but
* it's better to try to match offsets from the beginning.
*/
if (usdiff < USEC_PER_SEC &&
vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
if (!check_tsc_unstable()) {
offset = kvm->arch.cur_tsc_offset;
pr_debug("kvm: matched tsc offset for %llu\n", data);
} else {
u64 delta = nsec_to_cycles(vcpu, elapsed);
data += delta;
offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
}
matched = true;
} else {
/*
* We split periods of matched TSC writes into generations.
* For each generation, we track the original measured
* nanosecond time, offset, and write, so if TSCs are in
* sync, we can match exact offset, and if not, we can match
* exact software computation in compute_guest_tsc()
*
* These values are tracked in kvm->arch.cur_xxx variables.
*/
kvm->arch.cur_tsc_generation++;
kvm->arch.cur_tsc_nsec = ns;
kvm->arch.cur_tsc_write = data;
kvm->arch.cur_tsc_offset = offset;
matched = false;
pr_debug("kvm: new tsc generation %u, clock %llu\n",
kvm->arch.cur_tsc_generation, data);
}
/*
* We also track th most recent recorded KHZ, write and time to
* allow the matching interval to be extended at each write.
*/
kvm->arch.last_tsc_nsec = ns;
kvm->arch.last_tsc_write = data;
kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
/* Reset of TSC must disable overshoot protection below */
vcpu->arch.hv_clock.tsc_timestamp = 0;
vcpu->arch.last_guest_tsc = data;
/* Keep track of which generation this VCPU has synchronized to */
vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
update_ia32_tsc_adjust_msr(vcpu, offset);
kvm_x86_ops->write_tsc_offset(vcpu, offset);
raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
if (matched)
kvm->arch.nr_vcpus_matched_tsc++;
else
kvm->arch.nr_vcpus_matched_tsc = 0;
kvm_track_tsc_matching(vcpu);
spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
}
EXPORT_SYMBOL_GPL(kvm_write_tsc);
#ifdef CONFIG_X86_64
static cycle_t read_tsc(void)
{
cycle_t ret;
u64 last;
/*
* Empirically, a fence (of type that depends on the CPU)
* before rdtsc is enough to ensure that rdtsc is ordered
* with respect to loads. The various CPU manuals are unclear
* as to whether rdtsc can be reordered with later loads,
* but no one has ever seen it happen.
*/
rdtsc_barrier();
ret = (cycle_t)vget_cycles();
last = pvclock_gtod_data.clock.cycle_last;
if (likely(ret >= last))
return ret;
/*
* GCC likes to generate cmov here, but this branch is extremely
* predictable (it's just a funciton of time and the likely is
* very likely) and there's a data dependence, so force GCC
* to generate a branch instead. I don't barrier() because
* we don't actually need a barrier, and if this function
* ever gets inlined it will generate worse code.
*/
asm volatile ("");
return last;
}
static inline u64 vgettsc(cycle_t *cycle_now)
{
long v;
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
*cycle_now = read_tsc();
v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
return v * gtod->clock.mult;
}
static int do_monotonic(struct timespec *ts, cycle_t *cycle_now)
{
unsigned long seq;
u64 ns;
int mode;
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
ts->tv_nsec = 0;
do {
seq = read_seqcount_begin(>od->seq);
mode = gtod->clock.vclock_mode;
ts->tv_sec = gtod->monotonic_time_sec;
ns = gtod->monotonic_time_snsec;
ns += vgettsc(cycle_now);
ns >>= gtod->clock.shift;
} while (unlikely(read_seqcount_retry(>od->seq, seq)));
timespec_add_ns(ts, ns);
return mode;
}
/* returns true if host is using tsc clocksource */
static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
{
struct timespec ts;
/* checked again under seqlock below */
if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
return false;
if (do_monotonic(&ts, cycle_now) != VCLOCK_TSC)
return false;
monotonic_to_bootbased(&ts);
*kernel_ns = timespec_to_ns(&ts);
return true;
}
#endif
/*
*
* Assuming a stable TSC across physical CPUS, and a stable TSC
* across virtual CPUs, the following condition is possible.
* Each numbered line represents an event visible to both
* CPUs at the next numbered event.
*
* "timespecX" represents host monotonic time. "tscX" represents
* RDTSC value.
*
* VCPU0 on CPU0 | VCPU1 on CPU1
*
* 1. read timespec0,tsc0
* 2. | timespec1 = timespec0 + N
* | tsc1 = tsc0 + M
* 3. transition to guest | transition to guest
* 4. ret0 = timespec0 + (rdtsc - tsc0) |
* 5. | ret1 = timespec1 + (rdtsc - tsc1)
* | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
*
* Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
*
* - ret0 < ret1
* - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
* ...
* - 0 < N - M => M < N
*
* That is, when timespec0 != timespec1, M < N. Unfortunately that is not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.
*
* Rely on synchronization of host TSCs and guest TSCs for monotonicity.
*
*/
static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
{
#ifdef CONFIG_X86_64
struct kvm_arch *ka = &kvm->arch;
int vclock_mode;
bool host_tsc_clocksource, vcpus_matched;
vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
atomic_read(&kvm->online_vcpus));
/*
* If the host uses TSC clock, then passthrough TSC as stable
* to the guest.
*/
host_tsc_clocksource = kvm_get_time_and_clockread(
&ka->master_kernel_ns,
&ka->master_cycle_now);
ka->use_master_clock = host_tsc_clocksource & vcpus_matched;
if (ka->use_master_clock)
atomic_set(&kvm_guest_has_master_clock, 1);
vclock_mode = pvclock_gtod_data.clock.vclock_mode;
trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
vcpus_matched);
#endif
}
static int kvm_guest_time_update(struct kvm_vcpu *v)
{
unsigned long flags, this_tsc_khz;
struct kvm_vcpu_arch *vcpu = &v->arch;
struct kvm_arch *ka = &v->kvm->arch;
void *shared_kaddr;
s64 kernel_ns, max_kernel_ns;
u64 tsc_timestamp, host_tsc;
struct pvclock_vcpu_time_info *guest_hv_clock;
u8 pvclock_flags;
bool use_master_clock;
kernel_ns = 0;
host_tsc = 0;
/*
* If the host uses TSC clock, then passthrough TSC as stable
* to the guest.
*/
spin_lock(&ka->pvclock_gtod_sync_lock);
use_master_clock = ka->use_master_clock;
if (use_master_clock) {
host_tsc = ka->master_cycle_now;
kernel_ns = ka->master_kernel_ns;
}
spin_unlock(&ka->pvclock_gtod_sync_lock);
/* Keep irq disabled to prevent changes to the clock */
local_irq_save(flags);
this_tsc_khz = __get_cpu_var(cpu_tsc_khz);
if (unlikely(this_tsc_khz == 0)) {
local_irq_restore(flags);
kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
return 1;
}
if (!use_master_clock) {
host_tsc = native_read_tsc();
kernel_ns = get_kernel_ns();
}
tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc);
/*
* We may have to catch up the TSC to match elapsed wall clock
* time for two reasons, even if kvmclock is used.
* 1) CPU could have been running below the maximum TSC rate
* 2) Broken TSC compensation resets the base at each VCPU
* entry to avoid unknown leaps of TSC even when running
* again on the same CPU. This may cause apparent elapsed
* time to disappear, and the guest to stand still or run
* very slowly.
*/
if (vcpu->tsc_catchup) {
u64 tsc = compute_guest_tsc(v, kernel_ns);
if (tsc > tsc_timestamp) {
adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
tsc_timestamp = tsc;
}
}
local_irq_restore(flags);
if (!vcpu->time_page)
return 0;
/*
* Time as measured by the TSC may go backwards when resetting the base
* tsc_timestamp. The reason for this is that the TSC resolution is
* higher than the resolution of the other clock scales. Thus, many
* possible measurments of the TSC correspond to one measurement of any
* other clock, and so a spread of values is possible. This is not a
* problem for the computation of the nanosecond clock; with TSC rates
* around 1GHZ, there can only be a few cycles which correspond to one
* nanosecond value, and any path through this code will inevitably
* take longer than that. However, with the kernel_ns value itself,
* the precision may be much lower, down to HZ granularity. If the
* first sampling of TSC against kernel_ns ends in the low part of the
* range, and the second in the high end of the range, we can get:
*
* (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
*
* As the sampling errors potentially range in the thousands of cycles,
* it is possible such a time value has already been observed by the
* guest. To protect against this, we must compute the system time as
* observed by the guest and ensure the new system time is greater.
*/
max_kernel_ns = 0;
if (vcpu->hv_clock.tsc_timestamp) {
max_kernel_ns = vcpu->last_guest_tsc -
vcpu->hv_clock.tsc_timestamp;
max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
vcpu->hv_clock.tsc_to_system_mul,
vcpu->hv_clock.tsc_shift);
max_kernel_ns += vcpu->last_kernel_ns;
}
if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
&vcpu->hv_clock.tsc_shift,
&vcpu->hv_clock.tsc_to_system_mul);
vcpu->hw_tsc_khz = this_tsc_khz;
}
/* with a master <monotonic time, tsc value> tuple,
* pvclock clock reads always increase at the (scaled) rate
* of guest TSC - no need to deal with sampling errors.
*/
if (!use_master_clock) {
if (max_kernel_ns > kernel_ns)
kernel_ns = max_kernel_ns;
}
/* With all the info we got, fill in the values */
vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
vcpu->last_kernel_ns = kernel_ns;
vcpu->last_guest_tsc = tsc_timestamp;
/*
* The interface expects us to write an even number signaling that the
* update is finished. Since the guest won't see the intermediate
* state, we just increase by 2 at the end.
*/
vcpu->hv_clock.version += 2;
shared_kaddr = kmap_atomic(vcpu->time_page);
guest_hv_clock = shared_kaddr + vcpu->time_offset;
/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
pvclock_flags = (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
if (vcpu->pvclock_set_guest_stopped_request) {
pvclock_flags |= PVCLOCK_GUEST_STOPPED;
vcpu->pvclock_set_guest_stopped_request = false;
}
/* If the host uses TSC clocksource, then it is stable */
if (use_master_clock)
pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
vcpu->hv_clock.flags = pvclock_flags;
memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
sizeof(vcpu->hv_clock));
kunmap_atomic(shared_kaddr);
mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
return 0;
}
static bool msr_mtrr_valid(unsigned msr)
{
switch (msr) {
case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
case MSR_MTRRfix64K_00000:
case MSR_MTRRfix16K_80000:
case MSR_MTRRfix16K_A0000:
case MSR_MTRRfix4K_C0000:
case MSR_MTRRfix4K_C8000:
case MSR_MTRRfix4K_D0000:
case MSR_MTRRfix4K_D8000:
case MSR_MTRRfix4K_E0000:
case MSR_MTRRfix4K_E8000:
case MSR_MTRRfix4K_F0000:
case MSR_MTRRfix4K_F8000:
case MSR_MTRRdefType:
case MSR_IA32_CR_PAT:
return true;
case 0x2f8:
return true;
}
return false;
}
static bool valid_pat_type(unsigned t)
{
return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
}
static bool valid_mtrr_type(unsigned t)
{
return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
}
static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
int i;
if (!msr_mtrr_valid(msr))
return false;
if (msr == MSR_IA32_CR_PAT) {
for (i = 0; i < 8; i++)
if (!valid_pat_type((data >> (i * 8)) & 0xff))
return false;
return true;
} else if (msr == MSR_MTRRdefType) {
if (data & ~0xcff)
return false;
return valid_mtrr_type(data & 0xff);
} else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
for (i = 0; i < 8 ; i++)
if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
return false;
return true;
}
/* variable MTRRs */
return valid_mtrr_type(data & 0xff);
}
static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
if (!mtrr_valid(vcpu, msr, data))
return 1;
if (msr == MSR_MTRRdefType) {
vcpu->arch.mtrr_state.def_type = data;
vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
} else if (msr == MSR_MTRRfix64K_00000)
p[0] = data;
else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
p[1 + msr - MSR_MTRRfix16K_80000] = data;
else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
p[3 + msr - MSR_MTRRfix4K_C0000] = data;
else if (msr == MSR_IA32_CR_PAT)
vcpu->arch.pat = data;
else { /* Variable MTRRs */
int idx, is_mtrr_mask;
u64 *pt;
idx = (msr - 0x200) / 2;
is_mtrr_mask = msr - 0x200 - 2 * idx;
if (!is_mtrr_mask)
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
else
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
*pt = data;
}
kvm_mmu_reset_context(vcpu);
return 0;
}
static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
u64 mcg_cap = vcpu->arch.mcg_cap;
unsigned bank_num = mcg_cap & 0xff;
switch (msr) {
case MSR_IA32_MCG_STATUS:
vcpu->arch.mcg_status = data;
break;
case MSR_IA32_MCG_CTL:
if (!(mcg_cap & MCG_CTL_P))
return 1;
if (data != 0 && data != ~(u64)0)
return -1;
vcpu->arch.mcg_ctl = data;
break;
default:
if (msr >= MSR_IA32_MC0_CTL &&
msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
u32 offset = msr - MSR_IA32_MC0_CTL;
/* only 0 or all 1s can be written to IA32_MCi_CTL
* some Linux kernels though clear bit 10 in bank 4 to
* workaround a BIOS/GART TBL issue on AMD K8s, ignore
* this to avoid an uncatched #GP in the guest
*/
if ((offset & 0x3) == 0 &&
data != 0 && (data | (1 << 10)) != ~(u64)0)
return -1;
vcpu->arch.mce_banks[offset] = data;
break;
}
return 1;
}
return 0;
}
static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
{
struct kvm *kvm = vcpu->kvm;
int lm = is_long_mode(vcpu);
u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
: (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
: kvm->arch.xen_hvm_config.blob_size_32;
u32 page_num = data & ~PAGE_MASK;
u64 page_addr = data & PAGE_MASK;
u8 *page;
int r;
r = -E2BIG;
if (page_num >= blob_size)
goto out;
r = -ENOMEM;
page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
if (IS_ERR(page)) {
r = PTR_ERR(page);
goto out;
}
if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
goto out_free;
r = 0;
out_free:
kfree(page);
out:
return r;
}
static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
{
return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
}
static bool kvm_hv_msr_partition_wide(u32 msr)
{
bool r = false;
switch (msr) {
case HV_X64_MSR_GUEST_OS_ID:
case HV_X64_MSR_HYPERCALL:
r = true;
break;
}
return r;
}
static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
struct kvm *kvm = vcpu->kvm;
switch (msr) {
case HV_X64_MSR_GUEST_OS_ID:
kvm->arch.hv_guest_os_id = data;
/* setting guest os id to zero disables hypercall page */
if (!kvm->arch.hv_guest_os_id)
kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
break;
case HV_X64_MSR_HYPERCALL: {
u64 gfn;
unsigned long addr;
u8 instructions[4];
/* if guest os id is not set hypercall should remain disabled */
if (!kvm->arch.hv_guest_os_id)
break;
if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
kvm->arch.hv_hypercall = data;
break;
}
gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return 1;
kvm_x86_ops->patch_hypercall(vcpu, instructions);
((unsigned char *)instructions)[3] = 0xc3; /* ret */
if (__copy_to_user((void __user *)addr, instructions, 4))
return 1;
kvm->arch.hv_hypercall = data;
break;
}
default:
vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
"data 0x%llx\n", msr, data);
return 1;
}
return 0;
}
static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
switch (msr) {
case HV_X64_MSR_APIC_ASSIST_PAGE: {
unsigned long addr;
if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
vcpu->arch.hv_vapic = data;
break;
}
addr = gfn_to_hva(vcpu->kvm, data >>
HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
if (kvm_is_error_hva(addr))
return 1;
if (__clear_user((void __user *)addr, PAGE_SIZE))
return 1;
vcpu->arch.hv_vapic = data;
break;
}
case HV_X64_MSR_EOI:
return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
case HV_X64_MSR_ICR:
return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
case HV_X64_MSR_TPR:
return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
default:
vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
"data 0x%llx\n", msr, data);
return 1;
}
return 0;
}
static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
{
gpa_t gpa = data & ~0x3f;
/* Bits 2:5 are reserved, Should be zero */
if (data & 0x3c)
return 1;
vcpu->arch.apf.msr_val = data;
if (!(data & KVM_ASYNC_PF_ENABLED)) {
kvm_clear_async_pf_completion_queue(vcpu);
kvm_async_pf_hash_reset(vcpu);
return 0;
}
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
return 1;
vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
kvm_async_pf_wakeup_all(vcpu);
return 0;
}
static void kvmclock_reset(struct kvm_vcpu *vcpu)
{
if (vcpu->arch.time_page) {
kvm_release_page_dirty(vcpu->arch.time_page);
vcpu->arch.time_page = NULL;
}
}
static void accumulate_steal_time(struct kvm_vcpu *vcpu)
{
u64 delta;
if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
return;
delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
vcpu->arch.st.accum_steal = delta;
}
static void record_steal_time(struct kvm_vcpu *vcpu)
{
if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
return;
if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
&vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
return;
vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
vcpu->arch.st.steal.version += 2;
vcpu->arch.st.accum_steal = 0;
kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
&vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
}
int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
bool pr = false;
u32 msr = msr_info->index;
u64 data = msr_info->data;
switch (msr) {
case MSR_AMD64_NB_CFG:
case MSR_IA32_UCODE_REV:
case MSR_IA32_UCODE_WRITE:
case MSR_VM_HSAVE_PA:
case MSR_AMD64_PATCH_LOADER:
case MSR_AMD64_BU_CFG2:
break;
case MSR_EFER:
return set_efer(vcpu, data);
case MSR_K7_HWCR:
data &= ~(u64)0x40; /* ignore flush filter disable */
data &= ~(u64)0x100; /* ignore ignne emulation enable */
data &= ~(u64)0x8; /* ignore TLB cache disable */
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
data);
return 1;
}
break;
case MSR_FAM10H_MMIO_CONF_BASE:
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
"0x%llx\n", data);
return 1;
}
break;
case MSR_IA32_DEBUGCTLMSR:
if (!data) {
/* We support the non-activated case already */
break;
} else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
/* Values other than LBR and BTF are vendor-specific,
thus reserved and should throw a #GP */
return 1;
}
vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
__func__, data);
break;
case 0x200 ... 0x2ff:
return set_msr_mtrr(vcpu, msr, data);
case MSR_IA32_APICBASE:
kvm_set_apic_base(vcpu, data);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_write(vcpu, msr, data);
case MSR_IA32_TSCDEADLINE:
kvm_set_lapic_tscdeadline_msr(vcpu, data);
break;
case MSR_IA32_TSC_ADJUST:
if (guest_cpuid_has_tsc_adjust(vcpu)) {
if (!msr_info->host_initiated) {
u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
}
vcpu->arch.ia32_tsc_adjust_msr = data;
}
break;
case MSR_IA32_MISC_ENABLE:
vcpu->arch.ia32_misc_enable_msr = data;
break;
case MSR_KVM_WALL_CLOCK_NEW:
case MSR_KVM_WALL_CLOCK:
vcpu->kvm->arch.wall_clock = data;
kvm_write_wall_clock(vcpu->kvm, data);
break;
case MSR_KVM_SYSTEM_TIME_NEW:
case MSR_KVM_SYSTEM_TIME: {
kvmclock_reset(vcpu);
vcpu->arch.time = data;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
/* we verify if the enable bit is set... */
if (!(data & 1))
break;
/* ...but clean it before doing the actual write */
vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
/* Check that the address is 32-byte aligned. */
if (vcpu->arch.time_offset &
(sizeof(struct pvclock_vcpu_time_info) - 1))
break;
vcpu->arch.time_page =
gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
if (is_error_page(vcpu->arch.time_page))
vcpu->arch.time_page = NULL;
break;
}
case MSR_KVM_ASYNC_PF_EN:
if (kvm_pv_enable_async_pf(vcpu, data))
return 1;
break;
case MSR_KVM_STEAL_TIME:
if (unlikely(!sched_info_on()))
return 1;
if (data & KVM_STEAL_RESERVED_MASK)
return 1;
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
data & KVM_STEAL_VALID_BITS))
return 1;
vcpu->arch.st.msr_val = data;
if (!(data & KVM_MSR_ENABLED))
break;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
preempt_disable();
accumulate_steal_time(vcpu);
preempt_enable();
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
break;
case MSR_KVM_PV_EOI_EN:
if (kvm_lapic_enable_pv_eoi(vcpu, data))
return 1;
break;
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return set_msr_mce(vcpu, msr, data);
/* Performance counters are not protected by a CPUID bit,
* so we should check all of them in the generic path for the sake of
* cross vendor migration.
* Writing a zero into the event select MSRs disables them,
* which we perfectly emulate ;-). Any other value should be at least
* reported, some guests depend on them.
*/
case MSR_K7_EVNTSEL0:
case MSR_K7_EVNTSEL1:
case MSR_K7_EVNTSEL2:
case MSR_K7_EVNTSEL3:
if (data != 0)
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
/* at least RHEL 4 unconditionally writes to the perfctr registers,
* so we ignore writes to make it happy.
*/
case MSR_K7_PERFCTR0:
case MSR_K7_PERFCTR1:
case MSR_K7_PERFCTR2:
case MSR_K7_PERFCTR3:
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
pr = true;
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (pr || data != 0)
vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_K7_CLK_CTL:
/*
* Ignore all writes to this no longer documented MSR.
* Writes are only relevant for old K7 processors,
* all pre-dating SVM, but a recommended workaround from
* AMD for these chips. It is possible to specify the
* affected processor models on the command line, hence
* the need to ignore the workaround.
*/
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = set_msr_hyperv_pw(vcpu, msr, data);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return set_msr_hyperv(vcpu, msr, data);
break;
case MSR_IA32_BBL_CR_CTL3:
/* Drop writes to this legacy MSR -- see rdmsr
* counterpart for further detail.
*/
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.length = data;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.status = data;
break;
default:
if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
return xen_hvm_config(vcpu, data);
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
msr, data);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
msr, data);
break;
}
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_msr_common);
/*
* Reads an msr value (of 'msr_index') into 'pdata'.
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
{
return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
}
static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
if (!msr_mtrr_valid(msr))
return 1;
if (msr == MSR_MTRRdefType)
*pdata = vcpu->arch.mtrr_state.def_type +
(vcpu->arch.mtrr_state.enabled << 10);
else if (msr == MSR_MTRRfix64K_00000)
*pdata = p[0];
else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
*pdata = p[1 + msr - MSR_MTRRfix16K_80000];
else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
*pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
else if (msr == MSR_IA32_CR_PAT)
*pdata = vcpu->arch.pat;
else { /* Variable MTRRs */
int idx, is_mtrr_mask;
u64 *pt;
idx = (msr - 0x200) / 2;
is_mtrr_mask = msr - 0x200 - 2 * idx;
if (!is_mtrr_mask)
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
else
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
*pdata = *pt;
}
return 0;
}
static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data;
u64 mcg_cap = vcpu->arch.mcg_cap;
unsigned bank_num = mcg_cap & 0xff;
switch (msr) {
case MSR_IA32_P5_MC_ADDR:
case MSR_IA32_P5_MC_TYPE:
data = 0;
break;
case MSR_IA32_MCG_CAP:
data = vcpu->arch.mcg_cap;
break;
case MSR_IA32_MCG_CTL:
if (!(mcg_cap & MCG_CTL_P))
return 1;
data = vcpu->arch.mcg_ctl;
break;
case MSR_IA32_MCG_STATUS:
data = vcpu->arch.mcg_status;
break;
default:
if (msr >= MSR_IA32_MC0_CTL &&
msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
u32 offset = msr - MSR_IA32_MC0_CTL;
data = vcpu->arch.mce_banks[offset];
break;
}
return 1;
}
*pdata = data;
return 0;
}
static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data = 0;
struct kvm *kvm = vcpu->kvm;
switch (msr) {
case HV_X64_MSR_GUEST_OS_ID:
data = kvm->arch.hv_guest_os_id;
break;
case HV_X64_MSR_HYPERCALL:
data = kvm->arch.hv_hypercall;
break;
default:
vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
return 1;
}
*pdata = data;
return 0;
}
static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data = 0;
switch (msr) {
case HV_X64_MSR_VP_INDEX: {
int r;
struct kvm_vcpu *v;
kvm_for_each_vcpu(r, v, vcpu->kvm)
if (v == vcpu)
data = r;
break;
}
case HV_X64_MSR_EOI:
return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
case HV_X64_MSR_ICR:
return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
case HV_X64_MSR_TPR:
return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
case HV_X64_MSR_APIC_ASSIST_PAGE:
data = vcpu->arch.hv_vapic;
break;
default:
vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
return 1;
}
*pdata = data;
return 0;
}
int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data;
switch (msr) {
case MSR_IA32_PLATFORM_ID:
case MSR_IA32_EBL_CR_POWERON:
case MSR_IA32_DEBUGCTLMSR:
case MSR_IA32_LASTBRANCHFROMIP:
case MSR_IA32_LASTBRANCHTOIP:
case MSR_IA32_LASTINTFROMIP:
case MSR_IA32_LASTINTTOIP:
case MSR_K8_SYSCFG:
case MSR_K7_HWCR:
case MSR_VM_HSAVE_PA:
case MSR_K7_EVNTSEL0:
case MSR_K7_PERFCTR0:
case MSR_K8_INT_PENDING_MSG:
case MSR_AMD64_NB_CFG:
case MSR_FAM10H_MMIO_CONF_BASE:
case MSR_AMD64_BU_CFG2:
data = 0;
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_get_msr(vcpu, msr, pdata);
data = 0;
break;
case MSR_IA32_UCODE_REV:
data = 0x100000000ULL;
break;
case MSR_MTRRcap:
data = 0x500 | KVM_NR_VAR_MTRR;
break;
case 0x200 ... 0x2ff:
return get_msr_mtrr(vcpu, msr, pdata);
case 0xcd: /* fsb frequency */
data = 3;
break;
/*
* MSR_EBC_FREQUENCY_ID
* Conservative value valid for even the basic CPU models.
* Models 0,1: 000 in bits 23:21 indicating a bus speed of
* 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
* and 266MHz for model 3, or 4. Set Core Clock
* Frequency to System Bus Frequency Ratio to 1 (bits
* 31:24) even though these are only valid for CPU
* models > 2, however guests may end up dividing or
* multiplying by zero otherwise.
*/
case MSR_EBC_FREQUENCY_ID:
data = 1 << 24;
break;
case MSR_IA32_APICBASE:
data = kvm_get_apic_base(vcpu);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_read(vcpu, msr, pdata);
break;
case MSR_IA32_TSCDEADLINE:
data = kvm_get_lapic_tscdeadline_msr(vcpu);
break;
case MSR_IA32_TSC_ADJUST:
data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
break;
case MSR_IA32_MISC_ENABLE:
data = vcpu->arch.ia32_misc_enable_msr;
break;
case MSR_IA32_PERF_STATUS:
/* TSC increment by tick */
data = 1000ULL;
/* CPU multiplier */
data |= (((uint64_t)4ULL) << 40);
break;
case MSR_EFER:
data = vcpu->arch.efer;
break;
case MSR_KVM_WALL_CLOCK:
case MSR_KVM_WALL_CLOCK_NEW:
data = vcpu->kvm->arch.wall_clock;
break;
case MSR_KVM_SYSTEM_TIME:
case MSR_KVM_SYSTEM_TIME_NEW:
data = vcpu->arch.time;
break;
case MSR_KVM_ASYNC_PF_EN:
data = vcpu->arch.apf.msr_val;
break;
case MSR_KVM_STEAL_TIME:
data = vcpu->arch.st.msr_val;
break;
case MSR_KVM_PV_EOI_EN:
data = vcpu->arch.pv_eoi.msr_val;
break;
case MSR_IA32_P5_MC_ADDR:
case MSR_IA32_P5_MC_TYPE:
case MSR_IA32_MCG_CAP:
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return get_msr_mce(vcpu, msr, pdata);
case MSR_K7_CLK_CTL:
/*
* Provide expected ramp-up count for K7. All other
* are set to zero, indicating minimum divisors for
* every field.
*
* This prevents guest kernels on AMD host with CPU
* type 6, model 8 and higher from exploding due to
* the rdmsr failing.
*/
data = 0x20000000;
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = get_msr_hyperv_pw(vcpu, msr, pdata);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return get_msr_hyperv(vcpu, msr, pdata);
break;
case MSR_IA32_BBL_CR_CTL3:
/* This legacy MSR exists but isn't fully documented in current
* silicon. It is however accessed by winxp in very narrow
* scenarios where it sets bit #19, itself documented as
* a "reserved" bit. Best effort attempt to source coherent
* read data here should the balance of the register be
* interpreted by the guest:
*
* L2 cache control register 3: 64GB range, 256KB size,
* enabled, latency 0x1, configured
*/
data = 0xbe702111;
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
data = vcpu->arch.osvw.length;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
data = vcpu->arch.osvw.status;
break;
default:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_get_msr(vcpu, msr, pdata);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
data = 0;
}
break;
}
*pdata = data;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_get_msr_common);
/*
* Read or write a bunch of msrs. All parameters are kernel addresses.
*
* @return number of msrs set successfully.
*/
static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
struct kvm_msr_entry *entries,
int (*do_msr)(struct kvm_vcpu *vcpu,
unsigned index, u64 *data))
{
int i, idx;
idx = srcu_read_lock(&vcpu->kvm->srcu);
for (i = 0; i < msrs->nmsrs; ++i)
if (do_msr(vcpu, entries[i].index, &entries[i].data))
break;
srcu_read_unlock(&vcpu->kvm->srcu, idx);
return i;
}
/*
* Read or write a bunch of msrs. Parameters are user addresses.
*
* @return number of msrs set successfully.
*/
static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
int (*do_msr)(struct kvm_vcpu *vcpu,
unsigned index, u64 *data),
int writeback)
{
struct kvm_msrs msrs;
struct kvm_msr_entry *entries;
int r, n;
unsigned size;
r = -EFAULT;
if (copy_from_user(&msrs, user_msrs, sizeof msrs))
goto out;
r = -E2BIG;
if (msrs.nmsrs >= MAX_IO_MSRS)
goto out;
size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
entries = memdup_user(user_msrs->entries, size);
if (IS_ERR(entries)) {
r = PTR_ERR(entries);
goto out;
}
r = n = __msr_io(vcpu, &msrs, entries, do_msr);
if (r < 0)
goto out_free;
r = -EFAULT;
if (writeback && copy_to_user(user_msrs->entries, entries, size))
goto out_free;
r = n;
out_free:
kfree(entries);
out:
return r;
}
int kvm_dev_ioctl_check_extension(long ext)
{
int r;
switch (ext) {
case KVM_CAP_IRQCHIP:
case KVM_CAP_HLT:
case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
case KVM_CAP_SET_TSS_ADDR:
case KVM_CAP_EXT_CPUID:
case KVM_CAP_CLOCKSOURCE:
case KVM_CAP_PIT:
case KVM_CAP_NOP_IO_DELAY:
case KVM_CAP_MP_STATE:
case KVM_CAP_SYNC_MMU:
case KVM_CAP_USER_NMI:
case KVM_CAP_REINJECT_CONTROL:
case KVM_CAP_IRQ_INJECT_STATUS:
case KVM_CAP_ASSIGN_DEV_IRQ:
case KVM_CAP_IRQFD:
case KVM_CAP_IOEVENTFD:
case KVM_CAP_PIT2:
case KVM_CAP_PIT_STATE2:
case KVM_CAP_SET_IDENTITY_MAP_ADDR:
case KVM_CAP_XEN_HVM:
case KVM_CAP_ADJUST_CLOCK:
case KVM_CAP_VCPU_EVENTS:
case KVM_CAP_HYPERV:
case KVM_CAP_HYPERV_VAPIC:
case KVM_CAP_HYPERV_SPIN:
case KVM_CAP_PCI_SEGMENT:
case KVM_CAP_DEBUGREGS:
case KVM_CAP_X86_ROBUST_SINGLESTEP:
case KVM_CAP_XSAVE:
case KVM_CAP_ASYNC_PF:
case KVM_CAP_GET_TSC_KHZ:
case KVM_CAP_PCI_2_3:
case KVM_CAP_KVMCLOCK_CTRL:
case KVM_CAP_READONLY_MEM:
case KVM_CAP_IRQFD_RESAMPLE:
r = 1;
break;
case KVM_CAP_COALESCED_MMIO:
r = KVM_COALESCED_MMIO_PAGE_OFFSET;
break;
case KVM_CAP_VAPIC:
r = !kvm_x86_ops->cpu_has_accelerated_tpr();
break;
case KVM_CAP_NR_VCPUS:
r = KVM_SOFT_MAX_VCPUS;
break;
case KVM_CAP_MAX_VCPUS:
r = KVM_MAX_VCPUS;
break;
case KVM_CAP_NR_MEMSLOTS:
r = KVM_USER_MEM_SLOTS;
break;
case KVM_CAP_PV_MMU: /* obsolete */
r = 0;
break;
case KVM_CAP_IOMMU:
r = iommu_present(&pci_bus_type);
break;
case KVM_CAP_MCE:
r = KVM_MAX_MCE_BANKS;
break;
case KVM_CAP_XCRS:
r = cpu_has_xsave;
break;
case KVM_CAP_TSC_CONTROL:
r = kvm_has_tsc_control;
break;
case KVM_CAP_TSC_DEADLINE_TIMER:
r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
break;
default:
r = 0;
break;
}
return r;
}
long kvm_arch_dev_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
void __user *argp = (void __user *)arg;
long r;
switch (ioctl) {
case KVM_GET_MSR_INDEX_LIST: {
struct kvm_msr_list __user *user_msr_list = argp;
struct kvm_msr_list msr_list;
unsigned n;
r = -EFAULT;
if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
goto out;
n = msr_list.nmsrs;
msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
goto out;
r = -E2BIG;
if (n < msr_list.nmsrs)
goto out;
r = -EFAULT;
if (copy_to_user(user_msr_list->indices, &msrs_to_save,
num_msrs_to_save * sizeof(u32)))
goto out;
if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
&emulated_msrs,
ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
goto out;
r = 0;
break;
}
case KVM_GET_SUPPORTED_CPUID: {
struct kvm_cpuid2 __user *cpuid_arg = argp;
struct kvm_cpuid2 cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
cpuid_arg->entries);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
goto out;
r = 0;
break;
}
case KVM_X86_GET_MCE_CAP_SUPPORTED: {
u64 mce_cap;
mce_cap = KVM_MCE_CAP_SUPPORTED;
r = -EFAULT;
if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
goto out;
r = 0;
break;
}
default:
r = -EINVAL;
}
out:
return r;
}
static void wbinvd_ipi(void *garbage)
{
wbinvd();
}
static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
{
return vcpu->kvm->arch.iommu_domain &&
!(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
}
void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
{
/* Address WBINVD may be executed by guest */
if (need_emulate_wbinvd(vcpu)) {
if (kvm_x86_ops->has_wbinvd_exit())
cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
smp_call_function_single(vcpu->cpu,
wbinvd_ipi, NULL, 1);
}
kvm_x86_ops->vcpu_load(vcpu, cpu);
/* Apply any externally detected TSC adjustments (due to suspend) */
if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
vcpu->arch.tsc_offset_adjustment = 0;
set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
}
if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
native_read_tsc() - vcpu->arch.last_host_tsc;
if (tsc_delta < 0)
mark_tsc_unstable("KVM discovered backwards TSC");
if (check_tsc_unstable()) {
u64 offset = kvm_x86_ops->compute_tsc_offset(vcpu,
vcpu->arch.last_guest_tsc);
kvm_x86_ops->write_tsc_offset(vcpu, offset);
vcpu->arch.tsc_catchup = 1;
}
/*
* On a host with synchronized TSC, there is no need to update
* kvmclock on vcpu->cpu migration
*/
if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
if (vcpu->cpu != cpu)
kvm_migrate_timers(vcpu);
vcpu->cpu = cpu;
}
accumulate_steal_time(vcpu);
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
}
void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
{
kvm_x86_ops->vcpu_put(vcpu);
kvm_put_guest_fpu(vcpu);
vcpu->arch.last_host_tsc = native_read_tsc();
}
static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
struct kvm_lapic_state *s)
{
memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
return 0;
}
static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
struct kvm_lapic_state *s)
{
kvm_apic_post_state_restore(vcpu, s);
update_cr8_intercept(vcpu);
return 0;
}
static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
struct kvm_interrupt *irq)
{
if (irq->irq < 0 || irq->irq >= KVM_NR_INTERRUPTS)
return -EINVAL;
if (irqchip_in_kernel(vcpu->kvm))
return -ENXIO;
kvm_queue_interrupt(vcpu, irq->irq, false);
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
{
kvm_inject_nmi(vcpu);
return 0;
}
static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
struct kvm_tpr_access_ctl *tac)
{
if (tac->flags)
return -EINVAL;
vcpu->arch.tpr_access_reporting = !!tac->enabled;
return 0;
}
static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
u64 mcg_cap)
{
int r;
unsigned bank_num = mcg_cap & 0xff, bank;
r = -EINVAL;
if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
goto out;
if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
goto out;
r = 0;
vcpu->arch.mcg_cap = mcg_cap;
/* Init IA32_MCG_CTL to all 1s */
if (mcg_cap & MCG_CTL_P)
vcpu->arch.mcg_ctl = ~(u64)0;
/* Init IA32_MCi_CTL to all 1s */
for (bank = 0; bank < bank_num; bank++)
vcpu->arch.mce_banks[bank*4] = ~(u64)0;
out:
return r;
}
static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
struct kvm_x86_mce *mce)
{
u64 mcg_cap = vcpu->arch.mcg_cap;
unsigned bank_num = mcg_cap & 0xff;
u64 *banks = vcpu->arch.mce_banks;
if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
return -EINVAL;
/*
* if IA32_MCG_CTL is not all 1s, the uncorrected error
* reporting is disabled
*/
if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
vcpu->arch.mcg_ctl != ~(u64)0)
return 0;
banks += 4 * mce->bank;
/*
* if IA32_MCi_CTL is not all 1s, the uncorrected error
* reporting is disabled for the bank
*/
if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
return 0;
if (mce->status & MCI_STATUS_UC) {
if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
!kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return 0;
}
if (banks[1] & MCI_STATUS_VAL)
mce->status |= MCI_STATUS_OVER;
banks[2] = mce->addr;
banks[3] = mce->misc;
vcpu->arch.mcg_status = mce->mcg_status;
banks[1] = mce->status;
kvm_queue_exception(vcpu, MC_VECTOR);
} else if (!(banks[1] & MCI_STATUS_VAL)
|| !(banks[1] & MCI_STATUS_UC)) {
if (banks[1] & MCI_STATUS_VAL)
mce->status |= MCI_STATUS_OVER;
banks[2] = mce->addr;
banks[3] = mce->misc;
banks[1] = mce->status;
} else
banks[1] |= MCI_STATUS_OVER;
return 0;
}
static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
process_nmi(vcpu);
events->exception.injected =
vcpu->arch.exception.pending &&
!kvm_exception_is_soft(vcpu->arch.exception.nr);
events->exception.nr = vcpu->arch.exception.nr;
events->exception.has_error_code = vcpu->arch.exception.has_error_code;
events->exception.pad = 0;
events->exception.error_code = vcpu->arch.exception.error_code;
events->interrupt.injected =
vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
events->interrupt.nr = vcpu->arch.interrupt.nr;
events->interrupt.soft = 0;
events->interrupt.shadow =
kvm_x86_ops->get_interrupt_shadow(vcpu,
KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
events->nmi.injected = vcpu->arch.nmi_injected;
events->nmi.pending = vcpu->arch.nmi_pending != 0;
events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
events->nmi.pad = 0;
events->sipi_vector = vcpu->arch.sipi_vector;
events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
| KVM_VCPUEVENT_VALID_SIPI_VECTOR
| KVM_VCPUEVENT_VALID_SHADOW);
memset(&events->reserved, 0, sizeof(events->reserved));
}
static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
| KVM_VCPUEVENT_VALID_SIPI_VECTOR
| KVM_VCPUEVENT_VALID_SHADOW))
return -EINVAL;
process_nmi(vcpu);
vcpu->arch.exception.pending = events->exception.injected;
vcpu->arch.exception.nr = events->exception.nr;
vcpu->arch.exception.has_error_code = events->exception.has_error_code;
vcpu->arch.exception.error_code = events->exception.error_code;
vcpu->arch.interrupt.pending = events->interrupt.injected;
vcpu->arch.interrupt.nr = events->interrupt.nr;
vcpu->arch.interrupt.soft = events->interrupt.soft;
if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
kvm_x86_ops->set_interrupt_shadow(vcpu,
events->interrupt.shadow);
vcpu->arch.nmi_injected = events->nmi.injected;
if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
vcpu->arch.nmi_pending = events->nmi.pending;
kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
vcpu->arch.sipi_vector = events->sipi_vector;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
struct kvm_debugregs *dbgregs)
{
memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
dbgregs->dr6 = vcpu->arch.dr6;
dbgregs->dr7 = vcpu->arch.dr7;
dbgregs->flags = 0;
memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
}
static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
struct kvm_debugregs *dbgregs)
{
if (dbgregs->flags)
return -EINVAL;
memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
vcpu->arch.dr6 = dbgregs->dr6;
vcpu->arch.dr7 = dbgregs->dr7;
return 0;
}
static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
struct kvm_xsave *guest_xsave)
{
if (cpu_has_xsave)
memcpy(guest_xsave->region,
&vcpu->arch.guest_fpu.state->xsave,
xstate_size);
else {
memcpy(guest_xsave->region,
&vcpu->arch.guest_fpu.state->fxsave,
sizeof(struct i387_fxsave_struct));
*(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
XSTATE_FPSSE;
}
}
static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
struct kvm_xsave *guest_xsave)
{
u64 xstate_bv =
*(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
if (cpu_has_xsave)
memcpy(&vcpu->arch.guest_fpu.state->xsave,
guest_xsave->region, xstate_size);
else {
if (xstate_bv & ~XSTATE_FPSSE)
return -EINVAL;
memcpy(&vcpu->arch.guest_fpu.state->fxsave,
guest_xsave->region, sizeof(struct i387_fxsave_struct));
}
return 0;
}
static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
struct kvm_xcrs *guest_xcrs)
{
if (!cpu_has_xsave) {
guest_xcrs->nr_xcrs = 0;
return;
}
guest_xcrs->nr_xcrs = 1;
guest_xcrs->flags = 0;
guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
}
static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
struct kvm_xcrs *guest_xcrs)
{
int i, r = 0;
if (!cpu_has_xsave)
return -EINVAL;
if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
return -EINVAL;
for (i = 0; i < guest_xcrs->nr_xcrs; i++)
/* Only support XCR0 currently */
if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
guest_xcrs->xcrs[0].value);
break;
}
if (r)
r = -EINVAL;
return r;
}
/*
* kvm_set_guest_paused() indicates to the guest kernel that it has been
* stopped by the hypervisor. This function will be called from the host only.
* EINVAL is returned when the host attempts to set the flag for a guest that
* does not support pv clocks.
*/
static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
{
if (!vcpu->arch.time_page)
return -EINVAL;
vcpu->arch.pvclock_set_guest_stopped_request = true;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
return 0;
}
long kvm_arch_vcpu_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm_vcpu *vcpu = filp->private_data;
void __user *argp = (void __user *)arg;
int r;
union {
struct kvm_lapic_state *lapic;
struct kvm_xsave *xsave;
struct kvm_xcrs *xcrs;
void *buffer;
} u;
u.buffer = NULL;
switch (ioctl) {
case KVM_GET_LAPIC: {
r = -EINVAL;
if (!vcpu->arch.apic)
goto out;
u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
r = -ENOMEM;
if (!u.lapic)
goto out;
r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
goto out;
r = 0;
break;
}
case KVM_SET_LAPIC: {
r = -EINVAL;
if (!vcpu->arch.apic)
goto out;
u.lapic = memdup_user(argp, sizeof(*u.lapic));
if (IS_ERR(u.lapic))
return PTR_ERR(u.lapic);
r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
break;
}
case KVM_INTERRUPT: {
struct kvm_interrupt irq;
r = -EFAULT;
if (copy_from_user(&irq, argp, sizeof irq))
goto out;
r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
break;
}
case KVM_NMI: {
r = kvm_vcpu_ioctl_nmi(vcpu);
break;
}
case KVM_SET_CPUID: {
struct kvm_cpuid __user *cpuid_arg = argp;
struct kvm_cpuid cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
break;
}
case KVM_SET_CPUID2: {
struct kvm_cpuid2 __user *cpuid_arg = argp;
struct kvm_cpuid2 cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
cpuid_arg->entries);
break;
}
case KVM_GET_CPUID2: {
struct kvm_cpuid2 __user *cpuid_arg = argp;
struct kvm_cpuid2 cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
cpuid_arg->entries);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
goto out;
r = 0;
break;
}
case KVM_GET_MSRS:
r = msr_io(vcpu, argp, kvm_get_msr, 1);
break;
case KVM_SET_MSRS:
r = msr_io(vcpu, argp, do_set_msr, 0);
break;
case KVM_TPR_ACCESS_REPORTING: {
struct kvm_tpr_access_ctl tac;
r = -EFAULT;
if (copy_from_user(&tac, argp, sizeof tac))
goto out;
r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &tac, sizeof tac))
goto out;
r = 0;
break;
};
case KVM_SET_VAPIC_ADDR: {
struct kvm_vapic_addr va;
r = -EINVAL;
if (!irqchip_in_kernel(vcpu->kvm))
goto out;
r = -EFAULT;
if (copy_from_user(&va, argp, sizeof va))
goto out;
r = 0;
kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
break;
}
case KVM_X86_SETUP_MCE: {
u64 mcg_cap;
r = -EFAULT;
if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
goto out;
r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
break;
}
case KVM_X86_SET_MCE: {
struct kvm_x86_mce mce;
r = -EFAULT;
if (copy_from_user(&mce, argp, sizeof mce))
goto out;
r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
break;
}
case KVM_GET_VCPU_EVENTS: {
struct kvm_vcpu_events events;
kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
r = -EFAULT;
if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
break;
r = 0;
break;
}
case KVM_SET_VCPU_EVENTS: {
struct kvm_vcpu_events events;
r = -EFAULT;
if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
break;
r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
break;
}
case KVM_GET_DEBUGREGS: {
struct kvm_debugregs dbgregs;
kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
r = -EFAULT;
if (copy_to_user(argp, &dbgregs,
sizeof(struct kvm_debugregs)))
break;
r = 0;
break;
}
case KVM_SET_DEBUGREGS: {
struct kvm_debugregs dbgregs;
r = -EFAULT;
if (copy_from_user(&dbgregs, argp,
sizeof(struct kvm_debugregs)))
break;
r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
break;
}
case KVM_GET_XSAVE: {
u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
r = -ENOMEM;
if (!u.xsave)
break;
kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
r = -EFAULT;
if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
break;
r = 0;
break;
}
case KVM_SET_XSAVE: {
u.xsave = memdup_user(argp, sizeof(*u.xsave));
if (IS_ERR(u.xsave))
return PTR_ERR(u.xsave);
r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
break;
}
case KVM_GET_XCRS: {
u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
r = -ENOMEM;
if (!u.xcrs)
break;
kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
r = -EFAULT;
if (copy_to_user(argp, u.xcrs,
sizeof(struct kvm_xcrs)))
break;
r = 0;
break;
}
case KVM_SET_XCRS: {
u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
if (IS_ERR(u.xcrs))
return PTR_ERR(u.xcrs);
r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
break;
}
case KVM_SET_TSC_KHZ: {
u32 user_tsc_khz;
r = -EINVAL;
user_tsc_khz = (u32)arg;
if (user_tsc_khz >= kvm_max_guest_tsc_khz)
goto out;
if (user_tsc_khz == 0)
user_tsc_khz = tsc_khz;
kvm_set_tsc_khz(vcpu, user_tsc_khz);
r = 0;
goto out;
}
case KVM_GET_TSC_KHZ: {
r = vcpu->arch.virtual_tsc_khz;
goto out;
}
case KVM_KVMCLOCK_CTRL: {
r = kvm_set_guest_paused(vcpu);
goto out;
}
default:
r = -EINVAL;
}
out:
kfree(u.buffer);
return r;
}
int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
{
return VM_FAULT_SIGBUS;
}
static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
{
int ret;
if (addr > (unsigned int)(-3 * PAGE_SIZE))
return -EINVAL;
ret = kvm_x86_ops->set_tss_addr(kvm, addr);
return ret;
}
static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
u64 ident_addr)
{
kvm->arch.ept_identity_map_addr = ident_addr;
return 0;
}
static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
u32 kvm_nr_mmu_pages)
{
if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
return -EINVAL;
mutex_lock(&kvm->slots_lock);
kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
mutex_unlock(&kvm->slots_lock);
return 0;
}
static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
{
return kvm->arch.n_max_mmu_pages;
}
static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
{
int r;
r = 0;
switch (chip->chip_id) {
case KVM_IRQCHIP_PIC_MASTER:
memcpy(&chip->chip.pic,
&pic_irqchip(kvm)->pics[0],
sizeof(struct kvm_pic_state));
break;
case KVM_IRQCHIP_PIC_SLAVE:
memcpy(&chip->chip.pic,
&pic_irqchip(kvm)->pics[1],
sizeof(struct kvm_pic_state));
break;
case KVM_IRQCHIP_IOAPIC:
r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
break;
default:
r = -EINVAL;
break;
}
return r;
}
static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
{
int r;
r = 0;
switch (chip->chip_id) {
case KVM_IRQCHIP_PIC_MASTER:
spin_lock(&pic_irqchip(kvm)->lock);
memcpy(&pic_irqchip(kvm)->pics[0],
&chip->chip.pic,
sizeof(struct kvm_pic_state));
spin_unlock(&pic_irqchip(kvm)->lock);
break;
case KVM_IRQCHIP_PIC_SLAVE:
spin_lock(&pic_irqchip(kvm)->lock);
memcpy(&pic_irqchip(kvm)->pics[1],
&chip->chip.pic,
sizeof(struct kvm_pic_state));
spin_unlock(&pic_irqchip(kvm)->lock);
break;
case KVM_IRQCHIP_IOAPIC:
r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
break;
default:
r = -EINVAL;
break;
}
kvm_pic_update_irq(pic_irqchip(kvm));
return r;
}
static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
{
int r = 0;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return r;
}
static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
{
int r = 0;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return r;
}
static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
int r = 0;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
sizeof(ps->channels));
ps->flags = kvm->arch.vpit->pit_state.flags;
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
memset(&ps->reserved, 0, sizeof(ps->reserved));
return r;
}
static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
int r = 0, start = 0;
u32 prev_legacy, cur_legacy;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
if (!prev_legacy && cur_legacy)
start = 1;
memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
sizeof(kvm->arch.vpit->pit_state.channels));
kvm->arch.vpit->pit_state.flags = ps->flags;
kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return r;
}
static int kvm_vm_ioctl_reinject(struct kvm *kvm,
struct kvm_reinject_control *control)
{
if (!kvm->arch.vpit)
return -ENXIO;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return 0;
}
/**
* kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
* @kvm: kvm instance
* @log: slot id and address to which we copy the log
*
* We need to keep it in mind that VCPU threads can write to the bitmap
* concurrently. So, to avoid losing data, we keep the following order for
* each bit:
*
* 1. Take a snapshot of the bit and clear it if needed.
* 2. Write protect the corresponding page.
* 3. Flush TLB's if needed.
* 4. Copy the snapshot to the userspace.
*
* Between 2 and 3, the guest may write to the page using the remaining TLB
* entry. This is not a problem because the page will be reported dirty at
* step 4 using the snapshot taken before and step 3 ensures that successive
* writes will be logged for the next call.
*/
int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
{
int r;
struct kvm_memory_slot *memslot;
unsigned long n, i;
unsigned long *dirty_bitmap;
unsigned long *dirty_bitmap_buffer;
bool is_dirty = false;
mutex_lock(&kvm->slots_lock);
r = -EINVAL;
if (log->slot >= KVM_USER_MEM_SLOTS)
goto out;
memslot = id_to_memslot(kvm->memslots, log->slot);
dirty_bitmap = memslot->dirty_bitmap;
r = -ENOENT;
if (!dirty_bitmap)
goto out;
n = kvm_dirty_bitmap_bytes(memslot);
dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
memset(dirty_bitmap_buffer, 0, n);
spin_lock(&kvm->mmu_lock);
for (i = 0; i < n / sizeof(long); i++) {
unsigned long mask;
gfn_t offset;
if (!dirty_bitmap[i])
continue;
is_dirty = true;
mask = xchg(&dirty_bitmap[i], 0);
dirty_bitmap_buffer[i] = mask;
offset = i * BITS_PER_LONG;
kvm_mmu_write_protect_pt_masked(kvm, memslot, offset, mask);
}
if (is_dirty)
kvm_flush_remote_tlbs(kvm);
spin_unlock(&kvm->mmu_lock);
r = -EFAULT;
if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
goto out;
r = 0;
out:
mutex_unlock(&kvm->slots_lock);
return r;
}
int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event)
{
if (!irqchip_in_kernel(kvm))
return -ENXIO;
irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
irq_event->irq, irq_event->level);
return 0;
}
long kvm_arch_vm_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
void __user *argp = (void __user *)arg;
int r = -ENOTTY;
/*
* This union makes it completely explicit to gcc-3.x
* that these two variables' stack usage should be
* combined, not added together.
*/
union {
struct kvm_pit_state ps;
struct kvm_pit_state2 ps2;
struct kvm_pit_config pit_config;
} u;
switch (ioctl) {
case KVM_SET_TSS_ADDR:
r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
break;
case KVM_SET_IDENTITY_MAP_ADDR: {
u64 ident_addr;
r = -EFAULT;
if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
goto out;
r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
break;
}
case KVM_SET_NR_MMU_PAGES:
r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
break;
case KVM_GET_NR_MMU_PAGES:
r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
break;
case KVM_CREATE_IRQCHIP: {
struct kvm_pic *vpic;
mutex_lock(&kvm->lock);
r = -EEXIST;
if (kvm->arch.vpic)
goto create_irqchip_unlock;
r = -EINVAL;
if (atomic_read(&kvm->online_vcpus))
goto create_irqchip_unlock;
r = -ENOMEM;
vpic = kvm_create_pic(kvm);
if (vpic) {
r = kvm_ioapic_init(kvm);
if (r) {
mutex_lock(&kvm->slots_lock);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_master);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_slave);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_eclr);
mutex_unlock(&kvm->slots_lock);
kfree(vpic);
goto create_irqchip_unlock;
}
} else
goto create_irqchip_unlock;
smp_wmb();
kvm->arch.vpic = vpic;
smp_wmb();
r = kvm_setup_default_irq_routing(kvm);
if (r) {
mutex_lock(&kvm->slots_lock);
mutex_lock(&kvm->irq_lock);
kvm_ioapic_destroy(kvm);
kvm_destroy_pic(kvm);
mutex_unlock(&kvm->irq_lock);
mutex_unlock(&kvm->slots_lock);
}
create_irqchip_unlock:
mutex_unlock(&kvm->lock);
break;
}
case KVM_CREATE_PIT:
u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
goto create_pit;
case KVM_CREATE_PIT2:
r = -EFAULT;
if (copy_from_user(&u.pit_config, argp,
sizeof(struct kvm_pit_config)))
goto out;
create_pit:
mutex_lock(&kvm->slots_lock);
r = -EEXIST;
if (kvm->arch.vpit)
goto create_pit_unlock;
r = -ENOMEM;
kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
if (kvm->arch.vpit)
r = 0;
create_pit_unlock:
mutex_unlock(&kvm->slots_lock);
break;
case KVM_GET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip *chip;
chip = memdup_user(argp, sizeof(*chip));
if (IS_ERR(chip)) {
r = PTR_ERR(chip);
goto out;
}
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto get_irqchip_out;
r = kvm_vm_ioctl_get_irqchip(kvm, chip);
if (r)
goto get_irqchip_out;
r = -EFAULT;
if (copy_to_user(argp, chip, sizeof *chip))
goto get_irqchip_out;
r = 0;
get_irqchip_out:
kfree(chip);
break;
}
case KVM_SET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip *chip;
chip = memdup_user(argp, sizeof(*chip));
if (IS_ERR(chip)) {
r = PTR_ERR(chip);
goto out;
}
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto set_irqchip_out;
r = kvm_vm_ioctl_set_irqchip(kvm, chip);
if (r)
goto set_irqchip_out;
r = 0;
set_irqchip_out:
kfree(chip);
break;
}
case KVM_GET_PIT: {
r = -EFAULT;
if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
goto out;
r = 0;
break;
}
case KVM_SET_PIT: {
r = -EFAULT;
if (copy_from_user(&u.ps, argp, sizeof u.ps))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
break;
}
case KVM_GET_PIT2: {
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
goto out;
r = 0;
break;
}
case KVM_SET_PIT2: {
r = -EFAULT;
if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
break;
}
case KVM_REINJECT_CONTROL: {
struct kvm_reinject_control control;
r = -EFAULT;
if (copy_from_user(&control, argp, sizeof(control)))
goto out;
r = kvm_vm_ioctl_reinject(kvm, &control);
break;
}
case KVM_XEN_HVM_CONFIG: {
r = -EFAULT;
if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
sizeof(struct kvm_xen_hvm_config)))
goto out;
r = -EINVAL;
if (kvm->arch.xen_hvm_config.flags)
goto out;
r = 0;
break;
}
case KVM_SET_CLOCK: {
struct kvm_clock_data user_ns;
u64 now_ns;
s64 delta;
r = -EFAULT;
if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
goto out;
r = -EINVAL;
if (user_ns.flags)
goto out;
r = 0;
local_irq_disable();
now_ns = get_kernel_ns();
delta = user_ns.clock - now_ns;
local_irq_enable();
kvm->arch.kvmclock_offset = delta;
break;
}
case KVM_GET_CLOCK: {
struct kvm_clock_data user_ns;
u64 now_ns;
local_irq_disable();
now_ns = get_kernel_ns();
user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
local_irq_enable();
user_ns.flags = 0;
memset(&user_ns.pad, 0, sizeof(user_ns.pad));
r = -EFAULT;
if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
goto out;
r = 0;
break;
}
default:
;
}
out:
return r;
}
static void kvm_init_msr_list(void)
{
u32 dummy[2];
unsigned i, j;
/* skip the first msrs in the list. KVM-specific */
for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
continue;
if (j < i)
msrs_to_save[j] = msrs_to_save[i];
j++;
}
num_msrs_to_save = j;
}
static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
const void *v)
{
int handled = 0;
int n;
do {
n = min(len, 8);
if (!(vcpu->arch.apic &&
!kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
&& kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
break;
handled += n;
addr += n;
len -= n;
v += n;
} while (len);
return handled;
}
static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
{
int handled = 0;
int n;
do {
n = min(len, 8);
if (!(vcpu->arch.apic &&
!kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
&& kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
break;
trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
handled += n;
addr += n;
len -= n;
v += n;
} while (len);
return handled;
}
static void kvm_set_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
kvm_x86_ops->set_segment(vcpu, var, seg);
}
void kvm_get_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
kvm_x86_ops->get_segment(vcpu, var, seg);
}
gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
{
gpa_t t_gpa;
struct x86_exception exception;
BUG_ON(!mmu_is_nested(vcpu));
/* NPT walks are always user-walks */
access |= PFERR_USER_MASK;
t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
return t_gpa;
}
gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
}
gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
access |= PFERR_FETCH_MASK;
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
}
gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
access |= PFERR_WRITE_MASK;
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
}
/* uses this to access any guest's mapped memory without checking CPL */
gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
}
static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
struct kvm_vcpu *vcpu, u32 access,
struct x86_exception *exception)
{
void *data = val;
int r = X86EMUL_CONTINUE;
while (bytes) {
gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
exception);
unsigned offset = addr & (PAGE_SIZE-1);
unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
int ret;
if (gpa == UNMAPPED_GVA)
return X86EMUL_PROPAGATE_FAULT;
ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
if (ret < 0) {
r = X86EMUL_IO_NEEDED;
goto out;
}
bytes -= toread;
data += toread;
addr += toread;
}
out:
return r;
}
/* used for instruction fetching */
static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val, unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
access | PFERR_FETCH_MASK,
exception);
}
int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val, unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
exception);
}
EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val, unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
}
int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val,
unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
void *data = val;
int r = X86EMUL_CONTINUE;
while (bytes) {
gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
PFERR_WRITE_MASK,
exception);
unsigned offset = addr & (PAGE_SIZE-1);
unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
int ret;
if (gpa == UNMAPPED_GVA)
return X86EMUL_PROPAGATE_FAULT;
ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
if (ret < 0) {
r = X86EMUL_IO_NEEDED;
goto out;
}
bytes -= towrite;
data += towrite;
addr += towrite;
}
out:
return r;
}
EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
gpa_t *gpa, struct x86_exception *exception,
bool write)
{
u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
| (write ? PFERR_WRITE_MASK : 0);
if (vcpu_match_mmio_gva(vcpu, gva)
&& !permission_fault(vcpu->arch.walk_mmu, vcpu->arch.access, access)) {
*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
(gva & (PAGE_SIZE - 1));
trace_vcpu_match_mmio(gva, *gpa, write, false);
return 1;
}
*gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
if (*gpa == UNMAPPED_GVA)
return -1;
/* For APIC access vmexit */
if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
return 1;
if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
trace_vcpu_match_mmio(gva, *gpa, write, true);
return 1;
}
return 0;
}
int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
const void *val, int bytes)
{
int ret;
ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
if (ret < 0)
return 0;
kvm_mmu_pte_write(vcpu, gpa, val, bytes);
return 1;
}
struct read_write_emulator_ops {
int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
int bytes);
int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes);
int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
int bytes, void *val);
int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes);
bool write;
};
static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
{
if (vcpu->mmio_read_completed) {
trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
vcpu->mmio_fragments[0].gpa, *(u64 *)val);
vcpu->mmio_read_completed = 0;
return 1;
}
return 0;
}
static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
}
static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
return emulator_write_phys(vcpu, gpa, val, bytes);
}
static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
{
trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
return vcpu_mmio_write(vcpu, gpa, bytes, val);
}
static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
return X86EMUL_IO_NEEDED;
}
static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
return X86EMUL_CONTINUE;
}
static const struct read_write_emulator_ops read_emultor = {
.read_write_prepare = read_prepare,
.read_write_emulate = read_emulate,
.read_write_mmio = vcpu_mmio_read,
.read_write_exit_mmio = read_exit_mmio,
};
static const struct read_write_emulator_ops write_emultor = {
.read_write_emulate = write_emulate,
.read_write_mmio = write_mmio,
.read_write_exit_mmio = write_exit_mmio,
.write = true,
};
static int emulator_read_write_onepage(unsigned long addr, void *val,
unsigned int bytes,
struct x86_exception *exception,
struct kvm_vcpu *vcpu,
const struct read_write_emulator_ops *ops)
{
gpa_t gpa;
int handled, ret;
bool write = ops->write;
struct kvm_mmio_fragment *frag;
ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
if (ret < 0)
return X86EMUL_PROPAGATE_FAULT;
/* For APIC access vmexit */
if (ret)
goto mmio;
if (ops->read_write_emulate(vcpu, gpa, val, bytes))
return X86EMUL_CONTINUE;
mmio:
/*
* Is this MMIO handled locally?
*/
handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
if (handled == bytes)
return X86EMUL_CONTINUE;
gpa += handled;
bytes -= handled;
val += handled;
WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
frag->gpa = gpa;
frag->data = val;
frag->len = bytes;
return X86EMUL_CONTINUE;
}
int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
void *val, unsigned int bytes,
struct x86_exception *exception,
const struct read_write_emulator_ops *ops)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
gpa_t gpa;
int rc;
if (ops->read_write_prepare &&
ops->read_write_prepare(vcpu, val, bytes))
return X86EMUL_CONTINUE;
vcpu->mmio_nr_fragments = 0;
/* Crossing a page boundary? */
if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
int now;
now = -addr & ~PAGE_MASK;
rc = emulator_read_write_onepage(addr, val, now, exception,
vcpu, ops);
if (rc != X86EMUL_CONTINUE)
return rc;
addr += now;
val += now;
bytes -= now;
}
rc = emulator_read_write_onepage(addr, val, bytes, exception,
vcpu, ops);
if (rc != X86EMUL_CONTINUE)
return rc;
if (!vcpu->mmio_nr_fragments)
return rc;
gpa = vcpu->mmio_fragments[0].gpa;
vcpu->mmio_needed = 1;
vcpu->mmio_cur_fragment = 0;
vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
vcpu->run->exit_reason = KVM_EXIT_MMIO;
vcpu->run->mmio.phys_addr = gpa;
return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
}
static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
unsigned long addr,
void *val,
unsigned int bytes,
struct x86_exception *exception)
{
return emulator_read_write(ctxt, addr, val, bytes,
exception, &read_emultor);
}
int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
unsigned long addr,
const void *val,
unsigned int bytes,
struct x86_exception *exception)
{
return emulator_read_write(ctxt, addr, (void *)val, bytes,
exception, &write_emultor);
}
#define CMPXCHG_TYPE(t, ptr, old, new) \
(cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
#ifdef CONFIG_X86_64
# define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
#else
# define CMPXCHG64(ptr, old, new) \
(cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
#endif
static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
unsigned long addr,
const void *old,
const void *new,
unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
gpa_t gpa;
struct page *page;
char *kaddr;
bool exchanged;
/* guests cmpxchg8b have to be emulated atomically */
if (bytes > 8 || (bytes & (bytes - 1)))
goto emul_write;
gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
if (gpa == UNMAPPED_GVA ||
(gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
goto emul_write;
if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
goto emul_write;
page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
if (is_error_page(page))
goto emul_write;
kaddr = kmap_atomic(page);
kaddr += offset_in_page(gpa);
switch (bytes) {
case 1:
exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
break;
case 2:
exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
break;
case 4:
exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
break;
case 8:
exchanged = CMPXCHG64(kaddr, old, new);
break;
default:
BUG();
}
kunmap_atomic(kaddr);
kvm_release_page_dirty(page);
if (!exchanged)
return X86EMUL_CMPXCHG_FAILED;
kvm_mmu_pte_write(vcpu, gpa, new, bytes);
return X86EMUL_CONTINUE;
emul_write:
printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
return emulator_write_emulated(ctxt, addr, new, bytes, exception);
}
static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
{
/* TODO: String I/O for in kernel device */
int r;
if (vcpu->arch.pio.in)
r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
vcpu->arch.pio.size, pd);
else
r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
vcpu->arch.pio.port, vcpu->arch.pio.size,
pd);
return r;
}
static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
unsigned short port, void *val,
unsigned int count, bool in)
{
trace_kvm_pio(!in, port, size, count);
vcpu->arch.pio.port = port;
vcpu->arch.pio.in = in;
vcpu->arch.pio.count = count;
vcpu->arch.pio.size = size;
if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
vcpu->arch.pio.count = 0;
return 1;
}
vcpu->run->exit_reason = KVM_EXIT_IO;
vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
vcpu->run->io.size = size;
vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
vcpu->run->io.count = count;
vcpu->run->io.port = port;
return 0;
}
static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
int size, unsigned short port, void *val,
unsigned int count)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
int ret;
if (vcpu->arch.pio.count)
goto data_avail;
ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
if (ret) {
data_avail:
memcpy(val, vcpu->arch.pio_data, size * count);
vcpu->arch.pio.count = 0;
return 1;
}
return 0;
}
static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
int size, unsigned short port,
const void *val, unsigned int count)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
memcpy(vcpu->arch.pio_data, val, size * count);
return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
}
static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
{
return kvm_x86_ops->get_segment_base(vcpu, seg);
}
static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
{
kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
}
int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
{
if (!need_emulate_wbinvd(vcpu))
return X86EMUL_CONTINUE;
if (kvm_x86_ops->has_wbinvd_exit()) {
int cpu = get_cpu();
cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
wbinvd_ipi, NULL, 1);
put_cpu();
cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
} else
wbinvd();
return X86EMUL_CONTINUE;
}
EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
{
kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
}
int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
{
return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
}
int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
{
return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
}
static u64 mk_cr_64(u64 curr_cr, u32 new_val)
{
return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
}
static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
unsigned long value;
switch (cr) {
case 0:
value = kvm_read_cr0(vcpu);
break;
case 2:
value = vcpu->arch.cr2;
break;
case 3:
value = kvm_read_cr3(vcpu);
break;
case 4:
value = kvm_read_cr4(vcpu);
break;
case 8:
value = kvm_get_cr8(vcpu);
break;
default:
kvm_err("%s: unexpected cr %u\n", __func__, cr);
return 0;
}
return value;
}
static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
int res = 0;
switch (cr) {
case 0:
res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
break;
case 2:
vcpu->arch.cr2 = val;
break;
case 3:
res = kvm_set_cr3(vcpu, val);
break;
case 4:
res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
break;
case 8:
res = kvm_set_cr8(vcpu, val);
break;
default:
kvm_err("%s: unexpected cr %u\n", __func__, cr);
res = -1;
}
return res;
}
static void emulator_set_rflags(struct x86_emulate_ctxt *ctxt, ulong val)
{
kvm_set_rflags(emul_to_vcpu(ctxt), val);
}
static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
{
return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
}
static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
}
static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
}
static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
}
static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
}
static unsigned long emulator_get_cached_segment_base(
struct x86_emulate_ctxt *ctxt, int seg)
{
return get_segment_base(emul_to_vcpu(ctxt), seg);
}
static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
struct desc_struct *desc, u32 *base3,
int seg)
{
struct kvm_segment var;
kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
*selector = var.selector;
if (var.unusable) {
memset(desc, 0, sizeof(*desc));
return false;
}
if (var.g)
var.limit >>= 12;
set_desc_limit(desc, var.limit);
set_desc_base(desc, (unsigned long)var.base);
#ifdef CONFIG_X86_64
if (base3)
*base3 = var.base >> 32;
#endif
desc->type = var.type;
desc->s = var.s;
desc->dpl = var.dpl;
desc->p = var.present;
desc->avl = var.avl;
desc->l = var.l;
desc->d = var.db;
desc->g = var.g;
return true;
}
static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
struct desc_struct *desc, u32 base3,
int seg)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
struct kvm_segment var;
var.selector = selector;
var.base = get_desc_base(desc);
#ifdef CONFIG_X86_64
var.base |= ((u64)base3) << 32;
#endif
var.limit = get_desc_limit(desc);
if (desc->g)
var.limit = (var.limit << 12) | 0xfff;
var.type = desc->type;
var.present = desc->p;
var.dpl = desc->dpl;
var.db = desc->d;
var.s = desc->s;
var.l = desc->l;
var.g = desc->g;
var.avl = desc->avl;
var.present = desc->p;
var.unusable = !var.present;
var.padding = 0;
kvm_set_segment(vcpu, &var, seg);
return;
}
static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
u32 msr_index, u64 *pdata)
{
return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
}
static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
u32 msr_index, u64 data)
{
struct msr_data msr;
msr.data = data;
msr.index = msr_index;
msr.host_initiated = false;
return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
}
static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
u32 pmc, u64 *pdata)
{
return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
}
static void emulator_halt(struct x86_emulate_ctxt *ctxt)
{
emul_to_vcpu(ctxt)->arch.halt_request = 1;
}
static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
{
preempt_disable();
kvm_load_guest_fpu(emul_to_vcpu(ctxt));
/*
* CR0.TS may reference the host fpu state, not the guest fpu state,
* so it may be clear at this point.
*/
clts();
}
static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
{
preempt_enable();
}
static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
struct x86_instruction_info *info,
enum x86_intercept_stage stage)
{
return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
}
static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
{
kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
}
static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
{
return kvm_register_read(emul_to_vcpu(ctxt), reg);
}
static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
{
kvm_register_write(emul_to_vcpu(ctxt), reg, val);
}
static const struct x86_emulate_ops emulate_ops = {
.read_gpr = emulator_read_gpr,
.write_gpr = emulator_write_gpr,
.read_std = kvm_read_guest_virt_system,
.write_std = kvm_write_guest_virt_system,
.fetch = kvm_fetch_guest_virt,
.read_emulated = emulator_read_emulated,
.write_emulated = emulator_write_emulated,
.cmpxchg_emulated = emulator_cmpxchg_emulated,
.invlpg = emulator_invlpg,
.pio_in_emulated = emulator_pio_in_emulated,
.pio_out_emulated = emulator_pio_out_emulated,
.get_segment = emulator_get_segment,
.set_segment = emulator_set_segment,
.get_cached_segment_base = emulator_get_cached_segment_base,
.get_gdt = emulator_get_gdt,
.get_idt = emulator_get_idt,
.set_gdt = emulator_set_gdt,
.set_idt = emulator_set_idt,
.get_cr = emulator_get_cr,
.set_cr = emulator_set_cr,
.set_rflags = emulator_set_rflags,
.cpl = emulator_get_cpl,
.get_dr = emulator_get_dr,
.set_dr = emulator_set_dr,
.set_msr = emulator_set_msr,
.get_msr = emulator_get_msr,
.read_pmc = emulator_read_pmc,
.halt = emulator_halt,
.wbinvd = emulator_wbinvd,
.fix_hypercall = emulator_fix_hypercall,
.get_fpu = emulator_get_fpu,
.put_fpu = emulator_put_fpu,
.intercept = emulator_intercept,
.get_cpuid = emulator_get_cpuid,
};
static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
{
u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
/*
* an sti; sti; sequence only disable interrupts for the first
* instruction. So, if the last instruction, be it emulated or
* not, left the system with the INT_STI flag enabled, it
* means that the last instruction is an sti. We should not
* leave the flag on in this case. The same goes for mov ss
*/
if (!(int_shadow & mask))
kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
}
static void inject_emulated_exception(struct kvm_vcpu *vcpu)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
if (ctxt->exception.vector == PF_VECTOR)
kvm_propagate_fault(vcpu, &ctxt->exception);
else if (ctxt->exception.error_code_valid)
kvm_queue_exception_e(vcpu, ctxt->exception.vector,
ctxt->exception.error_code);
else
kvm_queue_exception(vcpu, ctxt->exception.vector);
}
static void init_decode_cache(struct x86_emulate_ctxt *ctxt)
{
memset(&ctxt->twobyte, 0,
(void *)&ctxt->_regs - (void *)&ctxt->twobyte);
ctxt->fetch.start = 0;
ctxt->fetch.end = 0;
ctxt->io_read.pos = 0;
ctxt->io_read.end = 0;
ctxt->mem_read.pos = 0;
ctxt->mem_read.end = 0;
}
static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
int cs_db, cs_l;
kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
ctxt->eflags = kvm_get_rflags(vcpu);
ctxt->eip = kvm_rip_read(vcpu);
ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
(ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
cs_l ? X86EMUL_MODE_PROT64 :
cs_db ? X86EMUL_MODE_PROT32 :
X86EMUL_MODE_PROT16;
ctxt->guest_mode = is_guest_mode(vcpu);
init_decode_cache(ctxt);
vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
}
int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
int ret;
init_emulate_ctxt(vcpu);
ctxt->op_bytes = 2;
ctxt->ad_bytes = 2;
ctxt->_eip = ctxt->eip + inc_eip;
ret = emulate_int_real(ctxt, irq);
if (ret != X86EMUL_CONTINUE)
return EMULATE_FAIL;
ctxt->eip = ctxt->_eip;
kvm_rip_write(vcpu, ctxt->eip);
kvm_set_rflags(vcpu, ctxt->eflags);
if (irq == NMI_VECTOR)
vcpu->arch.nmi_pending = 0;
else
vcpu->arch.interrupt.pending = false;
return EMULATE_DONE;
}
EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
static int handle_emulation_failure(struct kvm_vcpu *vcpu)
{
int r = EMULATE_DONE;
++vcpu->stat.insn_emulation_fail;
trace_kvm_emulate_insn_failed(vcpu);
if (!is_guest_mode(vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
r = EMULATE_FAIL;
}
kvm_queue_exception(vcpu, UD_VECTOR);
return r;
}
static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
bool write_fault_to_shadow_pgtable)
{
gpa_t gpa = cr2;
pfn_t pfn;
if (!vcpu->arch.mmu.direct_map) {
/*
* Write permission should be allowed since only
* write access need to be emulated.
*/
gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
/*
* If the mapping is invalid in guest, let cpu retry
* it to generate fault.
*/
if (gpa == UNMAPPED_GVA)
return true;
}
/*
* Do not retry the unhandleable instruction if it faults on the
* readonly host memory, otherwise it will goto a infinite loop:
* retry instruction -> write #PF -> emulation fail -> retry
* instruction -> ...
*/
pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
/*
* If the instruction failed on the error pfn, it can not be fixed,
* report the error to userspace.
*/
if (is_error_noslot_pfn(pfn))
return false;
kvm_release_pfn_clean(pfn);
/* The instructions are well-emulated on direct mmu. */
if (vcpu->arch.mmu.direct_map) {
unsigned int indirect_shadow_pages;
spin_lock(&vcpu->kvm->mmu_lock);
indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
spin_unlock(&vcpu->kvm->mmu_lock);
if (indirect_shadow_pages)
kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
return true;
}
/*
* if emulation was due to access to shadowed page table
* and it failed try to unshadow page and re-enter the
* guest to let CPU execute the instruction.
*/
kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
/*
* If the access faults on its page table, it can not
* be fixed by unprotecting shadow page and it should
* be reported to userspace.
*/
return !write_fault_to_shadow_pgtable;
}
static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
unsigned long cr2, int emulation_type)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
last_retry_eip = vcpu->arch.last_retry_eip;
last_retry_addr = vcpu->arch.last_retry_addr;
/*
* If the emulation is caused by #PF and it is non-page_table
* writing instruction, it means the VM-EXIT is caused by shadow
* page protected, we can zap the shadow page and retry this
* instruction directly.
*
* Note: if the guest uses a non-page-table modifying instruction
* on the PDE that points to the instruction, then we will unmap
* the instruction and go to an infinite loop. So, we cache the
* last retried eip and the last fault address, if we meet the eip
* and the address again, we can break out of the potential infinite
* loop.
*/
vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
if (!(emulation_type & EMULTYPE_RETRY))
return false;
if (x86_page_table_writing_insn(ctxt))
return false;
if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
return false;
vcpu->arch.last_retry_eip = ctxt->eip;
vcpu->arch.last_retry_addr = cr2;
if (!vcpu->arch.mmu.direct_map)
gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
return true;
}
static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
static int complete_emulated_pio(struct kvm_vcpu *vcpu);
int x86_emulate_instruction(struct kvm_vcpu *vcpu,
unsigned long cr2,
int emulation_type,
void *insn,
int insn_len)
{
int r;
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
bool writeback = true;
bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
/*
* Clear write_fault_to_shadow_pgtable here to ensure it is
* never reused.
*/
vcpu->arch.write_fault_to_shadow_pgtable = false;
kvm_clear_exception_queue(vcpu);
if (!(emulation_type & EMULTYPE_NO_DECODE)) {
init_emulate_ctxt(vcpu);
ctxt->interruptibility = 0;
ctxt->have_exception = false;
ctxt->perm_ok = false;
ctxt->only_vendor_specific_insn
= emulation_type & EMULTYPE_TRAP_UD;
r = x86_decode_insn(ctxt, insn, insn_len);
trace_kvm_emulate_insn_start(vcpu);
++vcpu->stat.insn_emulation;
if (r != EMULATION_OK) {
if (emulation_type & EMULTYPE_TRAP_UD)
return EMULATE_FAIL;
if (reexecute_instruction(vcpu, cr2,
write_fault_to_spt))
return EMULATE_DONE;
if (emulation_type & EMULTYPE_SKIP)
return EMULATE_FAIL;
return handle_emulation_failure(vcpu);
}
}
if (emulation_type & EMULTYPE_SKIP) {
kvm_rip_write(vcpu, ctxt->_eip);
return EMULATE_DONE;
}
if (retry_instruction(ctxt, cr2, emulation_type))
return EMULATE_DONE;
/* this is needed for vmware backdoor interface to work since it
changes registers values during IO operation */
if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
emulator_invalidate_register_cache(ctxt);
}
restart:
r = x86_emulate_insn(ctxt);
if (r == EMULATION_INTERCEPTED)
return EMULATE_DONE;
if (r == EMULATION_FAILED) {
if (reexecute_instruction(vcpu, cr2, write_fault_to_spt))
return EMULATE_DONE;
return handle_emulation_failure(vcpu);
}
if (ctxt->have_exception) {
inject_emulated_exception(vcpu);
r = EMULATE_DONE;
} else if (vcpu->arch.pio.count) {
if (!vcpu->arch.pio.in)
vcpu->arch.pio.count = 0;
else {
writeback = false;
vcpu->arch.complete_userspace_io = complete_emulated_pio;
}
r = EMULATE_DO_MMIO;
} else if (vcpu->mmio_needed) {
if (!vcpu->mmio_is_write)
writeback = false;
r = EMULATE_DO_MMIO;
vcpu->arch.complete_userspace_io = complete_emulated_mmio;
} else if (r == EMULATION_RESTART)
goto restart;
else
r = EMULATE_DONE;
if (writeback) {
toggle_interruptibility(vcpu, ctxt->interruptibility);
kvm_set_rflags(vcpu, ctxt->eflags);
kvm_make_request(KVM_REQ_EVENT, vcpu);
vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
kvm_rip_write(vcpu, ctxt->eip);
} else
vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
return r;
}
EXPORT_SYMBOL_GPL(x86_emulate_instruction);
int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
{
unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
size, port, &val, 1);
/* do not return to emulator after return from userspace */
vcpu->arch.pio.count = 0;
return ret;
}
EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
static void tsc_bad(void *info)
{
__this_cpu_write(cpu_tsc_khz, 0);
}
static void tsc_khz_changed(void *data)
{
struct cpufreq_freqs *freq = data;
unsigned long khz = 0;
if (data)
khz = freq->new;
else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
khz = cpufreq_quick_get(raw_smp_processor_id());
if (!khz)
khz = tsc_khz;
__this_cpu_write(cpu_tsc_khz, khz);
}
static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
void *data)
{
struct cpufreq_freqs *freq = data;
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i, send_ipi = 0;
/*
* We allow guests to temporarily run on slowing clocks,
* provided we notify them after, or to run on accelerating
* clocks, provided we notify them before. Thus time never
* goes backwards.
*
* However, we have a problem. We can't atomically update
* the frequency of a given CPU from this function; it is
* merely a notifier, which can be called from any CPU.
* Changing the TSC frequency at arbitrary points in time
* requires a recomputation of local variables related to
* the TSC for each VCPU. We must flag these local variables
* to be updated and be sure the update takes place with the
* new frequency before any guests proceed.
*
* Unfortunately, the combination of hotplug CPU and frequency
* change creates an intractable locking scenario; the order
* of when these callouts happen is undefined with respect to
* CPU hotplug, and they can race with each other. As such,
* merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
* undefined; you can actually have a CPU frequency change take
* place in between the computation of X and the setting of the
* variable. To protect against this problem, all updates of
* the per_cpu tsc_khz variable are done in an interrupt
* protected IPI, and all callers wishing to update the value
* must wait for a synchronous IPI to complete (which is trivial
* if the caller is on the CPU already). This establishes the
* necessary total order on variable updates.
*
* Note that because a guest time update may take place
* anytime after the setting of the VCPU's request bit, the
* correct TSC value must be set before the request. However,
* to ensure the update actually makes it to any guest which
* starts running in hardware virtualization between the set
* and the acquisition of the spinlock, we must also ping the
* CPU after setting the request bit.
*
*/
if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
return 0;
if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
return 0;
smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
raw_spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list) {
kvm_for_each_vcpu(i, vcpu, kvm) {
if (vcpu->cpu != freq->cpu)
continue;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
if (vcpu->cpu != smp_processor_id())
send_ipi = 1;
}
}
raw_spin_unlock(&kvm_lock);
if (freq->old < freq->new && send_ipi) {
/*
* We upscale the frequency. Must make the guest
* doesn't see old kvmclock values while running with
* the new frequency, otherwise we risk the guest sees
* time go backwards.
*
* In case we update the frequency for another cpu
* (which might be in guest context) send an interrupt
* to kick the cpu out of guest context. Next time
* guest context is entered kvmclock will be updated,
* so the guest will not see stale values.
*/
smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
}
return 0;
}
static struct notifier_block kvmclock_cpufreq_notifier_block = {
.notifier_call = kvmclock_cpufreq_notifier
};
static int kvmclock_cpu_notifier(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
switch (action) {
case CPU_ONLINE:
case CPU_DOWN_FAILED:
smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
break;
case CPU_DOWN_PREPARE:
smp_call_function_single(cpu, tsc_bad, NULL, 1);
break;
}
return NOTIFY_OK;
}
static struct notifier_block kvmclock_cpu_notifier_block = {
.notifier_call = kvmclock_cpu_notifier,
.priority = -INT_MAX
};
static void kvm_timer_init(void)
{
int cpu;
max_tsc_khz = tsc_khz;
register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
#ifdef CONFIG_CPU_FREQ
struct cpufreq_policy policy;
memset(&policy, 0, sizeof(policy));
cpu = get_cpu();
cpufreq_get_policy(&policy, cpu);
if (policy.cpuinfo.max_freq)
max_tsc_khz = policy.cpuinfo.max_freq;
put_cpu();
#endif
cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
}
pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
for_each_online_cpu(cpu)
smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
}
static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
int kvm_is_in_guest(void)
{
return __this_cpu_read(current_vcpu) != NULL;
}
static int kvm_is_user_mode(void)
{
int user_mode = 3;
if (__this_cpu_read(current_vcpu))
user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
return user_mode != 0;
}
static unsigned long kvm_get_guest_ip(void)
{
unsigned long ip = 0;
if (__this_cpu_read(current_vcpu))
ip = kvm_rip_read(__this_cpu_read(current_vcpu));
return ip;
}
static struct perf_guest_info_callbacks kvm_guest_cbs = {
.is_in_guest = kvm_is_in_guest,
.is_user_mode = kvm_is_user_mode,
.get_guest_ip = kvm_get_guest_ip,
};
void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
{
__this_cpu_write(current_vcpu, vcpu);
}
EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
{
__this_cpu_write(current_vcpu, NULL);
}
EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
static void kvm_set_mmio_spte_mask(void)
{
u64 mask;
int maxphyaddr = boot_cpu_data.x86_phys_bits;
/*
* Set the reserved bits and the present bit of an paging-structure
* entry to generate page fault with PFER.RSV = 1.
*/
mask = ((1ull << (62 - maxphyaddr + 1)) - 1) << maxphyaddr;
mask |= 1ull;
#ifdef CONFIG_X86_64
/*
* If reserved bit is not supported, clear the present bit to disable
* mmio page fault.
*/
if (maxphyaddr == 52)
mask &= ~1ull;
#endif
kvm_mmu_set_mmio_spte_mask(mask);
}
#ifdef CONFIG_X86_64
static void pvclock_gtod_update_fn(struct work_struct *work)
{
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i;
raw_spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list)
kvm_for_each_vcpu(i, vcpu, kvm)
set_bit(KVM_REQ_MASTERCLOCK_UPDATE, &vcpu->requests);
atomic_set(&kvm_guest_has_master_clock, 0);
raw_spin_unlock(&kvm_lock);
}
static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
/*
* Notification about pvclock gtod data update.
*/
static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
void *priv)
{
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
struct timekeeper *tk = priv;
update_pvclock_gtod(tk);
/* disable master clock if host does not trust, or does not
* use, TSC clocksource
*/
if (gtod->clock.vclock_mode != VCLOCK_TSC &&
atomic_read(&kvm_guest_has_master_clock) != 0)
queue_work(system_long_wq, &pvclock_gtod_work);
return 0;
}
static struct notifier_block pvclock_gtod_notifier = {
.notifier_call = pvclock_gtod_notify,
};
#endif
int kvm_arch_init(void *opaque)
{
int r;
struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
if (kvm_x86_ops) {
printk(KERN_ERR "kvm: already loaded the other module\n");
r = -EEXIST;
goto out;
}
if (!ops->cpu_has_kvm_support()) {
printk(KERN_ERR "kvm: no hardware support\n");
r = -EOPNOTSUPP;
goto out;
}
if (ops->disabled_by_bios()) {
printk(KERN_ERR "kvm: disabled by bios\n");
r = -EOPNOTSUPP;
goto out;
}
r = -ENOMEM;
shared_msrs = alloc_percpu(struct kvm_shared_msrs);
if (!shared_msrs) {
printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
goto out;
}
r = kvm_mmu_module_init();
if (r)
goto out_free_percpu;
kvm_set_mmio_spte_mask();
kvm_init_msr_list();
kvm_x86_ops = ops;
kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
PT_DIRTY_MASK, PT64_NX_MASK, 0);
kvm_timer_init();
perf_register_guest_info_callbacks(&kvm_guest_cbs);
if (cpu_has_xsave)
host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
kvm_lapic_init();
#ifdef CONFIG_X86_64
pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
#endif
return 0;
out_free_percpu:
free_percpu(shared_msrs);
out:
return r;
}
void kvm_arch_exit(void)
{
perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
#ifdef CONFIG_X86_64
pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
#endif
kvm_x86_ops = NULL;
kvm_mmu_module_exit();
free_percpu(shared_msrs);
}
int kvm_emulate_halt(struct kvm_vcpu *vcpu)
{
++vcpu->stat.halt_exits;
if (irqchip_in_kernel(vcpu->kvm)) {
vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
return 1;
} else {
vcpu->run->exit_reason = KVM_EXIT_HLT;
return 0;
}
}
EXPORT_SYMBOL_GPL(kvm_emulate_halt);
int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
{
u64 param, ingpa, outgpa, ret;
uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
bool fast, longmode;
int cs_db, cs_l;
/*
* hypercall generates UD from non zero cpl and real mode
* per HYPER-V spec
*/
if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
longmode = is_long_mode(vcpu) && cs_l == 1;
if (!longmode) {
param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
(kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
(kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
(kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
}
#ifdef CONFIG_X86_64
else {
param = kvm_register_read(vcpu, VCPU_REGS_RCX);
ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
}
#endif
code = param & 0xffff;
fast = (param >> 16) & 0x1;
rep_cnt = (param >> 32) & 0xfff;
rep_idx = (param >> 48) & 0xfff;
trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
switch (code) {
case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
kvm_vcpu_on_spin(vcpu);
break;
default:
res = HV_STATUS_INVALID_HYPERCALL_CODE;
break;
}
ret = res | (((u64)rep_done & 0xfff) << 32);
if (longmode) {
kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
} else {
kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
}
return 1;
}
int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
{
unsigned long nr, a0, a1, a2, a3, ret;
int r = 1;
if (kvm_hv_hypercall_enabled(vcpu->kvm))
return kvm_hv_hypercall(vcpu);
nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
trace_kvm_hypercall(nr, a0, a1, a2, a3);
if (!is_long_mode(vcpu)) {
nr &= 0xFFFFFFFF;
a0 &= 0xFFFFFFFF;
a1 &= 0xFFFFFFFF;
a2 &= 0xFFFFFFFF;
a3 &= 0xFFFFFFFF;
}
if (kvm_x86_ops->get_cpl(vcpu) != 0) {
ret = -KVM_EPERM;
goto out;
}
switch (nr) {
case KVM_HC_VAPIC_POLL_IRQ:
ret = 0;
break;
default:
ret = -KVM_ENOSYS;
break;
}
out:
kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
++vcpu->stat.hypercalls;
return r;
}
EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
char instruction[3];
unsigned long rip = kvm_rip_read(vcpu);
/*
* Blow out the MMU to ensure that no other VCPU has an active mapping
* to ensure that the updated hypercall appears atomically across all
* VCPUs.
*/
kvm_mmu_zap_all(vcpu->kvm);
kvm_x86_ops->patch_hypercall(vcpu, instruction);
return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
}
/*
* Check if userspace requested an interrupt window, and that the
* interrupt window is open.
*
* No need to exit to userspace if we already have an interrupt queued.
*/
static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
{
return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
vcpu->run->request_interrupt_window &&
kvm_arch_interrupt_allowed(vcpu));
}
static void post_kvm_run_save(struct kvm_vcpu *vcpu)
{
struct kvm_run *kvm_run = vcpu->run;
kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
kvm_run->cr8 = kvm_get_cr8(vcpu);
kvm_run->apic_base = kvm_get_apic_base(vcpu);
if (irqchip_in_kernel(vcpu->kvm))
kvm_run->ready_for_interrupt_injection = 1;
else
kvm_run->ready_for_interrupt_injection =
kvm_arch_interrupt_allowed(vcpu) &&
!kvm_cpu_has_interrupt(vcpu) &&
!kvm_event_needs_reinjection(vcpu);
}
static int vapic_enter(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
struct page *page;
if (!apic || !apic->vapic_addr)
return 0;
page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
if (is_error_page(page))
return -EFAULT;
vcpu->arch.apic->vapic_page = page;
return 0;
}
static void vapic_exit(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
int idx;
if (!apic || !apic->vapic_addr)
return;
idx = srcu_read_lock(&vcpu->kvm->srcu);
kvm_release_page_dirty(apic->vapic_page);
mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
}
static void update_cr8_intercept(struct kvm_vcpu *vcpu)
{
int max_irr, tpr;
if (!kvm_x86_ops->update_cr8_intercept)
return;
if (!vcpu->arch.apic)
return;
if (!vcpu->arch.apic->vapic_addr)
max_irr = kvm_lapic_find_highest_irr(vcpu);
else
max_irr = -1;
if (max_irr != -1)
max_irr >>= 4;
tpr = kvm_lapic_get_cr8(vcpu);
kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
}
static void inject_pending_event(struct kvm_vcpu *vcpu)
{
/* try to reinject previous events if any */
if (vcpu->arch.exception.pending) {
trace_kvm_inj_exception(vcpu->arch.exception.nr,
vcpu->arch.exception.has_error_code,
vcpu->arch.exception.error_code);
kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
vcpu->arch.exception.has_error_code,
vcpu->arch.exception.error_code,
vcpu->arch.exception.reinject);
return;
}
if (vcpu->arch.nmi_injected) {
kvm_x86_ops->set_nmi(vcpu);
return;
}
if (vcpu->arch.interrupt.pending) {
kvm_x86_ops->set_irq(vcpu);
return;
}
/* try to inject new event if pending */
if (vcpu->arch.nmi_pending) {
if (kvm_x86_ops->nmi_allowed(vcpu)) {
--vcpu->arch.nmi_pending;
vcpu->arch.nmi_injected = true;
kvm_x86_ops->set_nmi(vcpu);
}
} else if (kvm_cpu_has_injectable_intr(vcpu)) {
if (kvm_x86_ops->interrupt_allowed(vcpu)) {
kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
false);
kvm_x86_ops->set_irq(vcpu);
}
}
}
static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
{
if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
!vcpu->guest_xcr0_loaded) {
/* kvm_set_xcr() also depends on this */
xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
vcpu->guest_xcr0_loaded = 1;
}
}
static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
{
if (vcpu->guest_xcr0_loaded) {
if (vcpu->arch.xcr0 != host_xcr0)
xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
vcpu->guest_xcr0_loaded = 0;
}
}
static void process_nmi(struct kvm_vcpu *vcpu)
{
unsigned limit = 2;
/*
* x86 is limited to one NMI running, and one NMI pending after it.
* If an NMI is already in progress, limit further NMIs to just one.
* Otherwise, allow two (and we'll inject the first one immediately).
*/
if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
limit = 1;
vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
kvm_make_request(KVM_REQ_EVENT, vcpu);
}
static void kvm_gen_update_masterclock(struct kvm *kvm)
{
#ifdef CONFIG_X86_64
int i;
struct kvm_vcpu *vcpu;
struct kvm_arch *ka = &kvm->arch;
spin_lock(&ka->pvclock_gtod_sync_lock);
kvm_make_mclock_inprogress_request(kvm);
/* no guest entries from this point */
pvclock_update_vm_gtod_copy(kvm);
kvm_for_each_vcpu(i, vcpu, kvm)
set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
/* guest entries allowed */
kvm_for_each_vcpu(i, vcpu, kvm)
clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
spin_unlock(&ka->pvclock_gtod_sync_lock);
#endif
}
static void update_eoi_exitmap(struct kvm_vcpu *vcpu)
{
u64 eoi_exit_bitmap[4];
memset(eoi_exit_bitmap, 0, 32);
kvm_ioapic_calculate_eoi_exitmap(vcpu, eoi_exit_bitmap);
kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
}
static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
{
int r;
bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
vcpu->run->request_interrupt_window;
bool req_immediate_exit = 0;
if (vcpu->requests) {
if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
kvm_mmu_unload(vcpu);
if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
__kvm_migrate_timers(vcpu);
if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
kvm_gen_update_masterclock(vcpu->kvm);
if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
r = kvm_guest_time_update(vcpu);
if (unlikely(r))
goto out;
}
if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
kvm_mmu_sync_roots(vcpu);
if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
kvm_x86_ops->tlb_flush(vcpu);
if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
r = 0;
goto out;
}
if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
r = 0;
goto out;
}
if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
vcpu->fpu_active = 0;
kvm_x86_ops->fpu_deactivate(vcpu);
}
if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
/* Page is swapped out. Do synthetic halt */
vcpu->arch.apf.halted = true;
r = 1;
goto out;
}
if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
record_steal_time(vcpu);
if (kvm_check_request(KVM_REQ_NMI, vcpu))
process_nmi(vcpu);
req_immediate_exit =
kvm_check_request(KVM_REQ_IMMEDIATE_EXIT, vcpu);
if (kvm_check_request(KVM_REQ_PMU, vcpu))
kvm_handle_pmu_event(vcpu);
if (kvm_check_request(KVM_REQ_PMI, vcpu))
kvm_deliver_pmi(vcpu);
if (kvm_check_request(KVM_REQ_EOIBITMAP, vcpu))
update_eoi_exitmap(vcpu);
}
if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
inject_pending_event(vcpu);
/* enable NMI/IRQ window open exits if needed */
if (vcpu->arch.nmi_pending)
kvm_x86_ops->enable_nmi_window(vcpu);
else if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
kvm_x86_ops->enable_irq_window(vcpu);
if (kvm_lapic_enabled(vcpu)) {
/*
* Update architecture specific hints for APIC
* virtual interrupt delivery.
*/
if (kvm_x86_ops->hwapic_irr_update)
kvm_x86_ops->hwapic_irr_update(vcpu,
kvm_lapic_find_highest_irr(vcpu));
update_cr8_intercept(vcpu);
kvm_lapic_sync_to_vapic(vcpu);
}
}
r = kvm_mmu_reload(vcpu);
if (unlikely(r)) {
goto cancel_injection;
}
preempt_disable();
kvm_x86_ops->prepare_guest_switch(vcpu);
if (vcpu->fpu_active)
kvm_load_guest_fpu(vcpu);
kvm_load_guest_xcr0(vcpu);
vcpu->mode = IN_GUEST_MODE;
/* We should set ->mode before check ->requests,
* see the comment in make_all_cpus_request.
*/
smp_mb();
local_irq_disable();
if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
|| need_resched() || signal_pending(current)) {
vcpu->mode = OUTSIDE_GUEST_MODE;
smp_wmb();
local_irq_enable();
preempt_enable();
r = 1;
goto cancel_injection;
}
srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
if (req_immediate_exit)
smp_send_reschedule(vcpu->cpu);
kvm_guest_enter();
if (unlikely(vcpu->arch.switch_db_regs)) {
set_debugreg(0, 7);
set_debugreg(vcpu->arch.eff_db[0], 0);
set_debugreg(vcpu->arch.eff_db[1], 1);
set_debugreg(vcpu->arch.eff_db[2], 2);
set_debugreg(vcpu->arch.eff_db[3], 3);
}
trace_kvm_entry(vcpu->vcpu_id);
kvm_x86_ops->run(vcpu);
/*
* If the guest has used debug registers, at least dr7
* will be disabled while returning to the host.
* If we don't have active breakpoints in the host, we don't
* care about the messed up debug address registers. But if
* we have some of them active, restore the old state.
*/
if (hw_breakpoint_active())
hw_breakpoint_restore();
vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu,
native_read_tsc());
vcpu->mode = OUTSIDE_GUEST_MODE;
smp_wmb();
local_irq_enable();
++vcpu->stat.exits;
/*
* We must have an instruction between local_irq_enable() and
* kvm_guest_exit(), so the timer interrupt isn't delayed by
* the interrupt shadow. The stat.exits increment will do nicely.
* But we need to prevent reordering, hence this barrier():
*/
barrier();
kvm_guest_exit();
preempt_enable();
vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
/*
* Profile KVM exit RIPs:
*/
if (unlikely(prof_on == KVM_PROFILING)) {
unsigned long rip = kvm_rip_read(vcpu);
profile_hit(KVM_PROFILING, (void *)rip);
}
if (unlikely(vcpu->arch.tsc_always_catchup))
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
if (vcpu->arch.apic_attention)
kvm_lapic_sync_from_vapic(vcpu);
r = kvm_x86_ops->handle_exit(vcpu);
return r;
cancel_injection:
kvm_x86_ops->cancel_injection(vcpu);
if (unlikely(vcpu->arch.apic_attention))
kvm_lapic_sync_from_vapic(vcpu);
out:
return r;
}
static int __vcpu_run(struct kvm_vcpu *vcpu)
{
int r;
struct kvm *kvm = vcpu->kvm;
if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
pr_debug("vcpu %d received sipi with vector # %x\n",
vcpu->vcpu_id, vcpu->arch.sipi_vector);
kvm_lapic_reset(vcpu);
r = kvm_vcpu_reset(vcpu);
if (r)
return r;
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
}
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
r = vapic_enter(vcpu);
if (r) {
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
return r;
}
r = 1;
while (r > 0) {
if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
!vcpu->arch.apf.halted)
r = vcpu_enter_guest(vcpu);
else {
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
kvm_vcpu_block(vcpu);
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
if (kvm_check_request(KVM_REQ_UNHALT, vcpu))
{
switch(vcpu->arch.mp_state) {
case KVM_MP_STATE_HALTED:
vcpu->arch.mp_state =
KVM_MP_STATE_RUNNABLE;
case KVM_MP_STATE_RUNNABLE:
vcpu->arch.apf.halted = false;
break;
case KVM_MP_STATE_SIPI_RECEIVED:
default:
r = -EINTR;
break;
}
}
}
if (r <= 0)
break;
clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
if (kvm_cpu_has_pending_timer(vcpu))
kvm_inject_pending_timer_irqs(vcpu);
if (dm_request_for_irq_injection(vcpu)) {
r = -EINTR;
vcpu->run->exit_reason = KVM_EXIT_INTR;
++vcpu->stat.request_irq_exits;
}
kvm_check_async_pf_completion(vcpu);
if (signal_pending(current)) {
r = -EINTR;
vcpu->run->exit_reason = KVM_EXIT_INTR;
++vcpu->stat.signal_exits;
}
if (need_resched()) {
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
kvm_resched(vcpu);
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
}
}
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
vapic_exit(vcpu);
return r;
}
static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
{
int r;
vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
if (r != EMULATE_DONE)
return 0;
return 1;
}
static int complete_emulated_pio(struct kvm_vcpu *vcpu)
{
BUG_ON(!vcpu->arch.pio.count);
return complete_emulated_io(vcpu);
}
/*
* Implements the following, as a state machine:
*
* read:
* for each fragment
* for each mmio piece in the fragment
* write gpa, len
* exit
* copy data
* execute insn
*
* write:
* for each fragment
* for each mmio piece in the fragment
* write gpa, len
* copy data
* exit
*/
static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
{
struct kvm_run *run = vcpu->run;
struct kvm_mmio_fragment *frag;
unsigned len;
BUG_ON(!vcpu->mmio_needed);
/* Complete previous fragment */
frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
len = min(8u, frag->len);
if (!vcpu->mmio_is_write)
memcpy(frag->data, run->mmio.data, len);
if (frag->len <= 8) {
/* Switch to the next fragment. */
frag++;
vcpu->mmio_cur_fragment++;
} else {
/* Go forward to the next mmio piece. */
frag->data += len;
frag->gpa += len;
frag->len -= len;
}
if (vcpu->mmio_cur_fragment == vcpu->mmio_nr_fragments) {
vcpu->mmio_needed = 0;
if (vcpu->mmio_is_write)
return 1;
vcpu->mmio_read_completed = 1;
return complete_emulated_io(vcpu);
}
run->exit_reason = KVM_EXIT_MMIO;
run->mmio.phys_addr = frag->gpa;
if (vcpu->mmio_is_write)
memcpy(run->mmio.data, frag->data, min(8u, frag->len));
run->mmio.len = min(8u, frag->len);
run->mmio.is_write = vcpu->mmio_is_write;
vcpu->arch.complete_userspace_io = complete_emulated_mmio;
return 0;
}
int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
{
int r;
sigset_t sigsaved;
if (!tsk_used_math(current) && init_fpu(current))
return -ENOMEM;
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
kvm_vcpu_block(vcpu);
clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
r = -EAGAIN;
goto out;
}
/* re-sync apic's tpr */
if (!irqchip_in_kernel(vcpu->kvm)) {
if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
r = -EINVAL;
goto out;
}
}
if (unlikely(vcpu->arch.complete_userspace_io)) {
int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
vcpu->arch.complete_userspace_io = NULL;
r = cui(vcpu);
if (r <= 0)
goto out;
} else
WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
r = __vcpu_run(vcpu);
out:
post_kvm_run_save(vcpu);
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &sigsaved, NULL);
return r;
}
int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
/*
* We are here if userspace calls get_regs() in the middle of
* instruction emulation. Registers state needs to be copied
* back from emulation context to vcpu. Userspace shouldn't do
* that usually, but some bad designed PV devices (vmware
* backdoor interface) need this to work
*/
emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
}
regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
#ifdef CONFIG_X86_64
regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
#endif
regs->rip = kvm_rip_read(vcpu);
regs->rflags = kvm_get_rflags(vcpu);
return 0;
}
int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
#ifdef CONFIG_X86_64
kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
#endif
kvm_rip_write(vcpu, regs->rip);
kvm_set_rflags(vcpu, regs->rflags);
vcpu->arch.exception.pending = false;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
{
struct kvm_segment cs;
kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
*db = cs.db;
*l = cs.l;
}
EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
struct desc_ptr dt;
kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
kvm_x86_ops->get_idt(vcpu, &dt);
sregs->idt.limit = dt.size;
sregs->idt.base = dt.address;
kvm_x86_ops->get_gdt(vcpu, &dt);
sregs->gdt.limit = dt.size;
sregs->gdt.base = dt.address;
sregs->cr0 = kvm_read_cr0(vcpu);
sregs->cr2 = vcpu->arch.cr2;
sregs->cr3 = kvm_read_cr3(vcpu);
sregs->cr4 = kvm_read_cr4(vcpu);
sregs->cr8 = kvm_get_cr8(vcpu);
sregs->efer = vcpu->arch.efer;
sregs->apic_base = kvm_get_apic_base(vcpu);
memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
set_bit(vcpu->arch.interrupt.nr,
(unsigned long *)sregs->interrupt_bitmap);
return 0;
}
int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
struct kvm_mp_state *mp_state)
{
mp_state->mp_state = vcpu->arch.mp_state;
return 0;
}
int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
struct kvm_mp_state *mp_state)
{
vcpu->arch.mp_state = mp_state->mp_state;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
int reason, bool has_error_code, u32 error_code)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
int ret;
init_emulate_ctxt(vcpu);
ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
has_error_code, error_code);
if (ret)
return EMULATE_FAIL;
kvm_rip_write(vcpu, ctxt->eip);
kvm_set_rflags(vcpu, ctxt->eflags);
kvm_make_request(KVM_REQ_EVENT, vcpu);
return EMULATE_DONE;
}
EXPORT_SYMBOL_GPL(kvm_task_switch);
int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
int mmu_reset_needed = 0;
int pending_vec, max_bits, idx;
struct desc_ptr dt;
if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
return -EINVAL;
dt.size = sregs->idt.limit;
dt.address = sregs->idt.base;
kvm_x86_ops->set_idt(vcpu, &dt);
dt.size = sregs->gdt.limit;
dt.address = sregs->gdt.base;
kvm_x86_ops->set_gdt(vcpu, &dt);
vcpu->arch.cr2 = sregs->cr2;
mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
vcpu->arch.cr3 = sregs->cr3;
__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
kvm_set_cr8(vcpu, sregs->cr8);
mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
kvm_x86_ops->set_efer(vcpu, sregs->efer);
kvm_set_apic_base(vcpu, sregs->apic_base);
mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
vcpu->arch.cr0 = sregs->cr0;
mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
if (sregs->cr4 & X86_CR4_OSXSAVE)
kvm_update_cpuid(vcpu);
idx = srcu_read_lock(&vcpu->kvm->srcu);
if (!is_long_mode(vcpu) && is_pae(vcpu)) {
load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
mmu_reset_needed = 1;
}
srcu_read_unlock(&vcpu->kvm->srcu, idx);
if (mmu_reset_needed)
kvm_mmu_reset_context(vcpu);
max_bits = KVM_NR_INTERRUPTS;
pending_vec = find_first_bit(
(const unsigned long *)sregs->interrupt_bitmap, max_bits);
if (pending_vec < max_bits) {
kvm_queue_interrupt(vcpu, pending_vec, false);
pr_debug("Set back pending irq %d\n", pending_vec);
}
kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
update_cr8_intercept(vcpu);
/* Older userspace won't unhalt the vcpu on reset. */
if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
!is_protmode(vcpu))
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
struct kvm_guest_debug *dbg)
{
unsigned long rflags;
int i, r;
if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
r = -EBUSY;
if (vcpu->arch.exception.pending)
goto out;
if (dbg->control & KVM_GUESTDBG_INJECT_DB)
kvm_queue_exception(vcpu, DB_VECTOR);
else
kvm_queue_exception(vcpu, BP_VECTOR);
}
/*
* Read rflags as long as potentially injected trace flags are still
* filtered out.
*/
rflags = kvm_get_rflags(vcpu);
vcpu->guest_debug = dbg->control;
if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
vcpu->guest_debug = 0;
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
for (i = 0; i < KVM_NR_DB_REGS; ++i)
vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
} else {
for (i = 0; i < KVM_NR_DB_REGS; i++)
vcpu->arch.eff_db[i] = vcpu->arch.db[i];
}
kvm_update_dr7(vcpu);
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
get_segment_base(vcpu, VCPU_SREG_CS);
/*
* Trigger an rflags update that will inject or remove the trace
* flags.
*/
kvm_set_rflags(vcpu, rflags);
kvm_x86_ops->update_db_bp_intercept(vcpu);
r = 0;
out:
return r;
}
/*
* Translate a guest virtual address to a guest physical address.
*/
int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
struct kvm_translation *tr)
{
unsigned long vaddr = tr->linear_address;
gpa_t gpa;
int idx;
idx = srcu_read_lock(&vcpu->kvm->srcu);
gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
tr->physical_address = gpa;
tr->valid = gpa != UNMAPPED_GVA;
tr->writeable = 1;
tr->usermode = 0;
return 0;
}
int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
struct i387_fxsave_struct *fxsave =
&vcpu->arch.guest_fpu.state->fxsave;
memcpy(fpu->fpr, fxsave->st_space, 128);
fpu->fcw = fxsave->cwd;
fpu->fsw = fxsave->swd;
fpu->ftwx = fxsave->twd;
fpu->last_opcode = fxsave->fop;
fpu->last_ip = fxsave->rip;
fpu->last_dp = fxsave->rdp;
memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
return 0;
}
int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
struct i387_fxsave_struct *fxsave =
&vcpu->arch.guest_fpu.state->fxsave;
memcpy(fxsave->st_space, fpu->fpr, 128);
fxsave->cwd = fpu->fcw;
fxsave->swd = fpu->fsw;
fxsave->twd = fpu->ftwx;
fxsave->fop = fpu->last_opcode;
fxsave->rip = fpu->last_ip;
fxsave->rdp = fpu->last_dp;
memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
return 0;
}
int fx_init(struct kvm_vcpu *vcpu)
{
int err;
err = fpu_alloc(&vcpu->arch.guest_fpu);
if (err)
return err;
fpu_finit(&vcpu->arch.guest_fpu);
/*
* Ensure guest xcr0 is valid for loading
*/
vcpu->arch.xcr0 = XSTATE_FP;
vcpu->arch.cr0 |= X86_CR0_ET;
return 0;
}
EXPORT_SYMBOL_GPL(fx_init);
static void fx_free(struct kvm_vcpu *vcpu)
{
fpu_free(&vcpu->arch.guest_fpu);
}
void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
{
if (vcpu->guest_fpu_loaded)
return;
/*
* Restore all possible states in the guest,
* and assume host would use all available bits.
* Guest xcr0 would be loaded later.
*/
kvm_put_guest_xcr0(vcpu);
vcpu->guest_fpu_loaded = 1;
__kernel_fpu_begin();
fpu_restore_checking(&vcpu->arch.guest_fpu);
trace_kvm_fpu(1);
}
void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
{
kvm_put_guest_xcr0(vcpu);
if (!vcpu->guest_fpu_loaded)
return;
vcpu->guest_fpu_loaded = 0;
fpu_save_init(&vcpu->arch.guest_fpu);
__kernel_fpu_end();
++vcpu->stat.fpu_reload;
kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
trace_kvm_fpu(0);
}
void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
{
kvmclock_reset(vcpu);
free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
fx_free(vcpu);
kvm_x86_ops->vcpu_free(vcpu);
}
struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
unsigned int id)
{
if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
printk_once(KERN_WARNING
"kvm: SMP vm created on host with unstable TSC; "
"guest TSC will not be reliable\n");
return kvm_x86_ops->vcpu_create(kvm, id);
}
int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
{
int r;
vcpu->arch.mtrr_state.have_fixed = 1;
r = vcpu_load(vcpu);
if (r)
return r;
r = kvm_vcpu_reset(vcpu);
if (r == 0)
r = kvm_mmu_setup(vcpu);
vcpu_put(vcpu);
return r;
}
int kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
{
int r;
struct msr_data msr;
r = vcpu_load(vcpu);
if (r)
return r;
msr.data = 0x0;
msr.index = MSR_IA32_TSC;
msr.host_initiated = true;
kvm_write_tsc(vcpu, &msr);
vcpu_put(vcpu);
return r;
}
void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
{
int r;
vcpu->arch.apf.msr_val = 0;
r = vcpu_load(vcpu);
BUG_ON(r);
kvm_mmu_unload(vcpu);
vcpu_put(vcpu);
fx_free(vcpu);
kvm_x86_ops->vcpu_free(vcpu);
}
static int kvm_vcpu_reset(struct kvm_vcpu *vcpu)
{
atomic_set(&vcpu->arch.nmi_queued, 0);
vcpu->arch.nmi_pending = 0;
vcpu->arch.nmi_injected = false;
memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
vcpu->arch.dr6 = DR6_FIXED_1;
vcpu->arch.dr7 = DR7_FIXED_1;
kvm_update_dr7(vcpu);
kvm_make_request(KVM_REQ_EVENT, vcpu);
vcpu->arch.apf.msr_val = 0;
vcpu->arch.st.msr_val = 0;
kvmclock_reset(vcpu);
kvm_clear_async_pf_completion_queue(vcpu);
kvm_async_pf_hash_reset(vcpu);
vcpu->arch.apf.halted = false;
kvm_pmu_reset(vcpu);
memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
vcpu->arch.regs_avail = ~0;
vcpu->arch.regs_dirty = ~0;
return kvm_x86_ops->vcpu_reset(vcpu);
}
int kvm_arch_hardware_enable(void *garbage)
{
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i;
int ret;
u64 local_tsc;
u64 max_tsc = 0;
bool stable, backwards_tsc = false;
kvm_shared_msr_cpu_online();
ret = kvm_x86_ops->hardware_enable(garbage);
if (ret != 0)
return ret;
local_tsc = native_read_tsc();
stable = !check_tsc_unstable();
list_for_each_entry(kvm, &vm_list, vm_list) {
kvm_for_each_vcpu(i, vcpu, kvm) {
if (!stable && vcpu->cpu == smp_processor_id())
set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
if (stable && vcpu->arch.last_host_tsc > local_tsc) {
backwards_tsc = true;
if (vcpu->arch.last_host_tsc > max_tsc)
max_tsc = vcpu->arch.last_host_tsc;
}
}
}
/*
* Sometimes, even reliable TSCs go backwards. This happens on
* platforms that reset TSC during suspend or hibernate actions, but
* maintain synchronization. We must compensate. Fortunately, we can
* detect that condition here, which happens early in CPU bringup,
* before any KVM threads can be running. Unfortunately, we can't
* bring the TSCs fully up to date with real time, as we aren't yet far
* enough into CPU bringup that we know how much real time has actually
* elapsed; our helper function, get_kernel_ns() will be using boot
* variables that haven't been updated yet.
*
* So we simply find the maximum observed TSC above, then record the
* adjustment to TSC in each VCPU. When the VCPU later gets loaded,
* the adjustment will be applied. Note that we accumulate
* adjustments, in case multiple suspend cycles happen before some VCPU
* gets a chance to run again. In the event that no KVM threads get a
* chance to run, we will miss the entire elapsed period, as we'll have
* reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
* loose cycle time. This isn't too big a deal, since the loss will be
* uniform across all VCPUs (not to mention the scenario is extremely
* unlikely). It is possible that a second hibernate recovery happens
* much faster than a first, causing the observed TSC here to be
* smaller; this would require additional padding adjustment, which is
* why we set last_host_tsc to the local tsc observed here.
*
* N.B. - this code below runs only on platforms with reliable TSC,
* as that is the only way backwards_tsc is set above. Also note
* that this runs for ALL vcpus, which is not a bug; all VCPUs should
* have the same delta_cyc adjustment applied if backwards_tsc
* is detected. Note further, this adjustment is only done once,
* as we reset last_host_tsc on all VCPUs to stop this from being
* called multiple times (one for each physical CPU bringup).
*
* Platforms with unreliable TSCs don't have to deal with this, they
* will be compensated by the logic in vcpu_load, which sets the TSC to
* catchup mode. This will catchup all VCPUs to real time, but cannot
* guarantee that they stay in perfect synchronization.
*/
if (backwards_tsc) {
u64 delta_cyc = max_tsc - local_tsc;
list_for_each_entry(kvm, &vm_list, vm_list) {
kvm_for_each_vcpu(i, vcpu, kvm) {
vcpu->arch.tsc_offset_adjustment += delta_cyc;
vcpu->arch.last_host_tsc = local_tsc;
set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
&vcpu->requests);
}
/*
* We have to disable TSC offset matching.. if you were
* booting a VM while issuing an S4 host suspend....
* you may have some problem. Solving this issue is
* left as an exercise to the reader.
*/
kvm->arch.last_tsc_nsec = 0;
kvm->arch.last_tsc_write = 0;
}
}
return 0;
}
void kvm_arch_hardware_disable(void *garbage)
{
kvm_x86_ops->hardware_disable(garbage);
drop_user_return_notifiers(garbage);
}
int kvm_arch_hardware_setup(void)
{
return kvm_x86_ops->hardware_setup();
}
void kvm_arch_hardware_unsetup(void)
{
kvm_x86_ops->hardware_unsetup();
}
void kvm_arch_check_processor_compat(void *rtn)
{
kvm_x86_ops->check_processor_compatibility(rtn);
}
bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
{
return irqchip_in_kernel(vcpu->kvm) == (vcpu->arch.apic != NULL);
}
struct static_key kvm_no_apic_vcpu __read_mostly;
int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
{
struct page *page;
struct kvm *kvm;
int r;
BUG_ON(vcpu->kvm == NULL);
kvm = vcpu->kvm;
vcpu->arch.emulate_ctxt.ops = &emulate_ops;
if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
else
vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!page) {
r = -ENOMEM;
goto fail;
}
vcpu->arch.pio_data = page_address(page);
kvm_set_tsc_khz(vcpu, max_tsc_khz);
r = kvm_mmu_create(vcpu);
if (r < 0)
goto fail_free_pio_data;
if (irqchip_in_kernel(kvm)) {
r = kvm_create_lapic(vcpu);
if (r < 0)
goto fail_mmu_destroy;
} else
static_key_slow_inc(&kvm_no_apic_vcpu);
vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
GFP_KERNEL);
if (!vcpu->arch.mce_banks) {
r = -ENOMEM;
goto fail_free_lapic;
}
vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
goto fail_free_mce_banks;
r = fx_init(vcpu);
if (r)
goto fail_free_wbinvd_dirty_mask;
vcpu->arch.ia32_tsc_adjust_msr = 0x0;
kvm_async_pf_hash_reset(vcpu);
kvm_pmu_init(vcpu);
return 0;
fail_free_wbinvd_dirty_mask:
free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
fail_free_mce_banks:
kfree(vcpu->arch.mce_banks);
fail_free_lapic:
kvm_free_lapic(vcpu);
fail_mmu_destroy:
kvm_mmu_destroy(vcpu);
fail_free_pio_data:
free_page((unsigned long)vcpu->arch.pio_data);
fail:
return r;
}
void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
{
int idx;
kvm_pmu_destroy(vcpu);
kfree(vcpu->arch.mce_banks);
kvm_free_lapic(vcpu);
idx = srcu_read_lock(&vcpu->kvm->srcu);
kvm_mmu_destroy(vcpu);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
free_page((unsigned long)vcpu->arch.pio_data);
if (!irqchip_in_kernel(vcpu->kvm))
static_key_slow_dec(&kvm_no_apic_vcpu);
}
int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
{
if (type)
return -EINVAL;
INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
/* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
/* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
&kvm->arch.irq_sources_bitmap);
raw_spin_lock_init(&kvm->arch.tsc_write_lock);
mutex_init(&kvm->arch.apic_map_lock);
spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
pvclock_update_vm_gtod_copy(kvm);
return 0;
}
static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
{
int r;
r = vcpu_load(vcpu);
BUG_ON(r);
kvm_mmu_unload(vcpu);
vcpu_put(vcpu);
}
static void kvm_free_vcpus(struct kvm *kvm)
{
unsigned int i;
struct kvm_vcpu *vcpu;
/*
* Unpin any mmu pages first.
*/
kvm_for_each_vcpu(i, vcpu, kvm) {
kvm_clear_async_pf_completion_queue(vcpu);
kvm_unload_vcpu_mmu(vcpu);
}
kvm_for_each_vcpu(i, vcpu, kvm)
kvm_arch_vcpu_free(vcpu);
mutex_lock(&kvm->lock);
for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
kvm->vcpus[i] = NULL;
atomic_set(&kvm->online_vcpus, 0);
mutex_unlock(&kvm->lock);
}
void kvm_arch_sync_events(struct kvm *kvm)
{
kvm_free_all_assigned_devices(kvm);
kvm_free_pit(kvm);
}
void kvm_arch_destroy_vm(struct kvm *kvm)
{
kvm_iommu_unmap_guest(kvm);
kfree(kvm->arch.vpic);
kfree(kvm->arch.vioapic);
kvm_free_vcpus(kvm);
if (kvm->arch.apic_access_page)
put_page(kvm->arch.apic_access_page);
if (kvm->arch.ept_identity_pagetable)
put_page(kvm->arch.ept_identity_pagetable);
kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
}
void kvm_arch_free_memslot(struct kvm_memory_slot *free,
struct kvm_memory_slot *dont)
{
int i;
for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
kvm_kvfree(free->arch.rmap[i]);
free->arch.rmap[i] = NULL;
}
if (i == 0)
continue;
if (!dont || free->arch.lpage_info[i - 1] !=
dont->arch.lpage_info[i - 1]) {
kvm_kvfree(free->arch.lpage_info[i - 1]);
free->arch.lpage_info[i - 1] = NULL;
}
}
}
int kvm_arch_create_memslot(struct kvm_memory_slot *slot, unsigned long npages)
{
int i;
for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
unsigned long ugfn;
int lpages;
int level = i + 1;
lpages = gfn_to_index(slot->base_gfn + npages - 1,
slot->base_gfn, level) + 1;
slot->arch.rmap[i] =
kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
if (!slot->arch.rmap[i])
goto out_free;
if (i == 0)
continue;
slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
sizeof(*slot->arch.lpage_info[i - 1]));
if (!slot->arch.lpage_info[i - 1])
goto out_free;
if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
slot->arch.lpage_info[i - 1][0].write_count = 1;
if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
ugfn = slot->userspace_addr >> PAGE_SHIFT;
/*
* If the gfn and userspace address are not aligned wrt each
* other, or if explicitly asked to, disable large page
* support for this slot
*/
if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
!kvm_largepages_enabled()) {
unsigned long j;
for (j = 0; j < lpages; ++j)
slot->arch.lpage_info[i - 1][j].write_count = 1;
}
}
return 0;
out_free:
for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
kvm_kvfree(slot->arch.rmap[i]);
slot->arch.rmap[i] = NULL;
if (i == 0)
continue;
kvm_kvfree(slot->arch.lpage_info[i - 1]);
slot->arch.lpage_info[i - 1] = NULL;
}
return -ENOMEM;
}
int kvm_arch_prepare_memory_region(struct kvm *kvm,
struct kvm_memory_slot *memslot,
struct kvm_memory_slot old,
struct kvm_userspace_memory_region *mem,
bool user_alloc)
{
int npages = memslot->npages;
/*
* Only private memory slots need to be mapped here since
* KVM_SET_MEMORY_REGION ioctl is no longer supported.
*/
if ((memslot->id >= KVM_USER_MEM_SLOTS) && npages && !old.npages) {
unsigned long userspace_addr;
/*
* MAP_SHARED to prevent internal slot pages from being moved
* by fork()/COW.
*/
userspace_addr = vm_mmap(NULL, 0, npages * PAGE_SIZE,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, 0);
if (IS_ERR((void *)userspace_addr))
return PTR_ERR((void *)userspace_addr);
memslot->userspace_addr = userspace_addr;
}
return 0;
}
void kvm_arch_commit_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
struct kvm_memory_slot old,
bool user_alloc)
{
int nr_mmu_pages = 0, npages = mem->memory_size >> PAGE_SHIFT;
if ((mem->slot >= KVM_USER_MEM_SLOTS) && old.npages && !npages) {
int ret;
ret = vm_munmap(old.userspace_addr,
old.npages * PAGE_SIZE);
if (ret < 0)
printk(KERN_WARNING
"kvm_vm_ioctl_set_memory_region: "
"failed to munmap memory\n");
}
if (!kvm->arch.n_requested_mmu_pages)
nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
if (nr_mmu_pages)
kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
/*
* Write protect all pages for dirty logging.
* Existing largepage mappings are destroyed here and new ones will
* not be created until the end of the logging.
*/
if (npages && (mem->flags & KVM_MEM_LOG_DIRTY_PAGES))
kvm_mmu_slot_remove_write_access(kvm, mem->slot);
/*
* If memory slot is created, or moved, we need to clear all
* mmio sptes.
*/
if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT) {
kvm_mmu_zap_all(kvm);
kvm_reload_remote_mmus(kvm);
}
}
void kvm_arch_flush_shadow_all(struct kvm *kvm)
{
kvm_mmu_zap_all(kvm);
kvm_reload_remote_mmus(kvm);
}
void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
struct kvm_memory_slot *slot)
{
kvm_arch_flush_shadow_all(kvm);
}
int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
{
return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
!vcpu->arch.apf.halted)
|| !list_empty_careful(&vcpu->async_pf.done)
|| vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
|| atomic_read(&vcpu->arch.nmi_queued) ||
(kvm_arch_interrupt_allowed(vcpu) &&
kvm_cpu_has_interrupt(vcpu));
}
int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
{
return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
}
int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
{
return kvm_x86_ops->interrupt_allowed(vcpu);
}
bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
{
unsigned long current_rip = kvm_rip_read(vcpu) +
get_segment_base(vcpu, VCPU_SREG_CS);
return current_rip == linear_rip;
}
EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
{
unsigned long rflags;
rflags = kvm_x86_ops->get_rflags(vcpu);
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
rflags &= ~X86_EFLAGS_TF;
return rflags;
}
EXPORT_SYMBOL_GPL(kvm_get_rflags);
void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
{
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
rflags |= X86_EFLAGS_TF;
kvm_x86_ops->set_rflags(vcpu, rflags);
kvm_make_request(KVM_REQ_EVENT, vcpu);
}
EXPORT_SYMBOL_GPL(kvm_set_rflags);
void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
{
int r;
if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
is_error_page(work->page))
return;
r = kvm_mmu_reload(vcpu);
if (unlikely(r))
return;
if (!vcpu->arch.mmu.direct_map &&
work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
return;
vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
}
static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
{
return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
}
static inline u32 kvm_async_pf_next_probe(u32 key)
{
return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
}
static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
{
u32 key = kvm_async_pf_hash_fn(gfn);
while (vcpu->arch.apf.gfns[key] != ~0)
key = kvm_async_pf_next_probe(key);
vcpu->arch.apf.gfns[key] = gfn;
}
static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
{
int i;
u32 key = kvm_async_pf_hash_fn(gfn);
for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
(vcpu->arch.apf.gfns[key] != gfn &&
vcpu->arch.apf.gfns[key] != ~0); i++)
key = kvm_async_pf_next_probe(key);
return key;
}
bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
{
return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
}
static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
{
u32 i, j, k;
i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
while (true) {
vcpu->arch.apf.gfns[i] = ~0;
do {
j = kvm_async_pf_next_probe(j);
if (vcpu->arch.apf.gfns[j] == ~0)
return;
k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
/*
* k lies cyclically in ]i,j]
* | i.k.j |
* |....j i.k.| or |.k..j i...|
*/
} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
i = j;
}
}
static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
{
return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
sizeof(val));
}
void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
struct kvm_async_pf *work)
{
struct x86_exception fault;
trace_kvm_async_pf_not_present(work->arch.token, work->gva);
kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
(vcpu->arch.apf.send_user_only &&
kvm_x86_ops->get_cpl(vcpu) == 0))
kvm_make_request(KVM_REQ_APF_HALT, vcpu);
else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
fault.vector = PF_VECTOR;
fault.error_code_valid = true;
fault.error_code = 0;
fault.nested_page_fault = false;
fault.address = work->arch.token;
kvm_inject_page_fault(vcpu, &fault);
}
}
void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
struct kvm_async_pf *work)
{
struct x86_exception fault;
trace_kvm_async_pf_ready(work->arch.token, work->gva);
if (is_error_page(work->page))
work->arch.token = ~0; /* broadcast wakeup */
else
kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
fault.vector = PF_VECTOR;
fault.error_code_valid = true;
fault.error_code = 0;
fault.nested_page_fault = false;
fault.address = work->arch.token;
kvm_inject_page_fault(vcpu, &fault);
}
vcpu->arch.apf.halted = false;
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
}
bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
{
if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
return true;
else
return !kvm_event_needs_reinjection(vcpu) &&
kvm_x86_ops->interrupt_allowed(vcpu);
}
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5593_0 |
crossvul-cpp_data_good_128_0 | #include <math.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include "lua.h"
#include "lauxlib.h"
#define LUACMSGPACK_NAME "cmsgpack"
#define LUACMSGPACK_SAFE_NAME "cmsgpack_safe"
#define LUACMSGPACK_VERSION "lua-cmsgpack 0.4.0"
#define LUACMSGPACK_COPYRIGHT "Copyright (C) 2012, Salvatore Sanfilippo"
#define LUACMSGPACK_DESCRIPTION "MessagePack C implementation for Lua"
/* Allows a preprocessor directive to override MAX_NESTING */
#ifndef LUACMSGPACK_MAX_NESTING
#define LUACMSGPACK_MAX_NESTING 16 /* Max tables nesting. */
#endif
/* Check if float or double can be an integer without loss of precision */
#define IS_INT_TYPE_EQUIVALENT(x, T) (!isinf(x) && (T)(x) == (x))
#define IS_INT64_EQUIVALENT(x) IS_INT_TYPE_EQUIVALENT(x, int64_t)
#define IS_INT_EQUIVALENT(x) IS_INT_TYPE_EQUIVALENT(x, int)
/* If size of pointer is equal to a 4 byte integer, we're on 32 bits. */
#if UINTPTR_MAX == UINT_MAX
#define BITS_32 1
#else
#define BITS_32 0
#endif
#if BITS_32
#define lua_pushunsigned(L, n) lua_pushnumber(L, n)
#else
#define lua_pushunsigned(L, n) lua_pushinteger(L, n)
#endif
/* =============================================================================
* MessagePack implementation and bindings for Lua 5.1/5.2.
* Copyright(C) 2012 Salvatore Sanfilippo <antirez@gmail.com>
*
* http://github.com/antirez/lua-cmsgpack
*
* For MessagePack specification check the following web site:
* http://wiki.msgpack.org/display/MSGPACK/Format+specification
*
* See Copyright Notice at the end of this file.
*
* CHANGELOG:
* 19-Feb-2012 (ver 0.1.0): Initial release.
* 20-Feb-2012 (ver 0.2.0): Tables encoding improved.
* 20-Feb-2012 (ver 0.2.1): Minor bug fixing.
* 20-Feb-2012 (ver 0.3.0): Module renamed lua-cmsgpack (was lua-msgpack).
* 04-Apr-2014 (ver 0.3.1): Lua 5.2 support and minor bug fix.
* 07-Apr-2014 (ver 0.4.0): Multiple pack/unpack, lua allocator, efficiency.
* ========================================================================== */
/* -------------------------- Endian conversion --------------------------------
* We use it only for floats and doubles, all the other conversions performed
* in an endian independent fashion. So the only thing we need is a function
* that swaps a binary string if arch is little endian (and left it untouched
* otherwise). */
/* Reverse memory bytes if arch is little endian. Given the conceptual
* simplicity of the Lua build system we prefer check for endianess at runtime.
* The performance difference should be acceptable. */
void memrevifle(void *ptr, size_t len) {
unsigned char *p = (unsigned char *)ptr,
*e = (unsigned char *)p+len-1,
aux;
int test = 1;
unsigned char *testp = (unsigned char*) &test;
if (testp[0] == 0) return; /* Big endian, nothing to do. */
len /= 2;
while(len--) {
aux = *p;
*p = *e;
*e = aux;
p++;
e--;
}
}
/* ---------------------------- String buffer ----------------------------------
* This is a simple implementation of string buffers. The only operation
* supported is creating empty buffers and appending bytes to it.
* The string buffer uses 2x preallocation on every realloc for O(N) append
* behavior. */
typedef struct mp_buf {
unsigned char *b;
size_t len, free;
} mp_buf;
void *mp_realloc(lua_State *L, void *target, size_t osize,size_t nsize) {
void *(*local_realloc) (void *, void *, size_t osize, size_t nsize) = NULL;
void *ud;
local_realloc = lua_getallocf(L, &ud);
return local_realloc(ud, target, osize, nsize);
}
mp_buf *mp_buf_new(lua_State *L) {
mp_buf *buf = NULL;
/* Old size = 0; new size = sizeof(*buf) */
buf = (mp_buf*)mp_realloc(L, NULL, 0, sizeof(*buf));
buf->b = NULL;
buf->len = buf->free = 0;
return buf;
}
void mp_buf_append(lua_State *L, mp_buf *buf, const unsigned char *s, size_t len) {
if (buf->free < len) {
size_t newsize = (buf->len+len)*2;
buf->b = (unsigned char*)mp_realloc(L, buf->b, buf->len + buf->free, newsize);
buf->free = newsize - buf->len;
}
memcpy(buf->b+buf->len,s,len);
buf->len += len;
buf->free -= len;
}
void mp_buf_free(lua_State *L, mp_buf *buf) {
mp_realloc(L, buf->b, buf->len + buf->free, 0); /* realloc to 0 = free */
mp_realloc(L, buf, sizeof(*buf), 0);
}
/* ---------------------------- String cursor ----------------------------------
* This simple data structure is used for parsing. Basically you create a cursor
* using a string pointer and a length, then it is possible to access the
* current string position with cursor->p, check the remaining length
* in cursor->left, and finally consume more string using
* mp_cur_consume(cursor,len), to advance 'p' and subtract 'left'.
* An additional field cursor->error is set to zero on initialization and can
* be used to report errors. */
#define MP_CUR_ERROR_NONE 0
#define MP_CUR_ERROR_EOF 1 /* Not enough data to complete operation. */
#define MP_CUR_ERROR_BADFMT 2 /* Bad data format */
typedef struct mp_cur {
const unsigned char *p;
size_t left;
int err;
} mp_cur;
void mp_cur_init(mp_cur *cursor, const unsigned char *s, size_t len) {
cursor->p = s;
cursor->left = len;
cursor->err = MP_CUR_ERROR_NONE;
}
#define mp_cur_consume(_c,_len) do { _c->p += _len; _c->left -= _len; } while(0)
/* When there is not enough room we set an error in the cursor and return. This
* is very common across the code so we have a macro to make the code look
* a bit simpler. */
#define mp_cur_need(_c,_len) do { \
if (_c->left < _len) { \
_c->err = MP_CUR_ERROR_EOF; \
return; \
} \
} while(0)
/* ------------------------- Low level MP encoding -------------------------- */
void mp_encode_bytes(lua_State *L, mp_buf *buf, const unsigned char *s, size_t len) {
unsigned char hdr[5];
int hdrlen;
if (len < 32) {
hdr[0] = 0xa0 | (len&0xff); /* fix raw */
hdrlen = 1;
} else if (len <= 0xff) {
hdr[0] = 0xd9;
hdr[1] = len;
hdrlen = 2;
} else if (len <= 0xffff) {
hdr[0] = 0xda;
hdr[1] = (len&0xff00)>>8;
hdr[2] = len&0xff;
hdrlen = 3;
} else {
hdr[0] = 0xdb;
hdr[1] = (len&0xff000000)>>24;
hdr[2] = (len&0xff0000)>>16;
hdr[3] = (len&0xff00)>>8;
hdr[4] = len&0xff;
hdrlen = 5;
}
mp_buf_append(L,buf,hdr,hdrlen);
mp_buf_append(L,buf,s,len);
}
/* we assume IEEE 754 internal format for single and double precision floats. */
void mp_encode_double(lua_State *L, mp_buf *buf, double d) {
unsigned char b[9];
float f = d;
assert(sizeof(f) == 4 && sizeof(d) == 8);
if (d == (double)f) {
b[0] = 0xca; /* float IEEE 754 */
memcpy(b+1,&f,4);
memrevifle(b+1,4);
mp_buf_append(L,buf,b,5);
} else if (sizeof(d) == 8) {
b[0] = 0xcb; /* double IEEE 754 */
memcpy(b+1,&d,8);
memrevifle(b+1,8);
mp_buf_append(L,buf,b,9);
}
}
void mp_encode_int(lua_State *L, mp_buf *buf, int64_t n) {
unsigned char b[9];
int enclen;
if (n >= 0) {
if (n <= 127) {
b[0] = n & 0x7f; /* positive fixnum */
enclen = 1;
} else if (n <= 0xff) {
b[0] = 0xcc; /* uint 8 */
b[1] = n & 0xff;
enclen = 2;
} else if (n <= 0xffff) {
b[0] = 0xcd; /* uint 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else if (n <= 0xffffffffLL) {
b[0] = 0xce; /* uint 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
} else {
b[0] = 0xcf; /* uint 64 */
b[1] = (n & 0xff00000000000000LL) >> 56;
b[2] = (n & 0xff000000000000LL) >> 48;
b[3] = (n & 0xff0000000000LL) >> 40;
b[4] = (n & 0xff00000000LL) >> 32;
b[5] = (n & 0xff000000) >> 24;
b[6] = (n & 0xff0000) >> 16;
b[7] = (n & 0xff00) >> 8;
b[8] = n & 0xff;
enclen = 9;
}
} else {
if (n >= -32) {
b[0] = ((signed char)n); /* negative fixnum */
enclen = 1;
} else if (n >= -128) {
b[0] = 0xd0; /* int 8 */
b[1] = n & 0xff;
enclen = 2;
} else if (n >= -32768) {
b[0] = 0xd1; /* int 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else if (n >= -2147483648LL) {
b[0] = 0xd2; /* int 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
} else {
b[0] = 0xd3; /* int 64 */
b[1] = (n & 0xff00000000000000LL) >> 56;
b[2] = (n & 0xff000000000000LL) >> 48;
b[3] = (n & 0xff0000000000LL) >> 40;
b[4] = (n & 0xff00000000LL) >> 32;
b[5] = (n & 0xff000000) >> 24;
b[6] = (n & 0xff0000) >> 16;
b[7] = (n & 0xff00) >> 8;
b[8] = n & 0xff;
enclen = 9;
}
}
mp_buf_append(L,buf,b,enclen);
}
void mp_encode_array(lua_State *L, mp_buf *buf, int64_t n) {
unsigned char b[5];
int enclen;
if (n <= 15) {
b[0] = 0x90 | (n & 0xf); /* fix array */
enclen = 1;
} else if (n <= 65535) {
b[0] = 0xdc; /* array 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else {
b[0] = 0xdd; /* array 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
}
mp_buf_append(L,buf,b,enclen);
}
void mp_encode_map(lua_State *L, mp_buf *buf, int64_t n) {
unsigned char b[5];
int enclen;
if (n <= 15) {
b[0] = 0x80 | (n & 0xf); /* fix map */
enclen = 1;
} else if (n <= 65535) {
b[0] = 0xde; /* map 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else {
b[0] = 0xdf; /* map 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
}
mp_buf_append(L,buf,b,enclen);
}
/* --------------------------- Lua types encoding --------------------------- */
void mp_encode_lua_string(lua_State *L, mp_buf *buf) {
size_t len;
const char *s;
s = lua_tolstring(L,-1,&len);
mp_encode_bytes(L,buf,(const unsigned char*)s,len);
}
void mp_encode_lua_bool(lua_State *L, mp_buf *buf) {
unsigned char b = lua_toboolean(L,-1) ? 0xc3 : 0xc2;
mp_buf_append(L,buf,&b,1);
}
/* Lua 5.3 has a built in 64-bit integer type */
void mp_encode_lua_integer(lua_State *L, mp_buf *buf) {
#if (LUA_VERSION_NUM < 503) && BITS_32
lua_Number i = lua_tonumber(L,-1);
#else
lua_Integer i = lua_tointeger(L,-1);
#endif
mp_encode_int(L, buf, (int64_t)i);
}
/* Lua 5.2 and lower only has 64-bit doubles, so we need to
* detect if the double may be representable as an int
* for Lua < 5.3 */
void mp_encode_lua_number(lua_State *L, mp_buf *buf) {
lua_Number n = lua_tonumber(L,-1);
if (IS_INT64_EQUIVALENT(n)) {
mp_encode_lua_integer(L, buf);
} else {
mp_encode_double(L,buf,(double)n);
}
}
void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level);
/* Convert a lua table into a message pack list. */
void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) {
#if LUA_VERSION_NUM < 502
size_t len = lua_objlen(L,-1), j;
#else
size_t len = lua_rawlen(L,-1), j;
#endif
mp_encode_array(L,buf,len);
for (j = 1; j <= len; j++) {
lua_pushnumber(L,j);
lua_gettable(L,-2);
mp_encode_lua_type(L,buf,level+1);
}
}
/* Convert a lua table into a message pack key-value map. */
void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
size_t len = 0;
/* First step: count keys into table. No other way to do it with the
* Lua API, we need to iterate a first time. Note that an alternative
* would be to do a single run, and then hack the buffer to insert the
* map opcodes for message pack. Too hackish for this lib. */
lua_pushnil(L);
while(lua_next(L,-2)) {
lua_pop(L,1); /* remove value, keep key for next iteration. */
len++;
}
/* Step two: actually encoding of the map. */
mp_encode_map(L,buf,len);
lua_pushnil(L);
while(lua_next(L,-2)) {
/* Stack: ... key value */
lua_pushvalue(L,-2); /* Stack: ... key value key */
mp_encode_lua_type(L,buf,level+1); /* encode key */
mp_encode_lua_type(L,buf,level+1); /* encode val */
}
}
/* Returns true if the Lua table on top of the stack is exclusively composed
* of keys from numerical keys from 1 up to N, with N being the total number
* of elements, without any hole in the middle. */
int table_is_an_array(lua_State *L) {
int count = 0, max = 0;
#if LUA_VERSION_NUM < 503
lua_Number n;
#else
lua_Integer n;
#endif
/* Stack top on function entry */
int stacktop;
stacktop = lua_gettop(L);
lua_pushnil(L);
while(lua_next(L,-2)) {
/* Stack: ... key value */
lua_pop(L,1); /* Stack: ... key */
/* The <= 0 check is valid here because we're comparing indexes. */
#if LUA_VERSION_NUM < 503
if ((LUA_TNUMBER != lua_type(L,-1)) || (n = lua_tonumber(L, -1)) <= 0 ||
!IS_INT_EQUIVALENT(n))
#else
if (!lua_isinteger(L,-1) || (n = lua_tointeger(L, -1)) <= 0)
#endif
{
lua_settop(L, stacktop);
return 0;
}
max = (n > max ? n : max);
count++;
}
/* We have the total number of elements in "count". Also we have
* the max index encountered in "max". We can't reach this code
* if there are indexes <= 0. If you also note that there can not be
* repeated keys into a table, you have that if max==count you are sure
* that there are all the keys form 1 to count (both included). */
lua_settop(L, stacktop);
return max == count;
}
/* If the length operator returns non-zero, that is, there is at least
* an object at key '1', we serialize to message pack list. Otherwise
* we use a map. */
void mp_encode_lua_table(lua_State *L, mp_buf *buf, int level) {
if (table_is_an_array(L))
mp_encode_lua_table_as_array(L,buf,level);
else
mp_encode_lua_table_as_map(L,buf,level);
}
void mp_encode_lua_null(lua_State *L, mp_buf *buf) {
unsigned char b[1];
b[0] = 0xc0;
mp_buf_append(L,buf,b,1);
}
void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level) {
int t = lua_type(L,-1);
/* Limit the encoding of nested tables to a specified maximum depth, so that
* we survive when called against circular references in tables. */
if (t == LUA_TTABLE && level == LUACMSGPACK_MAX_NESTING) t = LUA_TNIL;
switch(t) {
case LUA_TSTRING: mp_encode_lua_string(L,buf); break;
case LUA_TBOOLEAN: mp_encode_lua_bool(L,buf); break;
case LUA_TNUMBER:
#if LUA_VERSION_NUM < 503
mp_encode_lua_number(L,buf); break;
#else
if (lua_isinteger(L, -1)) {
mp_encode_lua_integer(L, buf);
} else {
mp_encode_lua_number(L, buf);
}
break;
#endif
case LUA_TTABLE: mp_encode_lua_table(L,buf,level); break;
default: mp_encode_lua_null(L,buf); break;
}
lua_pop(L,1);
}
/*
* Packs all arguments as a stream for multiple upacking later.
* Returns error if no arguments provided.
*/
int mp_pack(lua_State *L) {
int nargs = lua_gettop(L);
int i;
mp_buf *buf;
if (nargs == 0)
return luaL_argerror(L, 0, "MessagePack pack needs input.");
if (!lua_checkstack(L, nargs))
return luaL_argerror(L, 0, "Too many arguments for MessagePack pack.");
buf = mp_buf_new(L);
for(i = 1; i <= nargs; i++) {
/* Copy argument i to top of stack for _encode processing;
* the encode function pops it from the stack when complete. */
lua_pushvalue(L, i);
mp_encode_lua_type(L,buf,0);
lua_pushlstring(L,(char*)buf->b,buf->len);
/* Reuse the buffer for the next operation by
* setting its free count to the total buffer size
* and the current position to zero. */
buf->free += buf->len;
buf->len = 0;
}
mp_buf_free(L, buf);
/* Concatenate all nargs buffers together */
lua_concat(L, nargs);
return 1;
}
/* ------------------------------- Decoding --------------------------------- */
void mp_decode_to_lua_type(lua_State *L, mp_cur *c);
void mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) {
assert(len <= UINT_MAX);
int index = 1;
lua_newtable(L);
while(len--) {
lua_pushnumber(L,index++);
mp_decode_to_lua_type(L,c);
if (c->err) return;
lua_settable(L,-3);
}
}
void mp_decode_to_lua_hash(lua_State *L, mp_cur *c, size_t len) {
assert(len <= UINT_MAX);
lua_newtable(L);
while(len--) {
mp_decode_to_lua_type(L,c); /* key */
if (c->err) return;
mp_decode_to_lua_type(L,c); /* value */
if (c->err) return;
lua_settable(L,-3);
}
}
/* Decode a Message Pack raw object pointed by the string cursor 'c' to
* a Lua type, that is left as the only result on the stack. */
void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
mp_cur_need(c,1);
/* If we return more than 18 elements, we must resize the stack to
* fit all our return values. But, there is no way to
* determine how many objects a msgpack will unpack to up front, so
* we request a +1 larger stack on each iteration (noop if stack is
* big enough, and when stack does require resize it doubles in size) */
luaL_checkstack(L, 1,
"too many return values at once; "
"use unpack_one or unpack_limit instead.");
switch(c->p[0]) {
case 0xcc: /* uint 8 */
mp_cur_need(c,2);
lua_pushunsigned(L,c->p[1]);
mp_cur_consume(c,2);
break;
case 0xd0: /* int 8 */
mp_cur_need(c,2);
lua_pushinteger(L,(signed char)c->p[1]);
mp_cur_consume(c,2);
break;
case 0xcd: /* uint 16 */
mp_cur_need(c,3);
lua_pushunsigned(L,
(c->p[1] << 8) |
c->p[2]);
mp_cur_consume(c,3);
break;
case 0xd1: /* int 16 */
mp_cur_need(c,3);
lua_pushinteger(L,(int16_t)
(c->p[1] << 8) |
c->p[2]);
mp_cur_consume(c,3);
break;
case 0xce: /* uint 32 */
mp_cur_need(c,5);
lua_pushunsigned(L,
((uint32_t)c->p[1] << 24) |
((uint32_t)c->p[2] << 16) |
((uint32_t)c->p[3] << 8) |
(uint32_t)c->p[4]);
mp_cur_consume(c,5);
break;
case 0xd2: /* int 32 */
mp_cur_need(c,5);
lua_pushinteger(L,
((int32_t)c->p[1] << 24) |
((int32_t)c->p[2] << 16) |
((int32_t)c->p[3] << 8) |
(int32_t)c->p[4]);
mp_cur_consume(c,5);
break;
case 0xcf: /* uint 64 */
mp_cur_need(c,9);
lua_pushunsigned(L,
((uint64_t)c->p[1] << 56) |
((uint64_t)c->p[2] << 48) |
((uint64_t)c->p[3] << 40) |
((uint64_t)c->p[4] << 32) |
((uint64_t)c->p[5] << 24) |
((uint64_t)c->p[6] << 16) |
((uint64_t)c->p[7] << 8) |
(uint64_t)c->p[8]);
mp_cur_consume(c,9);
break;
case 0xd3: /* int 64 */
mp_cur_need(c,9);
#if LUA_VERSION_NUM < 503
lua_pushnumber(L,
#else
lua_pushinteger(L,
#endif
((int64_t)c->p[1] << 56) |
((int64_t)c->p[2] << 48) |
((int64_t)c->p[3] << 40) |
((int64_t)c->p[4] << 32) |
((int64_t)c->p[5] << 24) |
((int64_t)c->p[6] << 16) |
((int64_t)c->p[7] << 8) |
(int64_t)c->p[8]);
mp_cur_consume(c,9);
break;
case 0xc0: /* nil */
lua_pushnil(L);
mp_cur_consume(c,1);
break;
case 0xc3: /* true */
lua_pushboolean(L,1);
mp_cur_consume(c,1);
break;
case 0xc2: /* false */
lua_pushboolean(L,0);
mp_cur_consume(c,1);
break;
case 0xca: /* float */
mp_cur_need(c,5);
assert(sizeof(float) == 4);
{
float f;
memcpy(&f,c->p+1,4);
memrevifle(&f,4);
lua_pushnumber(L,f);
mp_cur_consume(c,5);
}
break;
case 0xcb: /* double */
mp_cur_need(c,9);
assert(sizeof(double) == 8);
{
double d;
memcpy(&d,c->p+1,8);
memrevifle(&d,8);
lua_pushnumber(L,d);
mp_cur_consume(c,9);
}
break;
case 0xd9: /* raw 8 */
mp_cur_need(c,2);
{
size_t l = c->p[1];
mp_cur_need(c,2+l);
lua_pushlstring(L,(char*)c->p+2,l);
mp_cur_consume(c,2+l);
}
break;
case 0xda: /* raw 16 */
mp_cur_need(c,3);
{
size_t l = (c->p[1] << 8) | c->p[2];
mp_cur_need(c,3+l);
lua_pushlstring(L,(char*)c->p+3,l);
mp_cur_consume(c,3+l);
}
break;
case 0xdb: /* raw 32 */
mp_cur_need(c,5);
{
size_t l = ((size_t)c->p[1] << 24) |
((size_t)c->p[2] << 16) |
((size_t)c->p[3] << 8) |
(size_t)c->p[4];
mp_cur_consume(c,5);
mp_cur_need(c,l);
lua_pushlstring(L,(char*)c->p,l);
mp_cur_consume(c,l);
}
break;
case 0xdc: /* array 16 */
mp_cur_need(c,3);
{
size_t l = (c->p[1] << 8) | c->p[2];
mp_cur_consume(c,3);
mp_decode_to_lua_array(L,c,l);
}
break;
case 0xdd: /* array 32 */
mp_cur_need(c,5);
{
size_t l = ((size_t)c->p[1] << 24) |
((size_t)c->p[2] << 16) |
((size_t)c->p[3] << 8) |
(size_t)c->p[4];
mp_cur_consume(c,5);
mp_decode_to_lua_array(L,c,l);
}
break;
case 0xde: /* map 16 */
mp_cur_need(c,3);
{
size_t l = (c->p[1] << 8) | c->p[2];
mp_cur_consume(c,3);
mp_decode_to_lua_hash(L,c,l);
}
break;
case 0xdf: /* map 32 */
mp_cur_need(c,5);
{
size_t l = ((size_t)c->p[1] << 24) |
((size_t)c->p[2] << 16) |
((size_t)c->p[3] << 8) |
(size_t)c->p[4];
mp_cur_consume(c,5);
mp_decode_to_lua_hash(L,c,l);
}
break;
default: /* types that can't be idenitified by first byte value. */
if ((c->p[0] & 0x80) == 0) { /* positive fixnum */
lua_pushunsigned(L,c->p[0]);
mp_cur_consume(c,1);
} else if ((c->p[0] & 0xe0) == 0xe0) { /* negative fixnum */
lua_pushinteger(L,(signed char)c->p[0]);
mp_cur_consume(c,1);
} else if ((c->p[0] & 0xe0) == 0xa0) { /* fix raw */
size_t l = c->p[0] & 0x1f;
mp_cur_need(c,1+l);
lua_pushlstring(L,(char*)c->p+1,l);
mp_cur_consume(c,1+l);
} else if ((c->p[0] & 0xf0) == 0x90) { /* fix map */
size_t l = c->p[0] & 0xf;
mp_cur_consume(c,1);
mp_decode_to_lua_array(L,c,l);
} else if ((c->p[0] & 0xf0) == 0x80) { /* fix map */
size_t l = c->p[0] & 0xf;
mp_cur_consume(c,1);
mp_decode_to_lua_hash(L,c,l);
} else {
c->err = MP_CUR_ERROR_BADFMT;
}
}
}
int mp_unpack_full(lua_State *L, int limit, int offset) {
size_t len;
const char *s;
mp_cur c;
int cnt; /* Number of objects unpacked */
int decode_all = (!limit && !offset);
s = luaL_checklstring(L,1,&len); /* if no match, exits */
if (offset < 0 || limit < 0) /* requesting negative off or lim is invalid */
return luaL_error(L,
"Invalid request to unpack with offset of %d and limit of %d.",
offset, len);
else if (offset > len)
return luaL_error(L,
"Start offset %d greater than input length %d.", offset, len);
if (decode_all) limit = INT_MAX;
mp_cur_init(&c,(const unsigned char *)s+offset,len-offset);
/* We loop over the decode because this could be a stream
* of multiple top-level values serialized together */
for(cnt = 0; c.left > 0 && cnt < limit; cnt++) {
mp_decode_to_lua_type(L,&c);
if (c.err == MP_CUR_ERROR_EOF) {
return luaL_error(L,"Missing bytes in input.");
} else if (c.err == MP_CUR_ERROR_BADFMT) {
return luaL_error(L,"Bad data format in input.");
}
}
if (!decode_all) {
/* c->left is the remaining size of the input buffer.
* subtract the entire buffer size from the unprocessed size
* to get our next start offset */
int offset = len - c.left;
/* Return offset -1 when we have have processed the entire buffer. */
lua_pushinteger(L, c.left == 0 ? -1 : offset);
/* Results are returned with the arg elements still
* in place. Lua takes care of only returning
* elements above the args for us.
* In this case, we have one arg on the stack
* for this function, so we insert our first return
* value at position 2. */
lua_insert(L, 2);
cnt += 1; /* increase return count by one to make room for offset */
}
return cnt;
}
int mp_unpack(lua_State *L) {
return mp_unpack_full(L, 0, 0);
}
int mp_unpack_one(lua_State *L) {
int offset = luaL_optinteger(L, 2, 0);
/* Variable pop because offset may not exist */
lua_pop(L, lua_gettop(L)-1);
return mp_unpack_full(L, 1, offset);
}
int mp_unpack_limit(lua_State *L) {
int limit = luaL_checkinteger(L, 2);
int offset = luaL_optinteger(L, 3, 0);
/* Variable pop because offset may not exist */
lua_pop(L, lua_gettop(L)-1);
return mp_unpack_full(L, limit, offset);
}
int mp_safe(lua_State *L) {
int argc, err, total_results;
argc = lua_gettop(L);
/* This adds our function to the bottom of the stack
* (the "call this function" position) */
lua_pushvalue(L, lua_upvalueindex(1));
lua_insert(L, 1);
err = lua_pcall(L, argc, LUA_MULTRET, 0);
total_results = lua_gettop(L);
if (!err) {
return total_results;
} else {
lua_pushnil(L);
lua_insert(L,-2);
return 2;
}
}
/* -------------------------------------------------------------------------- */
const struct luaL_Reg cmds[] = {
{"pack", mp_pack},
{"unpack", mp_unpack},
{"unpack_one", mp_unpack_one},
{"unpack_limit", mp_unpack_limit},
{0}
};
int luaopen_create(lua_State *L) {
int i;
/* Manually construct our module table instead of
* relying on _register or _newlib */
lua_newtable(L);
for (i = 0; i < (sizeof(cmds)/sizeof(*cmds) - 1); i++) {
lua_pushcfunction(L, cmds[i].func);
lua_setfield(L, -2, cmds[i].name);
}
/* Add metadata */
lua_pushliteral(L, LUACMSGPACK_NAME);
lua_setfield(L, -2, "_NAME");
lua_pushliteral(L, LUACMSGPACK_VERSION);
lua_setfield(L, -2, "_VERSION");
lua_pushliteral(L, LUACMSGPACK_COPYRIGHT);
lua_setfield(L, -2, "_COPYRIGHT");
lua_pushliteral(L, LUACMSGPACK_DESCRIPTION);
lua_setfield(L, -2, "_DESCRIPTION");
return 1;
}
LUALIB_API int luaopen_cmsgpack(lua_State *L) {
luaopen_create(L);
#if LUA_VERSION_NUM < 502
/* Register name globally for 5.1 */
lua_pushvalue(L, -1);
lua_setglobal(L, LUACMSGPACK_NAME);
#endif
return 1;
}
LUALIB_API int luaopen_cmsgpack_safe(lua_State *L) {
int i;
luaopen_cmsgpack(L);
/* Wrap all functions in the safe handler */
for (i = 0; i < (sizeof(cmds)/sizeof(*cmds) - 1); i++) {
lua_getfield(L, -1, cmds[i].name);
lua_pushcclosure(L, mp_safe, 1);
lua_setfield(L, -2, cmds[i].name);
}
#if LUA_VERSION_NUM < 502
/* Register name globally for 5.1 */
lua_pushvalue(L, -1);
lua_setglobal(L, LUACMSGPACK_SAFE_NAME);
#endif
return 1;
}
/******************************************************************************
* Copyright (C) 2012 Salvatore Sanfilippo. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_128_0 |
crossvul-cpp_data_good_1050_4 | /* Copyright (C) 2000-2012 by George Williams */
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <fontforge-config.h>
#include "gdraw.h"
#include "ggadgetP.h"
#include "gkeysym.h"
#include "gresource.h"
#include "gwidget.h"
#include "ustring.h"
#include "utype.h"
#include <math.h>
extern void (*_GDraw_InsCharHook)(GDisplay *,unichar_t);
GBox _GGadget_gtextfield_box = GBOX_EMPTY; /* Don't initialize here */
static GBox glistfield_box = GBOX_EMPTY; /* Don't initialize here */
static GBox glistfieldmenu_box = GBOX_EMPTY; /* Don't initialize here */
static GBox gnumericfield_box = GBOX_EMPTY; /* Don't initialize here */
static GBox gnumericfieldspinner_box = GBOX_EMPTY; /* Don't initialize here */
FontInstance *_gtextfield_font = NULL;
static int gtextfield_inited = false;
static GResInfo listfield_ri, listfieldmenu_ri, numericfield_ri, numericfieldspinner_ri;
static GTextInfo text_lab[] = {
{ (unichar_t *) "Disabled", NULL, 0, 0, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ (unichar_t *) "Enabled" , NULL, 0, 0, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, '\0' }
};
static GTextInfo list_choices[] = {
{ (unichar_t *) "1", NULL, 0, 0, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ (unichar_t *) "2", NULL, 0, 0, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ (unichar_t *) "3", NULL, 0, 0, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, '\0' },
GTEXTINFO_EMPTY
};
static GGadgetCreateData text_gcd[] = {
{ GTextFieldCreate, { { 0, 0, 70, 0 }, NULL, 0, 0, 0, 0, 0, &text_lab[0], { NULL }, gg_visible, NULL, NULL }, NULL, NULL },
{ GTextFieldCreate, { { 0, 0, 70, 0 }, NULL, 0, 0, 0, 0, 0, &text_lab[1], { NULL }, gg_visible|gg_enabled, NULL, NULL }, NULL, NULL }
};
static GGadgetCreateData *tarray[] = { GCD_Glue, &text_gcd[0], GCD_Glue, &text_gcd[1], GCD_Glue, NULL, NULL };
static GGadgetCreateData textbox =
{ GHVGroupCreate, { { 2, 2, 0, 0 }, NULL, 0, 0, 0, 0, 0, NULL, { (GTextInfo *) tarray }, gg_visible|gg_enabled, NULL, NULL }, NULL, NULL };
static GResInfo gtextfield_ri = {
&listfield_ri, &ggadget_ri,NULL, NULL,
&_GGadget_gtextfield_box,
&_gtextfield_font,
&textbox,
NULL,
N_("Text Field"),
N_("Text Field"),
"GTextField",
"Gdraw",
false,
omf_font|omf_padding,
NULL,
GBOX_EMPTY,
NULL,
NULL,
NULL
};
static GGadgetCreateData textlist_gcd[] = {
{ GListFieldCreate, { GRECT_EMPTY, NULL, 0, 0, 0, 0, 0, &text_lab[0], { list_choices }, gg_visible, NULL, NULL }, NULL, NULL },
{ GListFieldCreate, { GRECT_EMPTY, NULL, 0, 0, 0, 0, 0, &text_lab[1], { list_choices }, gg_visible|gg_enabled, NULL, NULL }, NULL, NULL }
};
static GGadgetCreateData *tlarray[] = { GCD_Glue, &textlist_gcd[0], GCD_Glue, &textlist_gcd[1], GCD_Glue, NULL, NULL };
static GGadgetCreateData textlistbox =
{ GHVGroupCreate, { { 2, 2, 0, 0 }, NULL, 0, 0, 0, 0, 0, NULL, { (GTextInfo *) tlarray }, gg_visible|gg_enabled, NULL, NULL }, NULL, NULL };
static GResInfo listfield_ri = {
&listfieldmenu_ri, >extfield_ri,&listfieldmenu_ri, &listmark_ri,
&glistfield_box,
NULL,
&textlistbox,
NULL,
N_("List Field"),
N_("List Field (Combo Box)"),
"GComboBox",
"Gdraw",
false,
0,
NULL,
GBOX_EMPTY,
NULL,
NULL,
NULL
};
static GResInfo listfieldmenu_ri = {
&numericfield_ri, &listfield_ri, &listmark_ri,NULL,
&glistfieldmenu_box,
NULL,
&textlistbox,
NULL,
N_("List Field Menu"),
N_("Box surrounding the ListMark in a list field (combobox)"),
"GComboBoxMenu",
"Gdraw",
false,
omf_padding,
NULL,
GBOX_EMPTY,
NULL,
NULL,
NULL
};
static GGadgetCreateData num_gcd[] = {
{ GNumericFieldCreate, { { 0, 0, 50, 0 }, NULL, 0, 0, 0, 0, 0, &list_choices[0], { NULL }, gg_visible, NULL, NULL }, NULL, NULL },
{ GNumericFieldCreate, { { 0, 0, 50, 0 }, NULL, 0, 0, 0, 0, 0, &list_choices[0], { NULL }, gg_visible|gg_enabled, NULL, NULL }, NULL, NULL }
};
static GGadgetCreateData *narray[] = { GCD_Glue, &num_gcd[0], GCD_Glue, &num_gcd[1], GCD_Glue, NULL, NULL };
static GGadgetCreateData numbox =
{ GHVGroupCreate, { { 2, 2, 0, 0 }, NULL, 0, 0, 0, 0, 0, NULL, { (GTextInfo *) narray }, gg_visible|gg_enabled, NULL, NULL }, NULL, NULL };
static GResInfo numericfield_ri = {
&numericfieldspinner_ri, >extfield_ri,&numericfieldspinner_ri, NULL,
&gnumericfield_box,
NULL,
&numbox,
NULL,
N_("Numeric Field"),
N_("Numeric Field (Spinner)"),
"GNumericField",
"Gdraw",
false,
0,
NULL,
GBOX_EMPTY,
NULL,
NULL,
NULL
};
static GResInfo numericfieldspinner_ri = {
NULL, &numericfield_ri,NULL, NULL,
&gnumericfieldspinner_box,
NULL,
&numbox,
NULL,
N_("Numeric Field Sign"),
N_("The box around the up/down arrows of a numeric field (spinner)"),
"GNumericFieldSpinner",
"Gdraw",
false,
omf_border_type|omf_border_width|omf_padding,
NULL,
GBOX_EMPTY,
NULL,
NULL,
NULL
};
static unichar_t nullstr[] = { 0 }, nstr[] = { 'n', 0 },
newlinestr[] = { '\n', 0 }, tabstr[] = { '\t', 0 };
static void GListFieldSelected(GGadget *g, int i);
static int GTextField_Show(GTextField *gt, int pos);
static void GTPositionGIC(GTextField *gt);
static void GCompletionDestroy(GCompletionField *gc);
static void GTextFieldComplete(GTextField *gt,int from_tab);
static int GCompletionHandleKey(GTextField *gt,GEvent *event);
static int u2utf8_index(int pos,const char *start) {
const char *pt = start;
while ( --pos>=0 )
utf8_ildb(&pt);
return( pt-start );
}
static int utf82u_index(int pos, const char *start) {
int uc = 0;
const char *end = start+pos;
while ( start<end ) {
utf8_ildb(&start);
++uc;
}
return( uc );
}
static void GTextFieldChanged(GTextField *gt,int src) {
GEvent e;
e.type = et_controlevent;
e.w = gt->g.base;
e.u.control.subtype = et_textchanged;
e.u.control.g = >->g;
e.u.control.u.tf_changed.from_pulldown = src;
if ( gt->g.handle_controlevent != NULL )
(gt->g.handle_controlevent)(>->g,&e);
else
GDrawPostEvent(&e);
}
static void GTextFieldSaved(GTextField *gt) {
GEvent e;
e.type = et_controlevent;
e.w = gt->g.base;
e.u.control.subtype = et_save;
e.u.control.g = >->g;
if ( gt->g.handle_controlevent != NULL )
(gt->g.handle_controlevent)(>->g,&e);
else
GDrawPostEvent(&e);
}
static void GTextFieldFocusChanged(GTextField *gt,int gained) {
GEvent e;
if ( (gt->g.box->flags & box_active_border_inner) &&
( gt->g.state==gs_enabled || gt->g.state==gs_active )) {
int state = gained?gs_active:gs_enabled;
if ( state!=gt->g.state ) {
gt->g.state = state;
GGadgetRedraw((GGadget *) gt);
}
}
e.type = et_controlevent;
e.w = gt->g.base;
e.u.control.subtype = et_textfocuschanged;
e.u.control.g = >->g;
e.u.control.u.tf_focus.gained_focus = gained;
if ( gt->g.handle_controlevent != NULL )
(gt->g.handle_controlevent)(>->g,&e);
else
GDrawPostEvent(&e);
}
static void GTextFieldPangoRefigureLines(GTextField *gt, int start_of_change) {
char *utf8_text, *pt, *ept;
unichar_t *upt, *uept;
int i, uc;
GRect size;
free(gt->utf8_text);
if ( gt->lines8==NULL ) {
gt->lines8 = malloc(gt->lmax*sizeof(int32));
gt->lines8[0] = 0;
gt->lines8[1] = -1;
}
if ( gt->password ) {
int cnt = u_strlen(gt->text);
utf8_text = malloc(cnt+1);
memset(utf8_text,'*',cnt);
utf8_text[cnt] = '\0';
} else
utf8_text = u2utf8_copy(gt->text);
gt->utf8_text = utf8_text;
GDrawLayoutInit(gt->g.base,utf8_text,-1,NULL);
if ( !gt->multi_line ) {
GDrawLayoutExtents(gt->g.base,&size);
gt->xmax = size.width;
return;
}
if ( !gt->wrap ) {
pt = utf8_text;
i=0;
while ( ( ept = strchr(pt,'\n'))!=NULL ) {
if ( i>=gt->lmax ) {
gt->lines8 = realloc(gt->lines8,(gt->lmax+=10)*sizeof(int32));
gt->lines = realloc(gt->lines,gt->lmax*sizeof(int32));
}
gt->lines8[i++] = pt-utf8_text;
pt = ept+1;
}
if ( i>=gt->lmax ) {
gt->lines8 = realloc(gt->lines8,(gt->lmax+=10)*sizeof(int32));
gt->lines = realloc(gt->lines,gt->lmax*sizeof(int32));
}
gt->lines8[i++] = pt-utf8_text;
upt = gt->text;
i = 0;
while ( ( uept = u_strchr(upt,'\n'))!=NULL ) {
gt->lines[i++] = upt-gt->text;
upt = uept+1;
}
gt->lines[i++] = upt-gt->text;
} else {
int lcnt;
GDrawLayoutSetWidth(gt->g.base,gt->g.inner.width);
lcnt = GDrawLayoutLineCount(gt->g.base);
if ( lcnt+2>=gt->lmax ) {
gt->lines8 = realloc(gt->lines8,(gt->lmax=lcnt+10)*sizeof(int32));
gt->lines = realloc(gt->lines,gt->lmax*sizeof(int32));
}
pt = utf8_text; uc=0;
for ( i=0; i<lcnt; ++i ) {
gt->lines8[i] = GDrawLayoutLineStart(gt->g.base,i);
ept = utf8_text + gt->lines8[i];
while ( pt<ept ) {
++uc;
utf8_ildb((const char **) &pt);
}
gt->lines[i] = uc;
}
if ( i==0 ) {
gt->lines8[i] = strlen(utf8_text);
gt->lines[i] = u_strlen(gt->text);
} else {
gt->lines8[i] = gt->lines8[i-1] + strlen( utf8_text + gt->lines8[i-1]);
gt->lines [i] = gt->lines [i-1] + u_strlen( gt->text + gt->lines [i-1]);
}
}
if ( gt->lcnt!=i ) {
gt->lcnt = i;
if ( gt->vsb!=NULL )
GScrollBarSetBounds(>->vsb->g,0,gt->lcnt,
gt->g.inner.height<gt->fh? 1 : gt->g.inner.height/gt->fh);
if ( gt->loff_top+gt->g.inner.height/gt->fh>gt->lcnt ) {
gt->loff_top = gt->lcnt-gt->g.inner.height/gt->fh;
if ( gt->loff_top<0 ) gt->loff_top = 0;
if ( gt->vsb!=NULL )
GScrollBarSetPos(>->vsb->g,gt->loff_top);
}
}
if ( i>=gt->lmax )
gt->lines = realloc(gt->lines,(gt->lmax+=10)*sizeof(int32));
gt->lines8[i] = -1;
gt->lines[i++] = -1;
GDrawLayoutExtents(gt->g.base,&size);
gt->xmax = size.width;
if ( gt->hsb!=NULL ) {
GScrollBarSetBounds(>->hsb->g,0,gt->xmax,gt->g.inner.width);
}
GDrawLayoutSetWidth(gt->g.base,-1);
}
static void GTextFieldRefigureLines(GTextField *gt, int start_of_change) {
GDrawSetFont(gt->g.base,gt->font);
if ( gt->lines==NULL ) {
gt->lines = malloc(10*sizeof(int32));
gt->lines[0] = 0;
gt->lines[1] = -1;
gt->lmax = 10;
gt->lcnt = 1;
if ( gt->vsb!=NULL )
GScrollBarSetBounds(>->vsb->g,0,gt->lcnt,
gt->g.inner.height<gt->fh ? 1 : gt->g.inner.height/gt->fh);
}
GTextFieldPangoRefigureLines(gt,start_of_change);
return;
}
static void _GTextFieldReplace(GTextField *gt, const unichar_t *str) {
unichar_t *old = gt->oldtext;
unichar_t *new = malloc((u_strlen(gt->text)-(gt->sel_end-gt->sel_start) + u_strlen(str)+1)*sizeof(unichar_t));
gt->oldtext = gt->text;
gt->sel_oldstart = gt->sel_start;
gt->sel_oldend = gt->sel_end;
gt->sel_oldbase = gt->sel_base;
u_strncpy(new,gt->text,gt->sel_start);
u_strcpy(new+gt->sel_start,str);
gt->sel_start = u_strlen(new);
u_strcpy(new+gt->sel_start,gt->text+gt->sel_end);
gt->text = new;
gt->sel_end = gt->sel_base = gt->sel_start;
free(old);
GTextFieldRefigureLines(gt,gt->sel_oldstart);
}
static void GTextField_Replace(GTextField *gt, const unichar_t *str) {
_GTextFieldReplace(gt,str);
GTextField_Show(gt,gt->sel_start);
}
static int GTextFieldFindLine(GTextField *gt, int pos) {
int i;
for ( i=0; gt->lines[i+1]!=-1; ++i )
if ( pos<gt->lines[i+1])
break;
return( i );
}
static unichar_t *GTextFieldGetPtFromPos(GTextField *gt,int i,int xpos) {
int ll;
unichar_t *end;
ll = gt->lines[i+1]==-1?-1:gt->lines[i+1]-gt->lines[i]-1;
int index8, uc;
if ( gt->lines8[i+1]==-1 )
GDrawLayoutInit(gt->g.base,gt->utf8_text + gt->lines8[i],-1,NULL);
else {
GDrawLayoutInit(gt->g.base,gt->utf8_text + gt->lines8[i], gt->lines8[i+1]-gt->lines8[i], NULL);
}
index8 = GDrawLayoutXYToIndex(gt->g.base,xpos-gt->g.inner.x+gt->xoff_left,0);
uc = utf82u_index(index8,gt->utf8_text + gt->lines8[i]);
end = gt->text + gt->lines[i] + uc;
return( end );
}
static int GTextField_Show(GTextField *gt, int pos) {
int i, ll, xoff, loff;
int refresh=false;
GListField *ge = (GListField *) gt;
int width = gt->g.inner.width;
if ( gt->listfield || gt->numericfield )
width = ge->fieldrect.width - 2*(gt->g.inner.x - gt->g.r.x);
if ( pos < 0 ) pos = 0;
if ( pos > u_strlen(gt->text)) pos = u_strlen(gt->text);
i = GTextFieldFindLine(gt,pos);
loff = gt->loff_top;
if ( gt->lcnt<gt->g.inner.height/gt->fh || loff==0 )
loff = 0;
if ( i<loff )
loff = i;
if ( i>=loff+gt->g.inner.height/gt->fh ) {
loff = i-(gt->g.inner.height/gt->fh);
if ( gt->g.inner.height/gt->fh>2 )
++loff;
}
xoff = gt->xoff_left;
if ( gt->lines[i+1]==-1 ) ll = -1; else ll = gt->lines[i+1]-gt->lines[i]-1;
GRect size;
if ( gt->lines8[i+1]==-1 ) ll = strlen(gt->utf8_text+gt->lines8[i]); else ll = gt->lines8[i+1]-gt->lines8[i]-1;
GDrawLayoutInit(gt->g.base,gt->utf8_text+gt->lines8[i],ll,NULL);
GDrawLayoutExtents(gt->g.base,&size);
if ( size.width < width )
xoff = 0;
else {
int index8 = u2utf8_index(pos- gt->lines8[i],gt->utf8_text + gt->lines8[i]);
GDrawLayoutIndexToPos(gt->g.base,index8,&size);
if ( size.x + 2*size.width < width )
xoff = 0;
else
xoff = size.x - (width - size.width)/2;
if ( xoff<0 )
xoff = 0;
}
if ( xoff!=gt->xoff_left ) {
gt->xoff_left = xoff;
if ( gt->hsb!=NULL )
GScrollBarSetPos(>->hsb->g,xoff);
refresh = true;
}
if ( loff!=gt->loff_top ) {
gt->loff_top = loff;
if ( gt->vsb!=NULL )
GScrollBarSetPos(>->vsb->g,loff);
refresh = true;
}
GTPositionGIC(gt);
return( refresh );
}
static void *genunicodedata(void *_gt,int32 *len) {
GTextField *gt = _gt;
unichar_t *temp;
*len = gt->sel_end-gt->sel_start + 1;
temp = malloc((*len+2)*sizeof(unichar_t));
temp[0] = 0xfeff; /* KDE expects a byte order flag */
u_strncpy(temp+1,gt->text+gt->sel_start,gt->sel_end-gt->sel_start);
temp[*len+1] = 0;
return( temp );
}
static void *genutf8data(void *_gt,int32 *len) {
GTextField *gt = _gt;
unichar_t *temp =u_copyn(gt->text+gt->sel_start,gt->sel_end-gt->sel_start);
char *ret = u2utf8_copy(temp);
free(temp);
*len = strlen(ret);
return( ret );
}
static void *ddgenunicodedata(void *_gt,int32 *len) {
void *temp = genunicodedata(_gt,len);
GTextField *gt = _gt;
_GTextFieldReplace(gt,nullstr);
_ggadget_redraw(>->g);
return( temp );
}
static void *genlocaldata(void *_gt,int32 *len) {
GTextField *gt = _gt;
unichar_t *temp =u_copyn(gt->text+gt->sel_start,gt->sel_end-gt->sel_start);
char *ret = u2def_copy(temp);
free(temp);
*len = strlen(ret);
return( ret );
}
static void *ddgenlocaldata(void *_gt,int32 *len) {
void *temp = genlocaldata(_gt,len);
GTextField *gt = _gt;
_GTextFieldReplace(gt,nullstr);
_ggadget_redraw(>->g);
return( temp );
}
static void noop(void *_gt) {
}
static void GTextFieldGrabPrimarySelection(GTextField *gt) {
int ss = gt->sel_start, se = gt->sel_end;
GDrawGrabSelection(gt->g.base,sn_primary);
gt->sel_start = ss; gt->sel_end = se;
GDrawAddSelectionType(gt->g.base,sn_primary,"text/plain;charset=ISO-10646-UCS-4",gt,gt->sel_end-gt->sel_start,
sizeof(unichar_t),
genunicodedata,noop);
GDrawAddSelectionType(gt->g.base,sn_primary,"UTF8_STRING",gt,gt->sel_end-gt->sel_start,
sizeof(char),
genutf8data,noop);
GDrawAddSelectionType(gt->g.base,sn_primary,"text/plain;charset=UTF-8",gt,gt->sel_end-gt->sel_start,
sizeof(char),
genutf8data,noop);
GDrawAddSelectionType(gt->g.base,sn_primary,"STRING",gt,gt->sel_end-gt->sel_start,
sizeof(char),
genlocaldata,noop);
}
static void GTextFieldGrabDDSelection(GTextField *gt) {
GDrawGrabSelection(gt->g.base,sn_drag_and_drop);
GDrawAddSelectionType(gt->g.base,sn_drag_and_drop,"text/plain;charset=ISO-10646-UCS-4",gt,gt->sel_end-gt->sel_start,
sizeof(unichar_t),
ddgenunicodedata,noop);
GDrawAddSelectionType(gt->g.base,sn_drag_and_drop,"STRING",gt,gt->sel_end-gt->sel_start,sizeof(char),
ddgenlocaldata,noop);
}
static void GTextFieldGrabSelection(GTextField *gt, enum selnames sel ) {
if ( gt->sel_start!=gt->sel_end ) {
unichar_t *temp;
char *ctemp, *ctemp2;
int i;
uint16 *u2temp;
GDrawGrabSelection(gt->g.base,sel);
temp = malloc((gt->sel_end-gt->sel_start + 2)*sizeof(unichar_t));
temp[0] = 0xfeff; /* KDE expects a byte order flag */
u_strncpy(temp+1,gt->text+gt->sel_start,gt->sel_end-gt->sel_start);
ctemp = u2utf8_copy(temp+1);
ctemp2 = u2def_copy(temp+1);
GDrawAddSelectionType(gt->g.base,sel,"text/plain;charset=ISO-10646-UCS-4",temp,u_strlen(temp),
sizeof(unichar_t),
NULL,NULL);
u2temp = malloc((gt->sel_end-gt->sel_start + 2)*sizeof(uint16));
for ( i=0; temp[i]!=0; ++i )
u2temp[i] = temp[i];
u2temp[i] = 0;
GDrawAddSelectionType(gt->g.base,sel,"text/plain;charset=ISO-10646-UCS-2",u2temp,u_strlen(temp),
2,
NULL,NULL);
GDrawAddSelectionType(gt->g.base,sel,"UTF8_STRING",copy(ctemp),strlen(ctemp),
sizeof(char),
NULL,NULL);
GDrawAddSelectionType(gt->g.base,sel,"text/plain;charset=UTF-8",ctemp,strlen(ctemp),
sizeof(char),
NULL,NULL);
if ( ctemp2!=NULL && *ctemp2!='\0' /*strlen(ctemp2)==gt->sel_end-gt->sel_start*/ )
GDrawAddSelectionType(gt->g.base,sel,"STRING",ctemp2,strlen(ctemp2),
sizeof(char),
NULL,NULL);
else
free(ctemp2);
}
}
static int GTextFieldSelBackword(unichar_t *text,int start) {
unichar_t ch = text[start-1];
if ( start==0 )
/* Can't go back */;
else if ( isalnum(ch) || ch=='_' ) {
int i;
for ( i=start-1; i>=0 && ((text[i]<0x10000 && isalnum(text[i])) || text[i]=='_') ; --i );
start = i+1;
} else {
int i;
for ( i=start-1; i>=0 && !(text[i]<0x10000 && isalnum(text[i])) && text[i]!='_' ; --i );
start = i+1;
}
return( start );
}
static int GTextFieldSelForeword(unichar_t *text,int end) {
unichar_t ch = text[end];
if ( ch=='\0' )
/* Nothing */;
else if ( isalnum(ch) || ch=='_' ) {
int i;
for ( i=end; (text[i]<0x10000 && isalnum(text[i])) || text[i]=='_' ; ++i );
end = i;
} else {
int i;
for ( i=end; !(text[i]<0x10000 && isalnum(text[i])) && text[i]!='_' && text[i]!='\0' ; ++i );
end = i;
}
return( end );
}
static void GTextFieldSelectWord(GTextField *gt,int mid, int16 *start, int16 *end) {
unichar_t *text;
unichar_t ch = gt->text[mid];
text = gt->text;
ch = text[mid];
if ( ch=='\0' )
*start = *end = mid;
else if ( (ch<0x10000 && isspace(ch)) ) {
int i;
for ( i=mid; text[i]<0x10000 && isspace(text[i]); ++i );
*end = i;
for ( i=mid-1; i>=0 && text[i]<0x10000 && isspace(text[i]) ; --i );
*start = i+1;
} else if ( (ch<0x10000 && isalnum(ch)) || ch=='_' ) {
int i;
for ( i=mid; (text[i]<0x10000 && isalnum(text[i])) || text[i]=='_' ; ++i );
*end = i;
for ( i=mid-1; i>=0 && ((text[i]<0x10000 && isalnum(text[i])) || text[i]=='_') ; --i );
*start = i+1;
} else {
int i;
for ( i=mid; !(text[i]<0x10000 && isalnum(text[i])) && text[i]!='_' && text[i]!='\0' ; ++i );
*end = i;
for ( i=mid-1; i>=0 && !(text[i]<0x10000 && isalnum(text[i])) && text[i]!='_' ; --i );
*start = i+1;
}
}
static void GTextFieldSelectWords(GTextField *gt,int last) {
int16 ss, se;
GTextFieldSelectWord(gt,gt->sel_base,>->sel_start,>->sel_end);
if ( last!=gt->sel_base ) {
GTextFieldSelectWord(gt,last,&ss,&se);
if ( ss<gt->sel_start ) gt->sel_start = ss;
if ( se>gt->sel_end ) gt->sel_end = se;
}
}
static void GTextFieldPaste(GTextField *gt,enum selnames sel) {
if ( GDrawSelectionHasType(gt->g.base,sel,"UTF8_STRING") ||
GDrawSelectionHasType(gt->g.base,sel,"text/plain;charset=UTF-8")) {
unichar_t *temp; char *ctemp;
int32 len;
ctemp = GDrawRequestSelection(gt->g.base,sel,"UTF8_STRING",&len);
if ( ctemp==NULL || len==0 )
ctemp = GDrawRequestSelection(gt->g.base,sel,"text/plain;charset=UTF-8",&len);
if ( ctemp!=NULL ) {
temp = utf82u_copyn(ctemp,strlen(ctemp));
GTextField_Replace(gt,temp);
free(ctemp); free(temp);
}
/* Bug in the xorg library on 64 bit machines and 32 bit transfers don't work */
/* so avoid them, by looking for utf8 first */
} else if ( GDrawSelectionHasType(gt->g.base,sel,"text/plain;charset=ISO-10646-UCS-4")) {
unichar_t *temp;
int32 len;
temp = GDrawRequestSelection(gt->g.base,sel,"text/plain;charset=ISO-10646-UCS-4",&len);
/* Bug! I don't handle byte reversed selections. But I don't think there should be any anyway... */
if ( temp!=NULL )
GTextField_Replace(gt,temp[0]==0xfeff?temp+1:temp);
free(temp);
} else if ( GDrawSelectionHasType(gt->g.base,sel,"Unicode") ||
GDrawSelectionHasType(gt->g.base,sel,"text/plain;charset=ISO-10646-UCS-2")) {
unichar_t *temp;
uint16 *temp2;
int32 len;
temp2 = GDrawRequestSelection(gt->g.base,sel,"text/plain;charset=ISO-10646-UCS-2",&len);
if ( temp2==NULL || len==0 )
temp2 = GDrawRequestSelection(gt->g.base,sel,"Unicode",&len);
if ( temp2!=NULL ) {
int i;
temp = malloc((len/2+1)*sizeof(unichar_t));
for ( i=0; temp2[i]!=0; ++i )
temp[i] = temp2[i];
temp[i] = 0;
GTextField_Replace(gt,temp[0]==0xfeff?temp+1:temp);
free(temp);
}
free(temp2);
} else if ( GDrawSelectionHasType(gt->g.base,sel,"STRING")) {
unichar_t *temp; char *ctemp;
int32 len;
ctemp = GDrawRequestSelection(gt->g.base,sel,"STRING",&len);
if ( ctemp==NULL || len==0 )
ctemp = GDrawRequestSelection(gt->g.base,sel,"text/plain;charset=UTF-8",&len);
if ( ctemp!=NULL ) {
temp = def2u_copy(ctemp);
GTextField_Replace(gt,temp);
free(ctemp); free(temp);
}
}
}
static int gtextfield_editcmd(GGadget *g,enum editor_commands cmd) {
GTextField *gt = (GTextField *) g;
switch ( cmd ) {
case ec_selectall:
gt->sel_start = 0;
gt->sel_end = u_strlen(gt->text);
return( true );
case ec_clear:
GTextField_Replace(gt,nullstr);
_ggadget_redraw(g);
return( true );
case ec_cut:
GTextFieldGrabSelection(gt,sn_clipboard);
GTextField_Replace(gt,nullstr);
_ggadget_redraw(g);
break;
case ec_copy:
GTextFieldGrabSelection(gt,sn_clipboard);
return( true );
case ec_paste:
GTextFieldPaste(gt,sn_clipboard);
GTextField_Show(gt,gt->sel_start);
_ggadget_redraw(g);
break;
case ec_undo:
if ( gt->oldtext!=NULL ) {
unichar_t *temp = gt->text;
int16 s;
gt->text = gt->oldtext; gt->oldtext = temp;
s = gt->sel_start; gt->sel_start = gt->sel_oldstart; gt->sel_oldstart = s;
s = gt->sel_end; gt->sel_end = gt->sel_oldend; gt->sel_oldend = s;
s = gt->sel_base; gt->sel_base = gt->sel_oldbase; gt->sel_oldbase = s;
GTextFieldRefigureLines(gt, 0);
GTextField_Show(gt,gt->sel_end);
_ggadget_redraw(g);
}
break;
case ec_redo: /* Hmm. not sure */ /* we don't do anything */
return( true ); /* but probably best to return success */
case ec_backword:
if ( gt->sel_start==gt->sel_end && gt->sel_start!=0 ) {
gt->sel_start = GTextFieldSelBackword(gt->text,gt->sel_start);
}
GTextField_Replace(gt,nullstr);
_ggadget_redraw(g);
break;
case ec_deleteword:
if ( gt->sel_start==gt->sel_end && gt->sel_start!=0 )
GTextFieldSelectWord(gt,gt->sel_start,>->sel_start,>->sel_end);
GTextField_Replace(gt,nullstr);
_ggadget_redraw(g);
break;
default:
return( false );
}
GTextFieldChanged(gt,-1);
return( true );
}
static int _gtextfield_editcmd(GGadget *g,enum editor_commands cmd) {
if ( gtextfield_editcmd(g,cmd)) {
_ggadget_redraw(g);
GTPositionGIC((GTextField *) g);
return( true );
}
return( false );
}
static int GTBackPos(GTextField *gt,int pos, int ismeta) {
int newpos;
if ( ismeta )
newpos = GTextFieldSelBackword(gt->text,pos);
else
newpos = pos-1;
if ( newpos==-1 ) newpos = pos;
return( newpos );
}
static int GTForePos(GTextField *gt,int pos, int ismeta) {
int newpos=pos;
if ( ismeta )
newpos = GTextFieldSelForeword(gt->text,pos);
else {
if ( gt->text[pos]!=0 )
newpos = pos+1;
}
return( newpos );
}
unichar_t *_GGadgetFileToUString(char *filename,int max) {
FILE *file;
int ch, ch2, ch3;
int format=0;
unichar_t *space, *upt, *end;
file = fopen( filename,"r" );
if ( file==NULL )
return( NULL );
ch = getc(file); ch2 = getc(file); ch3 = getc(file);
ungetc(ch3,file);
if ( ch==0xfe && ch2==0xff )
format = 1; /* normal ucs2 */
else if ( ch==0xff && ch2==0xfe )
format = 2; /* byte-swapped ucs2 */
else if ( ch==0xef && ch2==0xbb && ch3==0xbf ) {
format = 3; /* utf8 */
getc(file);
} else {
getc(file); /* rewind probably undoes the ungetc, but let's not depend on it */
rewind(file);
}
space = upt = malloc((max+1)*sizeof(unichar_t));
end = space+max;
if ( format==3 ) { /* utf8 */
while ( upt<end ) {
ch=getc(file);
if ( ch==EOF )
break;
if ( ch<0x80 )
*upt++ = ch;
else if ( ch<0xe0 ) {
ch2 = getc(file);
*upt++ = ((ch&0x1f)<<6)|(ch2&0x3f);
} else if ( ch<0xf0 ) {
ch2 = getc(file); ch3 = getc(file);
*upt++ = ((ch&0xf)<<12)|((ch2&0x3f)<<6)|(ch3&0x3f);
} else {
int ch4, w;
ch2 = getc(file); ch3 = getc(file); ch4=getc(file);
w = ( ((ch&7)<<2) | ((ch2&0x30)>>4) ) -1;
*upt++ = 0xd800 | (w<<6) | ((ch2&0xf)<<2) | ((ch3&0x30)>>4);
if ( upt<end )
*upt++ = 0xdc00 | ((ch3&0xf)<<6) | (ch4&0x3f);
}
}
} else if ( format!=0 ) {
while ( upt<end ) {
ch = getc(file); ch2 = getc(file);
if ( ch2==EOF )
break;
if ( format==1 )
*upt ++ = (ch<<8)|ch2;
else
*upt ++ = (ch2<<8)|ch;
}
} else {
char buffer[400];
while ( fgets(buffer,sizeof(buffer),file)!=NULL ) {
def2u_strncpy(upt,buffer,end-upt);
upt += u_strlen(upt);
}
}
*upt = '\0';
fclose(file);
return( space );
}
static unichar_t txt[] = { '*','.','{','t','x','t',',','p','y','}', '\0' };
static unichar_t errort[] = { 'C','o','u','l','d',' ','n','o','t',' ','o','p','e','n', '\0' };
static unichar_t error[] = { 'C','o','u','l','d',' ','n','o','t',' ','o','p','e','n',' ','%','.','1','0','0','h','s', '\0' };
bool GTextFieldIsEmpty(GGadget *g) {
GTextField *gt = (GTextField *) g;
return gt->text == NULL || *gt->text == '\0';
}
static void GTextFieldImport(GTextField *gt) {
unichar_t *ret;
char *cret;
unichar_t *str;
if ( _ggadget_use_gettext ) {
char *temp = GWidgetOpenFile8(_("Open"),NULL,"*.{txt,py}",NULL,NULL);
ret = utf82u_copy(temp);
free(temp);
} else {
ret = GWidgetOpenFile(GStringGetResource(_STR_Open,NULL),NULL,
txt,NULL,NULL);
}
if ( ret==NULL )
return;
cret = u2def_copy(ret);
free(ret);
str = _GGadgetFileToUString(cret,65536);
if ( str==NULL ) {
if ( _ggadget_use_gettext )
GWidgetError8(_("Could not open file"), _("Could not open %.100s"),cret);
else
GWidgetError(errort,error,cret);
free(cret);
return;
}
free(cret);
GTextField_Replace(gt,str);
free(str);
}
static void GTextFieldSave(GTextField *gt,int utf8) {
unichar_t *ret;
char *cret;
FILE *file;
unichar_t *pt;
if ( _ggadget_use_gettext ) {
char *temp = GWidgetOpenFile8(_("Save"),NULL,"*.{txt,py}",NULL,NULL);
ret = utf82u_copy(temp);
free(temp);
} else
ret = GWidgetSaveAsFile(GStringGetResource(_STR_Save,NULL),NULL,
txt,NULL,NULL);
if ( ret==NULL )
return;
cret = u2def_copy(ret);
free(ret);
file = fopen(cret,"w");
if ( file==NULL ) {
if ( _ggadget_use_gettext )
GWidgetError8(_("Could not open file"), _("Could not open %.100s"),cret);
else
GWidgetError(errort,error,cret);
free(cret);
return;
}
free(cret);
if ( utf8 ) {
putc(0xef,file); /* Zero width something or other. Marks this as unicode, utf8 */
putc(0xbb,file);
putc(0xbf,file);
for ( pt = gt->text ; *pt; ++pt ) {
if ( *pt<0x80 )
putc(*pt,file);
else if ( *pt<0x800 ) {
putc(0xc0 | (*pt>>6), file);
putc(0x80 | (*pt&0x3f), file);
} else if ( *pt>=0xd800 && *pt<0xdc00 && pt[1]>=0xdc00 && pt[1]<0xe000 ) {
int u = ((*pt>>6)&0xf)+1, y = ((*pt&3)<<4) | ((pt[1]>>6)&0xf);
putc( 0xf0 | (u>>2),file );
putc( 0x80 | ((u&3)<<4) | ((*pt>>2)&0xf),file );
putc( 0x80 | y,file );
putc( 0x80 | (pt[1]&0x3f),file );
} else {
putc( 0xe0 | (*pt>>12),file );
putc( 0x80 | ((*pt>>6)&0x3f),file );
putc( 0x80 | (*pt&0x3f),file );
}
}
} else {
putc(0xfeff>>8,file); /* Zero width something or other. Marks this as unicode */
putc(0xfeff&0xff,file);
for ( pt = gt->text ; *pt; ++pt ) {
putc(*pt>>8,file);
putc(*pt&0xff,file);
}
}
fclose(file);
GTextFieldSaved(gt);
}
#define MID_Cut 1
#define MID_Copy 2
#define MID_Paste 3
#define MID_SelectAll 4
#define MID_Save 5
#define MID_SaveUCS2 6
#define MID_Import 7
#define MID_Undo 8
static GTextField *popup_kludge;
static void GTFPopupInvoked(GWindow v, GMenuItem *mi,GEvent *e) {
GTextField *gt;
if ( popup_kludge==NULL )
return;
gt = popup_kludge;
popup_kludge = NULL;
switch ( mi->mid ) {
case MID_Undo:
gtextfield_editcmd(>->g,ec_undo);
break;
case MID_Cut:
gtextfield_editcmd(>->g,ec_cut);
break;
case MID_Copy:
gtextfield_editcmd(>->g,ec_copy);
break;
case MID_Paste:
gtextfield_editcmd(>->g,ec_paste);
break;
case MID_SelectAll:
gtextfield_editcmd(>->g,ec_selectall);
break;
case MID_Save:
GTextFieldSave(gt,true);
break;
case MID_SaveUCS2:
GTextFieldSave(gt,false);
break;
case MID_Import:
GTextFieldImport(gt);
break;
}
_ggadget_redraw(>->g);
}
static GMenuItem gtf_popuplist[] = {
{ { (unichar_t *) "_Undo", NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 1, 0, '\0' }, 'Z', ksm_control, NULL, NULL, GTFPopupInvoked, MID_Undo },
{ { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 1, 0, 0, 0, '\0' }, '\0', 0, NULL, NULL, NULL, 0 }, /* line */
{ { (unichar_t *) "Cu_t", NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 1, 0, '\0' }, 'X', ksm_control, NULL, NULL, GTFPopupInvoked, MID_Cut },
{ { (unichar_t *) "_Copy", NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 1, 0, '\0' }, 'C', ksm_control, NULL, NULL, GTFPopupInvoked, MID_Copy },
{ { (unichar_t *) "_Paste", NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 1, 0, '\0' }, 'V', ksm_control, NULL, NULL, GTFPopupInvoked, MID_Paste },
{ { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 1, 0, 0, 0, '\0' }, '\0', 0, NULL, NULL, NULL, 0 }, /* line */
{ { (unichar_t *) "_Save in UTF8", NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 1, 0, '\0' }, 'S', ksm_control, NULL, NULL, GTFPopupInvoked, MID_Save },
{ { (unichar_t *) "Save in _UCS2", NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 1, 0, '\0' }, '\0', ksm_control, NULL, NULL, GTFPopupInvoked, MID_SaveUCS2 },
{ { (unichar_t *) "_Import", NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 1, 0, '\0' }, 'I', ksm_control, NULL, NULL, GTFPopupInvoked, MID_Import },
GMENUITEM_EMPTY
};
static int first = true;
static void GTFPopupMenu(GTextField *gt, GEvent *event) {
int no_sel = gt->sel_start==gt->sel_end;
if ( first ) {
gtf_popuplist[0].ti.text = (unichar_t *) _("_Undo");
gtf_popuplist[2].ti.text = (unichar_t *) _("Cu_t");
gtf_popuplist[3].ti.text = (unichar_t *) _("_Copy");
gtf_popuplist[4].ti.text = (unichar_t *) _("_Paste");
gtf_popuplist[6].ti.text = (unichar_t *) _("_Save in UTF8");
gtf_popuplist[7].ti.text = (unichar_t *) _("Save in _UCS2");
gtf_popuplist[8].ti.text = (unichar_t *) _("_Import");
first = false;
}
gtf_popuplist[0].ti.disabled = gt->oldtext==NULL; /* Undo */
gtf_popuplist[2].ti.disabled = no_sel; /* Cut */
gtf_popuplist[3].ti.disabled = no_sel; /* Copy */
gtf_popuplist[4].ti.disabled = !GDrawSelectionHasType(gt->g.base,sn_clipboard,"text/plain;charset=ISO-10646-UCS-2") &&
!GDrawSelectionHasType(gt->g.base,sn_clipboard,"UTF8_STRING") &&
!GDrawSelectionHasType(gt->g.base,sn_clipboard,"STRING");
popup_kludge = gt;
GMenuCreatePopupMenu(gt->g.base,event, gtf_popuplist);
}
static void GTextFieldIncrement(GTextField *gt,int amount) {
unichar_t *end;
double d = u_strtod(gt->text,&end);
char buf[40];
while ( *end==' ' ) ++end;
if ( *end!='\0' ) {
GDrawBeep(NULL);
return;
}
d = floor(d)+amount;
sprintf(buf,"%g", d);
free(gt->oldtext);
gt->oldtext = gt->text;
gt->text = uc_copy(buf);
free(gt->utf8_text);
gt->utf8_text = copy(buf);
_ggadget_redraw(>->g);
GTextFieldChanged(gt,-1);
}
static int GTextFieldDoChange(GTextField *gt, GEvent *event) {
int ss = gt->sel_start, se = gt->sel_end;
int pos, l, xpos, sel;
unichar_t *upt;
if ( ( event->u.chr.state&(GMenuMask()&~ksm_shift)) ||
event->u.chr.chars[0]<' ' || event->u.chr.chars[0]==0x7f ) {
switch ( event->u.chr.keysym ) {
case GK_BackSpace:
if ( gt->sel_start==gt->sel_end ) {
if ( gt->sel_start==0 )
return( 2 );
--gt->sel_start;
}
GTextField_Replace(gt,nullstr);
return( true );
break;
case GK_Delete:
if ( gt->sel_start==gt->sel_end ) {
if ( gt->text[gt->sel_start]==0 )
return( 2 );
++gt->sel_end;
}
GTextField_Replace(gt,nullstr);
return( true );
break;
case GK_Left: case GK_KP_Left:
if ( gt->sel_start==gt->sel_end ) {
gt->sel_start = GTBackPos(gt,gt->sel_start,event->u.chr.state&ksm_meta);
if ( !(event->u.chr.state&ksm_shift ))
gt->sel_end = gt->sel_start;
} else if ( event->u.chr.state&ksm_shift ) {
if ( gt->sel_end==gt->sel_base ) {
gt->sel_start = GTBackPos(gt,gt->sel_start,event->u.chr.state&ksm_meta);
} else {
gt->sel_end = GTBackPos(gt,gt->sel_end,event->u.chr.state&ksm_meta);
}
} else {
gt->sel_end = gt->sel_base = gt->sel_start;
}
GTextField_Show(gt,gt->sel_start);
return( 2 );
break;
case GK_Right: case GK_KP_Right:
if ( gt->sel_start==gt->sel_end ) {
gt->sel_end = GTForePos(gt,gt->sel_start,event->u.chr.state&ksm_meta);
if ( !(event->u.chr.state&ksm_shift ))
gt->sel_start = gt->sel_end;
} else if ( event->u.chr.state&ksm_shift ) {
if ( gt->sel_end==gt->sel_base ) {
gt->sel_start = GTForePos(gt,gt->sel_start,event->u.chr.state&ksm_meta);
} else {
gt->sel_end = GTForePos(gt,gt->sel_end,event->u.chr.state&ksm_meta);
}
} else {
gt->sel_start = gt->sel_base = gt->sel_end;
}
GTextField_Show(gt,gt->sel_start);
return( 2 );
break;
case GK_Up: case GK_KP_Up:
if ( gt->numericfield ) {
GTextFieldIncrement(gt,(event->u.chr.state&(ksm_shift|ksm_control))?10:1);
return( 2 );
}
if ( !gt->multi_line )
break;
if ( !( event->u.chr.state&ksm_shift ) && gt->sel_start!=gt->sel_end )
gt->sel_end = gt->sel_base = gt->sel_start;
else {
pos = gt->sel_start;
if ( ( event->u.chr.state&ksm_shift ) && gt->sel_start==gt->sel_base )
pos = gt->sel_end;
l = GTextFieldFindLine(gt,gt->sel_start);
GRect pos_rect;
int ll = gt->lines8[l+1]==-1 ? -1 : gt->lines8[l+1]-gt->lines8[l];
sel = u2utf8_index(gt->sel_start-gt->lines[l],gt->utf8_text+gt->lines8[l]);
GDrawLayoutInit(gt->g.base,gt->utf8_text+gt->lines8[l],ll,NULL);
GDrawLayoutIndexToPos(gt->g.base,sel,&pos_rect);
xpos = pos_rect.x;
if ( l!=0 ) {
GDrawLayoutInit(gt->g.base,gt->utf8_text+gt->lines8[l-1],gt->lines8[l]-gt->lines8[l-1],NULL);
pos = GDrawLayoutXYToIndex(gt->g.base,xpos,0);
pos = utf82u_index(pos+gt->lines8[l-1],gt->utf8_text);
}
if ( event->u.chr.state&ksm_shift ) {
if ( pos<gt->sel_base ) {
gt->sel_start = pos;
gt->sel_end = gt->sel_base;
} else {
gt->sel_start = gt->sel_base;
gt->sel_end = pos;
}
} else {
gt->sel_start = gt->sel_end = gt->sel_base = pos;
}
}
GTextField_Show(gt,gt->sel_start);
return( 2 );
break;
case GK_Down: case GK_KP_Down:
if ( gt->numericfield ) {
GTextFieldIncrement(gt,(event->u.chr.state&(ksm_shift|ksm_control))?-10:-1);
return( 2 );
}
if ( !gt->multi_line )
break;
if ( !( event->u.chr.state&ksm_shift ) && gt->sel_start!=gt->sel_end )
gt->sel_end = gt->sel_base = gt->sel_end;
else {
pos = gt->sel_start;
if ( ( event->u.chr.state&ksm_shift ) && gt->sel_start==gt->sel_base )
pos = gt->sel_end;
l = GTextFieldFindLine(gt,gt->sel_start);
GRect pos_rect;
int ll = gt->lines8[l+1]==-1 ? -1 : gt->lines8[l+1]-gt->lines8[l];
sel = u2utf8_index(gt->sel_start-gt->lines[l],gt->utf8_text+gt->lines8[l]);
GDrawLayoutInit(gt->g.base,gt->utf8_text+gt->lines8[l],ll,NULL);
GDrawLayoutIndexToPos(gt->g.base,sel,&pos_rect);
xpos = pos_rect.x;
if ( l<gt->lcnt-1 ) {
ll = gt->lines8[l+2]==-1 ? -1 : gt->lines8[l+2]-gt->lines8[l+1];
GDrawLayoutInit(gt->g.base,gt->utf8_text+gt->lines8[l+1],ll,NULL);
pos = GDrawLayoutXYToIndex(gt->g.base,xpos,0);
pos = utf82u_index(pos+gt->lines8[l+1],gt->utf8_text);
}
if ( event->u.chr.state&ksm_shift ) {
if ( pos<gt->sel_base ) {
gt->sel_start = pos;
gt->sel_end = gt->sel_base;
} else {
gt->sel_start = gt->sel_base;
gt->sel_end = pos;
}
} else {
gt->sel_start = gt->sel_end = gt->sel_base = pos;
}
}
GTextField_Show(gt,gt->sel_start);
return( 2 );
break;
case GK_Home: case GK_Begin: case GK_KP_Home: case GK_KP_Begin:
if ( !(event->u.chr.state&ksm_shift) ) {
gt->sel_start = gt->sel_base = gt->sel_end = 0;
} else {
gt->sel_start = 0; gt->sel_end = gt->sel_base;
}
GTextField_Show(gt,gt->sel_start);
return( 2 );
break;
/* Move to eol. (if already at eol, move to next eol) */
case 'E': case 'e':
if ( !( event->u.chr.state&ksm_control ) )
return( false );
upt = gt->text+gt->sel_base;
if ( *upt=='\n' )
++upt;
upt = u_strchr(upt,'\n');
if ( upt==NULL ) upt=gt->text+u_strlen(gt->text);
if ( !(event->u.chr.state&ksm_shift) ) {
gt->sel_start = gt->sel_base = gt->sel_end =upt-gt->text;
} else {
gt->sel_start = gt->sel_base; gt->sel_end = upt-gt->text;
}
GTextField_Show(gt,gt->sel_start);
return( 2 );
break;
case GK_End: case GK_KP_End:
if ( !(event->u.chr.state&ksm_shift) ) {
gt->sel_start = gt->sel_base = gt->sel_end = u_strlen(gt->text);
} else {
gt->sel_start = gt->sel_base; gt->sel_end = u_strlen(gt->text);
}
GTextField_Show(gt,gt->sel_start);
return( 2 );
break;
case 'D': case 'd':
if ( event->u.chr.state&ksm_control ) { /* delete word */
gtextfield_editcmd(>->g,ec_deleteword);
GTextField_Show(gt,gt->sel_start);
return( true );
}
break;
case 'W': case 'w':
if ( event->u.chr.state&ksm_control ) { /* backword */
gtextfield_editcmd(>->g,ec_backword);
GTextField_Show(gt,gt->sel_start);
return( true );
}
break;
case 'M': case 'm': case 'J': case 'j':
if ( !( event->u.chr.state&ksm_control ) )
return( false );
/* fall through into return case */
case GK_Return: case GK_Linefeed:
if ( gt->accepts_returns ) {
GTextField_Replace(gt,newlinestr);
return( true );
}
break;
case GK_Tab:
if ( gt->completionfield && ((GCompletionField *) gt)->completion!=NULL ) {
GTextFieldComplete(gt,true);
gt->was_completing = true;
return( 3 );
}
if ( gt->accepts_tabs ) {
GTextField_Replace(gt,tabstr);
return( true );
}
break;
default:
if ( GMenuIsCommand(event,H_("Select All|Ctl+A")) ) {
gtextfield_editcmd(>->g,ec_selectall);
return( 2 );
} else if ( GMenuIsCommand(event,H_("Copy|Ctl+C")) ) {
gtextfield_editcmd(>->g,ec_copy);
} else if ( GMenuIsCommand(event,H_("Paste|Ctl+V")) ) {
gtextfield_editcmd(>->g,ec_paste);
GTextField_Show(gt,gt->sel_start);
return( true );
} else if ( GMenuIsCommand(event,H_("Cut|Ctl+X")) ) {
gtextfield_editcmd(>->g,ec_cut);
GTextField_Show(gt,gt->sel_start);
return( true );
} else if ( GMenuIsCommand(event,H_("Undo|Ctl+Z")) ) {
gtextfield_editcmd(>->g,ec_undo);
GTextField_Show(gt,gt->sel_start);
return( true );
} else if ( GMenuIsCommand(event,H_("Save|Ctl+S")) ) {
GTextFieldSave(gt,true);
return( 2 );
} else if ( GMenuIsCommand(event,H_("Import...|Ctl+Shft+I")) ) {
GTextFieldImport(gt);
return( true );
} else
return( false );
break;
}
} else {
GTextField_Replace(gt,event->u.chr.chars);
return( 4 /* Do name completion */ );
}
if ( gt->sel_start == gt->sel_end )
gt->sel_base = gt->sel_start;
if ( ss!=gt->sel_start || se!=gt->sel_end )
GTextFieldGrabPrimarySelection(gt);
return( false );
}
static void _gt_cursor_pos(GTextField *gt, int sel_start, int *x, int *y) {
int l, sel;
*x = -1; *y= -1;
GDrawSetFont(gt->g.base,gt->font);
l = GTextFieldFindLine(gt,sel_start);
if ( l<gt->loff_top || l>=gt->loff_top + ((gt->g.inner.height+gt->fh/2)/gt->fh))
return;
*y = (l-gt->loff_top)*gt->fh;
GRect pos_rect;
int ll = gt->lines8[l+1]==-1 ? -1 : gt->lines8[l+1]-gt->lines8[l];
sel = u2utf8_index(sel_start-gt->lines[l],gt->utf8_text+gt->lines8[l]);
GDrawLayoutInit(gt->g.base,gt->utf8_text+gt->lines8[l],ll,NULL);
GDrawLayoutIndexToPos(gt->g.base,sel,&pos_rect);
*x = pos_rect.x - gt->xoff_left;
}
static void gt_cursor_pos(GTextField *gt, int *x, int *y) {
_gt_cursor_pos(gt,gt->sel_start,x,y);
}
static void GTPositionGIC(GTextField *gt) {
int x,y;
if ( !gt->g.has_focus || gt->gic==NULL )
return;
gt_cursor_pos(gt,&x,&y);
if ( x<0 )
return;
GDrawSetGIC(gt->g.base,gt->gic,gt->g.inner.x+x,gt->g.inner.y+y+gt->as);
}
static void gt_draw_cursor(GWindow pixmap, GTextField *gt) {
GRect old;
int x, y;
if ( !gt->cursor_on || gt->sel_start != gt->sel_end )
return;
gt_cursor_pos(gt,&x,&y);
if ( x<0 || x>=gt->g.inner.width )
return;
GDrawPushClip(pixmap,>->g.inner,&old);
GDrawSetDifferenceMode(pixmap);
GDrawSetFont(pixmap,gt->font);
GDrawSetLineWidth(pixmap,0);
GDrawDrawLine(pixmap,gt->g.inner.x+x,gt->g.inner.y+y,
gt->g.inner.x+x,gt->g.inner.y+y+gt->fh,
COLOR_WHITE);
GDrawPopClip(pixmap,&old);
}
static void GTextFieldDrawDDCursor(GTextField *gt, int pos) {
GRect old;
int x, y, l;
l = GTextFieldFindLine(gt,pos);
if ( l<gt->loff_top || l>=gt->loff_top + (gt->g.inner.height/gt->fh))
return;
_gt_cursor_pos(gt,pos,&x,&y);
if ( x<0 || x>=gt->g.inner.width )
return;
GDrawPushClip(gt->g.base,>->g.inner,&old);
GDrawSetDifferenceMode(gt->g.base);
GDrawSetFont(gt->g.base,gt->font);
GDrawSetLineWidth(gt->g.base,0);
GDrawSetDashedLine(gt->g.base,2,2,0);
GDrawDrawLine(gt->g.base,gt->g.inner.x+x,gt->g.inner.y+y,
gt->g.inner.x+x,gt->g.inner.y+y+gt->fh,
COLOR_WHITE);
GDrawPopClip(gt->g.base,&old);
GDrawSetDashedLine(gt->g.base,0,0,0);
gt->has_dd_cursor = !gt->has_dd_cursor;
gt->dd_cursor_pos = pos;
}
static void GTextFieldDrawLineSel(GWindow pixmap, GTextField *gt, int line ) {
GRect selr, sofar, nextch;
int s,e, y,llen,i,j;
/* Caller has checked to make sure selection applies to this line */
y = gt->g.inner.y+(line-gt->loff_top)*gt->fh;
selr = gt->g.inner; selr.y = y; selr.height = gt->fh;
if ( !gt->g.has_focus ) --selr.height;
llen = gt->lines[line+1]==-1?
u_strlen(gt->text+gt->lines[line])+gt->lines[line]:
gt->lines[line+1];
s = gt->sel_start<gt->lines[line]?gt->lines[line]:gt->sel_start;
e = gt->sel_end>gt->lines[line+1] && gt->lines[line+1]!=-1?gt->lines[line+1]-1:
gt->sel_end;
s = u2utf8_index(s-gt->lines[line],gt->utf8_text+gt->lines8[line]);
e = u2utf8_index(e-gt->lines[line],gt->utf8_text+gt->lines8[line]);
llen = gt->lines8[line+1]==-1? -1 : gt->lines8[line+1]-gt->lines8[line];
GDrawLayoutInit(pixmap,gt->utf8_text+gt->lines8[line],llen,NULL);
for ( i=s; i<e; ) {
GDrawLayoutIndexToPos(pixmap,i,&sofar);
for ( j=i+1; j<e; ++j ) {
GDrawLayoutIndexToPos(pixmap,j,&nextch);
if ( nextch.x != sofar.x+sofar.width )
break;
sofar.width += nextch.width;
}
if ( sofar.width<0 ) {
selr.x = sofar.x+sofar.width + gt->g.inner.x - gt->xoff_left;
selr.width = -sofar.width;
} else {
selr.x = sofar.x + gt->g.inner.x - gt->xoff_left;
selr.width = sofar.width;
}
GDrawFillRect(pixmap,&selr,gt->g.box->active_border);
i = j;
}
}
static void GTextFieldDrawLine(GWindow pixmap, GTextField *gt, int line, Color fg ) {
int y = gt->g.inner.y+(line-gt->loff_top)*gt->fh;
int ll = gt->lines[line+1]==-1 ? -1 : gt->lines[line+1]-gt->lines[line];
ll = gt->lines8[line+1]==-1? -1 : gt->lines8[line+1]-gt->lines8[line];
GDrawLayoutInit(pixmap,gt->utf8_text+gt->lines8[line],ll,NULL);
GDrawLayoutDraw(pixmap,gt->g.inner.x-gt->xoff_left,y+gt->as,fg);
}
static int gtextfield_expose(GWindow pixmap, GGadget *g, GEvent *event) {
GTextField *gt = (GTextField *) g;
GListField *ge = (GListField *) g;
GRect old1, old2, *r = &g->r;
Color fg;
int ll,i, last;
GRect unpadded_inner;
int pad;
if ( g->state == gs_invisible || gt->dontdraw )
return( false );
if ( gt->listfield || gt->numericfield ) r = &ge->fieldrect;
GDrawPushClip(pixmap,r,&old1);
GBoxDrawBackground(pixmap,r,g->box,
g->state==gs_enabled? gs_pressedactive: g->state,false);
GBoxDrawBorder(pixmap,r,g->box,g->state,false);
unpadded_inner = g->inner;
pad = GDrawPointsToPixels(g->base,g->box->padding);
unpadded_inner.x -= pad; unpadded_inner.y -= pad;
unpadded_inner.width += 2*pad; unpadded_inner.height += 2*pad;
GDrawPushClip(pixmap,&unpadded_inner,&old2);
GDrawSetFont(pixmap,gt->font);
fg = g->state==gs_disabled?g->box->disabled_foreground:
g->box->main_foreground==COLOR_DEFAULT?GDrawGetDefaultForeground(GDrawGetDisplayOfWindow(pixmap)):
g->box->main_foreground;
ll = 0;
if ( (last = gt->g.inner.height/gt->fh)==0 ) last = 1;
if ( gt->sel_start != gt->sel_end ) {
/* I used to have support for drawing on a bw display where the */
/* selection and the foreground color were the same (black) and */
/* selected text was white. No longer. */
/* Draw the entire selection first, then the text itself */
for ( i=gt->loff_top; i<gt->loff_top+last && gt->lines[i]!=-1; ++i ) {
if ( gt->sel_end>gt->lines[i] &&
(gt->lines[i+1]==-1 || gt->sel_start<gt->lines[i+1]))
GTextFieldDrawLineSel(pixmap,gt,i);
}
}
for ( i=gt->loff_top; i<gt->loff_top+last && gt->lines[i]!=-1; ++i )
GTextFieldDrawLine(pixmap,gt,i,fg);
GDrawPopClip(pixmap,&old2);
GDrawPopClip(pixmap,&old1);
gt_draw_cursor(pixmap, gt);
if ( gt->listfield ) {
int marklen = GDrawPointsToPixels(pixmap,_GListMarkSize);
GDrawPushClip(pixmap,&ge->buttonrect,&old1);
GBoxDrawBackground(pixmap,&ge->buttonrect,&glistfieldmenu_box,
g->state==gs_enabled? gs_pressedactive: g->state,false);
GBoxDrawBorder(pixmap,&ge->buttonrect,&glistfieldmenu_box,g->state,false);
GListMarkDraw(pixmap,
ge->buttonrect.x + (ge->buttonrect.width - marklen)/2,
g->inner.y,
g->inner.height,
g->state);
GDrawPopClip(pixmap,&old1);
} else if ( gt->numericfield ) {
int y, w;
int half;
GPoint pts[5];
int bp = GBoxBorderWidth(gt->g.base,&gnumericfieldspinner_box);
Color fg = g->state==gs_disabled?gnumericfieldspinner_box.disabled_foreground:
gnumericfieldspinner_box.main_foreground==COLOR_DEFAULT?GDrawGetDefaultForeground(GDrawGetDisplayOfWindow(pixmap)):
gnumericfieldspinner_box.main_foreground;
GBoxDrawBackground(pixmap,&ge->buttonrect,&gnumericfieldspinner_box,
g->state==gs_enabled? gs_pressedactive: g->state,false);
GBoxDrawBorder(pixmap,&ge->buttonrect,&gnumericfieldspinner_box,g->state,false);
/* GDrawDrawRect(pixmap,&ge->buttonrect,fg); */
y = ge->buttonrect.y + ge->buttonrect.height/2;
w = ge->buttonrect.width;
w &= ~1;
pts[0].x = ge->buttonrect.x+3+bp;
pts[1].x = ge->buttonrect.x+w-3-bp;
pts[2].x = ge->buttonrect.x + w/2;
half = pts[2].x-pts[0].x;
GDrawDrawLine(pixmap, pts[0].x-3,y, pts[1].x+3,y, fg );
pts[0].y = pts[1].y = y-2;
pts[2].y = pts[1].y-half;
pts[3] = pts[0];
GDrawFillPoly(pixmap,pts,3,fg);
pts[0].y = pts[1].y = y+2;
pts[2].y = pts[1].y+half;
pts[3] = pts[0];
GDrawFillPoly(pixmap,pts,3,fg);
}
return( true );
}
static int glistfield_mouse(GListField *ge, GEvent *event) {
if ( event->type!=et_mousedown )
return( true );
if ( ge->popup != NULL ) {
GDrawDestroyWindow(ge->popup);
ge->popup = NULL;
return( true );
}
ge->popup = GListPopupCreate(&ge->gt.g,GListFieldSelected,ge->ti);
return( true );
}
static int gnumericfield_mouse(GTextField *gt, GEvent *event) {
GListField *ge = (GListField *) gt;
if ( event->type==et_mousedown ) {
gt->incr_down = event->u.mouse.y > (ge->buttonrect.y + ge->buttonrect.height/2);
GTextFieldIncrement(gt,gt->incr_down?-1:1);
if ( gt->numeric_scroll==NULL )
gt->numeric_scroll = GDrawRequestTimer(gt->g.base,200,100,NULL);
} else if ( gt->numeric_scroll!=NULL ) {
GDrawCancelTimer(gt->numeric_scroll);
gt->numeric_scroll = NULL;
}
return( true );
}
static int GTextFieldDoDrop(GTextField *gt,GEvent *event,int endpos) {
if ( gt->has_dd_cursor )
GTextFieldDrawDDCursor(gt,gt->dd_cursor_pos);
if ( event->type == et_mousemove ) {
if ( GGadgetInnerWithin(>->g,event->u.mouse.x,event->u.mouse.y) ) {
if ( endpos<gt->sel_start || endpos>=gt->sel_end )
GTextFieldDrawDDCursor(gt,endpos);
} else if ( !GGadgetWithin(>->g,event->u.mouse.x,event->u.mouse.y) ) {
GDrawPostDragEvent(gt->g.base,event,et_drag);
}
} else {
if ( GGadgetInnerWithin(>->g,event->u.mouse.x,event->u.mouse.y) ) {
if ( endpos>=gt->sel_start && endpos<gt->sel_end ) {
gt->sel_start = gt->sel_end = endpos;
} else {
unichar_t *old=gt->oldtext, *temp;
int pos=0;
if ( event->u.mouse.state&ksm_control ) {
temp = malloc((u_strlen(gt->text)+gt->sel_end-gt->sel_start+1)*sizeof(unichar_t));
memcpy(temp,gt->text,endpos*sizeof(unichar_t));
memcpy(temp+endpos,gt->text+gt->sel_start,
(gt->sel_end-gt->sel_start)*sizeof(unichar_t));
u_strcpy(temp+endpos+gt->sel_end-gt->sel_start,gt->text+endpos);
} else if ( endpos>=gt->sel_end ) {
temp = u_copy(gt->text);
memcpy(temp+gt->sel_start,temp+gt->sel_end,
(endpos-gt->sel_end)*sizeof(unichar_t));
memcpy(temp+endpos-(gt->sel_end-gt->sel_start),
gt->text+gt->sel_start,(gt->sel_end-gt->sel_start)*sizeof(unichar_t));
pos = endpos;
} else /*if ( endpos<gt->sel_start )*/ {
temp = u_copy(gt->text);
memcpy(temp+endpos,gt->text+gt->sel_start,
(gt->sel_end-gt->sel_start)*sizeof(unichar_t));
memcpy(temp+endpos+gt->sel_end-gt->sel_start,gt->text+endpos,
(gt->sel_start-endpos)*sizeof(unichar_t));
pos = endpos+gt->sel_end-gt->sel_start;
}
gt->oldtext = gt->text;
gt->sel_oldstart = gt->sel_start;
gt->sel_oldend = gt->sel_end;
gt->sel_oldbase = gt->sel_base;
gt->sel_start = gt->sel_end = pos;
gt->text = temp;
free(old);
GTextFieldRefigureLines(gt, endpos<gt->sel_oldstart?endpos:gt->sel_oldstart);
}
} else if ( !GGadgetWithin(>->g,event->u.mouse.x,event->u.mouse.y) ) {
/* Don't delete the selection until someone actually accepts the drop */
/* Don't delete at all (copy not move) if control key is down */
if ( ( event->u.mouse.state&ksm_control ) )
GTextFieldGrabSelection(gt,sn_drag_and_drop);
else
GTextFieldGrabDDSelection(gt);
GDrawPostDragEvent(gt->g.base,event,et_drop);
}
gt->drag_and_drop = false;
GDrawSetCursor(gt->g.base,gt->old_cursor);
_ggadget_redraw(>->g);
}
return( false );
}
static int gtextfield_mouse(GGadget *g, GEvent *event) {
GTextField *gt = (GTextField *) g;
GListField *ge = (GListField *) g;
unichar_t *end=NULL, *end1, *end2;
int i=0,ll,curlen;
if ( gt->hidden_cursor ) {
GDrawSetCursor(gt->g.base,gt->old_cursor);
gt->hidden_cursor = false;
_GWidget_ClearGrabGadget(g);
}
if ( !g->takes_input || (g->state!=gs_enabled && g->state!=gs_active && g->state!=gs_focused ))
return( false );
if ( event->type == et_crossing )
return( false );
if ( gt->completionfield && ((GCompletionField *) gt)->choice_popup!=NULL &&
event->type==et_mousedown )
GCompletionDestroy((GCompletionField *) gt);
if (( gt->listfield && event->u.mouse.x>=ge->buttonrect.x &&
event->u.mouse.x<ge->buttonrect.x+ge->buttonrect.width &&
event->u.mouse.y>=ge->buttonrect.y &&
event->u.mouse.y<ge->buttonrect.y+ge->buttonrect.height ) ||
( gt->listfield && ge->popup!=NULL ))
return( glistfield_mouse(ge,event));
if ( gt->numericfield && event->u.mouse.x>=ge->buttonrect.x &&
event->u.mouse.x<ge->buttonrect.x+ge->buttonrect.width &&
event->u.mouse.y>=ge->buttonrect.y &&
event->u.mouse.y<ge->buttonrect.y+ge->buttonrect.height )
return( gnumericfield_mouse(gt,event));
if (( event->type==et_mouseup || event->type==et_mousedown ) &&
(event->u.mouse.button>=4 && event->u.mouse.button<=7)) {
int isv = event->u.mouse.button<=5;
if ( event->u.mouse.state&ksm_shift ) isv = !isv;
if ( isv && gt->vsb!=NULL )
return( GGadgetDispatchEvent(>->vsb->g,event));
else if ( !isv && gt->hsb!=NULL )
return( GGadgetDispatchEvent(>->hsb->g,event));
else
return( true );
}
if ( gt->pressed==NULL && event->type == et_mousemove && g->popup_msg!=NULL &&
GGadgetWithin(g,event->u.mouse.x,event->u.mouse.y))
GGadgetPreparePopup(g->base,g->popup_msg);
curlen = u_strlen(gt->text);
if ( event->type == et_mousedown || gt->pressed ) {
i = (event->u.mouse.y-g->inner.y)/gt->fh + gt->loff_top;
if ( i<0 ) i = 0;
if ( !gt->multi_line ) i = 0;
if ( i>=gt->lcnt ) {
end = gt->text+curlen;
i = gt->lcnt - 1;
if (i < 0) i = 0; // Can lcnt ever be 0?
} else
end = GTextFieldGetPtFromPos(gt,i,event->u.mouse.x);
}
if ( event->type == et_mousedown ) {
int end8;
if ( event->u.mouse.button==3 &&
GGadgetWithin(g,event->u.mouse.x,event->u.mouse.y)) {
GTFPopupMenu(gt,event);
return( true );
}
ll = gt->lines8[i+1]==-1?-1:gt->lines8[i+1]-gt->lines8[i]-1;
GDrawLayoutInit(gt->g.base,gt->utf8_text+gt->lines8[i],ll,NULL);
end8 = GDrawLayoutXYToIndex(gt->g.base,event->u.mouse.x-g->inner.x+gt->xoff_left,0);
end1 = end2 = gt->text + gt->lines[i] + utf82u_index(end8,gt->utf8_text+gt->lines8[i]);
gt->wordsel = gt->linesel = false;
if ( event->u.mouse.button==1 && event->u.mouse.clicks>=3 ) {
gt->sel_start = gt->lines[i]; gt->sel_end = gt->lines[i+1];
if ( gt->sel_end==-1 ) gt->sel_end = curlen;
gt->wordsel = false; gt->linesel = true;
} else if ( event->u.mouse.button==1 && event->u.mouse.clicks==2 ) {
gt->sel_start = gt->sel_end = gt->sel_base = end-gt->text;
gt->wordsel = true;
GTextFieldSelectWords(gt,gt->sel_base);
} else if ( end1-gt->text>=gt->sel_start && end2-gt->text<gt->sel_end &&
gt->sel_start!=gt->sel_end &&
event->u.mouse.button==1 ) {
gt->drag_and_drop = true;
if ( !gt->hidden_cursor )
gt->old_cursor = GDrawGetCursor(gt->g.base);
GDrawSetCursor(gt->g.base,ct_draganddrop);
} else if ( /*event->u.mouse.button!=3 &&*/ !(event->u.mouse.state&ksm_shift) ) {
if ( event->u.mouse.button==1 )
GTextFieldGrabPrimarySelection(gt);
gt->sel_start = gt->sel_end = gt->sel_base = end-gt->text;
} else if ( end-gt->text>gt->sel_base ) {
gt->sel_start = gt->sel_base;
gt->sel_end = end-gt->text;
} else {
gt->sel_start = gt->sel_base = gt->sel_end = end-gt->text;
}
if ( gt->pressed==NULL )
gt->pressed = GDrawRequestTimer(gt->g.base,200,100,NULL);
if ( gt->sel_start > curlen ) /* Ok to have selection at end, but beyond is an error */
fprintf( stderr, "About to crash\n" );
_ggadget_redraw(g);
return( true );
} else if ( gt->pressed && (event->type == et_mousemove || event->type == et_mouseup )) {
int refresh = true;
if ( gt->drag_and_drop ) {
refresh = GTextFieldDoDrop(gt,event,end-gt->text);
// curlen may be inaccurate now, but we recalculate after this guard set.
} else if ( gt->linesel ) {
int j;
for ( j=i; j>0 && gt->text[gt->lines[j]-1] != '\n'; --j )
;
gt->sel_start = gt->lines[j];
for ( j=i+1; gt->lines[j]!=-1 && gt->text[gt->lines[j]-1] != '\n'; ++j )
;
gt->sel_end = gt->lines[j]!=-1 ? gt->lines[j]-1 : curlen;
} else if ( gt->wordsel )
GTextFieldSelectWords(gt,end-gt->text);
else if ( event->u.mouse.button!=2 ) {
int e = end-gt->text;
if ( e>gt->sel_base ) {
gt->sel_start = gt->sel_base; gt->sel_end = e;
} else {
gt->sel_start = e; gt->sel_end = gt->sel_base;
}
}
if ( event->type==et_mouseup ) {
GDrawCancelTimer(gt->pressed); gt->pressed = NULL;
if ( event->u.mouse.button==2 )
GTextFieldPaste(gt,sn_primary);
if ( gt->sel_start==gt->sel_end )
GTextField_Show(gt,gt->sel_start);
GTextFieldChanged(gt,-1);
if ( gt->sel_start<gt->sel_end && _GDraw_InsCharHook!=NULL && !gt->donthook )
(_GDraw_InsCharHook)(GDrawGetDisplayOfWindow(gt->g.base),
gt->text[gt->sel_start]);
}
if ( gt->sel_end > u_strlen(gt->text) )
fprintf( stderr, "About to crash\n" );
if ( refresh )
_ggadget_redraw(g);
return( true );
}
return( false );
}
static int gtextfield_key(GGadget *g, GEvent *event) {
GTextField *gt = (GTextField *) g;
if ( !g->takes_input || (g->state!=gs_enabled && g->state!=gs_active && g->state!=gs_focused ))
return( false );
if ( gt->listfield && ((GListField *) gt)->popup!=NULL ) {
GWindow popup = ((GListField *) gt)->popup;
(GDrawGetEH(popup))(popup,event);
return( true );
}
if ( gt->completionfield && ((GCompletionField *) gt)->choice_popup!=NULL &&
GCompletionHandleKey(gt,event))
return( true );
if ( event->type == et_charup )
return( false );
if ( event->u.chr.keysym == GK_F1 || event->u.chr.keysym == GK_Help ||
(event->u.chr.keysym == GK_Return && !gt->accepts_returns ) ||
( event->u.chr.keysym == GK_Tab && !gt->accepts_tabs ) ||
event->u.chr.keysym == GK_BackTab || event->u.chr.keysym == GK_Escape )
return( false );
if ( !gt->hidden_cursor ) { /* hide the mouse pointer */
if ( !gt->drag_and_drop )
gt->old_cursor = GDrawGetCursor(gt->g.base);
GDrawSetCursor(g->base,ct_invisible);
gt->hidden_cursor = true;
_GWidget_SetGrabGadget(g); /* so that we get the next mouse movement to turn the cursor on */
}
if( gt->cursor_on ) { /* undraw the blinky text cursor if it is drawn */
gt_draw_cursor(g->base, gt);
gt->cursor_on = false;
}
switch ( GTextFieldDoChange(gt,event)) {
case 4:
/* We should try name completion */
if ( gt->completionfield && ((GCompletionField *) gt)->completion!=NULL &&
gt->was_completing && gt->sel_start == u_strlen(gt->text))
GTextFieldComplete(gt,false);
else
GTextFieldChanged(gt,-1);
break;
case 3:
/* They typed a Tab */
break;
case 2:
break;
case true:
GTextFieldChanged(gt,-1);
break;
case false:
return( false );
}
_ggadget_redraw(g);
return( true );
}
static int gtextfield_focus(GGadget *g, GEvent *event) {
GTextField *gt = (GTextField *) g;
if ( g->state == gs_invisible || g->state == gs_disabled )
return( false );
if ( gt->cursor!=NULL ) {
GDrawCancelTimer(gt->cursor);
gt->cursor = NULL;
gt->cursor_on = false;
}
if ( gt->hidden_cursor && !event->u.focus.gained_focus ) {
GDrawSetCursor(gt->g.base,gt->old_cursor);
gt->hidden_cursor = false;
}
gt->g.has_focus = event->u.focus.gained_focus;
if ( event->u.focus.gained_focus ) {
gt->cursor = GDrawRequestTimer(gt->g.base,400,400,NULL);
gt->cursor_on = true;
if ( event->u.focus.mnemonic_focus != mf_normal )
GTextFieldSelect(>->g,0,-1);
if ( gt->gic!=NULL )
GTPositionGIC(gt);
else if ( GWidgetGetInputContext(gt->g.base)!=NULL )
GDrawSetGIC(gt->g.base,GWidgetGetInputContext(gt->g.base),10000,10000);
}
_ggadget_redraw(g);
GTextFieldFocusChanged(gt,event->u.focus.gained_focus);
return( true );
}
static int gtextfield_timer(GGadget *g, GEvent *event) {
GTextField *gt = (GTextField *) g;
if ( !g->takes_input || (g->state!=gs_enabled && g->state!=gs_active && g->state!=gs_focused ))
return(false);
if ( gt->cursor == event->u.timer.timer ) {
if ( gt->cursor_on ) {
gt_draw_cursor(g->base, gt);
gt->cursor_on = false;
} else {
gt->cursor_on = true;
gt_draw_cursor(g->base, gt);
}
return( true );
}
if ( gt->numeric_scroll == event->u.timer.timer ) {
GTextFieldIncrement(gt,gt->incr_down?-1:1);
return( true );
}
if ( gt->pressed == event->u.timer.timer ) {
GEvent e;
GDrawSetFont(g->base,gt->font);
GDrawGetPointerPosition(g->base,&e);
if ( (e.u.mouse.x<g->r.x && gt->xoff_left>0 ) ||
(gt->multi_line && e.u.mouse.y<g->r.y && gt->loff_top>0 ) ||
( e.u.mouse.x >= g->r.x + g->r.width &&
gt->xmax-gt->xoff_left>g->inner.width ) ||
( e.u.mouse.y >= g->r.y + g->r.height &&
gt->lcnt-gt->loff_top > g->inner.height/gt->fh )) {
int l = gt->loff_top + (e.u.mouse.y-g->inner.y)/gt->fh;
int xpos; unichar_t *end;
if ( e.u.mouse.y<g->r.y && gt->loff_top>0 )
l = --gt->loff_top;
else if ( e.u.mouse.y >= g->r.y + g->r.height &&
gt->lcnt-gt->loff_top > g->inner.height/gt->fh ) {
++gt->loff_top;
l = gt->loff_top + g->inner.width/gt->fh;
} else if ( l<gt->loff_top )
l = gt->loff_top;
else if ( l>=gt->loff_top + g->inner.height/gt->fh )
l = gt->loff_top + g->inner.height/gt->fh-1;
if ( l>=gt->lcnt ) l = gt->lcnt-1;
xpos = e.u.mouse.x+gt->xoff_left;
if ( e.u.mouse.x<g->r.x && gt->xoff_left>0 ) {
gt->xoff_left -= gt->nw;
xpos = g->inner.x + gt->xoff_left;
} else if ( e.u.mouse.x >= g->r.x + g->r.width &&
gt->xmax-gt->xoff_left>g->inner.width ) {
gt->xoff_left += gt->nw;
xpos = g->inner.x + gt->xoff_left + g->inner.width;
}
end = GTextFieldGetPtFromPos(gt,l,xpos);
if ( end-gt->text > gt->sel_base ) {
gt->sel_start = gt->sel_base;
gt->sel_end = end-gt->text;
} else {
gt->sel_start = end-gt->text;
gt->sel_end = gt->sel_base;
}
_ggadget_redraw(g);
if ( gt->vsb!=NULL )
GScrollBarSetPos(>->vsb->g,gt->loff_top);
if ( gt->hsb!=NULL )
GScrollBarSetPos(>->hsb->g,gt->xoff_left);
}
return( true );
}
return( false );
}
static int gtextfield_sel(GGadget *g, GEvent *event) {
GTextField *gt = (GTextField *) g;
unichar_t *end;
int i;
if ( event->type == et_selclear ) {
if ( event->u.selclear.sel==sn_primary && gt->sel_start!=gt->sel_end ) {
gt->sel_start = gt->sel_end = gt->sel_base;
_ggadget_redraw(g);
return( true );
}
return( false );
}
if ( gt->has_dd_cursor )
GTextFieldDrawDDCursor(gt,gt->dd_cursor_pos);
GDrawSetFont(g->base,gt->font);
i = (event->u.drag_drop.y-g->inner.y)/gt->fh + gt->loff_top;
if ( !gt->multi_line ) i = 0;
if ( i>=gt->lcnt )
end = gt->text+u_strlen(gt->text);
else
end = GTextFieldGetPtFromPos(gt,i,event->u.drag_drop.x);
if ( event->type == et_drag ) {
GTextFieldDrawDDCursor(gt,end-gt->text);
} else if ( event->type == et_dragout ) {
/* this event exists simply to clear the dd cursor line. We've done */
/* that already */
} else if ( event->type == et_drop ) {
gt->sel_start = gt->sel_end = gt->sel_base = end-gt->text;
GTextFieldPaste(gt,sn_drag_and_drop);
GTextField_Show(gt,gt->sel_start);
GTextFieldChanged(gt,-1);
_ggadget_redraw(>->g);
} else
return( false );
return( true );
}
static void gtextfield_destroy(GGadget *g) {
GTextField *gt = (GTextField *) g;
if ( gt==NULL )
return;
if ( gt->listfield ) {
GListField *glf = (GListField *) g;
if ( glf->popup ) {
/* Must cleanup the popup before we die */
/* We do this instead of GDrawDestroyWindow because this method is synchronous */
GEvent die;
die.type = et_close;
die.w = glf->popup;
GDrawPostEvent(&die);
}
GTextInfoArrayFree(glf->ti);
}
if ( gt->completionfield )
GCompletionDestroy((GCompletionField *) g);
if ( gt->vsb!=NULL )
(gt->vsb->g.funcs->destroy)(>->vsb->g);
if ( gt->hsb!=NULL )
(gt->hsb->g.funcs->destroy)(>->hsb->g);
GDrawCancelTimer(gt->numeric_scroll);
GDrawCancelTimer(gt->pressed);
GDrawCancelTimer(gt->cursor);
free(gt->lines);
free(gt->oldtext);
free(gt->text);
free(gt->utf8_text);
free(gt->lines8);
_ggadget_destroy(g);
}
static void GTextFieldSetTitle(GGadget *g,const unichar_t *tit) {
GTextField *gt = (GTextField *) g;
unichar_t *old = gt->oldtext;
if ( tit==NULL || u_strcmp(tit,gt->text)==0 ) /* If it doesn't change anything, then don't trash undoes or selection */
return;
gt->oldtext = gt->text;
gt->sel_oldstart = gt->sel_start; gt->sel_oldend = gt->sel_end; gt->sel_oldbase = gt->sel_base;
gt->text = u_copy(tit); /* tit might be oldtext, so must copy before freeing */
free(old);
free(gt->utf8_text);
gt->utf8_text = u2utf8_copy(gt->text);
gt->sel_start = gt->sel_end = gt->sel_base = u_strlen(tit);
GTextFieldRefigureLines(gt,0);
GTextField_Show(gt,gt->sel_start);
_ggadget_redraw(g);
}
static const unichar_t *_GTextFieldGetTitle(GGadget *g) {
GTextField *gt = (GTextField *) g;
return( gt->text );
}
static void GTextFieldSetFont(GGadget *g,FontInstance *new) {
GTextField *gt = (GTextField *) g;
gt->font = new;
GTextFieldRefigureLines(gt,0);
}
static FontInstance *GTextFieldGetFont(GGadget *g) {
GTextField *gt = (GTextField *) g;
return( gt->font );
}
void GTextFieldShow(GGadget *g,int pos) {
GTextField *gt = (GTextField *) g;
GTextField_Show(gt,pos);
_ggadget_redraw(g);
}
void GTextFieldSelect(GGadget *g,int start, int end) {
GTextField *gt = (GTextField *) g;
GTextFieldGrabPrimarySelection(gt);
if ( end<0 ) {
end = u_strlen(gt->text);
if ( start<0 ) start = end;
}
if ( start>end ) { int temp = start; start = end; end = temp; }
if ( end>u_strlen(gt->text)) end = u_strlen(gt->text);
if ( start>u_strlen(gt->text)) start = end;
else if ( start<0 ) start=0;
gt->sel_start = gt->sel_base = start;
gt->sel_end = end;
_ggadget_redraw(g); /* Should be safe just to draw the textfield gadget, sbs won't have changed */
}
void GTextFieldReplace(GGadget *g,const unichar_t *txt) {
GTextField *gt = (GTextField *) g;
GTextField_Replace(gt,txt);
_ggadget_redraw(g);
}
static void GListFSelectOne(GGadget *g, int32 pos) {
GListField *gl = (GListField *) g;
int i;
for ( i=0; i<gl->ltot; ++i )
gl->ti[i]->selected = false;
if ( pos>=gl->ltot ) pos = gl->ltot-1;
if ( pos<0 ) pos = 0;
if ( gl->ltot>0 ) {
gl->ti[pos]->selected = true;
GTextFieldSetTitle(g,gl->ti[pos]->text);
}
}
static int32 GListFIsSelected(GGadget *g, int32 pos) {
GListField *gl = (GListField *) g;
if ( pos>=gl->ltot )
return( false );
if ( pos<0 )
return( false );
if ( gl->ltot>0 )
return( gl->ti[pos]->selected );
return( false );
}
static int32 GListFGetFirst(GGadget *g) {
int i;
GListField *gl = (GListField *) g;
for ( i=0; i<gl->ltot; ++i )
if ( gl->ti[i]->selected )
return( i );
return( -1 );
}
static GTextInfo **GListFGet(GGadget *g,int32 *len) {
GListField *gl = (GListField *) g;
if ( len!=NULL ) *len = gl->ltot;
return( gl->ti );
}
static GTextInfo *GListFGetItem(GGadget *g,int32 pos) {
GListField *gl = (GListField *) g;
if ( pos<0 || pos>=gl->ltot )
return( NULL );
return(gl->ti[pos]);
}
static void GListFSet(GGadget *g,GTextInfo **ti,int32 docopy) {
GListField *gl = (GListField *) g;
GTextInfoArrayFree(gl->ti);
if ( docopy || ti==NULL )
ti = GTextInfoArrayCopy(ti);
gl->ti = ti;
gl->ltot = GTextInfoArrayCount(ti);
}
static void GListFClear(GGadget *g) {
GListFSet(g,NULL,true);
}
static void gtextfield_redraw(GGadget *g) {
GTextField *gt = (GTextField *) g;
if ( gt->vsb!=NULL )
_ggadget_redraw((GGadget *) (gt->vsb));
if ( gt->hsb!=NULL )
_ggadget_redraw((GGadget *) (gt->hsb));
_ggadget_redraw(g);
}
static void gtextfield_move(GGadget *g, int32 x, int32 y ) {
GTextField *gt = (GTextField *) g;
int fxo=0, fyo=0, bxo, byo;
if ( gt->listfield || gt->numericfield ) {
fxo = ((GListField *) gt)->fieldrect.x - g->r.x;
fyo = ((GListField *) gt)->fieldrect.y - g->r.y;
bxo = ((GListField *) gt)->buttonrect.x - g->r.x;
byo = ((GListField *) gt)->buttonrect.y - g->r.y;
}
if ( gt->vsb!=NULL )
_ggadget_move((GGadget *) (gt->vsb),x+(gt->vsb->g.r.x-g->r.x),y);
if ( gt->hsb!=NULL )
_ggadget_move((GGadget *) (gt->hsb),x,y+(gt->hsb->g.r.y-g->r.y));
_ggadget_move(g,x,y);
if ( gt->listfield || gt->numericfield ) {
((GListField *) gt)->fieldrect.x = g->r.x + fxo;
((GListField *) gt)->fieldrect.y = g->r.y + fyo;
((GListField *) gt)->buttonrect.x = g->r.x + bxo;
((GListField *) gt)->buttonrect.y = g->r.y + byo;
}
}
static void gtextfield_resize(GGadget *g, int32 width, int32 height ) {
GTextField *gt = (GTextField *) g;
int gtwidth=width, gtheight=height, oldheight=0;
int fxo=0, fwo=0, fyo=0, bxo, byo;
int l;
if ( gt->listfield || gt->numericfield ) {
fxo = ((GListField *) gt)->fieldrect.x - g->r.x;
fwo = g->r.width - ((GListField *) gt)->fieldrect.width;
fyo = ((GListField *) gt)->fieldrect.y - g->r.y;
bxo = g->r.x+g->r.width - ((GListField *) gt)->buttonrect.x;
byo = ((GListField *) gt)->buttonrect.y - g->r.y;
}
if ( gt->hsb!=NULL ) {
oldheight = gt->hsb->g.r.y+gt->hsb->g.r.height-g->r.y;
gtheight = height - (oldheight-g->r.height);
}
if ( gt->vsb!=NULL ) {
int oldwidth = gt->vsb->g.r.x+gt->vsb->g.r.width-g->r.x;
gtwidth = width - (oldwidth-g->r.width);
_ggadget_move((GGadget *) (gt->vsb),gt->vsb->g.r.x+width-oldwidth,gt->vsb->g.r.y);
_ggadget_resize((GGadget *) (gt->vsb),gt->vsb->g.r.width,gtheight);
}
if ( gt->hsb!=NULL ) {
_ggadget_move((GGadget *) (gt->hsb),gt->hsb->g.r.x,gt->hsb->g.r.y+height-oldheight);
_ggadget_resize((GGadget *) (gt->hsb),gtwidth,gt->hsb->g.r.height);
}
_ggadget_resize(g,gtwidth, gtheight);
if ( gt->hsb==NULL && gt->xoff_left!=0 && !gt->multi_line &&
GDrawGetTextWidth(gt->g.base,gt->text,-1)<gt->g.inner.width )
gt->xoff_left = 0;
GTextFieldRefigureLines(gt,0);
if ( gt->vsb!=NULL ) {
GScrollBarSetBounds(>->vsb->g,0,gt->lcnt,
gt->g.inner.height<gt->fh ? 1 : gt->g.inner.height/gt->fh);
l = gt->loff_top;
if ( gt->loff_top>gt->lcnt-gt->g.inner.height/gt->fh )
l = gt->lcnt-gt->g.inner.height/gt->fh;
if ( l<0 ) l = 0;
if ( l!=gt->loff_top ) {
gt->loff_top = l;
GScrollBarSetPos(>->vsb->g,l);
_ggadget_redraw(>->g);
}
}
if ( gt->listfield || gt->numericfield) {
((GListField *) gt)->fieldrect.x = g->r.x + fxo;
((GListField *) gt)->fieldrect.width = g->r.width -fwo;
((GListField *) gt)->fieldrect.y = g->r.y + fyo;
((GListField *) gt)->buttonrect.x = g->r.x+g->r.width - bxo;
((GListField *) gt)->buttonrect.y = g->r.y + byo;
}
}
static GRect *gtextfield_getsize(GGadget *g, GRect *r ) {
GTextField *gt = (GTextField *) g;
_ggadget_getsize(g,r);
if ( gt->vsb!=NULL )
r->width = gt->vsb->g.r.x+gt->vsb->g.r.width-g->r.x;
if ( gt->hsb!=NULL )
r->height = gt->hsb->g.r.y+gt->hsb->g.r.height-g->r.y;
return( r );
}
static void gtextfield_setvisible(GGadget *g, int visible ) {
GTextField *gt = (GTextField *) g;
if ( gt->vsb!=NULL ) _ggadget_setvisible(>->vsb->g,visible);
if ( gt->hsb!=NULL ) _ggadget_setvisible(>->hsb->g,visible);
_ggadget_setvisible(g,visible);
}
static void gtextfield_setenabled(GGadget *g, int enabled ) {
GTextField *gt = (GTextField *) g;
if ( gt->vsb!=NULL ) _ggadget_setenabled(>->vsb->g,enabled);
if ( gt->hsb!=NULL ) _ggadget_setenabled(>->hsb->g,enabled);
_ggadget_setenabled(g,enabled);
}
static int gtextfield_vscroll(GGadget *g, GEvent *event) {
enum sb sbt = event->u.control.u.sb.type;
GTextField *gt = (GTextField *) (g->data);
int loff = gt->loff_top;
g = (GGadget *) gt;
if ( sbt==et_sb_top )
loff = 0;
else if ( sbt==et_sb_bottom ) {
loff = gt->lcnt - gt->g.inner.height/gt->fh;
} else if ( sbt==et_sb_up ) {
if ( gt->loff_top!=0 ) loff = gt->loff_top-1; else loff = 0;
} else if ( sbt==et_sb_down ) {
if ( gt->loff_top + gt->g.inner.height/gt->fh >= gt->lcnt )
loff = gt->lcnt - gt->g.inner.height/gt->fh;
else
++loff;
} else if ( sbt==et_sb_uppage ) {
int page = g->inner.height/gt->fh- (g->inner.height/gt->fh>2?1:0);
loff = gt->loff_top - page;
if ( loff<0 ) loff=0;
} else if ( sbt==et_sb_downpage ) {
int page = g->inner.height/gt->fh- (g->inner.height/gt->fh>2?1:0);
loff = gt->loff_top + page;
if ( loff + gt->g.inner.height/gt->fh >= gt->lcnt )
loff = gt->lcnt - gt->g.inner.height/gt->fh;
} else /* if ( sbt==et_sb_thumb || sbt==et_sb_thumbrelease ) */ {
loff = event->u.control.u.sb.pos;
}
if ( loff + gt->g.inner.height/gt->fh >= gt->lcnt )
loff = gt->lcnt - gt->g.inner.height/gt->fh;
if ( loff<0 ) loff = 0;
if ( loff!=gt->loff_top ) {
gt->loff_top = loff;
GScrollBarSetPos(>->vsb->g,loff);
_ggadget_redraw(>->g);
}
return( true );
}
static int gtextfield_hscroll(GGadget *g, GEvent *event) {
enum sb sbt = event->u.control.u.sb.type;
GTextField *gt = (GTextField *) (g->data);
int xoff = gt->xoff_left;
g = (GGadget *) gt;
if ( sbt==et_sb_top )
xoff = 0;
else if ( sbt==et_sb_bottom ) {
xoff = gt->xmax - gt->g.inner.width;
if ( xoff<0 ) xoff = 0;
} else if ( sbt==et_sb_up ) {
if ( gt->xoff_left>gt->nw ) xoff = gt->xoff_left-gt->nw; else xoff = 0;
} else if ( sbt==et_sb_down ) {
if ( gt->xoff_left + gt->nw + gt->g.inner.width >= gt->xmax )
xoff = gt->xmax - gt->g.inner.width;
else
xoff += gt->nw;
} else if ( sbt==et_sb_uppage ) {
int page = (3*g->inner.width)/4;
xoff = gt->xoff_left - page;
if ( xoff<0 ) xoff=0;
} else if ( sbt==et_sb_downpage ) {
int page = (3*g->inner.width)/4;
xoff = gt->xoff_left + page;
if ( xoff + gt->g.inner.width >= gt->xmax )
xoff = gt->xmax - gt->g.inner.width;
} else /* if ( sbt==et_sb_thumb || sbt==et_sb_thumbrelease ) */ {
xoff = event->u.control.u.sb.pos;
}
if ( xoff + gt->g.inner.width >= gt->xmax )
xoff = gt->xmax - gt->g.inner.width;
if ( xoff<0 ) xoff = 0;
if ( gt->xoff_left!=xoff ) {
gt->xoff_left = xoff;
GScrollBarSetPos(>->hsb->g,xoff);
_ggadget_redraw(>->g);
}
return( true );
}
static void GTextFieldSetDesiredSize(GGadget *g,GRect *outer,GRect *inner) {
GTextField *gt = (GTextField *) g;
if ( outer!=NULL ) {
g->desired_width = outer->width;
g->desired_height = outer->height;
} else if ( inner!=NULL ) {
int bp = GBoxBorderWidth(g->base,g->box);
int extra=0;
if ( gt->listfield ) {
extra = GDrawPointsToPixels(gt->g.base,_GListMarkSize) +
GDrawPointsToPixels(gt->g.base,_GGadget_TextImageSkip) +
2*GBoxBorderWidth(gt->g.base,&_GListMark_Box) +
GBoxBorderWidth(gt->g.base,&glistfieldmenu_box);
} else if ( gt->numericfield ) {
extra = GDrawPointsToPixels(gt->g.base,_GListMarkSize)/2 +
GDrawPointsToPixels(gt->g.base,_GGadget_TextImageSkip) +
2*GBoxBorderWidth(gt->g.base,&gnumericfieldspinner_box);
}
g->desired_width = inner->width + 2*bp + extra;
g->desired_height = inner->height + 2*bp;
if ( gt->multi_line ) {
int sbadd = GDrawPointsToPixels(gt->g.base,_GScrollBar_Width) +
GDrawPointsToPixels(gt->g.base,1);
g->desired_width += sbadd;
if ( !gt->wrap )
g->desired_height += sbadd;
}
}
}
static void GTextFieldGetDesiredSize(GGadget *g,GRect *outer,GRect *inner) {
GTextField *gt = (GTextField *) g;
int width=0, height;
int extra=0;
int bp = GBoxBorderWidth(g->base,g->box);
if ( gt->listfield ) {
extra = GDrawPointsToPixels(gt->g.base,_GListMarkSize) +
GDrawPointsToPixels(gt->g.base,_GGadget_TextImageSkip) +
2*GBoxBorderWidth(gt->g.base,&_GListMark_Box) +
GBoxBorderWidth(gt->g.base,&glistfieldmenu_box);
} else if ( gt->numericfield ) {
extra = GDrawPointsToPixels(gt->g.base,_GListMarkSize)/2 +
GDrawPointsToPixels(gt->g.base,_GGadget_TextImageSkip) +
2*GBoxBorderWidth(gt->g.base,&gnumericfieldspinner_box);
}
width = GGadgetScale(GDrawPointsToPixels(gt->g.base,80));
height = gt->multi_line? 4*gt->fh:gt->fh;
if ( g->desired_width>extra+2*bp ) width = g->desired_width - extra - 2*bp;
if ( g->desired_height>2*bp ) height = g->desired_height - 2*bp;
if ( gt->multi_line ) {
int sbadd = GDrawPointsToPixels(gt->g.base,_GScrollBar_Width) +
GDrawPointsToPixels(gt->g.base,1);
width += sbadd;
if ( !gt->wrap )
height += sbadd;
}
if ( inner!=NULL ) {
inner->x = inner->y = 0;
inner->width = width;
inner->height = height;
}
if ( outer!=NULL ) {
outer->x = outer->y = 0;
outer->width = width + extra + 2*bp;
outer->height = height + 2*bp;
}
}
static int gtextfield_FillsWindow(GGadget *g) {
return( ((GTextField *) g)->multi_line && g->prev==NULL &&
(_GWidgetGetGadgets(g->base)==g ||
_GWidgetGetGadgets(g->base)==(GGadget *) ((GTextField *) g)->vsb ||
_GWidgetGetGadgets(g->base)==(GGadget *) ((GTextField *) g)->hsb ));
}
struct gfuncs gtextfield_funcs = {
0,
sizeof(struct gfuncs),
gtextfield_expose,
gtextfield_mouse,
gtextfield_key,
_gtextfield_editcmd,
gtextfield_focus,
gtextfield_timer,
gtextfield_sel,
gtextfield_redraw,
gtextfield_move,
gtextfield_resize,
gtextfield_setvisible,
gtextfield_setenabled,
gtextfield_getsize,
_ggadget_getinnersize,
gtextfield_destroy,
GTextFieldSetTitle,
_GTextFieldGetTitle,
NULL,
NULL,
NULL,
GTextFieldSetFont,
GTextFieldGetFont,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
GTextFieldGetDesiredSize,
GTextFieldSetDesiredSize,
gtextfield_FillsWindow,
NULL
};
struct gfuncs glistfield_funcs = {
0,
sizeof(struct gfuncs),
gtextfield_expose,
gtextfield_mouse,
gtextfield_key,
gtextfield_editcmd,
gtextfield_focus,
gtextfield_timer,
gtextfield_sel,
gtextfield_redraw,
gtextfield_move,
gtextfield_resize,
gtextfield_setvisible,
gtextfield_setenabled,
gtextfield_getsize,
_ggadget_getinnersize,
gtextfield_destroy,
GTextFieldSetTitle,
_GTextFieldGetTitle,
NULL,
NULL,
NULL,
GTextFieldSetFont,
GTextFieldGetFont,
GListFClear,
GListFSet,
GListFGet,
GListFGetItem,
NULL,
GListFSelectOne,
GListFIsSelected,
GListFGetFirst,
NULL,
NULL,
NULL,
GTextFieldGetDesiredSize,
GTextFieldSetDesiredSize,
NULL,
NULL
};
static void GTextFieldInit() {
FontRequest rq;
memset(&rq,0,sizeof(rq));
GGadgetInit();
GDrawDecomposeFont(_ggadget_default_font,&rq);
rq.family_name = NULL;
rq.utf8_family_name = MONO_UI_FAMILIES;
_gtextfield_font = GDrawInstanciateFont(NULL,&rq);
_GGadgetCopyDefaultBox(&_GGadget_gtextfield_box);
_GGadget_gtextfield_box.padding = 3;
/*_GGadget_gtextfield_box.flags = box_active_border_inner;*/
_gtextfield_font = _GGadgetInitDefaultBox("GTextField.",&_GGadget_gtextfield_box,_gtextfield_font);
glistfield_box = _GGadget_gtextfield_box;
_GGadgetInitDefaultBox("GComboBox.",&glistfield_box,_gtextfield_font);
glistfieldmenu_box = glistfield_box;
glistfieldmenu_box.padding = 1;
_GGadgetInitDefaultBox("GComboBoxMenu.",&glistfieldmenu_box,_gtextfield_font);
gnumericfield_box = _GGadget_gtextfield_box;
_GGadgetInitDefaultBox("GNumericField.",&gnumericfield_box,_gtextfield_font);
gnumericfieldspinner_box = gnumericfield_box;
gnumericfieldspinner_box.border_type = bt_none;
gnumericfieldspinner_box.border_width = 0;
gnumericfieldspinner_box.padding = 0;
_GGadgetInitDefaultBox("GNumericFieldSpinner.",&gnumericfieldspinner_box,_gtextfield_font);
gtextfield_inited = true;
}
static void GTextFieldAddVSb(GTextField *gt) {
GGadgetData gd;
memset(&gd,'\0',sizeof(gd));
gd.pos.y = gt->g.r.y; gd.pos.height = gt->g.r.height;
gd.pos.width = GDrawPointsToPixels(gt->g.base,_GScrollBar_Width);
gd.pos.x = gt->g.r.x+gt->g.r.width - gd.pos.width;
gd.flags = (gt->g.state==gs_invisible?0:gg_visible)|gg_enabled|gg_pos_in_pixels|gg_sb_vert;
gd.handle_controlevent = gtextfield_vscroll;
gt->vsb = (GScrollBar *) GScrollBarCreate(gt->g.base,&gd,gt);
gt->vsb->g.contained = true;
gd.pos.width += GDrawPointsToPixels(gt->g.base,1);
gt->g.r.width -= gd.pos.width;
gt->g.inner.width -= gd.pos.width;
}
static void GTextFieldAddHSb(GTextField *gt) {
GGadgetData gd;
memset(&gd,'\0',sizeof(gd));
gd.pos.x = gt->g.r.x; gd.pos.width = gt->g.r.width;
gd.pos.height = GDrawPointsToPixels(gt->g.base,_GScrollBar_Width);
gd.pos.y = gt->g.r.y+gt->g.r.height - gd.pos.height;
gd.flags = (gt->g.state==gs_invisible?0:gg_visible)|gg_enabled|gg_pos_in_pixels;
gd.handle_controlevent = gtextfield_hscroll;
gt->hsb = (GScrollBar *) GScrollBarCreate(gt->g.base,&gd,gt);
gt->hsb->g.contained = true;
gd.pos.height += GDrawPointsToPixels(gt->g.base,1);
gt->g.r.height -= gd.pos.height;
gt->g.inner.height -= gd.pos.height;
if ( gt->vsb!=NULL ) {
gt->vsb->g.r.height -= gd.pos.height;
gt->vsb->g.inner.height -= gd.pos.height;
}
}
static void GTextFieldFit(GTextField *gt) {
GTextBounds bounds;
int as=0, ds, ld, width=0;
GRect inner, outer;
int bp = GBoxBorderWidth(gt->g.base,gt->g.box);
{
FontInstance *old = GDrawSetFont(gt->g.base,gt->font);
FontRequest rq;
int tries;
for ( tries = 0; tries<2; ++tries ) {
width = GDrawGetTextBounds(gt->g.base,gt->text, -1, &bounds);
GDrawWindowFontMetrics(gt->g.base,gt->font,&as, &ds, &ld);
if ( gt->g.r.height==0 || as+ds-3+2*bp<=gt->g.r.height || tries==1 )
break;
/* Doesn't fit. Try a smaller size */
GDrawDecomposeFont(gt->font,&rq);
--rq.point_size;
gt->font = GDrawInstanciateFont(gt->g.base,&rq);
}
gt->fh = as+ds;
gt->as = as;
gt->nw = GDrawGetTextWidth(gt->g.base,nstr, 1);
GDrawSetFont(gt->g.base,old);
}
GTextFieldGetDesiredSize(>->g,&outer,&inner);
if ( gt->g.r.width==0 ) {
int extra=0;
if ( gt->listfield ) {
extra = GDrawPointsToPixels(gt->g.base,_GListMarkSize) +
2*GDrawPointsToPixels(gt->g.base,_GGadget_TextImageSkip) +
GBoxBorderWidth(gt->g.base,&_GListMark_Box);
} else if ( gt->numericfield ) {
extra = GDrawPointsToPixels(gt->g.base,_GListMarkSize)/2 +
GDrawPointsToPixels(gt->g.base,_GGadget_TextImageSkip) +
2*GBoxBorderWidth(gt->g.base,&gnumericfieldspinner_box);
}
gt->g.r.width = outer.width;
gt->g.inner.width = inner.width;
gt->g.inner.x = gt->g.r.x + (outer.width-inner.width-extra)/2;
} else {
gt->g.inner.x = gt->g.r.x + bp;
gt->g.inner.width = gt->g.r.width - 2*bp;
}
if ( gt->g.r.height==0 ) {
gt->g.r.height = outer.height;
gt->g.inner.height = inner.height;
gt->g.inner.y = gt->g.r.y + (outer.height-gt->g.inner.height)/2;
} else {
gt->g.inner.y = gt->g.r.y + bp;
gt->g.inner.height = gt->g.r.height - 2*bp;
}
if ( gt->multi_line ) {
GTextFieldAddVSb(gt);
if ( !gt->wrap )
GTextFieldAddHSb(gt);
}
if ( gt->listfield || gt->numericfield ) {
GListField *ge = (GListField *) gt;
int extra;
if ( gt->listfield )
extra = GDrawPointsToPixels(gt->g.base,_GListMarkSize) +
GDrawPointsToPixels(gt->g.base,_GGadget_TextImageSkip) +
2*GBoxBorderWidth(gt->g.base,&_GListMark_Box)+
GBoxBorderWidth(gt->g.base,&glistfieldmenu_box);
else {
extra = GDrawPointsToPixels(gt->g.base,_GListMarkSize)/2 +
GDrawPointsToPixels(gt->g.base,_GGadget_TextImageSkip) +
2*GBoxBorderWidth(gt->g.base,&gnumericfieldspinner_box);
}
ge->fieldrect = ge->buttonrect = gt->g.r;
ge->fieldrect.width -= extra;
extra -= GDrawPointsToPixels(gt->g.base,_GGadget_TextImageSkip)/2;
ge->buttonrect.x = ge->buttonrect.x+ge->buttonrect.width-extra;
ge->buttonrect.width = extra;
if ( gt->numericfield )
++ge->fieldrect.width;
}
}
static GTextField *_GTextFieldCreate(GTextField *gt, struct gwindow *base, GGadgetData *gd,void *data, GBox *def) {
if ( !gtextfield_inited )
GTextFieldInit();
gt->g.funcs = >extfield_funcs;
_GGadget_Create(>->g,base,gd,data,def);
gt->g.takes_input = true; gt->g.takes_keyboard = true; gt->g.focusable = true;
if ( gd->label!=NULL ) {
if ( gd->label->text_is_1byte )
gt->text = /* def2u_*/ utf82u_copy((char *) gd->label->text);
else if ( gd->label->text_in_resource )
gt->text = u_copy((unichar_t *) GStringGetResource((intpt) gd->label->text,>->g.mnemonic));
else
gt->text = u_copy(gd->label->text);
gt->sel_start = gt->sel_end = gt->sel_base = u_strlen(gt->text);
}
if ( gt->text==NULL )
gt->text = calloc(1,sizeof(unichar_t));
gt->font = _gtextfield_font;
if ( gd->label!=NULL && gd->label->font!=NULL )
gt->font = gd->label->font;
if ( (gd->flags & gg_textarea_wrap) && gt->multi_line )
gt->wrap = true;
else if ( (gd->flags & gg_textarea_wrap) ) /* only used by gchardlg.c no need to make it look nice */
gt->donthook = true;
GTextFieldFit(gt);
_GGadget_FinalPosition(>->g,base,gd);
GTextFieldRefigureLines(gt,0);
if ( gd->flags & gg_group_end )
_GGadgetCloseGroup(>->g);
GWidgetIndicateFocusGadget(>->g);
if ( gd->flags & gg_text_xim )
gt->gic = GWidgetCreateInputContext(base,gic_overspot|gic_orlesser);
return( gt );
}
GGadget *GTextFieldCreate(struct gwindow *base, GGadgetData *gd,void *data) {
GTextField *gt = _GTextFieldCreate(calloc(1,sizeof(GTextField)),base,gd,data,&_GGadget_gtextfield_box);
return( >->g );
}
GGadget *GPasswordCreate(struct gwindow *base, GGadgetData *gd,void *data) {
GTextField *gt = _GTextFieldCreate(calloc(1,sizeof(GTextField)),base,gd,data,&_GGadget_gtextfield_box);
gt->password = true;
GTextFieldRefigureLines(gt, 0);
return( >->g );
}
GGadget *GNumericFieldCreate(struct gwindow *base, GGadgetData *gd,void *data) {
GTextField *gt = calloc(1,sizeof(GNumericField));
gt->numericfield = true;
_GTextFieldCreate(gt,base,gd,data,&gnumericfield_box);
return( >->g );
}
GGadget *GTextCompletionCreate(struct gwindow *base, GGadgetData *gd,void *data) {
GTextField *gt = calloc(1,sizeof(GCompletionField));
gt->accepts_tabs = true;
gt->completionfield = true;
gt->was_completing = true;
((GCompletionField *) gt)->completion = gd->u.completion;
_GTextFieldCreate(gt,base,gd,data,&_GGadget_gtextfield_box);
gt->accepts_tabs = ((GCompletionField *) gt)->completion != NULL;
return( >->g );
}
GGadget *GTextAreaCreate(struct gwindow *base, GGadgetData *gd,void *data) {
GTextField *gt = calloc(1,sizeof(GTextField));
gt->multi_line = true;
gt->accepts_returns = true;
_GTextFieldCreate(gt,base,gd,data,&_GGadget_gtextfield_box);
return( >->g );
}
static void GListFieldSelected(GGadget *g, int i) {
GListField *ge = (GListField *) g;
ge->popup = NULL;
_GWidget_ClearGrabGadget(&ge->gt.g);
if ( i<0 || i>=ge->ltot || ge->ti[i]->text==NULL )
return;
GTextFieldSetTitle(g,ge->ti[i]->text);
_ggadget_redraw(g);
GTextFieldChanged(&ge->gt,i);
}
GGadget *GSimpleListFieldCreate(struct gwindow *base, GGadgetData *gd,void *data) {
GListField *ge = calloc(1,sizeof(GListField));
ge->gt.listfield = true;
if ( gd->u.list!=NULL )
ge->ti = GTextInfoArrayFromList(gd->u.list,&ge->ltot);
_GTextFieldCreate(&ge->gt,base,gd,data,&glistfield_box);
ge->gt.g.funcs = &glistfield_funcs;
return( &ge->gt.g );
}
static unichar_t **GListField_NameCompletion(GGadget *t,int from_tab) {
const unichar_t *spt; unichar_t **ret;
GTextInfo **ti;
int32 len;
int i, cnt, doit, match_len;
spt = _GGadgetGetTitle(t);
if ( spt==NULL )
return( NULL );
match_len = u_strlen(spt);
ti = GGadgetGetList(t,&len);
ret = NULL;
for ( doit=0; doit<2; ++doit ) {
cnt=0;
for ( i=0; i<len; ++i ) {
if ( ti[i]->text && u_strncmp(ti[i]->text,spt,match_len)==0 ) {
if ( doit )
ret[cnt] = u_copy(ti[i]->text);
++cnt;
}
}
if ( doit )
ret[cnt] = NULL;
else if ( cnt==0 )
return( NULL );
else
ret = malloc((cnt+1)*sizeof(unichar_t *));
}
return( ret );
}
GGadget *GListFieldCreate(struct gwindow *base, GGadgetData *gd,void *data) {
GListField *ge = calloc(1,sizeof(GCompletionField));
ge->gt.listfield = true;
if ( gd->u.list!=NULL )
ge->ti = GTextInfoArrayFromList(gd->u.list,&ge->ltot);
ge->gt.accepts_tabs = true;
ge->gt.completionfield = true;
/* ge->gt.was_completing = true; */
((GCompletionField *) ge)->completion = GListField_NameCompletion;
_GTextFieldCreate(&ge->gt,base,gd,data,&_GGadget_gtextfield_box);
ge->gt.g.funcs = &glistfield_funcs;
return( &ge->gt.g );
}
/* ************************************************************************** */
/* ***************************** text completion **************************** */
/* ************************************************************************** */
static void GCompletionDestroy(GCompletionField *gc) {
int i;
if ( gc->choice_popup!=NULL ) {
GWindow cp = gc->choice_popup;
gc->choice_popup = NULL;
GDrawSetUserData(cp,NULL);
GDrawDestroyWindow(cp);
}
if ( gc->choices!=NULL ) {
for ( i=0; gc->choices[i]!=NULL; ++i )
free(gc->choices[i]);
free(gc->choices);
gc->choices = NULL;
}
}
static int GTextFieldSetTitleRmDotDotDot(GGadget *g,unichar_t *tit) {
unichar_t *pt = uc_strstr(tit," ...");
if ( pt!=NULL )
*pt = '\0';
GTextFieldSetTitle(g,tit);
if ( pt!=NULL )
*pt = ' ';
return( pt!=NULL );
}
static int popup_eh(GWindow popup,GEvent *event) {
GGadget *owner = GDrawGetUserData(popup);
GTextField *gt = (GTextField *) owner;
GCompletionField *gc = (GCompletionField *) owner;
GRect old1, r;
Color fg;
int i, bp;
if ( owner==NULL ) /* dying */
return( true );
bp = GBoxBorderWidth(owner->base,owner->box);
if ( event->type == et_expose ) {
GDrawPushClip(popup,&event->u.expose.rect,&old1);
GDrawSetFont(popup,gt->font);
GBoxDrawBackground(popup,&event->u.expose.rect,owner->box,
owner->state,false);
GDrawGetSize(popup,&r);
r.x = r.y = 0;
GBoxDrawBorder(popup,&r,owner->box,owner->state,false);
r.x += bp; r.width -= 2*bp;
fg = owner->box->main_foreground==COLOR_DEFAULT?GDrawGetDefaultForeground(GDrawGetDisplayOfWindow(popup)):
owner->box->main_foreground;
for ( i=0; gc->choices[i]!=NULL; ++i ) {
if ( i==gc->selected ) {
r.y = i*gt->fh+bp;
r.height = gt->fh;
GDrawFillRect(popup,&r,owner->box->active_border);
}
GDrawDrawText(popup,bp,i*gt->fh+gt->as+bp,gc->choices[i],-1,fg);
}
GDrawPopClip(popup,&old1);
} else if ( event->type == et_mouseup ) {
gc->selected = (event->u.mouse.y-bp)/gt->fh;
if ( gc->selected>=0 && gc->selected<gc->ctot ) {
int tryagain = GTextFieldSetTitleRmDotDotDot(owner,gc->choices[gc->selected]);
GTextFieldChanged(gt,-1);
GCompletionDestroy(gc);
if ( tryagain )
GTextFieldComplete(gt,false);
} else {
gc->selected = -1;
GDrawRequestExpose(popup,NULL,false);
}
} else if ( event->type == et_char ) {
return( gtextfield_key(owner,event));
}
return( true );
}
static void GCompletionCreatePopup(GCompletionField *gc) {
int width, maxw, i;
GWindowAttrs pattrs;
GWindow base = gc->gl.gt.g.base;
GDisplay *disp = GDrawGetDisplayOfWindow(base);
GWindow root = GDrawGetRoot(disp);
int bp = GBoxBorderWidth(base,gc->gl.gt.g.box);
GRect pos, screen;
GPoint pt;
GDrawSetFont(base,gc->gl.gt.font);
maxw = 0;
for ( i=0; i<gc->ctot; ++i ) {
width = GDrawGetTextWidth(base,gc->choices[i],-1);
if ( width > maxw ) maxw = width;
}
maxw += 2*bp;
pos.width = maxw; pos.height = gc->gl.gt.fh*gc->ctot+2*bp;
if ( pos.width < gc->gl.gt.g.r.width )
pos.width = gc->gl.gt.g.r.width;
pattrs.mask = wam_events|wam_nodecor|wam_positioned|wam_cursor|
wam_transient|wam_verytransient/*|wam_bordwidth|wam_bordcol*/;
pattrs.event_masks = -1;
pattrs.nodecoration = true;
pattrs.positioned = true;
pattrs.cursor = ct_pointer;
pattrs.transient = GWidgetGetTopWidget(base);
pattrs.border_width = 1;
pattrs.border_color = gc->gl.gt.g.box->main_foreground;
GDrawGetSize(root,&screen);
pt.x = gc->gl.gt.g.r.x;
pt.y = gc->gl.gt.g.r.y + gc->gl.gt.g.r.height;
GDrawTranslateCoordinates(base,root,&pt);
if ( pt.y+pos.height > screen.height ) {
if ( pt.y-gc->gl.gt.g.r.height-pos.height>=0 ) {
/* Is there more room above the widget ?? */
pt.y -= gc->gl.gt.g.r.height;
pt.y -= pos.height;
} else if ( pt.x + gc->gl.gt.g.r.width + maxw <= screen.width ) {
pt.x += gc->gl.gt.g.r.width;
pt.y = 0;
} else
pt.x = pt.y = 0;
}
pos.x = pt.x; pos.y = pt.y;
gc->choice_popup = GWidgetCreateTopWindow(disp,&pos,popup_eh,gc,&pattrs);
GDrawSetGIC(gc->choice_popup,GWidgetCreateInputContext(gc->choice_popup,gic_overspot|gic_orlesser),
gc->gl.gt.g.inner.x,gc->gl.gt.g.inner.y+gc->gl.gt.as);
GDrawSetVisible(gc->choice_popup,true);
/* Don't grab this one. User should be free to ignore it */
}
static int ucmp(const void *_s1, const void *_s2) {
return( u_strcmp(*(const unichar_t **)_s1,*(const unichar_t **)_s2));
}
#define MAXLINES 30 /* Maximum # entries allowed in popup window */
#define MAXBRACKETS 30 /* Maximum # chars allowed in [] pairs */
static void GTextFieldComplete(GTextField *gt,int from_tab) {
GCompletionField *gc = (GCompletionField *) gt;
unichar_t **ret;
int i, len, orig_len;
unichar_t *pt1, *pt2, ch;
/* If not from_tab, then the textfield has already been changed and we */
/* must mark it as such (but don't mark twice) */
ret = (gc->completion)(>->g,from_tab);
if ( ret==NULL || ret[0]==NULL ) {
if ( from_tab )
GDrawBeep(NULL);
else
GTextFieldChanged(gt,-1);
free(ret);
} else {
orig_len = u_strlen(gt->text);
len = u_strlen(ret[0]);
for ( i=1; ret[i]!=NULL; ++i ) {
for ( pt1=ret[0], pt2=ret[i]; *pt1==*pt2 && pt1-ret[0]<len ; ++pt1, ++pt2 );
len = pt1-ret[0];
}
if ( orig_len!=len ) {
ch = ret[0][len]; ret[0][len] = '\0';
GTextFieldSetTitle(>->g,ret[0]);
ret[0][len] = ch;
if ( !from_tab )
GTextFieldSelect(>->g,orig_len,len);
GTextFieldChanged(gt,-1);
} else if ( !from_tab )
GTextFieldChanged(gt,-1);
if ( ret[1]!=NULL ) {
gc->choices = ret;
gc->selected = -1;
if ( from_tab ) GDrawBeep(NULL);
qsort(ret,i,sizeof(unichar_t *),ucmp);
gc->ctot = i;
if ( i>=MAXLINES ) {
/* Try to shrink the list by just showing initial stubs of the */
/* names with multiple entries with a common next character */
/* So if we have matched against "a" and we have "abc", "abd" "acc" */
/* the show "ab..." and "acc" */
unichar_t **ret2=NULL, last_ch = -1;
int cnt, doit, type2=false;
for ( doit=0; doit<2; ++doit ) {
for ( i=cnt=0; ret[i]!=NULL; ++i ) {
if ( last_ch!=ret[i][len] ) {
if ( doit && type2 ) {
int c2 = cnt/MAXBRACKETS, c3 = cnt%MAXBRACKETS;
if ( ret[i][len]=='\0' )
continue;
if ( c3==0 ) {
ret2[c2] = calloc((len+MAXBRACKETS+2+4+1),sizeof(unichar_t));
memcpy(ret2[c2],ret[i],len*sizeof(unichar_t));
ret2[c2][len] = '[';
}
ret2[c2][len+1+c3] = ret[i][len];
uc_strcpy(ret2[c2]+len+2+c3,"] ...");
} else if ( doit ) {
ret2[cnt] = malloc((u_strlen(ret[i])+5)*sizeof(unichar_t));
u_strcpy(ret2[cnt],ret[i]);
}
++cnt;
last_ch = ret[i][len];
} else if ( doit && !type2 ) {
int j;
for ( j=len+1; ret[i][j]!='\0' && ret[i][j] == ret2[cnt-1][j]; ++j );
uc_strcpy(ret2[cnt-1]+j," ...");
}
}
if ( cnt>=MAXLINES*MAXBRACKETS )
break;
if ( cnt>=MAXLINES && !doit ) {
type2 = (cnt+MAXBRACKETS-1)/MAXBRACKETS;
ret2 = malloc((type2+1)*sizeof(unichar_t *));
} else if ( !doit )
ret2 = malloc((cnt+1)*sizeof(unichar_t *));
else {
if ( type2 )
cnt = type2;
ret2[cnt] = NULL;
}
}
if ( ret2!=NULL ) {
for ( i=0; ret[i]!=NULL; ++i )
free(ret[i]);
free(ret);
ret = gc->choices = ret2;
i = gc->ctot = cnt;
}
}
if ( gc->ctot>=MAXLINES ) {
/* Too many choices. Don't popup a list of them */
gc->choices = NULL;
for ( i=0; ret[i]!=NULL; ++i )
free(ret[i]);
free(ret);
} else {
gc->ctot = i;
GCompletionCreatePopup(gc);
}
} else {
free(ret[1]);
free(ret);
}
}
}
static int GCompletionHandleKey(GTextField *gt,GEvent *event) {
GCompletionField *gc = (GCompletionField *) gt;
int dir = 0;
if ( gc->choice_popup==NULL || event->type == et_charup )
return( false );
if ( event->u.chr.keysym == GK_Up || event->u.chr.keysym == GK_KP_Up )
dir = -1;
else if ( event->u.chr.keysym == GK_Down || event->u.chr.keysym == GK_KP_Down )
dir = 1;
if ( dir==0 || event->u.chr.chars[0]!='\0' ) {
/* For normal characters we destroy the popup window and pretend it */
/* wasn't there */
GCompletionDestroy(gc);
if ( event->u.chr.keysym == GK_Escape )
gt->was_completing = false;
return( event->u.chr.keysym == GK_Escape || /* Eat an escape, other chars will be processed further */
event->u.chr.keysym == GK_Return );
}
if (( gc->selected==-1 && dir==-1 ) || ( gc->selected==gc->ctot-1 && dir==1 ))
return( true );
gc->selected += dir;
if ( gc->selected!=-1 )
GTextFieldSetTitleRmDotDotDot(>->g,gc->choices[gc->selected]);
GTextFieldChanged(gt,-1);
GDrawRequestExpose(gc->choice_popup,NULL,false);
return( true );
}
void GCompletionFieldSetCompletion(GGadget *g,GTextCompletionHandler completion) {
((GCompletionField *) g)->completion = completion;
((GTextField *) g)->accepts_tabs = ((GCompletionField *) g)->completion != NULL;
}
void GCompletionFieldSetCompletionMode(GGadget *g,int enabled) {
((GTextField *) g)->was_completing = enabled;
}
GResInfo *_GTextFieldRIHead(void) {
if ( !gtextfield_inited )
GTextFieldInit();
return( >extfield_ri );
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1050_4 |
crossvul-cpp_data_bad_4897_0 | /* Router advertisement
* Copyright (C) 2005 6WIND <jean-mickael.guerin@6wind.com>
* Copyright (C) 1999 Kunihiro Ishiguro
*
* This file is part of GNU Zebra.
*
* GNU Zebra is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* GNU Zebra is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Zebra; see the file COPYING. If not, write to the Free
* Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include <zebra.h>
#include "memory.h"
#include "sockopt.h"
#include "thread.h"
#include "if.h"
#include "log.h"
#include "prefix.h"
#include "linklist.h"
#include "command.h"
#include "privs.h"
#include "vrf.h"
#include "zebra/interface.h"
#include "zebra/rtadv.h"
#include "zebra/debug.h"
#include "zebra/rib.h"
#include "zebra/zserv.h"
extern struct zebra_privs_t zserv_privs;
#if defined (HAVE_IPV6) && defined (HAVE_RTADV)
#ifdef OPEN_BSD
#include <netinet/icmp6.h>
#endif
/* If RFC2133 definition is used. */
#ifndef IPV6_JOIN_GROUP
#define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP
#endif
#ifndef IPV6_LEAVE_GROUP
#define IPV6_LEAVE_GROUP IPV6_DROP_MEMBERSHIP
#endif
#define ALLNODE "ff02::1"
#define ALLROUTER "ff02::2"
extern struct zebra_t zebrad;
enum rtadv_event {RTADV_START, RTADV_STOP, RTADV_TIMER,
RTADV_TIMER_MSEC, RTADV_READ};
static void rtadv_event (struct zebra_vrf *, enum rtadv_event, int);
static int if_join_all_router (int, struct interface *);
static int if_leave_all_router (int, struct interface *);
static int
rtadv_recv_packet (int sock, u_char *buf, int buflen,
struct sockaddr_in6 *from, ifindex_t *ifindex,
int *hoplimit)
{
int ret;
struct msghdr msg;
struct iovec iov;
struct cmsghdr *cmsgptr;
struct in6_addr dst;
char adata[1024];
/* Fill in message and iovec. */
msg.msg_name = (void *) from;
msg.msg_namelen = sizeof (struct sockaddr_in6);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = (void *) adata;
msg.msg_controllen = sizeof adata;
iov.iov_base = buf;
iov.iov_len = buflen;
/* If recvmsg fail return minus value. */
ret = recvmsg (sock, &msg, 0);
if (ret < 0)
return ret;
for (cmsgptr = ZCMSG_FIRSTHDR(&msg); cmsgptr != NULL;
cmsgptr = CMSG_NXTHDR(&msg, cmsgptr))
{
/* I want interface index which this packet comes from. */
if (cmsgptr->cmsg_level == IPPROTO_IPV6 &&
cmsgptr->cmsg_type == IPV6_PKTINFO)
{
struct in6_pktinfo *ptr;
ptr = (struct in6_pktinfo *) CMSG_DATA (cmsgptr);
*ifindex = ptr->ipi6_ifindex;
memcpy(&dst, &ptr->ipi6_addr, sizeof(ptr->ipi6_addr));
}
/* Incoming packet's hop limit. */
if (cmsgptr->cmsg_level == IPPROTO_IPV6 &&
cmsgptr->cmsg_type == IPV6_HOPLIMIT)
{
int *hoptr = (int *) CMSG_DATA (cmsgptr);
*hoplimit = *hoptr;
}
}
return ret;
}
#define RTADV_MSG_SIZE 4096
/* Send router advertisement packet. */
static void
rtadv_send_packet (int sock, struct interface *ifp)
{
struct msghdr msg;
struct iovec iov;
struct cmsghdr *cmsgptr;
struct in6_pktinfo *pkt;
struct sockaddr_in6 addr;
#ifdef HAVE_STRUCT_SOCKADDR_DL
struct sockaddr_dl *sdl;
#endif /* HAVE_STRUCT_SOCKADDR_DL */
static void *adata = NULL;
unsigned char buf[RTADV_MSG_SIZE];
struct nd_router_advert *rtadv;
int ret;
int len = 0;
struct zebra_if *zif;
struct rtadv_prefix *rprefix;
u_char all_nodes_addr[] = {0xff,0x02,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
struct listnode *node;
u_int16_t pkt_RouterLifetime;
/*
* Allocate control message bufffer. This is dynamic because
* CMSG_SPACE is not guaranteed not to call a function. Note that
* the size will be different on different architectures due to
* differing alignment rules.
*/
if (adata == NULL)
{
/* XXX Free on shutdown. */
adata = malloc(CMSG_SPACE(sizeof(struct in6_pktinfo)));
if (adata == NULL)
zlog_err("rtadv_send_packet: can't malloc control data\n");
}
/* Logging of packet. */
if (IS_ZEBRA_DEBUG_PACKET)
zlog_debug ("Router advertisement send to %s", ifp->name);
/* Fill in sockaddr_in6. */
memset (&addr, 0, sizeof (struct sockaddr_in6));
addr.sin6_family = AF_INET6;
#ifdef SIN6_LEN
addr.sin6_len = sizeof (struct sockaddr_in6);
#endif /* SIN6_LEN */
addr.sin6_port = htons (IPPROTO_ICMPV6);
IPV6_ADDR_COPY (&addr.sin6_addr, all_nodes_addr);
/* Fetch interface information. */
zif = ifp->info;
/* Make router advertisement message. */
rtadv = (struct nd_router_advert *) buf;
rtadv->nd_ra_type = ND_ROUTER_ADVERT;
rtadv->nd_ra_code = 0;
rtadv->nd_ra_cksum = 0;
rtadv->nd_ra_curhoplimit = 64;
/* RFC4191: Default Router Preference is 0 if Router Lifetime is 0. */
rtadv->nd_ra_flags_reserved =
zif->rtadv.AdvDefaultLifetime == 0 ? 0 : zif->rtadv.DefaultPreference;
rtadv->nd_ra_flags_reserved <<= 3;
if (zif->rtadv.AdvManagedFlag)
rtadv->nd_ra_flags_reserved |= ND_RA_FLAG_MANAGED;
if (zif->rtadv.AdvOtherConfigFlag)
rtadv->nd_ra_flags_reserved |= ND_RA_FLAG_OTHER;
if (zif->rtadv.AdvHomeAgentFlag)
rtadv->nd_ra_flags_reserved |= ND_RA_FLAG_HOME_AGENT;
/* Note that according to Neighbor Discovery (RFC 4861 [18]),
* AdvDefaultLifetime is by default based on the value of
* MaxRtrAdvInterval. AdvDefaultLifetime is used in the Router Lifetime
* field of Router Advertisements. Given that this field is expressed
* in seconds, a small MaxRtrAdvInterval value can result in a zero
* value for this field. To prevent this, routers SHOULD keep
* AdvDefaultLifetime in at least one second, even if the use of
* MaxRtrAdvInterval would result in a smaller value. -- RFC6275, 7.5 */
pkt_RouterLifetime = zif->rtadv.AdvDefaultLifetime != -1 ?
zif->rtadv.AdvDefaultLifetime :
MAX (1, 0.003 * zif->rtadv.MaxRtrAdvInterval);
rtadv->nd_ra_router_lifetime = htons (pkt_RouterLifetime);
rtadv->nd_ra_reachable = htonl (zif->rtadv.AdvReachableTime);
rtadv->nd_ra_retransmit = htonl (0);
len = sizeof (struct nd_router_advert);
/* If both the Home Agent Preference and Home Agent Lifetime are set to
* their default values specified above, this option SHOULD NOT be
* included in the Router Advertisement messages sent by this home
* agent. -- RFC6275, 7.4 */
if
(
zif->rtadv.AdvHomeAgentFlag &&
(zif->rtadv.HomeAgentPreference || zif->rtadv.HomeAgentLifetime != -1)
)
{
struct nd_opt_homeagent_info *ndopt_hai =
(struct nd_opt_homeagent_info *)(buf + len);
ndopt_hai->nd_opt_hai_type = ND_OPT_HA_INFORMATION;
ndopt_hai->nd_opt_hai_len = 1;
ndopt_hai->nd_opt_hai_reserved = 0;
ndopt_hai->nd_opt_hai_preference = htons(zif->rtadv.HomeAgentPreference);
/* 16-bit unsigned integer. The lifetime associated with the home
* agent in units of seconds. The default value is the same as the
* Router Lifetime, as specified in the main body of the Router
* Advertisement. The maximum value corresponds to 18.2 hours. A
* value of 0 MUST NOT be used. -- RFC6275, 7.5 */
ndopt_hai->nd_opt_hai_lifetime = htons
(
zif->rtadv.HomeAgentLifetime != -1 ?
zif->rtadv.HomeAgentLifetime :
MAX (1, pkt_RouterLifetime) /* 0 is OK for RL, but not for HAL*/
);
len += sizeof(struct nd_opt_homeagent_info);
}
if (zif->rtadv.AdvIntervalOption)
{
struct nd_opt_adv_interval *ndopt_adv =
(struct nd_opt_adv_interval *)(buf + len);
ndopt_adv->nd_opt_ai_type = ND_OPT_ADV_INTERVAL;
ndopt_adv->nd_opt_ai_len = 1;
ndopt_adv->nd_opt_ai_reserved = 0;
ndopt_adv->nd_opt_ai_interval = htonl(zif->rtadv.MaxRtrAdvInterval);
len += sizeof(struct nd_opt_adv_interval);
}
/* Fill in prefix. */
for (ALL_LIST_ELEMENTS_RO (zif->rtadv.AdvPrefixList, node, rprefix))
{
struct nd_opt_prefix_info *pinfo;
pinfo = (struct nd_opt_prefix_info *) (buf + len);
pinfo->nd_opt_pi_type = ND_OPT_PREFIX_INFORMATION;
pinfo->nd_opt_pi_len = 4;
pinfo->nd_opt_pi_prefix_len = rprefix->prefix.prefixlen;
pinfo->nd_opt_pi_flags_reserved = 0;
if (rprefix->AdvOnLinkFlag)
pinfo->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_ONLINK;
if (rprefix->AdvAutonomousFlag)
pinfo->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_AUTO;
if (rprefix->AdvRouterAddressFlag)
pinfo->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_RADDR;
pinfo->nd_opt_pi_valid_time = htonl (rprefix->AdvValidLifetime);
pinfo->nd_opt_pi_preferred_time = htonl (rprefix->AdvPreferredLifetime);
pinfo->nd_opt_pi_reserved2 = 0;
IPV6_ADDR_COPY (&pinfo->nd_opt_pi_prefix, &rprefix->prefix.prefix);
#ifdef DEBUG
{
u_char buf[INET6_ADDRSTRLEN];
zlog_debug ("DEBUG %s", inet_ntop (AF_INET6, &pinfo->nd_opt_pi_prefix,
buf, INET6_ADDRSTRLEN));
}
#endif /* DEBUG */
len += sizeof (struct nd_opt_prefix_info);
}
/* Hardware address. */
if (ifp->hw_addr_len != 0)
{
buf[len++] = ND_OPT_SOURCE_LINKADDR;
/* Option length should be rounded up to next octet if
the link address does not end on an octet boundary. */
buf[len++] = (ifp->hw_addr_len + 9) >> 3;
memcpy (buf + len, ifp->hw_addr, ifp->hw_addr_len);
len += ifp->hw_addr_len;
/* Pad option to end on an octet boundary. */
memset (buf + len, 0, -(ifp->hw_addr_len + 2) & 0x7);
len += -(ifp->hw_addr_len + 2) & 0x7;
}
/* MTU */
if (zif->rtadv.AdvLinkMTU)
{
struct nd_opt_mtu * opt = (struct nd_opt_mtu *) (buf + len);
opt->nd_opt_mtu_type = ND_OPT_MTU;
opt->nd_opt_mtu_len = 1;
opt->nd_opt_mtu_reserved = 0;
opt->nd_opt_mtu_mtu = htonl (zif->rtadv.AdvLinkMTU);
len += sizeof (struct nd_opt_mtu);
}
msg.msg_name = (void *) &addr;
msg.msg_namelen = sizeof (struct sockaddr_in6);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = (void *) adata;
msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
msg.msg_flags = 0;
iov.iov_base = buf;
iov.iov_len = len;
cmsgptr = ZCMSG_FIRSTHDR(&msg);
cmsgptr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
cmsgptr->cmsg_level = IPPROTO_IPV6;
cmsgptr->cmsg_type = IPV6_PKTINFO;
pkt = (struct in6_pktinfo *) CMSG_DATA (cmsgptr);
memset (&pkt->ipi6_addr, 0, sizeof (struct in6_addr));
pkt->ipi6_ifindex = ifp->ifindex;
ret = sendmsg (sock, &msg, 0);
if (ret < 0)
{
zlog_err ("rtadv_send_packet: sendmsg %d (%s)\n",
errno, safe_strerror(errno));
}
}
static int
rtadv_timer (struct thread *thread)
{
struct zebra_vrf *zvrf = THREAD_ARG (thread);
struct listnode *node, *nnode;
struct interface *ifp;
struct zebra_if *zif;
int period;
zvrf->rtadv.ra_timer = NULL;
if (zvrf->rtadv.adv_msec_if_count == 0)
{
period = 1000; /* 1 s */
rtadv_event (zvrf, RTADV_TIMER, 1 /* 1 s */);
}
else
{
period = 10; /* 10 ms */
rtadv_event (zvrf, RTADV_TIMER_MSEC, 10 /* 10 ms */);
}
for (ALL_LIST_ELEMENTS (vrf_iflist (zvrf->vrf_id), node, nnode, ifp))
{
if (if_is_loopback (ifp) || ! if_is_operative (ifp))
continue;
zif = ifp->info;
if (zif->rtadv.AdvSendAdvertisements)
{
zif->rtadv.AdvIntervalTimer -= period;
if (zif->rtadv.AdvIntervalTimer <= 0)
{
/* FIXME: using MaxRtrAdvInterval each time isn't what section
6.2.4 of RFC4861 tells to do. */
zif->rtadv.AdvIntervalTimer = zif->rtadv.MaxRtrAdvInterval;
rtadv_send_packet (zvrf->rtadv.sock, ifp);
}
}
}
return 0;
}
static void
rtadv_process_solicit (struct interface *ifp)
{
struct zebra_vrf *zvrf = vrf_info_lookup (ifp->vrf_id);
zlog_info ("Router solicitation received on %s vrf %u", ifp->name, zvrf->vrf_id);
rtadv_send_packet (zvrf->rtadv.sock, ifp);
}
static void
rtadv_process_advert (void)
{
zlog_info ("Router advertisement received");
}
static void
rtadv_process_packet (u_char *buf, unsigned int len, ifindex_t ifindex,
int hoplimit, vrf_id_t vrf_id)
{
struct icmp6_hdr *icmph;
struct interface *ifp;
struct zebra_if *zif;
/* Interface search. */
ifp = if_lookup_by_index_vrf (ifindex, vrf_id);
if (ifp == NULL)
{
zlog_warn ("Unknown interface index: %d, vrf %u", ifindex, vrf_id);
return;
}
if (if_is_loopback (ifp))
return;
/* Check interface configuration. */
zif = ifp->info;
if (! zif->rtadv.AdvSendAdvertisements)
return;
/* ICMP message length check. */
if (len < sizeof (struct icmp6_hdr))
{
zlog_warn ("Invalid ICMPV6 packet length: %d", len);
return;
}
icmph = (struct icmp6_hdr *) buf;
/* ICMP message type check. */
if (icmph->icmp6_type != ND_ROUTER_SOLICIT &&
icmph->icmp6_type != ND_ROUTER_ADVERT)
{
zlog_warn ("Unwanted ICMPV6 message type: %d", icmph->icmp6_type);
return;
}
/* Hoplimit check. */
if (hoplimit >= 0 && hoplimit != 255)
{
zlog_warn ("Invalid hoplimit %d for router advertisement ICMP packet",
hoplimit);
return;
}
/* Check ICMP message type. */
if (icmph->icmp6_type == ND_ROUTER_SOLICIT)
rtadv_process_solicit (ifp);
else if (icmph->icmp6_type == ND_ROUTER_ADVERT)
rtadv_process_advert ();
return;
}
static int
rtadv_read (struct thread *thread)
{
int sock;
int len;
u_char buf[RTADV_MSG_SIZE];
struct sockaddr_in6 from;
ifindex_t ifindex = 0;
int hoplimit = -1;
struct zebra_vrf *zvrf = THREAD_ARG (thread);
sock = THREAD_FD (thread);
zvrf->rtadv.ra_read = NULL;
/* Register myself. */
rtadv_event (zvrf, RTADV_READ, sock);
len = rtadv_recv_packet (sock, buf, BUFSIZ, &from, &ifindex, &hoplimit);
if (len < 0)
{
zlog_warn ("router solicitation recv failed: %s.", safe_strerror (errno));
return len;
}
rtadv_process_packet (buf, (unsigned)len, ifindex, hoplimit, zvrf->vrf_id);
return 0;
}
static int
rtadv_make_socket (vrf_id_t vrf_id)
{
int sock;
int ret;
struct icmp6_filter filter;
if ( zserv_privs.change (ZPRIVS_RAISE) )
zlog_err ("rtadv_make_socket: could not raise privs, %s",
safe_strerror (errno) );
sock = vrf_socket (AF_INET6, SOCK_RAW, IPPROTO_ICMPV6, vrf_id);
if ( zserv_privs.change (ZPRIVS_LOWER) )
zlog_err ("rtadv_make_socket: could not lower privs, %s",
safe_strerror (errno) );
/* When we can't make ICMPV6 socket simply back. Router
advertisement feature will not be supported. */
if (sock < 0)
{
close (sock);
return -1;
}
ret = setsockopt_ipv6_pktinfo (sock, 1);
if (ret < 0)
{
close (sock);
return ret;
}
ret = setsockopt_ipv6_multicast_loop (sock, 0);
if (ret < 0)
{
close (sock);
return ret;
}
ret = setsockopt_ipv6_unicast_hops (sock, 255);
if (ret < 0)
{
close (sock);
return ret;
}
ret = setsockopt_ipv6_multicast_hops (sock, 255);
if (ret < 0)
{
close (sock);
return ret;
}
ret = setsockopt_ipv6_hoplimit (sock, 1);
if (ret < 0)
{
close (sock);
return ret;
}
ICMP6_FILTER_SETBLOCKALL(&filter);
ICMP6_FILTER_SETPASS (ND_ROUTER_SOLICIT, &filter);
ICMP6_FILTER_SETPASS (ND_ROUTER_ADVERT, &filter);
ret = setsockopt (sock, IPPROTO_ICMPV6, ICMP6_FILTER, &filter,
sizeof (struct icmp6_filter));
if (ret < 0)
{
zlog_info ("ICMP6_FILTER set fail: %s", safe_strerror (errno));
return ret;
}
return sock;
}
static struct rtadv_prefix *
rtadv_prefix_new (void)
{
return XCALLOC (MTYPE_RTADV_PREFIX, sizeof (struct rtadv_prefix));
}
static void
rtadv_prefix_free (struct rtadv_prefix *rtadv_prefix)
{
XFREE (MTYPE_RTADV_PREFIX, rtadv_prefix);
}
static struct rtadv_prefix *
rtadv_prefix_lookup (struct list *rplist, struct prefix_ipv6 *p)
{
struct listnode *node;
struct rtadv_prefix *rprefix;
for (ALL_LIST_ELEMENTS_RO (rplist, node, rprefix))
if (prefix_same ((struct prefix *) &rprefix->prefix, (struct prefix *) p))
return rprefix;
return NULL;
}
static struct rtadv_prefix *
rtadv_prefix_get (struct list *rplist, struct prefix_ipv6 *p)
{
struct rtadv_prefix *rprefix;
rprefix = rtadv_prefix_lookup (rplist, p);
if (rprefix)
return rprefix;
rprefix = rtadv_prefix_new ();
memcpy (&rprefix->prefix, p, sizeof (struct prefix_ipv6));
listnode_add (rplist, rprefix);
return rprefix;
}
static void
rtadv_prefix_set (struct zebra_if *zif, struct rtadv_prefix *rp)
{
struct rtadv_prefix *rprefix;
rprefix = rtadv_prefix_get (zif->rtadv.AdvPrefixList, &rp->prefix);
/* Set parameters. */
rprefix->AdvValidLifetime = rp->AdvValidLifetime;
rprefix->AdvPreferredLifetime = rp->AdvPreferredLifetime;
rprefix->AdvOnLinkFlag = rp->AdvOnLinkFlag;
rprefix->AdvAutonomousFlag = rp->AdvAutonomousFlag;
rprefix->AdvRouterAddressFlag = rp->AdvRouterAddressFlag;
}
static int
rtadv_prefix_reset (struct zebra_if *zif, struct rtadv_prefix *rp)
{
struct rtadv_prefix *rprefix;
rprefix = rtadv_prefix_lookup (zif->rtadv.AdvPrefixList, &rp->prefix);
if (rprefix != NULL)
{
listnode_delete (zif->rtadv.AdvPrefixList, (void *) rprefix);
rtadv_prefix_free (rprefix);
return 1;
}
else
return 0;
}
DEFUN (ipv6_nd_suppress_ra,
ipv6_nd_suppress_ra_cmd,
"ipv6 nd suppress-ra",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Suppress Router Advertisement\n")
{
struct interface *ifp;
struct zebra_if *zif;
struct zebra_vrf *zvrf;
ifp = vty->index;
zif = ifp->info;
zvrf = vrf_info_lookup (ifp->vrf_id);
if (if_is_loopback (ifp))
{
vty_out (vty, "Invalid interface%s", VTY_NEWLINE);
return CMD_WARNING;
}
if (zif->rtadv.AdvSendAdvertisements)
{
zif->rtadv.AdvSendAdvertisements = 0;
zif->rtadv.AdvIntervalTimer = 0;
zvrf->rtadv.adv_if_count--;
if_leave_all_router (zvrf->rtadv.sock, ifp);
if (zvrf->rtadv.adv_if_count == 0)
rtadv_event (zvrf, RTADV_STOP, 0);
}
return CMD_SUCCESS;
}
DEFUN (no_ipv6_nd_suppress_ra,
no_ipv6_nd_suppress_ra_cmd,
"no ipv6 nd suppress-ra",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Suppress Router Advertisement\n")
{
struct interface *ifp;
struct zebra_if *zif;
struct zebra_vrf *zvrf;
ifp = vty->index;
zif = ifp->info;
zvrf = vrf_info_lookup (ifp->vrf_id);
if (if_is_loopback (ifp))
{
vty_out (vty, "Invalid interface%s", VTY_NEWLINE);
return CMD_WARNING;
}
if (! zif->rtadv.AdvSendAdvertisements)
{
zif->rtadv.AdvSendAdvertisements = 1;
zif->rtadv.AdvIntervalTimer = 0;
zvrf->rtadv.adv_if_count++;
if_join_all_router (zvrf->rtadv.sock, ifp);
if (zvrf->rtadv.adv_if_count == 1)
rtadv_event (zvrf, RTADV_START, zvrf->rtadv.sock);
}
return CMD_SUCCESS;
}
DEFUN (ipv6_nd_ra_interval_msec,
ipv6_nd_ra_interval_msec_cmd,
"ipv6 nd ra-interval msec <70-1800000>",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Router Advertisement interval\n"
"Router Advertisement interval in milliseconds\n")
{
unsigned interval;
struct interface *ifp = (struct interface *) vty->index;
struct zebra_if *zif = ifp->info;
struct zebra_vrf *zvrf = vrf_info_lookup (ifp->vrf_id);
VTY_GET_INTEGER_RANGE ("router advertisement interval", interval, argv[0], 70, 1800000);
if ((zif->rtadv.AdvDefaultLifetime != -1 && interval > (unsigned)zif->rtadv.AdvDefaultLifetime * 1000))
{
vty_out (vty, "This ra-interval would conflict with configured ra-lifetime!%s", VTY_NEWLINE);
return CMD_WARNING;
}
if (zif->rtadv.MaxRtrAdvInterval % 1000)
zvrf->rtadv.adv_msec_if_count--;
if (interval % 1000)
zvrf->rtadv.adv_msec_if_count++;
zif->rtadv.MaxRtrAdvInterval = interval;
zif->rtadv.MinRtrAdvInterval = 0.33 * interval;
zif->rtadv.AdvIntervalTimer = 0;
return CMD_SUCCESS;
}
DEFUN (ipv6_nd_ra_interval,
ipv6_nd_ra_interval_cmd,
"ipv6 nd ra-interval <1-1800>",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Router Advertisement interval\n"
"Router Advertisement interval in seconds\n")
{
unsigned interval;
struct interface *ifp = (struct interface *) vty->index;
struct zebra_if *zif = ifp->info;
struct zebra_vrf *zvrf = vrf_info_lookup (ifp->vrf_id);
VTY_GET_INTEGER_RANGE ("router advertisement interval", interval, argv[0], 1, 1800);
if ((zif->rtadv.AdvDefaultLifetime != -1 && interval > (unsigned)zif->rtadv.AdvDefaultLifetime))
{
vty_out (vty, "This ra-interval would conflict with configured ra-lifetime!%s", VTY_NEWLINE);
return CMD_WARNING;
}
if (zif->rtadv.MaxRtrAdvInterval % 1000)
zvrf->rtadv.adv_msec_if_count--;
/* convert to milliseconds */
interval = interval * 1000;
zif->rtadv.MaxRtrAdvInterval = interval;
zif->rtadv.MinRtrAdvInterval = 0.33 * interval;
zif->rtadv.AdvIntervalTimer = 0;
return CMD_SUCCESS;
}
DEFUN (no_ipv6_nd_ra_interval,
no_ipv6_nd_ra_interval_cmd,
"no ipv6 nd ra-interval",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Router Advertisement interval\n")
{
struct interface *ifp;
struct zebra_if *zif;
struct zebra_vrf *zvrf;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zvrf = vrf_info_lookup (ifp->vrf_id);
if (zif->rtadv.MaxRtrAdvInterval % 1000)
zvrf->rtadv.adv_msec_if_count--;
zif->rtadv.MaxRtrAdvInterval = RTADV_MAX_RTR_ADV_INTERVAL;
zif->rtadv.MinRtrAdvInterval = RTADV_MIN_RTR_ADV_INTERVAL;
zif->rtadv.AdvIntervalTimer = zif->rtadv.MaxRtrAdvInterval;
return CMD_SUCCESS;
}
ALIAS (no_ipv6_nd_ra_interval,
no_ipv6_nd_ra_interval_val_cmd,
"no ipv6 nd ra-interval <1-1800>",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Router Advertisement interval\n")
ALIAS (no_ipv6_nd_ra_interval,
no_ipv6_nd_ra_interval_msec_val_cmd,
"no ipv6 nd ra-interval msec <1-1800000>",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Router Advertisement interval\n"
"Router Advertisement interval in milliseconds\n")
DEFUN (ipv6_nd_ra_lifetime,
ipv6_nd_ra_lifetime_cmd,
"ipv6 nd ra-lifetime <0-9000>",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Router lifetime\n"
"Router lifetime in seconds (0 stands for a non-default gw)\n")
{
int lifetime;
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
VTY_GET_INTEGER_RANGE ("router lifetime", lifetime, argv[0], 0, 9000);
/* The value to be placed in the Router Lifetime field
* of Router Advertisements sent from the interface,
* in seconds. MUST be either zero or between
* MaxRtrAdvInterval and 9000 seconds. -- RFC4861, 6.2.1 */
if ((lifetime != 0 && lifetime * 1000 < zif->rtadv.MaxRtrAdvInterval))
{
vty_out (vty, "This ra-lifetime would conflict with configured ra-interval%s", VTY_NEWLINE);
return CMD_WARNING;
}
zif->rtadv.AdvDefaultLifetime = lifetime;
return CMD_SUCCESS;
}
DEFUN (no_ipv6_nd_ra_lifetime,
no_ipv6_nd_ra_lifetime_cmd,
"no ipv6 nd ra-lifetime",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Router lifetime\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.AdvDefaultLifetime = -1;
return CMD_SUCCESS;
}
ALIAS (no_ipv6_nd_ra_lifetime,
no_ipv6_nd_ra_lifetime_val_cmd,
"no ipv6 nd ra-lifetime <0-9000>",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Router lifetime\n"
"Router lifetime in seconds (0 stands for a non-default gw)\n")
DEFUN (ipv6_nd_reachable_time,
ipv6_nd_reachable_time_cmd,
"ipv6 nd reachable-time <1-3600000>",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Reachable time\n"
"Reachable time in milliseconds\n")
{
struct interface *ifp = (struct interface *) vty->index;
struct zebra_if *zif = ifp->info;
VTY_GET_INTEGER_RANGE ("reachable time", zif->rtadv.AdvReachableTime, argv[0], 1, RTADV_MAX_REACHABLE_TIME);
return CMD_SUCCESS;
}
DEFUN (no_ipv6_nd_reachable_time,
no_ipv6_nd_reachable_time_cmd,
"no ipv6 nd reachable-time",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Reachable time\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.AdvReachableTime = 0;
return CMD_SUCCESS;
}
ALIAS (no_ipv6_nd_reachable_time,
no_ipv6_nd_reachable_time_val_cmd,
"no ipv6 nd reachable-time <1-3600000>",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Reachable time\n"
"Reachable time in milliseconds\n")
DEFUN (ipv6_nd_homeagent_preference,
ipv6_nd_homeagent_preference_cmd,
"ipv6 nd home-agent-preference <0-65535>",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Home Agent preference\n"
"preference value (default is 0, least preferred)\n")
{
struct interface *ifp = (struct interface *) vty->index;
struct zebra_if *zif = ifp->info;
VTY_GET_INTEGER_RANGE ("home agent preference", zif->rtadv.HomeAgentPreference, argv[0], 0, 65535);
return CMD_SUCCESS;
}
DEFUN (no_ipv6_nd_homeagent_preference,
no_ipv6_nd_homeagent_preference_cmd,
"no ipv6 nd home-agent-preference",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Home Agent preference\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.HomeAgentPreference = 0;
return CMD_SUCCESS;
}
ALIAS (no_ipv6_nd_homeagent_preference,
no_ipv6_nd_homeagent_preference_val_cmd,
"no ipv6 nd home-agent-preference <0-65535>",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Home Agent preference\n"
"preference value (default is 0, least preferred)\n")
DEFUN (ipv6_nd_homeagent_lifetime,
ipv6_nd_homeagent_lifetime_cmd,
"ipv6 nd home-agent-lifetime <0-65520>",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Home Agent lifetime\n"
"Home Agent lifetime in seconds (0 to track ra-lifetime)\n")
{
struct interface *ifp = (struct interface *) vty->index;
struct zebra_if *zif = ifp->info;
VTY_GET_INTEGER_RANGE ("home agent lifetime", zif->rtadv.HomeAgentLifetime, argv[0], 0, RTADV_MAX_HALIFETIME);
return CMD_SUCCESS;
}
DEFUN (no_ipv6_nd_homeagent_lifetime,
no_ipv6_nd_homeagent_lifetime_cmd,
"no ipv6 nd home-agent-lifetime",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Home Agent lifetime\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.HomeAgentLifetime = -1;
return CMD_SUCCESS;
}
ALIAS (no_ipv6_nd_homeagent_lifetime,
no_ipv6_nd_homeagent_lifetime_val_cmd,
"no ipv6 nd home-agent-lifetime <0-65520>",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Home Agent lifetime\n"
"Home Agent lifetime in seconds (0 to track ra-lifetime)\n")
DEFUN (ipv6_nd_managed_config_flag,
ipv6_nd_managed_config_flag_cmd,
"ipv6 nd managed-config-flag",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Managed address configuration flag\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.AdvManagedFlag = 1;
return CMD_SUCCESS;
}
DEFUN (no_ipv6_nd_managed_config_flag,
no_ipv6_nd_managed_config_flag_cmd,
"no ipv6 nd managed-config-flag",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Managed address configuration flag\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.AdvManagedFlag = 0;
return CMD_SUCCESS;
}
DEFUN (ipv6_nd_homeagent_config_flag,
ipv6_nd_homeagent_config_flag_cmd,
"ipv6 nd home-agent-config-flag",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Home Agent configuration flag\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.AdvHomeAgentFlag = 1;
return CMD_SUCCESS;
}
DEFUN (no_ipv6_nd_homeagent_config_flag,
no_ipv6_nd_homeagent_config_flag_cmd,
"no ipv6 nd home-agent-config-flag",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Home Agent configuration flag\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.AdvHomeAgentFlag = 0;
return CMD_SUCCESS;
}
DEFUN (ipv6_nd_adv_interval_config_option,
ipv6_nd_adv_interval_config_option_cmd,
"ipv6 nd adv-interval-option",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Advertisement Interval Option\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.AdvIntervalOption = 1;
return CMD_SUCCESS;
}
DEFUN (no_ipv6_nd_adv_interval_config_option,
no_ipv6_nd_adv_interval_config_option_cmd,
"no ipv6 nd adv-interval-option",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Advertisement Interval Option\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.AdvIntervalOption = 0;
return CMD_SUCCESS;
}
DEFUN (ipv6_nd_other_config_flag,
ipv6_nd_other_config_flag_cmd,
"ipv6 nd other-config-flag",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Other statefull configuration flag\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.AdvOtherConfigFlag = 1;
return CMD_SUCCESS;
}
DEFUN (no_ipv6_nd_other_config_flag,
no_ipv6_nd_other_config_flag_cmd,
"no ipv6 nd other-config-flag",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Other statefull configuration flag\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.AdvOtherConfigFlag = 0;
return CMD_SUCCESS;
}
DEFUN (ipv6_nd_prefix,
ipv6_nd_prefix_cmd,
"ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) "
"(<0-4294967295>|infinite) (off-link|) (no-autoconfig|) (router-address|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Valid lifetime in seconds\n"
"Infinite valid lifetime\n"
"Preferred lifetime in seconds\n"
"Infinite preferred lifetime\n"
"Do not use prefix for onlink determination\n"
"Do not use prefix for autoconfiguration\n"
"Set Router Address flag\n")
{
int i;
int ret;
int cursor = 1;
struct interface *ifp;
struct zebra_if *zebra_if;
struct rtadv_prefix rp;
ifp = (struct interface *) vty->index;
zebra_if = ifp->info;
ret = str2prefix_ipv6 (argv[0], &rp.prefix);
if (!ret)
{
vty_out (vty, "Malformed IPv6 prefix%s", VTY_NEWLINE);
return CMD_WARNING;
}
apply_mask_ipv6 (&rp.prefix); /* RFC4861 4.6.2 */
rp.AdvOnLinkFlag = 1;
rp.AdvAutonomousFlag = 1;
rp.AdvRouterAddressFlag = 0;
rp.AdvValidLifetime = RTADV_VALID_LIFETIME;
rp.AdvPreferredLifetime = RTADV_PREFERRED_LIFETIME;
if (argc > 1)
{
if ((isdigit((unsigned char)argv[1][0]))
|| strncmp (argv[1], "i", 1) == 0)
{
if ( strncmp (argv[1], "i", 1) == 0)
rp.AdvValidLifetime = UINT32_MAX;
else
rp.AdvValidLifetime = (u_int32_t) strtoll (argv[1],
(char **)NULL, 10);
if ( strncmp (argv[2], "i", 1) == 0)
rp.AdvPreferredLifetime = UINT32_MAX;
else
rp.AdvPreferredLifetime = (u_int32_t) strtoll (argv[2],
(char **)NULL, 10);
if (rp.AdvPreferredLifetime > rp.AdvValidLifetime)
{
vty_out (vty, "Invalid preferred lifetime%s", VTY_NEWLINE);
return CMD_WARNING;
}
cursor = cursor + 2;
}
if (argc > cursor)
{
for (i = cursor; i < argc; i++)
{
if (strncmp (argv[i], "of", 2) == 0)
rp.AdvOnLinkFlag = 0;
if (strncmp (argv[i], "no", 2) == 0)
rp.AdvAutonomousFlag = 0;
if (strncmp (argv[i], "ro", 2) == 0)
rp.AdvRouterAddressFlag = 1;
}
}
}
rtadv_prefix_set (zebra_if, &rp);
return CMD_SUCCESS;
}
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_val_nortaddr_cmd,
"ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) "
"(<0-4294967295>|infinite) (off-link|) (no-autoconfig|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Valid lifetime in seconds\n"
"Infinite valid lifetime\n"
"Preferred lifetime in seconds\n"
"Infinite preferred lifetime\n"
"Do not use prefix for onlink determination\n"
"Do not use prefix for autoconfiguration\n")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_val_rev_cmd,
"ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) "
"(<0-4294967295>|infinite) (no-autoconfig|) (off-link|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Valid lifetime in seconds\n"
"Infinite valid lifetime\n"
"Preferred lifetime in seconds\n"
"Infinite preferred lifetime\n"
"Do not use prefix for autoconfiguration\n"
"Do not use prefix for onlink determination\n")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_val_rev_rtaddr_cmd,
"ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) "
"(<0-4294967295>|infinite) (no-autoconfig|) (off-link|) (router-address|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Valid lifetime in seconds\n"
"Infinite valid lifetime\n"
"Preferred lifetime in seconds\n"
"Infinite preferred lifetime\n"
"Do not use prefix for autoconfiguration\n"
"Do not use prefix for onlink determination\n"
"Set Router Address flag\n")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_val_noauto_cmd,
"ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) "
"(<0-4294967295>|infinite) (no-autoconfig|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Valid lifetime in seconds\n"
"Infinite valid lifetime\n"
"Preferred lifetime in seconds\n"
"Infinite preferred lifetime\n"
"Do not use prefix for autoconfiguration")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_val_offlink_cmd,
"ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) "
"(<0-4294967295>|infinite) (off-link|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Valid lifetime in seconds\n"
"Infinite valid lifetime\n"
"Preferred lifetime in seconds\n"
"Infinite preferred lifetime\n"
"Do not use prefix for onlink determination\n")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_val_rtaddr_cmd,
"ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) "
"(<0-4294967295>|infinite) (router-address|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Valid lifetime in seconds\n"
"Infinite valid lifetime\n"
"Preferred lifetime in seconds\n"
"Infinite preferred lifetime\n"
"Set Router Address flag\n")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_val_cmd,
"ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) "
"(<0-4294967295>|infinite)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Valid lifetime in seconds\n"
"Infinite valid lifetime\n"
"Preferred lifetime in seconds\n"
"Infinite preferred lifetime\n")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_noval_cmd,
"ipv6 nd prefix X:X::X:X/M (no-autoconfig|) (off-link|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Do not use prefix for autoconfiguration\n"
"Do not use prefix for onlink determination\n")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_noval_rev_cmd,
"ipv6 nd prefix X:X::X:X/M (off-link|) (no-autoconfig|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Do not use prefix for onlink determination\n"
"Do not use prefix for autoconfiguration\n")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_noval_noauto_cmd,
"ipv6 nd prefix X:X::X:X/M (no-autoconfig|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Do not use prefix for autoconfiguration\n")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_noval_offlink_cmd,
"ipv6 nd prefix X:X::X:X/M (off-link|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Do not use prefix for onlink determination\n")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_noval_rtaddr_cmd,
"ipv6 nd prefix X:X::X:X/M (router-address|)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n"
"Set Router Address flag\n")
ALIAS (ipv6_nd_prefix,
ipv6_nd_prefix_prefix_cmd,
"ipv6 nd prefix X:X::X:X/M",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n")
DEFUN (no_ipv6_nd_prefix,
no_ipv6_nd_prefix_cmd,
"no ipv6 nd prefix IPV6PREFIX",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Prefix information\n"
"IPv6 prefix\n")
{
int ret;
struct interface *ifp;
struct zebra_if *zebra_if;
struct rtadv_prefix rp;
ifp = (struct interface *) vty->index;
zebra_if = ifp->info;
ret = str2prefix_ipv6 (argv[0], &rp.prefix);
if (!ret)
{
vty_out (vty, "Malformed IPv6 prefix%s", VTY_NEWLINE);
return CMD_WARNING;
}
apply_mask_ipv6 (&rp.prefix); /* RFC4861 4.6.2 */
ret = rtadv_prefix_reset (zebra_if, &rp);
if (!ret)
{
vty_out (vty, "Non-exist IPv6 prefix%s", VTY_NEWLINE);
return CMD_WARNING;
}
return CMD_SUCCESS;
}
DEFUN (ipv6_nd_router_preference,
ipv6_nd_router_preference_cmd,
"ipv6 nd router-preference (high|medium|low)",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Default router preference\n"
"High default router preference\n"
"Low default router preference\n"
"Medium default router preference (default)\n")
{
struct interface *ifp;
struct zebra_if *zif;
int i = 0;
ifp = (struct interface *) vty->index;
zif = ifp->info;
while (0 != rtadv_pref_strs[i])
{
if (strncmp (argv[0], rtadv_pref_strs[i], 1) == 0)
{
zif->rtadv.DefaultPreference = i;
return CMD_SUCCESS;
}
i++;
}
return CMD_ERR_NO_MATCH;
}
DEFUN (no_ipv6_nd_router_preference,
no_ipv6_nd_router_preference_cmd,
"no ipv6 nd router-preference",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Default router preference\n")
{
struct interface *ifp;
struct zebra_if *zif;
ifp = (struct interface *) vty->index;
zif = ifp->info;
zif->rtadv.DefaultPreference = RTADV_PREF_MEDIUM; /* Default per RFC4191. */
return CMD_SUCCESS;
}
ALIAS (no_ipv6_nd_router_preference,
no_ipv6_nd_router_preference_val_cmd,
"no ipv6 nd router-preference (high|medium|low)",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Default router preference\n"
"High default router preference\n"
"Low default router preference\n"
"Medium default router preference (default)\n")
DEFUN (ipv6_nd_mtu,
ipv6_nd_mtu_cmd,
"ipv6 nd mtu <1-65535>",
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Advertised MTU\n"
"MTU in bytes\n")
{
struct interface *ifp = (struct interface *) vty->index;
struct zebra_if *zif = ifp->info;
VTY_GET_INTEGER_RANGE ("MTU", zif->rtadv.AdvLinkMTU, argv[0], 1, 65535);
return CMD_SUCCESS;
}
DEFUN (no_ipv6_nd_mtu,
no_ipv6_nd_mtu_cmd,
"no ipv6 nd mtu",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Advertised MTU\n")
{
struct interface *ifp = (struct interface *) vty->index;
struct zebra_if *zif = ifp->info;
zif->rtadv.AdvLinkMTU = 0;
return CMD_SUCCESS;
}
ALIAS (no_ipv6_nd_mtu,
no_ipv6_nd_mtu_val_cmd,
"no ipv6 nd mtu <1-65535>",
NO_STR
"Interface IPv6 config commands\n"
"Neighbor discovery\n"
"Advertised MTU\n"
"MTU in bytes\n")
/* Write configuration about router advertisement. */
void
rtadv_config_write (struct vty *vty, struct interface *ifp)
{
struct zebra_if *zif;
struct listnode *node;
struct rtadv_prefix *rprefix;
char buf[PREFIX_STRLEN];
int interval;
zif = ifp->info;
if (! if_is_loopback (ifp))
{
if (zif->rtadv.AdvSendAdvertisements)
vty_out (vty, " no ipv6 nd suppress-ra%s", VTY_NEWLINE);
}
interval = zif->rtadv.MaxRtrAdvInterval;
if (interval % 1000)
vty_out (vty, " ipv6 nd ra-interval msec %d%s", interval,
VTY_NEWLINE);
else
if (interval != RTADV_MAX_RTR_ADV_INTERVAL)
vty_out (vty, " ipv6 nd ra-interval %d%s", interval / 1000,
VTY_NEWLINE);
if (zif->rtadv.AdvIntervalOption)
vty_out (vty, " ipv6 nd adv-interval-option%s", VTY_NEWLINE);
if (zif->rtadv.AdvDefaultLifetime != -1)
vty_out (vty, " ipv6 nd ra-lifetime %d%s", zif->rtadv.AdvDefaultLifetime,
VTY_NEWLINE);
if (zif->rtadv.HomeAgentPreference)
vty_out (vty, " ipv6 nd home-agent-preference %u%s",
zif->rtadv.HomeAgentPreference, VTY_NEWLINE);
if (zif->rtadv.HomeAgentLifetime != -1)
vty_out (vty, " ipv6 nd home-agent-lifetime %u%s",
zif->rtadv.HomeAgentLifetime, VTY_NEWLINE);
if (zif->rtadv.AdvHomeAgentFlag)
vty_out (vty, " ipv6 nd home-agent-config-flag%s", VTY_NEWLINE);
if (zif->rtadv.AdvReachableTime)
vty_out (vty, " ipv6 nd reachable-time %d%s", zif->rtadv.AdvReachableTime,
VTY_NEWLINE);
if (zif->rtadv.AdvManagedFlag)
vty_out (vty, " ipv6 nd managed-config-flag%s", VTY_NEWLINE);
if (zif->rtadv.AdvOtherConfigFlag)
vty_out (vty, " ipv6 nd other-config-flag%s", VTY_NEWLINE);
if (zif->rtadv.DefaultPreference != RTADV_PREF_MEDIUM)
vty_out (vty, " ipv6 nd router-preference %s%s",
rtadv_pref_strs[zif->rtadv.DefaultPreference],
VTY_NEWLINE);
if (zif->rtadv.AdvLinkMTU)
vty_out (vty, " ipv6 nd mtu %d%s", zif->rtadv.AdvLinkMTU, VTY_NEWLINE);
for (ALL_LIST_ELEMENTS_RO (zif->rtadv.AdvPrefixList, node, rprefix))
{
vty_out (vty, " ipv6 nd prefix %s",
prefix2str (&rprefix->prefix, buf, sizeof(buf)));
if ((rprefix->AdvValidLifetime != RTADV_VALID_LIFETIME) ||
(rprefix->AdvPreferredLifetime != RTADV_PREFERRED_LIFETIME))
{
if (rprefix->AdvValidLifetime == UINT32_MAX)
vty_out (vty, " infinite");
else
vty_out (vty, " %u", rprefix->AdvValidLifetime);
if (rprefix->AdvPreferredLifetime == UINT32_MAX)
vty_out (vty, " infinite");
else
vty_out (vty, " %u", rprefix->AdvPreferredLifetime);
}
if (!rprefix->AdvOnLinkFlag)
vty_out (vty, " off-link");
if (!rprefix->AdvAutonomousFlag)
vty_out (vty, " no-autoconfig");
if (rprefix->AdvRouterAddressFlag)
vty_out (vty, " router-address");
vty_out (vty, "%s", VTY_NEWLINE);
}
}
static void
rtadv_event (struct zebra_vrf *zvrf, enum rtadv_event event, int val)
{
struct rtadv *rtadv = &zvrf->rtadv;
switch (event)
{
case RTADV_START:
if (! rtadv->ra_read)
rtadv->ra_read = thread_add_read (zebrad.master, rtadv_read, zvrf, val);
if (! rtadv->ra_timer)
rtadv->ra_timer = thread_add_event (zebrad.master, rtadv_timer,
zvrf, 0);
break;
case RTADV_STOP:
if (rtadv->ra_timer)
{
thread_cancel (rtadv->ra_timer);
rtadv->ra_timer = NULL;
}
if (rtadv->ra_read)
{
thread_cancel (rtadv->ra_read);
rtadv->ra_read = NULL;
}
break;
case RTADV_TIMER:
if (! rtadv->ra_timer)
rtadv->ra_timer = thread_add_timer (zebrad.master, rtadv_timer, zvrf,
val);
break;
case RTADV_TIMER_MSEC:
if (! rtadv->ra_timer)
rtadv->ra_timer = thread_add_timer_msec (zebrad.master, rtadv_timer,
zvrf, val);
break;
case RTADV_READ:
if (! rtadv->ra_read)
rtadv->ra_read = thread_add_read (zebrad.master, rtadv_read, zvrf, val);
break;
default:
break;
}
return;
}
void
rtadv_init (struct zebra_vrf *zvrf)
{
zvrf->rtadv.sock = rtadv_make_socket (zvrf->vrf_id);
}
void
rtadv_terminate (struct zebra_vrf *zvrf)
{
rtadv_event (zvrf, RTADV_STOP, 0);
if (zvrf->rtadv.sock >= 0)
{
close (zvrf->rtadv.sock);
zvrf->rtadv.sock = -1;
}
zvrf->rtadv.adv_if_count = 0;
zvrf->rtadv.adv_msec_if_count = 0;
}
void
rtadv_cmd_init (void)
{
install_element (INTERFACE_NODE, &ipv6_nd_suppress_ra_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_suppress_ra_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_ra_interval_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_ra_interval_msec_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_ra_interval_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_ra_interval_val_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_ra_interval_msec_val_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_ra_lifetime_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_ra_lifetime_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_ra_lifetime_val_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_reachable_time_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_reachable_time_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_reachable_time_val_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_managed_config_flag_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_managed_config_flag_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_other_config_flag_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_other_config_flag_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_homeagent_config_flag_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_homeagent_config_flag_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_homeagent_preference_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_homeagent_preference_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_homeagent_preference_val_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_homeagent_lifetime_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_homeagent_lifetime_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_homeagent_lifetime_val_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_adv_interval_config_option_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_adv_interval_config_option_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_rev_rtaddr_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_nortaddr_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_rev_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_noauto_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_offlink_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_rtaddr_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_noval_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_noval_rev_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_noval_noauto_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_noval_offlink_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_noval_rtaddr_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_prefix_prefix_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_prefix_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_router_preference_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_router_preference_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_router_preference_val_cmd);
install_element (INTERFACE_NODE, &ipv6_nd_mtu_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_mtu_cmd);
install_element (INTERFACE_NODE, &no_ipv6_nd_mtu_val_cmd);
}
static int
if_join_all_router (int sock, struct interface *ifp)
{
int ret;
struct ipv6_mreq mreq;
memset (&mreq, 0, sizeof (struct ipv6_mreq));
inet_pton (AF_INET6, ALLROUTER, &mreq.ipv6mr_multiaddr);
mreq.ipv6mr_interface = ifp->ifindex;
ret = setsockopt (sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
(char *) &mreq, sizeof mreq);
if (ret < 0)
zlog_warn ("can't setsockopt IPV6_JOIN_GROUP: %s", safe_strerror (errno));
zlog_info ("rtadv: %s join to all-routers multicast group", ifp->name);
return 0;
}
static int
if_leave_all_router (int sock, struct interface *ifp)
{
int ret;
struct ipv6_mreq mreq;
memset (&mreq, 0, sizeof (struct ipv6_mreq));
inet_pton (AF_INET6, ALLROUTER, &mreq.ipv6mr_multiaddr);
mreq.ipv6mr_interface = ifp->ifindex;
ret = setsockopt (sock, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
(char *) &mreq, sizeof mreq);
if (ret < 0)
zlog_warn ("can't setsockopt IPV6_LEAVE_GROUP: %s", safe_strerror (errno));
zlog_info ("rtadv: %s leave from all-routers multicast group", ifp->name);
return 0;
}
#else
void
rtadv_init (struct zebra_vrf *zvrf)
{
/* Empty.*/;
}
void
rtadv_terminate (struct zebra_vrf *zvrf)
{
/* Empty.*/;
}
void
rtadv_cmd_init (void)
{
/* Empty.*/;
}
#endif /* HAVE_RTADV && HAVE_IPV6 */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4897_0 |
crossvul-cpp_data_good_1100_1 | #ifndef NGIFLIB_NO_FILE
#include <stdio.h>
#endif /* NGIFLIB_NO_FILE */
#include "ngiflib.h"
/* decodeur GIF en C portable (pas de pb big/little endian)
* Thomas BERNARD. janvier 2004.
* (c) 2004-2019 Thomas Bernard. All rights reserved
*/
/* Fonction de debug */
#ifdef DEBUG
void fprintf_ngiflib_img(FILE * f, struct ngiflib_img * i) {
fprintf(f, " * ngiflib_img @ %p\n", i);
fprintf(f, " next = %p\n", i->next);
fprintf(f, " parent = %p\n", i->parent);
fprintf(f, " palette = %p\n", i->palette);
fprintf(f, " %3d couleurs", i->ncolors);
if(i->interlaced) fprintf(f, " interlaced");
fprintf(f, "\n taille : %dx%d, pos (%d,%d)\n", i->width, i->height, i->posX, i->posY);
fprintf(f, " sort_flag=%x localpalbits=%d\n", i->sort_flag, i->localpalbits);
}
#endif /* DEBUG */
void GifImgDestroy(struct ngiflib_img * i) {
if(i==NULL) return;
if(i->next) GifImgDestroy(i->next);
if(i->palette && (i->palette != i->parent->palette))
ngiflib_free(i->palette);
ngiflib_free(i);
}
/* Fonction de debug */
#ifdef DEBUG
void fprintf_ngiflib_gif(FILE * f, struct ngiflib_gif * g) {
struct ngiflib_img * i;
fprintf(f, "* ngiflib_gif @ %p %s\n", g, g->signature);
fprintf(f, " %dx%d, %d bits, %d couleurs\n", g->width, g->height, g->imgbits, g->ncolors);
fprintf(f, " palette = %p, backgroundcolorindex %d\n", g->palette, g->backgroundindex);
fprintf(f, " pixelaspectratio = %d\n", g->pixaspectratio);
fprintf(f, " frbuff = %p\n", g->frbuff.p8);
fprintf(f, " cur_img = %p\n", g->cur_img);
fprintf(f, " %d images :\n", g->nimg);
i = g->first_img;
while(i) {
fprintf_ngiflib_img(f, i);
i = i->next;
}
}
#endif /* DEBUG */
void GifDestroy(struct ngiflib_gif * g) {
if(g==NULL) return;
GifImgDestroy(g->first_img);
if(g->palette) ngiflib_free(g->palette);
if(g->frbuff.p8) ngiflib_free(g->frbuff.p8);
ngiflib_free(g);
}
/* u8 GetByte(struct ngiflib_gif * g);
* fonction qui renvoie un octet du fichier .gif
* on pourait optimiser en faisant 2 fonctions.
*/
static u8 GetByte(struct ngiflib_gif * g) {
#ifndef NGIFLIB_NO_FILE
if(g->mode & NGIFLIB_MODE_FROM_MEM) {
#endif /* NGIFLIB_NO_FILE */
return *(g->input.bytes++);
#ifndef NGIFLIB_NO_FILE
} else {
return (u8)(getc(g->input.file));
}
#endif /* NGIFLIB_NO_FILE */
}
/* u16 GetWord()
* Renvoie un mot de 16bits
* N'est pas influencee par l'endianess du CPU !
*/
static u16 GetWord(struct ngiflib_gif * g) {
u16 r = (u16)GetByte(g);
r |= ((u16)GetByte(g) << 8);
return r;
}
/* int GetByteStr(struct ngiflib_gif * g, u8 * p, int n);
* prend en argument un pointeur sur la destination
* et le nombre d'octet a lire.
* Renvoie 0 si l'operation a reussi, -1 sinon.
*/
static int GetByteStr(struct ngiflib_gif * g, u8 * p, int n) {
if(!p) return -1;
#ifndef NGIFLIB_NO_FILE
if(g->mode & NGIFLIB_MODE_FROM_MEM) {
#endif /* NGIFLIB_NO_FILE */
ngiflib_memcpy(p, g->input.bytes, n);
g->input.bytes += n;
return 0;
#ifndef NGIFLIB_NO_FILE
} else {
size_t read;
read = fread(p, 1, n, g->input.file);
return ((int)read == n) ? 0 : -1;
}
#endif /* NGIFLIB_NO_FILE */
}
/* void WritePixel(struct ngiflib_img * i, u8 v);
* ecrit le pixel de valeur v dans le frame buffer
*/
static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) {
struct ngiflib_gif * p = i->parent;
if(v!=i->gce.transparent_color || !i->gce.transparent_flag) {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
*context->frbuff_p.p8 = v;
#ifndef NGIFLIB_INDEXED_ONLY
} else
*context->frbuff_p.p32 =
GifIndexToTrueColor(i->palette, v);
#endif /* NGIFLIB_INDEXED_ONLY */
}
if(--(context->Xtogo) <= 0) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(p->line_cb) p->line_cb(p, context->line_p, context->curY);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
context->Xtogo = i->width;
switch(context->pass) {
case 0:
context->curY++;
break;
case 1: /* 1st pass : every eighth row starting from 0 */
context->curY += 8;
break;
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY += 8;
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY += 4;
break;
case 4: /* 4th pass : every odd row */
context->curY += 2;
break;
}
while(context->pass > 0 && context->pass < 4 &&
context->curY >= p->height) {
switch(++context->pass) {
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY = i->posY + 4;
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY = i->posY + 2;
break;
case 4: /* 4th pass : every odd row */
context->curY = i->posY + 1;
break;
}
}
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;
context->frbuff_p.p8 = context->line_p.p8 + i->posX;
#else
context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#ifndef NGIFLIB_INDEXED_ONLY
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;
context->frbuff_p.p32 = context->line_p.p32 + i->posX;
#else
context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
context->frbuff_p.p8++;
#ifndef NGIFLIB_INDEXED_ONLY
} else {
context->frbuff_p.p32++;
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
}
/* void WritePixels(struct ngiflib_img * i, const u8 * pixels, u16 n);
* ecrit les pixels dans le frame buffer
*/
static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) {
u16 tocopy;
struct ngiflib_gif * p = i->parent;
while(n > 0) {
tocopy = (context->Xtogo < n) ? context->Xtogo : n;
if(!i->gce.transparent_flag) {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy);
pixels += tocopy;
context->frbuff_p.p8 += tocopy;
#ifndef NGIFLIB_INDEXED_ONLY
} else {
int j;
for(j = (int)tocopy; j > 0; j--) {
*(context->frbuff_p.p32++) =
GifIndexToTrueColor(i->palette, *pixels++);
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
int j;
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels;
pixels++;
context->frbuff_p.p8++;
}
#ifndef NGIFLIB_INDEXED_ONLY
} else {
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) {
*context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels);
}
pixels++;
context->frbuff_p.p32++;
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
context->Xtogo -= tocopy;
if(context->Xtogo == 0) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(p->line_cb) p->line_cb(p, context->line_p, context->curY);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
context->Xtogo = i->width;
switch(context->pass) {
case 0:
context->curY++;
break;
case 1: /* 1st pass : every eighth row starting from 0 */
context->curY += 8;
break;
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY += 8;
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY += 4;
break;
case 4: /* 4th pass : every odd row */
context->curY += 2;
break;
}
while(context->pass > 0 && context->pass < 4 &&
context->curY >= p->height) {
switch(++context->pass) {
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY = i->posY + 4;
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY = i->posY + 2;
break;
case 4: /* 4th pass : every odd row */
context->curY = i->posY + 1;
break;
}
}
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;
context->frbuff_p.p8 = context->line_p.p8 + i->posX;
#else
context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#ifndef NGIFLIB_INDEXED_ONLY
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;
context->frbuff_p.p32 = context->line_p.p32 + i->posX;
#else
context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
n -= tocopy;
}
}
/*
* u16 GetGifWord(struct ngiflib_img * i);
* Renvoie un code LZW (taille variable)
*/
static u16 GetGifWord(struct ngiflib_img * i, struct ngiflib_decode_context * context) {
u16 r;
int bits_todo;
u16 newbyte;
bits_todo = (int)context->nbbit - (int)context->restbits;
if( bits_todo <= 0) { /* nbbit <= restbits */
r = context->lbyte;
context->restbits -= context->nbbit;
context->lbyte >>= context->nbbit;
} else if( bits_todo > 8 ) { /* nbbit > restbits + 8 */
if(context->restbyte >= 2) {
context->restbyte -= 2;
r = *context->srcbyte++;
} else {
if(context->restbyte == 0) {
context->restbyte = GetByte(i->parent);
#if defined(DEBUG) && !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte);
#endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */
GetByteStr(i->parent, context->byte_buffer, context->restbyte);
context->srcbyte = context->byte_buffer;
}
r = *context->srcbyte++;
if(--context->restbyte == 0) {
context->restbyte = GetByte(i->parent);
#if defined(DEBUG) && !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte);
#endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */
GetByteStr(i->parent, context->byte_buffer, context->restbyte);
context->srcbyte = context->byte_buffer;
}
context->restbyte--;
}
newbyte = *context->srcbyte++;
r |= newbyte << 8;
r = (r << context->restbits) | context->lbyte;
context->restbits = 16 - bits_todo;
context->lbyte = newbyte >> (bits_todo - 8);
} else /*if( bits_todo > 0 )*/ { /* nbbit > restbits */
if(context->restbyte == 0) {
context->restbyte = GetByte(i->parent);
#if defined(DEBUG) && !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte);
#endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */
GetByteStr(i->parent, context->byte_buffer, context->restbyte);
context->srcbyte = context->byte_buffer;
}
newbyte = *context->srcbyte++;
context->restbyte--;
r = (newbyte << context->restbits) | context->lbyte;
context->restbits = 8 - bits_todo;
context->lbyte = newbyte >> bits_todo;
}
return (r & context->max); /* applique le bon masque pour eliminer les bits en trop */
}
/* ------------------------------------------------ */
static void FillGifBackGround(struct ngiflib_gif * g) {
long n = (long)g->width*g->height;
#ifndef NGIFLIB_INDEXED_ONLY
u32 bg_truecolor;
#endif /* NGIFLIB_INDEXED_ONLY */
if((g->frbuff.p8==NULL)||(g->palette==NULL)) return;
#ifndef NGIFLIB_INDEXED_ONLY
if(g->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
ngiflib_memset(g->frbuff.p8, g->backgroundindex, n);
#ifndef NGIFLIB_INDEXED_ONLY
} else {
u32 * p = g->frbuff.p32;
bg_truecolor = GifIndexToTrueColor(g->palette, g->backgroundindex);
while(n-->0) *p++ = bg_truecolor;
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
/* ------------------------------------------------ */
int CheckGif(u8 * b) {
return (b[0]=='G')&&(b[1]=='I')&&(b[2]=='F')&&(b[3]=='8');
}
/* ------------------------------------------------ */
static int DecodeGifImg(struct ngiflib_img * i) {
struct ngiflib_decode_context context;
long npix;
u8 * stackp;
u8 * stack_top;
u16 clr;
u16 eof;
u16 free;
u16 act_code = 0;
u16 old_code = 0;
u16 read_byt;
u16 ab_prfx[4096];
u8 ab_suffx[4096];
u8 ab_stack[4096];
u8 flags;
u8 casspecial = 0;
if(!i) return -1;
i->posX = GetWord(i->parent); /* offsetX */
i->posY = GetWord(i->parent); /* offsetY */
i->width = GetWord(i->parent); /* SizeX */
i->height = GetWord(i->parent); /* SizeY */
if((i->width > i->parent->width) || (i->height > i->parent->height)) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n");
#endif
return -1;
}
if((i->posX + i->width) > i->parent->width) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n");
#endif
i->posX = i->parent->width - i->width;
}
if((i->posY + i->height) > i->parent->height) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n");
#endif
i->posY = i->parent->height - i->height;
}
context.Xtogo = i->width;
context.curY = i->posY;
#ifdef NGIFLIB_INDEXED_ONLY
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#else
if(i->parent->mode & NGIFLIB_MODE_INDEXED) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width;
context.frbuff_p.p32 = context.line_p.p32 + i->posX;
#else
context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
npix = (long)i->width * i->height;
flags = GetByte(i->parent);
i->interlaced = (flags & 64) >> 6;
context.pass = i->interlaced ? 1 : 0;
i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */
i->localpalbits = (flags & 7) + 1;
if(flags&128) { /* palette locale */
int k;
int localpalsize = 1 << i->localpalbits;
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize);
for(k=0; k<localpalsize; k++) {
i->palette[k].r = GetByte(i->parent);
i->palette[k].g = GetByte(i->parent);
i->palette[k].b = GetByte(i->parent);
}
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
i->palette = i->parent->palette;
i->localpalbits = i->parent->imgbits;
}
i->ncolors = 1 << i->localpalbits;
i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */
if (i->imgbits > 11) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Invalid LZW Minimum Code Size : %d\n", (int)i->imgbits);
#endif
return -1;
}
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) {
if(i->interlaced) fprintf(i->parent->log, "interlaced ");
fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n",
i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors);
}
#endif /* !defined(NGIFLIB_NO_FILE) */
if(i->imgbits==1) { /* fix for 1bit images ? */
i->imgbits = 2;
}
clr = 1 << i->imgbits;
eof = clr + 1;
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
stackp = stack_top = ab_stack + 4096;
context.restbits = 0; /* initialise le "buffer" de lecture */
context.restbyte = 0; /* des codes LZW */
context.lbyte = 0;
for(;;) {
act_code = GetGifWord(i, &context);
if(act_code==eof) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 0;
}
if(npix==0) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 1;
}
if(act_code==clr) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (%hu) (free=%hu) npix=%ld\n", clr, free, npix);
#endif /* !defined(NGIFLIB_NO_FILE) */
/* clear */
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
act_code = GetGifWord(i, &context); /* the first code after the clear code is concrete */
if (act_code >= clr)
{
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Invalid code %hu just after clear(%hu) !\n", act_code, clr);
#endif /* !defined(NGIFLIB_NO_FILE) */
return -1;
}
casspecial = (u8)act_code;
old_code = act_code;
if(npix > 0) WritePixel(i, &context, casspecial);
npix--;
} else if(act_code > free) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Invalid code %hu (free=%hu) !\n", act_code, free);
#endif /* !defined(NGIFLIB_NO_FILE) */
return -1;
} else {
read_byt = act_code;
if(act_code == free) { /* code pas encore dans alphabet */
/* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */
*(--stackp) = casspecial; /* dernier debut de chaine ! */
act_code = old_code;
}
/* printf("actcode=%d\n", act_code); */
while(act_code > clr) { /* code non concret */
/* fillstackloop empile les suffixes ! */
*(--stackp) = ab_suffx[act_code];
act_code = ab_prfx[act_code]; /* prefixe */
}
/* act_code est concret */
casspecial = (u8)act_code; /* dernier debut de chaine ! */
*(--stackp) = casspecial; /* push on stack */
if(npix >= (stack_top - stackp)) {
WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */
} else if(npix > 0) { /* "pixel overflow" */
WritePixels(i, &context, stackp, npix);
}
npix -= (stack_top - stackp);
stackp = stack_top;
/* putchar('\n'); */
if(free < 4096) { /* la taille du dico est 4096 max ! */
ab_prfx[free] = old_code;
ab_suffx[free] = (u8)act_code;
free++;
if((free > context.max) && (context.nbbit < 12)) {
context.nbbit++; /* 1 bit de plus pour les codes LZW */
context.max += context.max + 1;
}
}
old_code = read_byt;
}
}
return 0;
}
/* ------------------------------------------------
* int LoadGif(struct ngiflib_gif *);
* s'assurer que nimg=0 au depart !
* retourne :
* 0 si GIF termin�
* un nombre negatif si ERREUR
* 1 si image Decod�e
* rappeler pour decoder les images suivantes
* ------------------------------------------------ */
int LoadGif(struct ngiflib_gif * g) {
struct ngiflib_gce gce;
u8 sign;
u8 tmp;
int i;
if(!g) return -1;
gce.gce_present = 0;
if(g->nimg==0) {
GetByteStr(g, g->signature, 6);
g->signature[6] = '\0';
if( g->signature[0] != 'G'
|| g->signature[1] != 'I'
|| g->signature[2] != 'F'
|| g->signature[3] != '8') {
return -1;
}
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "%s\n", g->signature);
#endif /* !defined(NGIFLIB_NO_FILE) */
g->width = GetWord(g);
g->height = GetWord(g);
/* allocate frame buffer */
#ifndef NGIFLIB_INDEXED_ONLY
if((g->mode & NGIFLIB_MODE_INDEXED)==0)
g->frbuff.p32 = ngiflib_malloc(4*(long)g->height*(long)g->width);
else
#endif /* NGIFLIB_INDEXED_ONLY */
g->frbuff.p8 = ngiflib_malloc((long)g->height*(long)g->width);
tmp = GetByte(g);/* <Packed Fields> = Global Color Table Flag 1 Bit
Color Resolution 3 Bits
Sort Flag 1 Bit
Size of Global Color Table 3 Bits */
g->colorresolution = ((tmp & 0x70) >> 4) + 1;
g->sort_flag = (tmp & 8) >> 3;
g->imgbits = (tmp & 7) + 1; /* Global Palette color resolution */
g->ncolors = 1 << g->imgbits;
g->backgroundindex = GetByte(g);
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "%hux%hu %hhubits %hu couleurs bg=%hhu\n",
g->width, g->height, g->imgbits, g->ncolors, g->backgroundindex);
#endif /* NGIFLIB_INDEXED_ONLY */
g->pixaspectratio = GetByte(g); /* pixel aspect ratio (0 : unspecified) */
if(tmp&0x80) {
/* la palette globale suit. */
g->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*g->ncolors);
for(i=0; i<g->ncolors; i++) {
g->palette[i].r = GetByte(g);
g->palette[i].g = GetByte(g);
g->palette[i].b = GetByte(g);
#if defined(DEBUG) && !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "%3d %02X %02X %02X\n", i, g->palette[i].r,g->palette[i].g,g->palette[i].b);
#endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */
}
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(g->palette_cb) g->palette_cb(g, g->palette, g->ncolors);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
g->palette = NULL;
}
g->netscape_loop_count = -1;
}
for(;;) {
char appid_auth[11];
u8 id,size;
int blockindex;
sign = GetByte(g); /* signature du prochain bloc */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "BLOCK SIGNATURE 0x%02X '%c'\n", sign, (sign >= 32) ? sign : '.');
#endif /* NGIFLIB_INDEXED_ONLY */
switch(sign) {
case 0x3B: /* END OF GIF */
return 0;
case '!': /* Extension introducer 0x21 */
id = GetByte(g);
blockindex = 0;
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "extension (id=0x%02hhx)\n", id);
#endif /* NGIFLIB_NO_FILE */
while( (size = GetByte(g)) ) {
u8 ext[256];
GetByteStr(g, ext, size);
switch(id) {
case 0xF9: /* Graphic Control Extension */
/* The scope of this extension is the first graphic
* rendering block to follow. */
gce.gce_present = 1;
gce.disposal_method = (ext[0] >> 2) & 7;
gce.transparent_flag = ext[0] & 1;
gce.user_input_flag = (ext[0] >> 1) & 1;
gce.delay_time = ext[1] | (ext[2]<<8);
gce.transparent_color = ext[3];
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "disposal_method=%hhu delay_time=%hu (transp=%hhu)transparent_color=0x%02hhX\n",
gce.disposal_method, gce.delay_time, gce.transparent_flag, gce.transparent_color);
#endif /* NGIFLIB_INDEXED_ONLY */
/* this propably should be adjusted depending on the disposal_method
* of the _previous_ image. */
if(gce.transparent_flag && ((g->nimg == 0) || gce.disposal_method == 2)) {
FillGifBackGround(g);
}
break;
case 0xFE: /* Comment Extension. */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
if(blockindex==0) fprintf(g->log, "-------------------- Comment extension --------------------\n");
ext[size] = '\0';
fputs((char *)ext, g->log);
}
#endif /* NGIFLIB_NO_FILE */
break;
case 0xFF: /* application extension */
/* NETSCAPE2.0 extension :
* http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension */
if(blockindex==0) {
ngiflib_memcpy(appid_auth, ext, 11);
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
fprintf(g->log, "---------------- Application extension ---------------\n");
fprintf(g->log, "Application identifier : '%.8s', auth code : %02X %02X %02X (",
appid_auth, ext[8], ext[9], ext[10]);
fputc((ext[8]<32)?' ':ext[8], g->log);
fputc((ext[9]<32)?' ':ext[9], g->log);
fputc((ext[10]<32)?' ':ext[10], g->log);
fprintf(g->log, ")\n");
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
fprintf(g->log, "Datas (as hex) : ");
for(i=0; i<size; i++) {
fprintf(g->log, "%02x ", ext[i]);
}
fprintf(g->log, "\nDatas (as text) : '");
for(i=0; i<size; i++) {
putc((ext[i]<32)?' ':ext[i], g->log);
}
fprintf(g->log, "'\n");
}
#endif /* NGIFLIB_INDEXED_ONLY */
if(0 == ngiflib_memcmp(appid_auth, "NETSCAPE2.0", 11)) {
/* ext[0] : Sub-block ID */
if(ext[0] == 1) {
/* 1 : Netscape Looping Extension. */
g->netscape_loop_count = (int)ext[1] | ((int)ext[2] << 8);
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
fprintf(g->log, "NETSCAPE loop_count = %d\n", g->netscape_loop_count);
}
#endif /* NGIFLIB_NO_FILE */
}
}
}
break;
case 0x01: /* plain text extension */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
fprintf(g->log, "Plain text extension blockindex=%d\n", blockindex);
for(i=0; i<size; i++) {
putc((ext[i]<32)?' ':ext[i], g->log);
}
putc('\n', g->log);
}
#endif /* NGIFLIB_INDEXED_ONLY */
break;
}
blockindex++;
}
switch(id) {
case 0x01: /* plain text extension */
case 0xFE: /* Comment Extension. */
case 0xFF: /* application extension */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
fprintf(g->log, "-----------------------------------------------------------\n");
}
#endif /* NGIFLIB_NO_FILE */
break;
}
break;
case 0x2C: /* Image separator */
if(g->nimg==0) {
g->cur_img = ngiflib_malloc(sizeof(struct ngiflib_img));
if(g->cur_img == NULL) return -2; /* memory error */
g->first_img = g->cur_img;
} else {
g->cur_img->next = ngiflib_malloc(sizeof(struct ngiflib_img));
if(g->cur_img->next == NULL) return -2; /* memory error */
g->cur_img = g->cur_img->next;
}
ngiflib_memset(g->cur_img, 0, sizeof(struct ngiflib_img));
g->cur_img->parent = g;
if(gce.gce_present) {
ngiflib_memcpy(&g->cur_img->gce, &gce, sizeof(struct ngiflib_gce));
} else {
ngiflib_memset(&g->cur_img->gce, 0, sizeof(struct ngiflib_gce));
}
if (DecodeGifImg(g->cur_img) < 0) return -1;
g->nimg++;
tmp = GetByte(g);/* 0 final */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "ZERO TERMINATOR 0x%02X\n", tmp);
#endif /* NGIFLIB_INDEXED_ONLY */
return 1; /* image decod�e */
default:
/* unexpected byte */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "unexpected signature 0x%02X\n", sign);
#endif /* NGIFLIB_INDEXED_ONLY */
return -1;
}
}
}
u32 GifIndexToTrueColor(struct ngiflib_rgb * palette, u8 v) {
return palette[v].b | (palette[v].g << 8) | (palette[v].r << 16);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1100_1 |
crossvul-cpp_data_bad_5734_0 | /*
* Go2Webinar decoder
* Copyright (c) 2012 Konstantin Shishkov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Go2Webinar decoder
*/
#include <zlib.h>
#include "libavutil/intreadwrite.h"
#include "avcodec.h"
#include "bytestream.h"
#include "dsputil.h"
#include "get_bits.h"
#include "internal.h"
#include "mjpeg.h"
enum ChunkType {
FRAME_INFO = 0xC8,
TILE_DATA,
CURSOR_POS,
CURSOR_SHAPE,
CHUNK_CC,
CHUNK_CD
};
enum Compression {
COMPR_EPIC_J_B = 2,
COMPR_KEMPF_J_B,
};
static const uint8_t luma_quant[64] = {
8, 6, 5, 8, 12, 20, 26, 31,
6, 6, 7, 10, 13, 29, 30, 28,
7, 7, 8, 12, 20, 29, 35, 28,
7, 9, 11, 15, 26, 44, 40, 31,
9, 11, 19, 28, 34, 55, 52, 39,
12, 18, 28, 32, 41, 52, 57, 46,
25, 32, 39, 44, 52, 61, 60, 51,
36, 46, 48, 49, 56, 50, 52, 50
};
static const uint8_t chroma_quant[64] = {
9, 9, 12, 24, 50, 50, 50, 50,
9, 11, 13, 33, 50, 50, 50, 50,
12, 13, 28, 50, 50, 50, 50, 50,
24, 33, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50,
};
typedef struct JPGContext {
DSPContext dsp;
ScanTable scantable;
VLC dc_vlc[2], ac_vlc[2];
int prev_dc[3];
DECLARE_ALIGNED(16, int16_t, block)[6][64];
uint8_t *buf;
} JPGContext;
typedef struct G2MContext {
JPGContext jc;
int version;
int compression;
int width, height, bpp;
int tile_width, tile_height;
int tiles_x, tiles_y, tile_x, tile_y;
int got_header;
uint8_t *framebuf;
int framebuf_stride, old_width, old_height;
uint8_t *synth_tile, *jpeg_tile;
int tile_stride, old_tile_w, old_tile_h;
uint8_t *kempf_buf, *kempf_flags;
uint8_t *cursor;
int cursor_stride;
int cursor_fmt;
int cursor_w, cursor_h, cursor_x, cursor_y;
int cursor_hot_x, cursor_hot_y;
} G2MContext;
static av_cold int build_vlc(VLC *vlc, const uint8_t *bits_table,
const uint8_t *val_table, int nb_codes,
int is_ac)
{
uint8_t huff_size[256] = { 0 };
uint16_t huff_code[256];
uint16_t huff_sym[256];
int i;
ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
for (i = 0; i < 256; i++)
huff_sym[i] = i + 16 * is_ac;
if (is_ac)
huff_sym[0] = 16 * 256;
return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
huff_code, 2, 2, huff_sym, 2, 2, 0);
}
static av_cold int jpg_init(AVCodecContext *avctx, JPGContext *c)
{
int ret;
ret = build_vlc(&c->dc_vlc[0], avpriv_mjpeg_bits_dc_luminance,
avpriv_mjpeg_val_dc, 12, 0);
if (ret)
return ret;
ret = build_vlc(&c->dc_vlc[1], avpriv_mjpeg_bits_dc_chrominance,
avpriv_mjpeg_val_dc, 12, 0);
if (ret)
return ret;
ret = build_vlc(&c->ac_vlc[0], avpriv_mjpeg_bits_ac_luminance,
avpriv_mjpeg_val_ac_luminance, 251, 1);
if (ret)
return ret;
ret = build_vlc(&c->ac_vlc[1], avpriv_mjpeg_bits_ac_chrominance,
avpriv_mjpeg_val_ac_chrominance, 251, 1);
if (ret)
return ret;
ff_dsputil_init(&c->dsp, avctx);
ff_init_scantable(c->dsp.idct_permutation, &c->scantable,
ff_zigzag_direct);
return 0;
}
static av_cold void jpg_free_context(JPGContext *ctx)
{
int i;
for (i = 0; i < 2; i++) {
ff_free_vlc(&ctx->dc_vlc[i]);
ff_free_vlc(&ctx->ac_vlc[i]);
}
av_freep(&ctx->buf);
}
static void jpg_unescape(const uint8_t *src, int src_size,
uint8_t *dst, int *dst_size)
{
const uint8_t *src_end = src + src_size;
uint8_t *dst_start = dst;
while (src < src_end) {
uint8_t x = *src++;
*dst++ = x;
if (x == 0xFF && !*src)
src++;
}
*dst_size = dst - dst_start;
}
static int jpg_decode_block(JPGContext *c, GetBitContext *gb,
int plane, int16_t *block)
{
int dc, val, pos;
const int is_chroma = !!plane;
const uint8_t *qmat = is_chroma ? chroma_quant : luma_quant;
c->dsp.clear_block(block);
dc = get_vlc2(gb, c->dc_vlc[is_chroma].table, 9, 3);
if (dc < 0)
return AVERROR_INVALIDDATA;
if (dc)
dc = get_xbits(gb, dc);
dc = dc * qmat[0] + c->prev_dc[plane];
block[0] = dc;
c->prev_dc[plane] = dc;
pos = 0;
while (pos < 63) {
val = get_vlc2(gb, c->ac_vlc[is_chroma].table, 9, 3);
if (val < 0)
return AVERROR_INVALIDDATA;
pos += val >> 4;
val &= 0xF;
if (pos > 63)
return val ? AVERROR_INVALIDDATA : 0;
if (val) {
int nbits = val;
val = get_xbits(gb, nbits);
val *= qmat[ff_zigzag_direct[pos]];
block[c->scantable.permutated[pos]] = val;
}
}
return 0;
}
static inline void yuv2rgb(uint8_t *out, int Y, int U, int V)
{
out[0] = av_clip_uint8(Y + ( 91881 * V + 32768 >> 16));
out[1] = av_clip_uint8(Y + (-22554 * U - 46802 * V + 32768 >> 16));
out[2] = av_clip_uint8(Y + (116130 * U + 32768 >> 16));
}
static int jpg_decode_data(JPGContext *c, int width, int height,
const uint8_t *src, int src_size,
uint8_t *dst, int dst_stride,
const uint8_t *mask, int mask_stride, int num_mbs,
int swapuv)
{
GetBitContext gb;
uint8_t *tmp;
int mb_w, mb_h, mb_x, mb_y, i, j;
int bx, by;
int unesc_size;
int ret;
tmp = av_realloc(c->buf, src_size + FF_INPUT_BUFFER_PADDING_SIZE);
if (!tmp)
return AVERROR(ENOMEM);
c->buf = tmp;
jpg_unescape(src, src_size, c->buf, &unesc_size);
memset(c->buf + unesc_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
init_get_bits(&gb, c->buf, unesc_size * 8);
width = FFALIGN(width, 16);
mb_w = width >> 4;
mb_h = (height + 15) >> 4;
if (!num_mbs)
num_mbs = mb_w * mb_h;
for (i = 0; i < 3; i++)
c->prev_dc[i] = 1024;
bx = by = 0;
for (mb_y = 0; mb_y < mb_h; mb_y++) {
for (mb_x = 0; mb_x < mb_w; mb_x++) {
if (mask && !mask[mb_x]) {
bx += 16;
continue;
}
for (j = 0; j < 2; j++) {
for (i = 0; i < 2; i++) {
if ((ret = jpg_decode_block(c, &gb, 0,
c->block[i + j * 2])) != 0)
return ret;
c->dsp.idct(c->block[i + j * 2]);
}
}
for (i = 1; i < 3; i++) {
if ((ret = jpg_decode_block(c, &gb, i, c->block[i + 3])) != 0)
return ret;
c->dsp.idct(c->block[i + 3]);
}
for (j = 0; j < 16; j++) {
uint8_t *out = dst + bx * 3 + (by + j) * dst_stride;
for (i = 0; i < 16; i++) {
int Y, U, V;
Y = c->block[(j >> 3) * 2 + (i >> 3)][(i & 7) + (j & 7) * 8];
U = c->block[4 ^ swapuv][(i >> 1) + (j >> 1) * 8] - 128;
V = c->block[5 ^ swapuv][(i >> 1) + (j >> 1) * 8] - 128;
yuv2rgb(out + i * 3, Y, U, V);
}
}
if (!--num_mbs)
return 0;
bx += 16;
}
bx = 0;
by += 16;
if (mask)
mask += mask_stride;
}
return 0;
}
static void kempf_restore_buf(const uint8_t *src, int len,
uint8_t *dst, int stride,
const uint8_t *jpeg_tile, int tile_stride,
int width, int height,
const uint8_t *pal, int npal, int tidx)
{
GetBitContext gb;
int i, j, nb, col;
init_get_bits(&gb, src, len * 8);
if (npal <= 2) nb = 1;
else if (npal <= 4) nb = 2;
else if (npal <= 16) nb = 4;
else nb = 8;
for (j = 0; j < height; j++, dst += stride, jpeg_tile += tile_stride) {
if (get_bits(&gb, 8))
continue;
for (i = 0; i < width; i++) {
col = get_bits(&gb, nb);
if (col != tidx)
memcpy(dst + i * 3, pal + col * 3, 3);
else
memcpy(dst + i * 3, jpeg_tile + i * 3, 3);
}
}
}
static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y,
const uint8_t *src, int src_size)
{
int width, height;
int hdr, zsize, npal, tidx = -1, ret;
int i, j;
const uint8_t *src_end = src + src_size;
uint8_t pal[768], transp[3];
uLongf dlen = (c->tile_width + 1) * c->tile_height;
int sub_type;
int nblocks, cblocks, bstride;
int bits, bitbuf, coded;
uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 +
tile_y * c->tile_height * c->framebuf_stride;
if (src_size < 2)
return AVERROR_INVALIDDATA;
width = FFMIN(c->width - tile_x * c->tile_width, c->tile_width);
height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
hdr = *src++;
sub_type = hdr >> 5;
if (sub_type == 0) {
int j;
memcpy(transp, src, 3);
src += 3;
for (j = 0; j < height; j++, dst += c->framebuf_stride)
for (i = 0; i < width; i++)
memcpy(dst + i * 3, transp, 3);
return 0;
} else if (sub_type == 1) {
return jpg_decode_data(&c->jc, width, height, src, src_end - src,
dst, c->framebuf_stride, NULL, 0, 0, 0);
}
if (sub_type != 2) {
memcpy(transp, src, 3);
src += 3;
}
npal = *src++ + 1;
memcpy(pal, src, npal * 3); src += npal * 3;
if (sub_type != 2) {
for (i = 0; i < npal; i++) {
if (!memcmp(pal + i * 3, transp, 3)) {
tidx = i;
break;
}
}
}
if (src_end - src < 2)
return 0;
zsize = (src[0] << 8) | src[1]; src += 2;
if (src_end - src < zsize)
return AVERROR_INVALIDDATA;
ret = uncompress(c->kempf_buf, &dlen, src, zsize);
if (ret)
return AVERROR_INVALIDDATA;
src += zsize;
if (sub_type == 2) {
kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
NULL, 0, width, height, pal, npal, tidx);
return 0;
}
nblocks = *src++ + 1;
cblocks = 0;
bstride = FFALIGN(width, 16) >> 4;
// blocks are coded LSB and we need normal bitreader for JPEG data
bits = 0;
for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) {
for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) {
if (!bits) {
bitbuf = *src++;
bits = 8;
}
coded = bitbuf & 1;
bits--;
bitbuf >>= 1;
cblocks += coded;
if (cblocks > nblocks)
return AVERROR_INVALIDDATA;
c->kempf_flags[j + i * bstride] = coded;
}
}
memset(c->jpeg_tile, 0, c->tile_stride * height);
jpg_decode_data(&c->jc, width, height, src, src_end - src,
c->jpeg_tile, c->tile_stride,
c->kempf_flags, bstride, nblocks, 0);
kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
c->jpeg_tile, c->tile_stride,
width, height, pal, npal, tidx);
return 0;
}
static int g2m_init_buffers(G2MContext *c)
{
int aligned_height;
if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
c->framebuf_stride = FFALIGN(c->width * 3, 16);
aligned_height = FFALIGN(c->height, 16);
av_free(c->framebuf);
c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);
if (!c->framebuf)
return AVERROR(ENOMEM);
}
if (!c->synth_tile || !c->jpeg_tile ||
c->old_tile_w < c->tile_width ||
c->old_tile_h < c->tile_height) {
c->tile_stride = FFALIGN(c->tile_width * 3, 16);
aligned_height = FFALIGN(c->tile_height, 16);
av_free(c->synth_tile);
av_free(c->jpeg_tile);
av_free(c->kempf_buf);
av_free(c->kempf_flags);
c->synth_tile = av_mallocz(c->tile_stride * aligned_height);
c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height);
c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height
+ FF_INPUT_BUFFER_PADDING_SIZE);
c->kempf_flags = av_mallocz( c->tile_width * aligned_height);
if (!c->synth_tile || !c->jpeg_tile ||
!c->kempf_buf || !c->kempf_flags)
return AVERROR(ENOMEM);
}
return 0;
}
static int g2m_load_cursor(AVCodecContext *avctx, G2MContext *c,
GetByteContext *gb)
{
int i, j, k;
uint8_t *dst;
uint32_t bits;
uint32_t cur_size, cursor_w, cursor_h, cursor_stride;
uint32_t cursor_hot_x, cursor_hot_y;
int cursor_fmt;
uint8_t *tmp;
cur_size = bytestream2_get_be32(gb);
cursor_w = bytestream2_get_byte(gb);
cursor_h = bytestream2_get_byte(gb);
cursor_hot_x = bytestream2_get_byte(gb);
cursor_hot_y = bytestream2_get_byte(gb);
cursor_fmt = bytestream2_get_byte(gb);
cursor_stride = cursor_w * 4;
if (cursor_w < 1 || cursor_w > 256 ||
cursor_h < 1 || cursor_h > 256) {
av_log(avctx, AV_LOG_ERROR, "Invalid cursor dimensions %dx%d\n",
cursor_w, cursor_h);
return AVERROR_INVALIDDATA;
}
if (cursor_hot_x > cursor_w || cursor_hot_y > cursor_h) {
av_log(avctx, AV_LOG_WARNING, "Invalid hotspot position %d,%d\n",
cursor_hot_x, cursor_hot_y);
cursor_hot_x = FFMIN(cursor_hot_x, cursor_w - 1);
cursor_hot_y = FFMIN(cursor_hot_y, cursor_h - 1);
}
if (cur_size - 9 > bytestream2_get_bytes_left(gb) ||
c->cursor_w * c->cursor_h / 4 > cur_size) {
av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %d/%d\n",
cur_size, bytestream2_get_bytes_left(gb));
return AVERROR_INVALIDDATA;
}
if (cursor_fmt != 1 && cursor_fmt != 32) {
avpriv_report_missing_feature(avctx, "Cursor format %d",
cursor_fmt);
return AVERROR_PATCHWELCOME;
}
if (cursor_fmt == 1 && cursor_w % 32) {
avpriv_report_missing_feature(avctx, "odd monochrome cursor width %d", cursor_w);
return AVERROR_PATCHWELCOME;
}
tmp = av_realloc(c->cursor, cursor_stride * cursor_h);
if (!tmp) {
av_log(avctx, AV_LOG_ERROR, "Cannot allocate cursor buffer\n");
return AVERROR(ENOMEM);
}
c->cursor = tmp;
c->cursor_w = cursor_w;
c->cursor_h = cursor_h;
c->cursor_hot_x = cursor_hot_x;
c->cursor_hot_y = cursor_hot_y;
c->cursor_fmt = cursor_fmt;
c->cursor_stride = cursor_stride;
dst = c->cursor;
switch (c->cursor_fmt) {
case 1: // old monochrome
for (j = 0; j < c->cursor_h; j++) {
for (i = 0; i < c->cursor_w; i += 32) {
bits = bytestream2_get_be32(gb);
for (k = 0; k < 32; k++) {
dst[0] = !!(bits & 0x80000000);
dst += 4;
bits <<= 1;
}
}
}
dst = c->cursor;
for (j = 0; j < c->cursor_h; j++) {
for (i = 0; i < c->cursor_w; i += 32) {
bits = bytestream2_get_be32(gb);
for (k = 0; k < 32; k++) {
int mask_bit = !!(bits & 0x80000000);
switch (dst[0] * 2 + mask_bit) {
case 0:
dst[0] = 0xFF; dst[1] = 0x00;
dst[2] = 0x00; dst[3] = 0x00;
break;
case 1:
dst[0] = 0xFF; dst[1] = 0xFF;
dst[2] = 0xFF; dst[3] = 0xFF;
break;
default:
dst[0] = 0x00; dst[1] = 0x00;
dst[2] = 0x00; dst[3] = 0x00;
}
dst += 4;
bits <<= 1;
}
}
}
break;
case 32: // full colour
/* skip monochrome version of the cursor and decode RGBA instead */
bytestream2_skip(gb, c->cursor_h * (FFALIGN(c->cursor_w, 32) >> 3));
for (j = 0; j < c->cursor_h; j++) {
for (i = 0; i < c->cursor_w; i++) {
int val = bytestream2_get_be32(gb);
*dst++ = val >> 0;
*dst++ = val >> 8;
*dst++ = val >> 16;
*dst++ = val >> 24;
}
}
break;
default:
return AVERROR_PATCHWELCOME;
}
return 0;
}
#define APPLY_ALPHA(src, new, alpha) \
src = (src * (256 - alpha) + new * alpha) >> 8
static void g2m_paint_cursor(G2MContext *c, uint8_t *dst, int stride)
{
int i, j;
int x, y, w, h;
const uint8_t *cursor;
if (!c->cursor)
return;
x = c->cursor_x - c->cursor_hot_x;
y = c->cursor_y - c->cursor_hot_y;
cursor = c->cursor;
w = c->cursor_w;
h = c->cursor_h;
if (x + w > c->width)
w = c->width - x;
if (y + h > c->height)
h = c->height - y;
if (x < 0) {
w += x;
cursor += -x * 4;
} else {
dst += x * 3;
}
if (y < 0) {
h += y;
cursor += -y * c->cursor_stride;
} else {
dst += y * stride;
}
if (w < 0 || h < 0)
return;
for (j = 0; j < h; j++) {
for (i = 0; i < w; i++) {
uint8_t alpha = cursor[i * 4];
APPLY_ALPHA(dst[i * 3 + 0], cursor[i * 4 + 1], alpha);
APPLY_ALPHA(dst[i * 3 + 1], cursor[i * 4 + 2], alpha);
APPLY_ALPHA(dst[i * 3 + 2], cursor[i * 4 + 3], alpha);
}
dst += stride;
cursor += c->cursor_stride;
}
}
static int g2m_decode_frame(AVCodecContext *avctx, void *data,
int *got_picture_ptr, AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
G2MContext *c = avctx->priv_data;
AVFrame *pic = data;
GetByteContext bc, tbc;
int magic;
int got_header = 0;
uint32_t chunk_size;
int chunk_type;
int i;
int ret;
if (buf_size < 12) {
av_log(avctx, AV_LOG_ERROR,
"Frame should have at least 12 bytes, got %d instead\n",
buf_size);
return AVERROR_INVALIDDATA;
}
bytestream2_init(&bc, buf, buf_size);
magic = bytestream2_get_be32(&bc);
if ((magic & ~0xF) != MKBETAG('G', '2', 'M', '0') ||
(magic & 0xF) < 2 || (magic & 0xF) > 4) {
av_log(avctx, AV_LOG_ERROR, "Wrong magic %08X\n", magic);
return AVERROR_INVALIDDATA;
}
if ((magic & 0xF) != 4) {
av_log(avctx, AV_LOG_ERROR, "G2M2 and G2M3 are not yet supported\n");
return AVERROR(ENOSYS);
}
while (bytestream2_get_bytes_left(&bc) > 5) {
chunk_size = bytestream2_get_le32(&bc) - 1;
chunk_type = bytestream2_get_byte(&bc);
if (chunk_size > bytestream2_get_bytes_left(&bc)) {
av_log(avctx, AV_LOG_ERROR, "Invalid chunk size %d type %02X\n",
chunk_size, chunk_type);
break;
}
switch (chunk_type) {
case FRAME_INFO:
c->got_header = 0;
if (chunk_size < 21) {
av_log(avctx, AV_LOG_ERROR, "Invalid frame info size %d\n",
chunk_size);
break;
}
c->width = bytestream2_get_be32(&bc);
c->height = bytestream2_get_be32(&bc);
if (c->width < 16 || c->width > avctx->width ||
c->height < 16 || c->height > avctx->height) {
av_log(avctx, AV_LOG_ERROR,
"Invalid frame dimensions %dx%d\n",
c->width, c->height);
ret = AVERROR_INVALIDDATA;
goto header_fail;
}
if (c->width != avctx->width || c->height != avctx->height)
avcodec_set_dimensions(avctx, c->width, c->height);
c->compression = bytestream2_get_be32(&bc);
if (c->compression != 2 && c->compression != 3) {
av_log(avctx, AV_LOG_ERROR,
"Unknown compression method %d\n",
c->compression);
return AVERROR_PATCHWELCOME;
}
c->tile_width = bytestream2_get_be32(&bc);
c->tile_height = bytestream2_get_be32(&bc);
if (!c->tile_width || !c->tile_height) {
av_log(avctx, AV_LOG_ERROR,
"Invalid tile dimensions %dx%d\n",
c->tile_width, c->tile_height);
ret = AVERROR_INVALIDDATA;
goto header_fail;
}
c->tiles_x = (c->width + c->tile_width - 1) / c->tile_width;
c->tiles_y = (c->height + c->tile_height - 1) / c->tile_height;
c->bpp = bytestream2_get_byte(&bc);
chunk_size -= 21;
bytestream2_skip(&bc, chunk_size);
if (g2m_init_buffers(c)) {
ret = AVERROR(ENOMEM);
goto header_fail;
}
got_header = 1;
break;
case TILE_DATA:
if (!c->tiles_x || !c->tiles_y) {
av_log(avctx, AV_LOG_WARNING,
"No frame header - skipping tile\n");
bytestream2_skip(&bc, bytestream2_get_bytes_left(&bc));
break;
}
if (chunk_size < 2) {
av_log(avctx, AV_LOG_ERROR, "Invalid tile data size %d\n",
chunk_size);
break;
}
c->tile_x = bytestream2_get_byte(&bc);
c->tile_y = bytestream2_get_byte(&bc);
if (c->tile_x >= c->tiles_x || c->tile_y >= c->tiles_y) {
av_log(avctx, AV_LOG_ERROR,
"Invalid tile pos %d,%d (in %dx%d grid)\n",
c->tile_x, c->tile_y, c->tiles_x, c->tiles_y);
break;
}
chunk_size -= 2;
ret = 0;
switch (c->compression) {
case COMPR_EPIC_J_B:
av_log(avctx, AV_LOG_ERROR,
"ePIC j-b compression is not implemented yet\n");
return AVERROR(ENOSYS);
case COMPR_KEMPF_J_B:
ret = kempf_decode_tile(c, c->tile_x, c->tile_y,
buf + bytestream2_tell(&bc),
chunk_size);
break;
}
if (ret && c->framebuf)
av_log(avctx, AV_LOG_ERROR, "Error decoding tile %d,%d\n",
c->tile_x, c->tile_y);
bytestream2_skip(&bc, chunk_size);
break;
case CURSOR_POS:
if (chunk_size < 5) {
av_log(avctx, AV_LOG_ERROR, "Invalid cursor pos size %d\n",
chunk_size);
break;
}
c->cursor_x = bytestream2_get_be16(&bc);
c->cursor_y = bytestream2_get_be16(&bc);
bytestream2_skip(&bc, chunk_size - 4);
break;
case CURSOR_SHAPE:
if (chunk_size < 8) {
av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %d\n",
chunk_size);
break;
}
bytestream2_init(&tbc, buf + bytestream2_tell(&bc),
chunk_size - 4);
g2m_load_cursor(avctx, c, &tbc);
bytestream2_skip(&bc, chunk_size);
break;
case CHUNK_CC:
case CHUNK_CD:
bytestream2_skip(&bc, chunk_size);
break;
default:
av_log(avctx, AV_LOG_WARNING, "Skipping chunk type %02X\n",
chunk_type);
bytestream2_skip(&bc, chunk_size);
}
}
if (got_header)
c->got_header = 1;
if (c->width && c->height && c->framebuf) {
if ((ret = ff_get_buffer(avctx, pic, 0)) < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return ret;
}
pic->key_frame = got_header;
pic->pict_type = got_header ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
for (i = 0; i < avctx->height; i++)
memcpy(pic->data[0] + i * pic->linesize[0],
c->framebuf + i * c->framebuf_stride,
c->width * 3);
g2m_paint_cursor(c, pic->data[0], pic->linesize[0]);
*got_picture_ptr = 1;
}
return buf_size;
header_fail:
c->width = c->height = 0;
c->tiles_x = c->tiles_y = 0;
return ret;
}
static av_cold int g2m_decode_init(AVCodecContext *avctx)
{
G2MContext * const c = avctx->priv_data;
int ret;
if ((ret = jpg_init(avctx, &c->jc)) != 0) {
av_log(avctx, AV_LOG_ERROR, "Cannot initialise VLCs\n");
jpg_free_context(&c->jc);
return AVERROR(ENOMEM);
}
avctx->pix_fmt = AV_PIX_FMT_RGB24;
return 0;
}
static av_cold int g2m_decode_end(AVCodecContext *avctx)
{
G2MContext * const c = avctx->priv_data;
jpg_free_context(&c->jc);
av_freep(&c->kempf_buf);
av_freep(&c->kempf_flags);
av_freep(&c->synth_tile);
av_freep(&c->jpeg_tile);
av_freep(&c->cursor);
av_freep(&c->framebuf);
return 0;
}
AVCodec ff_g2m_decoder = {
.name = "g2m",
.long_name = NULL_IF_CONFIG_SMALL("Go2Meeting"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_G2M,
.priv_data_size = sizeof(G2MContext),
.init = g2m_decode_init,
.close = g2m_decode_end,
.decode = g2m_decode_frame,
.capabilities = CODEC_CAP_DR1,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5734_0 |
crossvul-cpp_data_good_938_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP N N M M %
% P P NN N MM MM %
% PPPP N N N M M M %
% P N NN M M %
% P N N M M %
% %
% %
% Read/Write PBMPlus Portable Anymap Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
/*
Typedef declarations.
*/
typedef struct _CommentInfo
{
char
*comment;
size_t
extent;
} CommentInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePNMImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P N M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPNM() returns MagickTrue if the image format type, identified by the
% magick string, is PNM.
%
% The format of the IsPNM method is:
%
% MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o extent: Specifies the extent of the magick string.
%
*/
static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
{
if (extent < 2)
return(MagickFalse);
if ((*magick == (unsigned char) 'P') &&
((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') ||
(magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') ||
(magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f')))
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPNMImage() reads a Portable Anymap image file and returns it.
% It allocates the memory necessary for the new Image structure and returns
% a pointer to the new image.
%
% The format of the ReadPNMImage method is:
%
% Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static int PNMComment(Image *image,CommentInfo *comment_info,
ExceptionInfo *exception)
{
int
c;
register char
*p;
/*
Read comment.
*/
p=comment_info->comment+strlen(comment_info->comment);
for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++)
{
if ((size_t) (p-comment_info->comment+1) >= comment_info->extent)
{
comment_info->extent<<=1;
comment_info->comment=(char *) ResizeQuantumMemory(
comment_info->comment,comment_info->extent,
sizeof(*comment_info->comment));
if (comment_info->comment == (char *) NULL)
return(-1);
p=comment_info->comment+strlen(comment_info->comment);
}
c=ReadBlobByte(image);
if (c != EOF)
{
*p=(char) c;
*(p+1)='\0';
}
}
return(c);
}
static unsigned int PNMInteger(Image *image,CommentInfo *comment_info,
const unsigned int base,ExceptionInfo *exception)
{
int
c;
unsigned int
value;
/*
Skip any leading whitespace.
*/
do
{
c=ReadBlobByte(image);
if (c == EOF)
return(0);
if (c == (int) '#')
c=PNMComment(image,comment_info,exception);
} while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'));
if (base == 2)
return((unsigned int) (c-(int) '0'));
/*
Evaluate number.
*/
value=0;
while (isdigit(c) != 0)
{
if (value <= (unsigned int) (INT_MAX/10))
{
value*=10;
if (value <= (unsigned int) (INT_MAX-(c-(int) '0')))
value+=c-(int) '0';
}
c=ReadBlobByte(image);
if (c == EOF)
return(0);
}
if (c == (int) '#')
c=PNMComment(image,comment_info,exception);
return(value);
}
static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowPNMException(exception,message) \
{ \
if (comment_info.comment != (char *) NULL) \
comment_info.comment=DestroyString(comment_info.comment); \
ThrowReaderException((exception),(message)); \
}
char
format;
CommentInfo
comment_info;
double
quantum_scale;
Image
*image;
MagickBooleanType
status;
QuantumAny
max_value;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
depth,
extent,
packet_size;
ssize_t
count,
row,
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PNM image.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
do
{
/*
Initialize image structure.
*/
comment_info.comment=AcquireString(NULL);
comment_info.extent=MagickPathExtent;
if ((count != 1) || (format != 'P'))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
max_value=1;
quantum_type=RGBQuantum;
quantum_scale=1.0;
format=(char) ReadBlobByte(image);
if (format != '7')
{
/*
PBM, PGM, PPM, and PNM.
*/
image->columns=(size_t) PNMInteger(image,&comment_info,10,exception);
image->rows=(size_t) PNMInteger(image,&comment_info,10,exception);
if ((format == 'f') || (format == 'F'))
{
char
scale[MagickPathExtent];
if (ReadBlobString(image,scale) != (char *) NULL)
quantum_scale=StringToDouble(scale,(char **) NULL);
}
else
{
if ((format == '1') || (format == '4'))
max_value=1; /* bitmap */
else
max_value=(QuantumAny) PNMInteger(image,&comment_info,10,
exception);
}
}
else
{
char
keyword[MagickPathExtent],
value[MagickPathExtent];
int
c;
register char
*p;
/*
PAM.
*/
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == '#')
{
/*
Comment.
*/
c=PNMComment(image,&comment_info,exception);
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
p=keyword;
do
{
if ((size_t) (p-keyword) < (MagickPathExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c));
*p='\0';
if (LocaleCompare(keyword,"endhdr") == 0)
break;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
p=value;
while (isalnum(c) || (c == '_'))
{
if ((size_t) (p-value) < (MagickPathExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"depth") == 0)
packet_size=StringToUnsignedLong(value);
(void) packet_size;
if (LocaleCompare(keyword,"height") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"maxval") == 0)
max_value=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"TUPLTYPE") == 0)
{
if (LocaleCompare(value,"BLACKANDWHITE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"GRAYSCALE") == 0)
{
quantum_type=GrayQuantum;
(void) SetImageColorspace(image,GRAYColorspace,exception);
}
if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"RGB_ALPHA") == 0)
{
image->alpha_trait=BlendPixelTrait;
quantum_type=RGBAQuantum;
}
if (LocaleCompare(value,"CMYK") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace,exception);
quantum_type=CMYKQuantum;
}
if (LocaleCompare(value,"CMYK_ALPHA") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=CMYKAQuantum;
}
}
if (LocaleCompare(keyword,"width") == 0)
image->columns=StringToUnsignedLong(value);
}
}
if ((image->columns == 0) || (image->rows == 0))
ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize");
if ((max_value == 0) || (max_value > 4294967295UL))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
for (depth=1; GetQuantumRange(depth) < max_value; depth++) ;
image->depth=depth;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image))
ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile");
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
comment_info.comment=DestroyString(comment_info.comment); \
return(DestroyImageList(image));
}
(void) ResetImagePixels(image,exception);
/*
Convert PNM pixels to runextent-encoded MIFF packets.
*/
row=0;
y=0;
switch (format)
{
case '1':
{
/*
Convert PBM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGray(image,PNMInteger(image,&comment_info,2,exception) ==
0 ? QuantumRange : 0,q);
if (EOFBlob(image) != MagickFalse)
break;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=BilevelType;
break;
}
case '2':
{
Quantum
intensity;
/*
Convert PGM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10,
exception),max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelGray(image,intensity,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=GrayscaleType;
break;
}
case '3':
{
/*
Convert PNM image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Quantum
pixel;
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10,
exception),max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelRed(image,pixel,q);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10,
exception),max_value);
SetPixelGreen(image,pixel,q);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10,
exception),max_value);
SetPixelBlue(image,pixel,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
break;
}
case '4':
{
/*
Convert PBM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
if (image->storage_class == PseudoClass)
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumMinIsWhite(quantum_info,MagickTrue);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
ssize_t
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '5':
{
/*
Convert PGM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
}
else if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
}
else
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '6':
{
/*
Convert PNM raster image to pixel packets.
*/
quantum_type=RGBQuantum;
extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
{
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
default:
{
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
}
else if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
}
else
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
size_t
channels;
/*
Convert PAM raster image to pixel packets.
*/
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
channels=1;
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
channels=4;
break;
}
default:
{
channels=3;
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
channels++;
extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
if (image->depth != 1)
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
else
SetPixelAlpha(image,QuantumRange-
ScaleAnyToQuantum(pixel,max_value),q);
}
q+=GetPixelChannels(image);
}
}
else if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
else
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
else if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
else
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
break;
}
default:
{
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
else if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
else
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
break;
}
}
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case 'F':
case 'f':
{
/*
Convert PFM raster image to pixel packets.
*/
if (format == 'f')
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian;
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumDepth(image,quantum_info,32);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale));
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
ssize_t
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1),
image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
default:
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
}
if (*comment_info.comment != '\0')
(void) SetImageProperty(image,"comment",comment_info.comment,exception);
comment_info.comment=DestroyString(comment_info.comment);
if (y < (ssize_t) image->rows)
ThrowPNMException(CorruptImageError,"UnableToReadImageData");
if (EOFBlob(image) != MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((format == '1') || (format == '2') || (format == '3'))
do
{
/*
Skip to end of line.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
if (count != 1)
break;
if (format == 'P')
break;
} while (format != '\n');
count=ReadBlob(image,1,(unsigned char *) &format);
if ((count == 1) && (format == 'P'))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count == 1) && (format == 'P'));
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPNMImage() adds properties for the PNM image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPNMImage method is:
%
% size_t RegisterPNMImage(void)
%
*/
ModuleExport size_t RegisterPNMImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("PNM","PAM","Common 2-dimensional bitmap format");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNM","PBM",
"Portable bitmap format (black and white)");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->mime_type=ConstantString("image/x-portable-bitmap");
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNM","PFM","Portable float format");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNM","PGM","Portable graymap format (gray scale)");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->mime_type=ConstantString("image/x-portable-greymap");
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNM","PNM","Portable anymap");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->magick=(IsImageFormatHandler *) IsPNM;
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNM","PPM","Portable pixmap format (color)");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPNMImage() removes format registrations made by the
% PNM module from the list of supported formats.
%
% The format of the UnregisterPNMImage method is:
%
% UnregisterPNMImage(void)
%
*/
ModuleExport void UnregisterPNMImage(void)
{
(void) UnregisterMagickInfo("PAM");
(void) UnregisterMagickInfo("PBM");
(void) UnregisterMagickInfo("PGM");
(void) UnregisterMagickInfo("PNM");
(void) UnregisterMagickInfo("PPM");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePNMImage() writes an image to a file in the PNM rasterfile format.
%
% The format of the WritePNMImage method is:
%
% MagickBooleanType WritePNMImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
format,
magick[MagickPathExtent];
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
Quantum
index;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MagickPathExtent);
max_value=GetQuantumRange(image->depth);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment",exception);
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MagickPathExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MagickPathExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent);
if (IdentifyImageMonochrome(image,exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MagickPathExtent);
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"TUPLTYPE %s\nENDHDR\n",type);
(void) WriteBlobString(image,buffer);
}
/*
Convert runextent encoded to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)),
ScaleQuantumToChar(GetPixelGreen(image,p)),
ScaleQuantumToChar(GetPixelBlue(image,p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)),
ScaleQuantumToShort(GetPixelGreen(image,p)),
ScaleQuantumToShort(GetPixelBlue(image,p)));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)),
ScaleQuantumToLong(GetPixelGreen(image,p)),
ScaleQuantumToLong(GetPixelBlue(image,p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
register unsigned char
*pixels;
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
register unsigned char
*pixels;
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)),
max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToLong(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
register unsigned char
*pixels;
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register unsigned char
*pixels;
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
register unsigned char
*pixels;
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_938_0 |
crossvul-cpp_data_bad_1537_1 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 1993 by OpenVision Technologies, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appears in all copies and
* that both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of OpenVision not be used
* in advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. OpenVision makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
* OPENVISION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL OPENVISION BE LIABLE FOR ANY SPECIAL, 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.
*/
/*
* Copyright (C) 1998 by the FundsXpress, INC.
*
* All rights reserved.
*
* Export of this software from the United States of America may require
* a specific license from the United States Government. It is the
* responsibility of any person or organization contemplating export to
* obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of FundsXpress. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. FundsXpress makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/*
* Copyright (c) 2006-2008, Novell, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The copyright holder's name is not used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* $Id$
*/
/* For declaration of krb5_ser_context_init */
#include "k5-int.h"
#include "gssapiP_krb5.h"
#include "mglueP.h"
#ifndef NO_PASSWORD
#include <pwd.h>
#endif
/** exported constants defined in gssapi_krb5{,_nx}.h **/
/* these are bogus, but will compile */
/*
* The OID of the draft krb5 mechanism, assigned by IETF, is:
* iso(1) org(3) dod(5) internet(1) security(5)
* kerberosv5(2) = 1.3.5.1.5.2
* The OID of the krb5_name type is:
* iso(1) member-body(2) US(840) mit(113554) infosys(1) gssapi(2)
* krb5(2) krb5_name(1) = 1.2.840.113554.1.2.2.1
* The OID of the krb5_principal type is:
* iso(1) member-body(2) US(840) mit(113554) infosys(1) gssapi(2)
* krb5(2) krb5_principal(2) = 1.2.840.113554.1.2.2.2
* The OID of the proposed standard krb5 mechanism is:
* iso(1) member-body(2) US(840) mit(113554) infosys(1) gssapi(2)
* krb5(2) = 1.2.840.113554.1.2.2
* The OID of the proposed standard krb5 v2 mechanism is:
* iso(1) member-body(2) US(840) mit(113554) infosys(1) gssapi(2)
* krb5v2(3) = 1.2.840.113554.1.2.3
* Provisionally reserved for Kerberos session key algorithm
* identifiers is:
* iso(1) member-body(2) US(840) mit(113554) infosys(1) gssapi(2)
* krb5(2) krb5_enctype(4) = 1.2.840.113554.1.2.2.4
* Provisionally reserved for Kerberos mechanism-specific APIs:
* iso(1) member-body(2) US(840) mit(113554) infosys(1) gssapi(2)
* krb5(2) krb5_gssapi_ext(5) = 1.2.840.113554.1.2.2.5
*/
/*
* Encoding rules: The first two values are encoded in one byte as 40
* * value1 + value2. Subsequent values are encoded base 128, most
* significant digit first, with the high bit (\200) set on all octets
* except the last in each value's encoding.
*/
#define NO_CI_FLAGS_X_OID_LENGTH 6
#define NO_CI_FLAGS_X_OID "\x2a\x85\x70\x2b\x0d\x1d"
const gss_OID_desc krb5_gss_oid_array[] = {
/* this is the official, rfc-specified OID */
{GSS_MECH_KRB5_OID_LENGTH, GSS_MECH_KRB5_OID},
/* this pre-RFC mech OID */
{GSS_MECH_KRB5_OLD_OID_LENGTH, GSS_MECH_KRB5_OLD_OID},
/* this is the unofficial, incorrect mech OID emitted by MS */
{GSS_MECH_KRB5_WRONG_OID_LENGTH, GSS_MECH_KRB5_WRONG_OID},
/* IAKERB OID */
{GSS_MECH_IAKERB_OID_LENGTH, GSS_MECH_IAKERB_OID},
/* this is the v2 assigned OID */
{9, "\052\206\110\206\367\022\001\002\003"},
/* these two are name type OID's */
/* 2.1.1. Kerberos Principal Name Form: (rfc 1964)
* This name form shall be represented by the Object Identifier {iso(1)
* member-body(2) United States(840) mit(113554) infosys(1) gssapi(2)
* krb5(2) krb5_name(1)}. The recommended symbolic name for this type
* is "GSS_KRB5_NT_PRINCIPAL_NAME". */
{10, "\052\206\110\206\367\022\001\002\002\001"},
/* gss_nt_krb5_principal. Object identifier for a krb5_principal. Do not use. */
{10, "\052\206\110\206\367\022\001\002\002\002"},
{NO_CI_FLAGS_X_OID_LENGTH, NO_CI_FLAGS_X_OID},
{ 0, 0 }
};
const gss_OID_desc * const gss_mech_krb5 = krb5_gss_oid_array+0;
const gss_OID_desc * const gss_mech_krb5_old = krb5_gss_oid_array+1;
const gss_OID_desc * const gss_mech_krb5_wrong = krb5_gss_oid_array+2;
const gss_OID_desc * const gss_mech_iakerb = krb5_gss_oid_array+3;
const gss_OID_desc * const gss_nt_krb5_name = krb5_gss_oid_array+5;
const gss_OID_desc * const gss_nt_krb5_principal = krb5_gss_oid_array+6;
const gss_OID_desc * const GSS_KRB5_NT_PRINCIPAL_NAME = krb5_gss_oid_array+5;
const gss_OID_desc * const GSS_KRB5_CRED_NO_CI_FLAGS_X = krb5_gss_oid_array+7;
static const gss_OID_set_desc oidsets[] = {
{1, (gss_OID) krb5_gss_oid_array+0}, /* RFC OID */
{1, (gss_OID) krb5_gss_oid_array+1}, /* pre-RFC OID */
{3, (gss_OID) krb5_gss_oid_array+0}, /* all names for krb5 mech */
{4, (gss_OID) krb5_gss_oid_array+0}, /* all krb5 names and IAKERB */
};
const gss_OID_set_desc * const gss_mech_set_krb5 = oidsets+0;
const gss_OID_set_desc * const gss_mech_set_krb5_old = oidsets+1;
const gss_OID_set_desc * const gss_mech_set_krb5_both = oidsets+2;
const gss_OID_set_desc * const kg_all_mechs = oidsets+3;
g_set kg_vdb = G_SET_INIT;
/** default credential support */
/*
* init_sec_context() will explicitly re-acquire default credentials,
* so handling the expiration/invalidation condition here isn't needed.
*/
OM_uint32
kg_get_defcred(minor_status, cred)
OM_uint32 *minor_status;
gss_cred_id_t *cred;
{
OM_uint32 major;
if ((major = krb5_gss_acquire_cred(minor_status,
(gss_name_t) NULL, GSS_C_INDEFINITE,
GSS_C_NULL_OID_SET, GSS_C_INITIATE,
cred, NULL, NULL)) && GSS_ERROR(major)) {
return(major);
}
*minor_status = 0;
return(GSS_S_COMPLETE);
}
OM_uint32
kg_sync_ccache_name (krb5_context context, OM_uint32 *minor_status)
{
OM_uint32 err = 0;
/*
* Sync up the context ccache name with the GSSAPI ccache name.
* If kg_ccache_name is NULL -- normal unless someone has called
* gss_krb5_ccache_name() -- then the system default ccache will
* be picked up and used by resetting the context default ccache.
* This is needed for platforms which support multiple ccaches.
*/
if (!err) {
/* if NULL, resets the context default ccache */
err = krb5_cc_set_default_name(context,
(char *) k5_getspecific(K5_KEY_GSS_KRB5_CCACHE_NAME));
}
*minor_status = err;
return (*minor_status == 0) ? GSS_S_COMPLETE : GSS_S_FAILURE;
}
/* This function returns whether or not the caller set a cccache name. Used by
* gss_acquire_cred to figure out if the caller wants to only look at this
* ccache or search the cache collection for the desired name */
OM_uint32
kg_caller_provided_ccache_name (OM_uint32 *minor_status,
int *out_caller_provided_name)
{
if (out_caller_provided_name) {
*out_caller_provided_name =
(k5_getspecific(K5_KEY_GSS_KRB5_CCACHE_NAME) != NULL);
}
*minor_status = 0;
return GSS_S_COMPLETE;
}
OM_uint32
kg_get_ccache_name (OM_uint32 *minor_status, const char **out_name)
{
const char *name = NULL;
OM_uint32 err = 0;
char *kg_ccache_name;
kg_ccache_name = k5_getspecific(K5_KEY_GSS_KRB5_CCACHE_NAME);
if (kg_ccache_name != NULL) {
name = strdup(kg_ccache_name);
if (name == NULL)
err = ENOMEM;
} else {
krb5_context context = NULL;
/* Reset the context default ccache (see text above), and then
retrieve it. */
err = krb5_gss_init_context(&context);
if (!err)
err = krb5_cc_set_default_name (context, NULL);
if (!err) {
name = krb5_cc_default_name(context);
if (name) {
name = strdup(name);
if (name == NULL)
err = ENOMEM;
}
}
if (err && context)
save_error_info(err, context);
if (context)
krb5_free_context(context);
}
if (!err) {
if (out_name) {
*out_name = name;
}
}
*minor_status = err;
return (*minor_status == 0) ? GSS_S_COMPLETE : GSS_S_FAILURE;
}
OM_uint32
kg_set_ccache_name (OM_uint32 *minor_status, const char *name)
{
char *new_name = NULL;
char *swap = NULL;
char *kg_ccache_name;
krb5_error_code kerr;
if (name) {
new_name = strdup(name);
if (new_name == NULL) {
*minor_status = ENOMEM;
return GSS_S_FAILURE;
}
}
kg_ccache_name = k5_getspecific(K5_KEY_GSS_KRB5_CCACHE_NAME);
swap = kg_ccache_name;
kg_ccache_name = new_name;
new_name = swap;
kerr = k5_setspecific(K5_KEY_GSS_KRB5_CCACHE_NAME, kg_ccache_name);
if (kerr != 0) {
/* Can't store, so free up the storage. */
free(kg_ccache_name);
/* ??? free(new_name); */
*minor_status = kerr;
return GSS_S_FAILURE;
}
free (new_name);
*minor_status = 0;
return GSS_S_COMPLETE;
}
#define g_OID_prefix_equal(o1, o2) \
(((o1)->length >= (o2)->length) && \
(memcmp((o1)->elements, (o2)->elements, (o2)->length) == 0))
/*
* gss_inquire_sec_context_by_oid() methods
*/
static struct {
gss_OID_desc oid;
OM_uint32 (*func)(OM_uint32 *, const gss_ctx_id_t, const gss_OID, gss_buffer_set_t *);
} krb5_gss_inquire_sec_context_by_oid_ops[] = {
{
{GSS_KRB5_GET_TKT_FLAGS_OID_LENGTH, GSS_KRB5_GET_TKT_FLAGS_OID},
gss_krb5int_get_tkt_flags
},
{
{GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_OID_LENGTH, GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_OID},
gss_krb5int_extract_authz_data_from_sec_context
},
{
{GSS_KRB5_INQ_SSPI_SESSION_KEY_OID_LENGTH, GSS_KRB5_INQ_SSPI_SESSION_KEY_OID},
gss_krb5int_inq_session_key
},
{
{GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID_LENGTH, GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID},
gss_krb5int_export_lucid_sec_context
},
{
{GSS_KRB5_EXTRACT_AUTHTIME_FROM_SEC_CONTEXT_OID_LENGTH, GSS_KRB5_EXTRACT_AUTHTIME_FROM_SEC_CONTEXT_OID},
gss_krb5int_extract_authtime_from_sec_context
}
};
OM_uint32 KRB5_CALLCONV
krb5_gss_inquire_sec_context_by_oid (OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
krb5_gss_ctx_id_rec *ctx;
size_t i;
if (minor_status == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*minor_status = 0;
if (desired_object == GSS_C_NO_OID)
return GSS_S_CALL_INACCESSIBLE_READ;
if (data_set == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*data_set = GSS_C_NO_BUFFER_SET;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (ctx->terminated || !ctx->established)
return GSS_S_NO_CONTEXT;
for (i = 0; i < sizeof(krb5_gss_inquire_sec_context_by_oid_ops)/
sizeof(krb5_gss_inquire_sec_context_by_oid_ops[0]); i++) {
if (g_OID_prefix_equal(desired_object, &krb5_gss_inquire_sec_context_by_oid_ops[i].oid)) {
return (*krb5_gss_inquire_sec_context_by_oid_ops[i].func)(minor_status,
context_handle,
desired_object,
data_set);
}
}
*minor_status = EINVAL;
return GSS_S_UNAVAILABLE;
}
/*
* gss_inquire_cred_by_oid() methods
*/
#if 0
static struct {
gss_OID_desc oid;
OM_uint32 (*func)(OM_uint32 *, const gss_cred_id_t, const gss_OID, gss_buffer_set_t *);
} krb5_gss_inquire_cred_by_oid_ops[] = {
};
#endif
static OM_uint32 KRB5_CALLCONV
krb5_gss_inquire_cred_by_oid(OM_uint32 *minor_status,
const gss_cred_id_t cred_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
OM_uint32 major_status = GSS_S_FAILURE;
#if 0
size_t i;
#endif
if (minor_status == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*minor_status = 0;
if (desired_object == GSS_C_NO_OID)
return GSS_S_CALL_INACCESSIBLE_READ;
if (data_set == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*data_set = GSS_C_NO_BUFFER_SET;
if (cred_handle == GSS_C_NO_CREDENTIAL) {
*minor_status = (OM_uint32)KRB5_NOCREDS_SUPPLIED;
return GSS_S_NO_CRED;
}
major_status = krb5_gss_validate_cred(minor_status, cred_handle);
if (GSS_ERROR(major_status))
return major_status;
#if 0
for (i = 0; i < sizeof(krb5_gss_inquire_cred_by_oid_ops)/
sizeof(krb5_gss_inquire_cred_by_oid_ops[0]); i++) {
if (g_OID_prefix_equal(desired_object, &krb5_gss_inquire_cred_by_oid_ops[i].oid)) {
return (*krb5_gss_inquire_cred_by_oid_ops[i].func)(minor_status,
cred_handle,
desired_object,
data_set);
}
}
#endif
*minor_status = EINVAL;
return GSS_S_UNAVAILABLE;
}
/*
* gss_set_sec_context_option() methods
* (Disabled until we have something to populate the array.)
*/
#if 0
static struct {
gss_OID_desc oid;
OM_uint32 (*func)(OM_uint32 *, gss_ctx_id_t *, const gss_OID, const gss_buffer_t);
} krb5_gss_set_sec_context_option_ops[] = {
};
#endif
OM_uint32 KRB5_CALLCONV
krb5_gss_set_sec_context_option (OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
const gss_OID desired_object,
const gss_buffer_t value)
{
#if 0
size_t i;
#endif
if (minor_status == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*minor_status = 0;
if (context_handle == NULL)
return GSS_S_CALL_INACCESSIBLE_READ;
if (desired_object == GSS_C_NO_OID)
return GSS_S_CALL_INACCESSIBLE_READ;
#if 0
for (i = 0; i < sizeof(krb5_gss_set_sec_context_option_ops)/
sizeof(krb5_gss_set_sec_context_option_ops[0]); i++) {
if (g_OID_prefix_equal(desired_object, &krb5_gss_set_sec_context_option_ops[i].oid)) {
return (*krb5_gss_set_sec_context_option_ops[i].func)(minor_status,
context_handle,
desired_object,
value);
}
}
#endif
*minor_status = EINVAL;
return GSS_S_UNAVAILABLE;
}
static OM_uint32
no_ci_flags(OM_uint32 *minor_status,
gss_cred_id_t *cred_handle,
const gss_OID desired_oid,
const gss_buffer_t value)
{
krb5_gss_cred_id_t cred;
cred = (krb5_gss_cred_id_t) *cred_handle;
cred->suppress_ci_flags = 1;
*minor_status = 0;
return GSS_S_COMPLETE;
}
/*
* gssspi_set_cred_option() methods
*/
static struct {
gss_OID_desc oid;
OM_uint32 (*func)(OM_uint32 *, gss_cred_id_t *, const gss_OID, const gss_buffer_t);
} krb5_gssspi_set_cred_option_ops[] = {
{
{GSS_KRB5_COPY_CCACHE_OID_LENGTH, GSS_KRB5_COPY_CCACHE_OID},
gss_krb5int_copy_ccache
},
{
{GSS_KRB5_SET_ALLOWABLE_ENCTYPES_OID_LENGTH, GSS_KRB5_SET_ALLOWABLE_ENCTYPES_OID},
gss_krb5int_set_allowable_enctypes
},
{
{GSS_KRB5_SET_CRED_RCACHE_OID_LENGTH, GSS_KRB5_SET_CRED_RCACHE_OID},
gss_krb5int_set_cred_rcache
},
{
{GSS_KRB5_IMPORT_CRED_OID_LENGTH, GSS_KRB5_IMPORT_CRED_OID},
gss_krb5int_import_cred
},
{
{NO_CI_FLAGS_X_OID_LENGTH, NO_CI_FLAGS_X_OID},
no_ci_flags
},
};
static OM_uint32 KRB5_CALLCONV
krb5_gssspi_set_cred_option(OM_uint32 *minor_status,
gss_cred_id_t *cred_handle,
const gss_OID desired_object,
const gss_buffer_t value)
{
OM_uint32 major_status = GSS_S_FAILURE;
size_t i;
if (minor_status == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
if (cred_handle == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*minor_status = 0;
if (desired_object == GSS_C_NO_OID)
return GSS_S_CALL_INACCESSIBLE_READ;
if (*cred_handle != GSS_C_NO_CREDENTIAL) {
major_status = krb5_gss_validate_cred(minor_status, *cred_handle);
if (GSS_ERROR(major_status))
return major_status;
}
for (i = 0; i < sizeof(krb5_gssspi_set_cred_option_ops)/
sizeof(krb5_gssspi_set_cred_option_ops[0]); i++) {
if (g_OID_prefix_equal(desired_object, &krb5_gssspi_set_cred_option_ops[i].oid)) {
return (*krb5_gssspi_set_cred_option_ops[i].func)(minor_status,
cred_handle,
desired_object,
value);
}
}
*minor_status = EINVAL;
return GSS_S_UNAVAILABLE;
}
/*
* gssspi_mech_invoke() methods
*/
static struct {
gss_OID_desc oid;
OM_uint32 (*func)(OM_uint32 *, const gss_OID, const gss_OID, gss_buffer_t);
} krb5_gssspi_mech_invoke_ops[] = {
{
{GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_OID_LENGTH, GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_OID},
gss_krb5int_register_acceptor_identity
},
{
{GSS_KRB5_CCACHE_NAME_OID_LENGTH, GSS_KRB5_CCACHE_NAME_OID},
gss_krb5int_ccache_name
},
{
{GSS_KRB5_FREE_LUCID_SEC_CONTEXT_OID_LENGTH, GSS_KRB5_FREE_LUCID_SEC_CONTEXT_OID},
gss_krb5int_free_lucid_sec_context
},
#ifndef _WIN32
{
{GSS_KRB5_USE_KDC_CONTEXT_OID_LENGTH, GSS_KRB5_USE_KDC_CONTEXT_OID},
krb5int_gss_use_kdc_context
},
#endif
};
static OM_uint32 KRB5_CALLCONV
krb5_gssspi_mech_invoke (OM_uint32 *minor_status,
const gss_OID desired_mech,
const gss_OID desired_object,
gss_buffer_t value)
{
size_t i;
if (minor_status == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*minor_status = 0;
if (desired_mech == GSS_C_NO_OID)
return GSS_S_BAD_MECH;
if (desired_object == GSS_C_NO_OID)
return GSS_S_CALL_INACCESSIBLE_READ;
for (i = 0; i < sizeof(krb5_gssspi_mech_invoke_ops)/
sizeof(krb5_gssspi_mech_invoke_ops[0]); i++) {
if (g_OID_prefix_equal(desired_object, &krb5_gssspi_mech_invoke_ops[i].oid)) {
return (*krb5_gssspi_mech_invoke_ops[i].func)(minor_status,
desired_mech,
desired_object,
value);
}
}
*minor_status = EINVAL;
return GSS_S_UNAVAILABLE;
}
#define GS2_KRB5_SASL_NAME "GS2-KRB5"
#define GS2_KRB5_SASL_NAME_LEN (sizeof(GS2_KRB5_SASL_NAME) - 1)
#define GS2_IAKERB_SASL_NAME "GS2-IAKERB"
#define GS2_IAKERB_SASL_NAME_LEN (sizeof(GS2_IAKERB_SASL_NAME) - 1)
static OM_uint32 KRB5_CALLCONV
krb5_gss_inquire_mech_for_saslname(OM_uint32 *minor_status,
const gss_buffer_t sasl_mech_name,
gss_OID *mech_type)
{
*minor_status = 0;
if (sasl_mech_name->length == GS2_KRB5_SASL_NAME_LEN &&
memcmp(sasl_mech_name->value,
GS2_KRB5_SASL_NAME, GS2_KRB5_SASL_NAME_LEN) == 0) {
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_krb5;
return GSS_S_COMPLETE;
} else if (sasl_mech_name->length == GS2_IAKERB_SASL_NAME_LEN &&
memcmp(sasl_mech_name->value,
GS2_IAKERB_SASL_NAME, GS2_IAKERB_SASL_NAME_LEN) == 0) {
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_iakerb;
return GSS_S_COMPLETE;
}
return GSS_S_BAD_MECH;
}
static OM_uint32 KRB5_CALLCONV
krb5_gss_inquire_saslname_for_mech(OM_uint32 *minor_status,
const gss_OID desired_mech,
gss_buffer_t sasl_mech_name,
gss_buffer_t mech_name,
gss_buffer_t mech_description)
{
if (g_OID_equal(desired_mech, gss_mech_iakerb)) {
if (!g_make_string_buffer(GS2_IAKERB_SASL_NAME, sasl_mech_name) ||
!g_make_string_buffer("iakerb", mech_name) ||
!g_make_string_buffer("Initial and Pass Through Authentication "
"Kerberos Mechanism (IAKERB)",
mech_description))
goto fail;
} else {
if (!g_make_string_buffer(GS2_KRB5_SASL_NAME, sasl_mech_name) ||
!g_make_string_buffer("krb5", mech_name) ||
!g_make_string_buffer("Kerberos 5 GSS-API Mechanism",
mech_description))
goto fail;
}
*minor_status = 0;
return GSS_S_COMPLETE;
fail:
*minor_status = ENOMEM;
return GSS_S_FAILURE;
}
static OM_uint32 KRB5_CALLCONV
krb5_gss_inquire_attrs_for_mech(OM_uint32 *minor_status,
gss_const_OID mech,
gss_OID_set *mech_attrs,
gss_OID_set *known_mech_attrs)
{
OM_uint32 major, tmpMinor;
if (mech_attrs == NULL) {
*minor_status = 0;
return GSS_S_COMPLETE;
}
major = gss_create_empty_oid_set(minor_status, mech_attrs);
if (GSS_ERROR(major))
goto cleanup;
#define MA_SUPPORTED(ma) do { \
major = gss_add_oid_set_member(minor_status, (gss_OID)ma, \
mech_attrs); \
if (GSS_ERROR(major)) \
goto cleanup; \
} while (0)
MA_SUPPORTED(GSS_C_MA_MECH_CONCRETE);
MA_SUPPORTED(GSS_C_MA_ITOK_FRAMED);
MA_SUPPORTED(GSS_C_MA_AUTH_INIT);
MA_SUPPORTED(GSS_C_MA_AUTH_TARG);
MA_SUPPORTED(GSS_C_MA_DELEG_CRED);
MA_SUPPORTED(GSS_C_MA_INTEG_PROT);
MA_SUPPORTED(GSS_C_MA_CONF_PROT);
MA_SUPPORTED(GSS_C_MA_MIC);
MA_SUPPORTED(GSS_C_MA_WRAP);
MA_SUPPORTED(GSS_C_MA_PROT_READY);
MA_SUPPORTED(GSS_C_MA_REPLAY_DET);
MA_SUPPORTED(GSS_C_MA_OOS_DET);
MA_SUPPORTED(GSS_C_MA_CBINDINGS);
MA_SUPPORTED(GSS_C_MA_CTX_TRANS);
if (g_OID_equal(mech, gss_mech_iakerb)) {
MA_SUPPORTED(GSS_C_MA_AUTH_INIT_INIT);
MA_SUPPORTED(GSS_C_MA_NOT_DFLT_MECH);
} else if (!g_OID_equal(mech, gss_mech_krb5)) {
MA_SUPPORTED(GSS_C_MA_DEPRECATED);
}
cleanup:
if (GSS_ERROR(major))
gss_release_oid_set(&tmpMinor, mech_attrs);
return major;
}
static OM_uint32 KRB5_CALLCONV
krb5_gss_localname(OM_uint32 *minor,
const gss_name_t pname,
const gss_const_OID mech_type,
gss_buffer_t localname)
{
krb5_context context;
krb5_error_code code;
krb5_gss_name_t kname;
char lname[BUFSIZ];
code = krb5_gss_init_context(&context);
if (code != 0) {
*minor = code;
return GSS_S_FAILURE;
}
kname = (krb5_gss_name_t)pname;
code = krb5_aname_to_localname(context, kname->princ,
sizeof(lname), lname);
if (code != 0) {
*minor = KRB5_NO_LOCALNAME;
krb5_free_context(context);
return GSS_S_FAILURE;
}
krb5_free_context(context);
localname->value = gssalloc_strdup(lname);
localname->length = strlen(lname);
return (code == 0) ? GSS_S_COMPLETE : GSS_S_FAILURE;
}
static OM_uint32 KRB5_CALLCONV
krb5_gss_authorize_localname(OM_uint32 *minor,
const gss_name_t pname,
gss_const_buffer_t local_user,
gss_const_OID name_type)
{
krb5_context context;
krb5_error_code code;
krb5_gss_name_t kname;
char *user;
int user_ok;
if (name_type != GSS_C_NO_OID &&
!g_OID_equal(name_type, GSS_C_NT_USER_NAME)) {
return GSS_S_BAD_NAMETYPE;
}
kname = (krb5_gss_name_t)pname;
code = krb5_gss_init_context(&context);
if (code != 0) {
*minor = code;
return GSS_S_FAILURE;
}
user = k5memdup0(local_user->value, local_user->length, &code);
if (user == NULL) {
*minor = code;
krb5_free_context(context);
return GSS_S_FAILURE;
}
user_ok = krb5_kuserok(context, kname->princ, user);
free(user);
krb5_free_context(context);
*minor = 0;
return user_ok ? GSS_S_COMPLETE : GSS_S_UNAUTHORIZED;
}
static struct gss_config krb5_mechanism = {
{ GSS_MECH_KRB5_OID_LENGTH, GSS_MECH_KRB5_OID },
NULL,
krb5_gss_acquire_cred,
krb5_gss_release_cred,
krb5_gss_init_sec_context,
#ifdef LEAN_CLIENT
NULL,
#else
krb5_gss_accept_sec_context,
#endif
krb5_gss_process_context_token,
krb5_gss_delete_sec_context,
krb5_gss_context_time,
krb5_gss_get_mic,
krb5_gss_verify_mic,
#if defined(IOV_SHIM_EXERCISE_WRAP) || defined(IOV_SHIM_EXERCISE)
NULL,
#else
krb5_gss_wrap,
#endif
#if defined(IOV_SHIM_EXERCISE_UNWRAP) || defined(IOV_SHIM_EXERCISE)
NULL,
#else
krb5_gss_unwrap,
#endif
krb5_gss_display_status,
krb5_gss_indicate_mechs,
krb5_gss_compare_name,
krb5_gss_display_name,
krb5_gss_import_name,
krb5_gss_release_name,
krb5_gss_inquire_cred,
NULL, /* add_cred */
#ifdef LEAN_CLIENT
NULL,
NULL,
#else
krb5_gss_export_sec_context,
krb5_gss_import_sec_context,
#endif
krb5_gss_inquire_cred_by_mech,
krb5_gss_inquire_names_for_mech,
krb5_gss_inquire_context,
krb5_gss_internal_release_oid,
krb5_gss_wrap_size_limit,
krb5_gss_localname,
krb5_gss_authorize_localname,
krb5_gss_export_name,
krb5_gss_duplicate_name,
krb5_gss_store_cred,
krb5_gss_inquire_sec_context_by_oid,
krb5_gss_inquire_cred_by_oid,
krb5_gss_set_sec_context_option,
krb5_gssspi_set_cred_option,
krb5_gssspi_mech_invoke,
NULL, /* wrap_aead */
NULL, /* unwrap_aead */
krb5_gss_wrap_iov,
krb5_gss_unwrap_iov,
krb5_gss_wrap_iov_length,
NULL, /* complete_auth_token */
krb5_gss_acquire_cred_impersonate_name,
NULL, /* krb5_gss_add_cred_impersonate_name */
NULL, /* display_name_ext */
krb5_gss_inquire_name,
krb5_gss_get_name_attribute,
krb5_gss_set_name_attribute,
krb5_gss_delete_name_attribute,
krb5_gss_export_name_composite,
krb5_gss_map_name_to_any,
krb5_gss_release_any_name_mapping,
krb5_gss_pseudo_random,
NULL, /* set_neg_mechs */
krb5_gss_inquire_saslname_for_mech,
krb5_gss_inquire_mech_for_saslname,
krb5_gss_inquire_attrs_for_mech,
krb5_gss_acquire_cred_from,
krb5_gss_store_cred_into,
krb5_gss_acquire_cred_with_password,
krb5_gss_export_cred,
krb5_gss_import_cred,
NULL, /* import_sec_context_by_mech */
NULL, /* import_name_by_mech */
NULL, /* import_cred_by_mech */
krb5_gss_get_mic_iov,
krb5_gss_verify_mic_iov,
krb5_gss_get_mic_iov_length,
};
/* Functions which use security contexts or acquire creds are IAKERB-specific;
* other functions can borrow from the krb5 mech. */
static struct gss_config iakerb_mechanism = {
{ GSS_MECH_KRB5_OID_LENGTH, GSS_MECH_KRB5_OID },
NULL,
iakerb_gss_acquire_cred,
krb5_gss_release_cred,
iakerb_gss_init_sec_context,
#ifdef LEAN_CLIENT
NULL,
#else
iakerb_gss_accept_sec_context,
#endif
iakerb_gss_process_context_token,
iakerb_gss_delete_sec_context,
iakerb_gss_context_time,
iakerb_gss_get_mic,
iakerb_gss_verify_mic,
#if defined(IOV_SHIM_EXERCISE_WRAP) || defined(IOV_SHIM_EXERCISE)
NULL,
#else
iakerb_gss_wrap,
#endif
#if defined(IOV_SHIM_EXERCISE_UNWRAP) || defined(IOV_SHIM_EXERCISE)
NULL,
#else
iakerb_gss_unwrap,
#endif
krb5_gss_display_status,
krb5_gss_indicate_mechs,
krb5_gss_compare_name,
krb5_gss_display_name,
krb5_gss_import_name,
krb5_gss_release_name,
krb5_gss_inquire_cred,
NULL, /* add_cred */
#ifdef LEAN_CLIENT
NULL,
NULL,
#else
iakerb_gss_export_sec_context,
NULL,
#endif
krb5_gss_inquire_cred_by_mech,
krb5_gss_inquire_names_for_mech,
iakerb_gss_inquire_context,
krb5_gss_internal_release_oid,
iakerb_gss_wrap_size_limit,
krb5_gss_localname,
krb5_gss_authorize_localname,
krb5_gss_export_name,
krb5_gss_duplicate_name,
krb5_gss_store_cred,
iakerb_gss_inquire_sec_context_by_oid,
krb5_gss_inquire_cred_by_oid,
iakerb_gss_set_sec_context_option,
krb5_gssspi_set_cred_option,
krb5_gssspi_mech_invoke,
NULL, /* wrap_aead */
NULL, /* unwrap_aead */
iakerb_gss_wrap_iov,
iakerb_gss_unwrap_iov,
iakerb_gss_wrap_iov_length,
NULL, /* complete_auth_token */
NULL, /* acquire_cred_impersonate_name */
NULL, /* add_cred_impersonate_name */
NULL, /* display_name_ext */
krb5_gss_inquire_name,
krb5_gss_get_name_attribute,
krb5_gss_set_name_attribute,
krb5_gss_delete_name_attribute,
krb5_gss_export_name_composite,
krb5_gss_map_name_to_any,
krb5_gss_release_any_name_mapping,
iakerb_gss_pseudo_random,
NULL, /* set_neg_mechs */
krb5_gss_inquire_saslname_for_mech,
krb5_gss_inquire_mech_for_saslname,
krb5_gss_inquire_attrs_for_mech,
krb5_gss_acquire_cred_from,
krb5_gss_store_cred_into,
iakerb_gss_acquire_cred_with_password,
krb5_gss_export_cred,
krb5_gss_import_cred,
NULL, /* import_sec_context_by_mech */
NULL, /* import_name_by_mech */
NULL, /* import_cred_by_mech */
iakerb_gss_get_mic_iov,
iakerb_gss_verify_mic_iov,
iakerb_gss_get_mic_iov_length,
};
#ifdef _GSS_STATIC_LINK
#include "mglueP.h"
static int gss_iakerbmechglue_init(void)
{
struct gss_mech_config mech_iakerb;
memset(&mech_iakerb, 0, sizeof(mech_iakerb));
mech_iakerb.mech = &iakerb_mechanism;
mech_iakerb.mechNameStr = "iakerb";
mech_iakerb.mech_type = (gss_OID)gss_mech_iakerb;
gssint_register_mechinfo(&mech_iakerb);
return 0;
}
static int gss_krb5mechglue_init(void)
{
struct gss_mech_config mech_krb5;
memset(&mech_krb5, 0, sizeof(mech_krb5));
mech_krb5.mech = &krb5_mechanism;
mech_krb5.mechNameStr = "kerberos_v5";
mech_krb5.mech_type = (gss_OID)gss_mech_krb5;
gssint_register_mechinfo(&mech_krb5);
mech_krb5.mechNameStr = "kerberos_v5_old";
mech_krb5.mech_type = (gss_OID)gss_mech_krb5_old;
gssint_register_mechinfo(&mech_krb5);
mech_krb5.mechNameStr = "mskrb";
mech_krb5.mech_type = (gss_OID)gss_mech_krb5_wrong;
gssint_register_mechinfo(&mech_krb5);
return 0;
}
#else
MAKE_INIT_FUNCTION(gss_krb5int_lib_init);
MAKE_FINI_FUNCTION(gss_krb5int_lib_fini);
gss_mechanism KRB5_CALLCONV
gss_mech_initialize(void)
{
return &krb5_mechanism;
}
#endif /* _GSS_STATIC_LINK */
int gss_krb5int_lib_init(void)
{
int err;
#ifdef SHOW_INITFINI_FUNCS
printf("gss_krb5int_lib_init\n");
#endif
add_error_table(&et_k5g_error_table);
#ifndef LEAN_CLIENT
err = k5_mutex_finish_init(&gssint_krb5_keytab_lock);
if (err)
return err;
#endif /* LEAN_CLIENT */
err = k5_key_register(K5_KEY_GSS_KRB5_SET_CCACHE_OLD_NAME, free);
if (err)
return err;
err = k5_key_register(K5_KEY_GSS_KRB5_CCACHE_NAME, free);
if (err)
return err;
err = k5_key_register(K5_KEY_GSS_KRB5_ERROR_MESSAGE,
krb5_gss_delete_error_info);
if (err)
return err;
#ifndef _WIN32
err = k5_mutex_finish_init(&kg_kdc_flag_mutex);
if (err)
return err;
err = k5_mutex_finish_init(&kg_vdb.mutex);
if (err)
return err;
#endif
#ifdef _GSS_STATIC_LINK
err = gss_krb5mechglue_init();
if (err)
return err;
err = gss_iakerbmechglue_init();
if (err)
return err;
#endif
return 0;
}
void gss_krb5int_lib_fini(void)
{
#ifndef _GSS_STATIC_LINK
if (!INITIALIZER_RAN(gss_krb5int_lib_init) || PROGRAM_EXITING()) {
# ifdef SHOW_INITFINI_FUNCS
printf("gss_krb5int_lib_fini: skipping\n");
# endif
return;
}
#endif
#ifdef SHOW_INITFINI_FUNCS
printf("gss_krb5int_lib_fini\n");
#endif
remove_error_table(&et_k5g_error_table);
k5_key_delete(K5_KEY_GSS_KRB5_SET_CCACHE_OLD_NAME);
k5_key_delete(K5_KEY_GSS_KRB5_CCACHE_NAME);
k5_key_delete(K5_KEY_GSS_KRB5_ERROR_MESSAGE);
k5_mutex_destroy(&kg_vdb.mutex);
#ifndef _WIN32
k5_mutex_destroy(&kg_kdc_flag_mutex);
#endif
#ifndef LEAN_CLIENT
k5_mutex_destroy(&gssint_krb5_keytab_lock);
#endif /* LEAN_CLIENT */
}
#ifdef _GSS_STATIC_LINK
extern OM_uint32 gssint_lib_init(void);
#endif
OM_uint32 gss_krb5int_initialize_library (void)
{
#ifdef _GSS_STATIC_LINK
return gssint_mechglue_initialize_library();
#else
return CALL_INIT_FUNCTION(gss_krb5int_lib_init);
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1537_1 |
crossvul-cpp_data_good_374_0 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* RFC4616 PLAIN authentication
* Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#include "urldata.h"
#include "vauth/vauth.h"
#include "curl_base64.h"
#include "curl_md5.h"
#include "warnless.h"
#include "strtok.h"
#include "sendf.h"
#include "curl_printf.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
/*
* Curl_auth_create_plain_message()
*
* This is used to generate an already encoded PLAIN message ready
* for sending to the recipient.
*
* Parameters:
*
* data [in] - The session handle.
* userp [in] - The user name.
* passwdp [in] - The user's password.
* outptr [in/out] - The address where a pointer to newly allocated memory
* holding the result will be stored upon completion.
* outlen [out] - The length of the output message.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_auth_create_plain_message(struct Curl_easy *data,
const char *userp,
const char *passwdp,
char **outptr, size_t *outlen)
{
CURLcode result;
char *plainauth;
size_t ulen;
size_t plen;
size_t plainlen;
*outlen = 0;
*outptr = NULL;
ulen = strlen(userp);
plen = strlen(passwdp);
/* Compute binary message length. Check for overflows. */
if((ulen > SIZE_T_MAX/4) || (plen > (SIZE_T_MAX/2 - 2)))
return CURLE_OUT_OF_MEMORY;
plainlen = 2 * ulen + plen + 2;
plainauth = malloc(plainlen);
if(!plainauth)
return CURLE_OUT_OF_MEMORY;
/* Calculate the reply */
memcpy(plainauth, userp, ulen);
plainauth[ulen] = '\0';
memcpy(plainauth + ulen + 1, userp, ulen);
plainauth[2 * ulen + 1] = '\0';
memcpy(plainauth + 2 * ulen + 2, passwdp, plen);
/* Base64 encode the reply */
result = Curl_base64_encode(data, plainauth, plainlen, outptr, outlen);
free(plainauth);
return result;
}
/*
* Curl_auth_create_login_message()
*
* This is used to generate an already encoded LOGIN message containing the
* user name or password ready for sending to the recipient.
*
* Parameters:
*
* data [in] - The session handle.
* valuep [in] - The user name or user's password.
* outptr [in/out] - The address where a pointer to newly allocated memory
* holding the result will be stored upon completion.
* outlen [out] - The length of the output message.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_auth_create_login_message(struct Curl_easy *data,
const char *valuep, char **outptr,
size_t *outlen)
{
size_t vlen = strlen(valuep);
if(!vlen) {
/* Calculate an empty reply */
*outptr = strdup("=");
if(*outptr) {
*outlen = (size_t) 1;
return CURLE_OK;
}
*outlen = 0;
return CURLE_OUT_OF_MEMORY;
}
/* Base64 encode the value */
return Curl_base64_encode(data, valuep, vlen, outptr, outlen);
}
/*
* Curl_auth_create_external_message()
*
* This is used to generate an already encoded EXTERNAL message containing
* the user name ready for sending to the recipient.
*
* Parameters:
*
* data [in] - The session handle.
* user [in] - The user name.
* outptr [in/out] - The address where a pointer to newly allocated memory
* holding the result will be stored upon completion.
* outlen [out] - The length of the output message.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_auth_create_external_message(struct Curl_easy *data,
const char *user, char **outptr,
size_t *outlen)
{
/* This is the same formatting as the login message */
return Curl_auth_create_login_message(data, user, outptr, outlen);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_374_0 |
crossvul-cpp_data_bad_344_7 | /*
* sc.c: General functions
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#ifdef ENABLE_OPENSSL
#include <openssl/crypto.h> /* for OPENSSL_cleanse */
#endif
#include "internal.h"
#ifdef PACKAGE_VERSION
static const char *sc_version = PACKAGE_VERSION;
#else
static const char *sc_version = "(undef)";
#endif
const char *sc_get_version(void)
{
return sc_version;
}
int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen)
{
int err = SC_SUCCESS;
size_t left, count = 0, in_len;
if (in == NULL || out == NULL || outlen == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
left = *outlen;
in_len = strlen(in);
while (*in != '\0') {
int byte = 0, nybbles = 2;
while (nybbles-- && *in && *in != ':' && *in != ' ') {
char c;
byte <<= 4;
c = *in++;
if ('0' <= c && c <= '9')
c -= '0';
else
if ('a' <= c && c <= 'f')
c = c - 'a' + 10;
else
if ('A' <= c && c <= 'F')
c = c - 'A' + 10;
else {
err = SC_ERROR_INVALID_ARGUMENTS;
goto out;
}
byte |= c;
}
/* Detect premature end of string before byte is complete */
if (in_len > 1 && *in == '\0' && nybbles >= 0) {
err = SC_ERROR_INVALID_ARGUMENTS;
break;
}
if (*in == ':' || *in == ' ')
in++;
if (left <= 0) {
err = SC_ERROR_BUFFER_TOO_SMALL;
break;
}
out[count++] = (u8) byte;
left--;
}
out:
*outlen = count;
return err;
}
int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len,
int in_sep)
{
unsigned int n, sep_len;
char *pos, *end, sep;
sep = (char)in_sep;
sep_len = sep > 0 ? 1 : 0;
pos = out;
end = out + out_len;
for (n = 0; n < in_len; n++) {
if (pos + 3 + sep_len >= end)
return SC_ERROR_BUFFER_TOO_SMALL;
if (n && sep_len)
*pos++ = sep;
sprintf(pos, "%02x", in[n]);
pos += 2;
}
*pos = '\0';
return SC_SUCCESS;
}
/*
* Right trim all non-printable characters
*/
size_t sc_right_trim(u8 *buf, size_t len) {
size_t i;
if (!buf)
return 0;
if (len > 0) {
for(i = len-1; i > 0; i--) {
if(!isprint(buf[i])) {
buf[i] = '\0';
len--;
continue;
}
break;
}
}
return len;
}
u8 *ulong2bebytes(u8 *buf, unsigned long x)
{
if (buf != NULL) {
buf[3] = (u8) (x & 0xff);
buf[2] = (u8) ((x >> 8) & 0xff);
buf[1] = (u8) ((x >> 16) & 0xff);
buf[0] = (u8) ((x >> 24) & 0xff);
}
return buf;
}
u8 *ushort2bebytes(u8 *buf, unsigned short x)
{
if (buf != NULL) {
buf[1] = (u8) (x & 0xff);
buf[0] = (u8) ((x >> 8) & 0xff);
}
return buf;
}
unsigned long bebytes2ulong(const u8 *buf)
{
if (buf == NULL)
return 0UL;
return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]);
}
unsigned short bebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short) (buf[0] << 8 | buf[1]);
}
unsigned short lebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short)buf[1] << 8 | (unsigned short)buf[0];
}
void sc_init_oid(struct sc_object_id *oid)
{
int ii;
if (!oid)
return;
for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++)
oid->value[ii] = -1;
}
int sc_format_oid(struct sc_object_id *oid, const char *in)
{
int ii, ret = SC_ERROR_INVALID_ARGUMENTS;
const char *p;
char *q;
if (oid == NULL || in == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
sc_init_oid(oid);
p = in;
for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) {
oid->value[ii] = strtol(p, &q, 10);
if (!*q)
break;
if (!(q[0] == '.' && isdigit(q[1])))
goto out;
p = q + 1;
}
if (!sc_valid_oid(oid))
goto out;
ret = SC_SUCCESS;
out:
if (ret)
sc_init_oid(oid);
return ret;
}
int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2)
{
int i;
if (oid1 == NULL || oid2 == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) {
if (oid1->value[i] != oid2->value[i])
return 0;
if (oid1->value[i] == -1)
break;
}
return 1;
}
int sc_valid_oid(const struct sc_object_id *oid)
{
int ii;
if (!oid)
return 0;
if (oid->value[0] == -1 || oid->value[1] == -1)
return 0;
if (oid->value[0] > 2 || oid->value[1] > 39)
return 0;
for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++)
if (oid->value[ii])
break;
if (ii==SC_MAX_OBJECT_ID_OCTETS)
return 0;
return 1;
}
int sc_detect_card_presence(sc_reader_t *reader)
{
int r;
LOG_FUNC_CALLED(reader->ctx);
if (reader->ops->detect_card_presence == NULL)
LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED);
r = reader->ops->detect_card_presence(reader);
LOG_FUNC_RETURN(reader->ctx, r);
}
int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len,
int idx, int count)
{
if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(path, 0, sizeof(*path));
memcpy(path->value, id, id_len);
path->len = id_len;
path->type = type;
path->index = idx;
path->count = count;
return SC_SUCCESS;
}
void sc_format_path(const char *str, sc_path_t *path)
{
int type = SC_PATH_TYPE_PATH;
if (path) {
memset(path, 0, sizeof(*path));
if (*str == 'i' || *str == 'I') {
type = SC_PATH_TYPE_FILE_ID;
str++;
}
path->len = sizeof(path->value);
if (sc_hex_to_bin(str, path->value, &path->len) >= 0) {
path->type = type;
}
path->count = -1;
}
}
int sc_append_path(sc_path_t *dest, const sc_path_t *src)
{
return sc_concatenate_path(dest, dest, src);
}
int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen)
{
if (dest->len + idlen > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memcpy(dest->value + dest->len, id, idlen);
dest->len += idlen;
return SC_SUCCESS;
}
int sc_append_file_id(sc_path_t *dest, unsigned int fid)
{
u8 id[2] = { fid >> 8, fid & 0xff };
return sc_append_path_id(dest, id, 2);
}
int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2)
{
sc_path_t tpath;
if (d == NULL || p1 == NULL || p2 == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME)
/* we do not support concatenation of AIDs at the moment */
return SC_ERROR_NOT_SUPPORTED;
if (p1->len + p2->len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(&tpath, 0, sizeof(sc_path_t));
memcpy(tpath.value, p1->value, p1->len);
memcpy(tpath.value + p1->len, p2->value, p2->len);
tpath.len = p1->len + p2->len;
tpath.type = SC_PATH_TYPE_PATH;
/* use 'index' and 'count' entry of the second path object */
tpath.index = p2->index;
tpath.count = p2->count;
/* the result is currently always as path */
tpath.type = SC_PATH_TYPE_PATH;
*d = tpath;
return SC_SUCCESS;
}
const char *sc_print_path(const sc_path_t *path)
{
static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE];
if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS)
buffer[0] = '\0';
return buffer;
}
int sc_path_print(char *buf, size_t buflen, const sc_path_t *path)
{
size_t i;
if (buf == NULL || path == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (buflen < path->len * 2 + path->aid.len * 2 + 1)
return SC_ERROR_BUFFER_TOO_SMALL;
buf[0] = '\0';
if (path->aid.len) {
for (i = 0; i < path->aid.len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]);
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
}
for (i = 0; i < path->len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]);
if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME)
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
return SC_SUCCESS;
}
int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2)
{
return path1->len == path2->len
&& !memcmp(path1->value, path2->value, path1->len);
}
int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path)
{
sc_path_t tpath;
if (prefix->len > path->len)
return 0;
tpath = *path;
tpath.len = prefix->len;
return sc_compare_path(&tpath, prefix);
}
const sc_path_t *sc_get_mf_path(void)
{
static const sc_path_t mf_path = {
{0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2,
0,
0,
SC_PATH_TYPE_PATH,
{{0},0}
};
return &mf_path;
}
int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation,
unsigned int method, unsigned long key_ref)
{
sc_acl_entry_t *p, *_new;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return SC_ERROR_INVALID_ARGUMENTS;
}
switch (method) {
case SC_AC_NEVER:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 1;
return SC_SUCCESS;
case SC_AC_NONE:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 2;
return SC_SUCCESS;
case SC_AC_UNKNOWN:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 3;
return SC_SUCCESS;
default:
/* NONE and UNKNOWN get zapped when a new AC is added.
* If the ACL is NEVER, additional entries will be
* dropped silently. */
if (file->acl[operation] == (sc_acl_entry_t *) 1)
return SC_SUCCESS;
if (file->acl[operation] == (sc_acl_entry_t *) 2
|| file->acl[operation] == (sc_acl_entry_t *) 3)
file->acl[operation] = NULL;
}
/* If the entry is already present (e.g. due to the mapping)
* of the card's AC with OpenSC's), don't add it again. */
for (p = file->acl[operation]; p != NULL; p = p->next) {
if ((p->method == method) && (p->key_ref == key_ref))
return SC_SUCCESS;
}
_new = malloc(sizeof(sc_acl_entry_t));
if (_new == NULL)
return SC_ERROR_OUT_OF_MEMORY;
_new->method = method;
_new->key_ref = key_ref;
_new->next = NULL;
p = file->acl[operation];
if (p == NULL) {
file->acl[operation] = _new;
return SC_SUCCESS;
}
while (p->next != NULL)
p = p->next;
p->next = _new;
return SC_SUCCESS;
}
const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file,
unsigned int operation)
{
sc_acl_entry_t *p;
static const sc_acl_entry_t e_never = {
SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_none = {
SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_unknown = {
SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return NULL;
}
p = file->acl[operation];
if (p == (sc_acl_entry_t *) 1)
return &e_never;
if (p == (sc_acl_entry_t *) 2)
return &e_none;
if (p == (sc_acl_entry_t *) 3)
return &e_unknown;
return file->acl[operation];
}
void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation)
{
sc_acl_entry_t *e;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return;
}
e = file->acl[operation];
if (e == (sc_acl_entry_t *) 1 ||
e == (sc_acl_entry_t *) 2 ||
e == (sc_acl_entry_t *) 3) {
file->acl[operation] = NULL;
return;
}
while (e != NULL) {
sc_acl_entry_t *tmp = e->next;
free(e);
e = tmp;
}
file->acl[operation] = NULL;
}
sc_file_t * sc_file_new(void)
{
sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t));
if (file == NULL)
return NULL;
file->magic = SC_FILE_MAGIC;
return file;
}
void sc_file_free(sc_file_t *file)
{
unsigned int i;
if (file == NULL || !sc_file_valid(file))
return;
file->magic = 0;
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_clear_acl_entries(file, i);
if (file->sec_attr)
free(file->sec_attr);
if (file->prop_attr)
free(file->prop_attr);
if (file->type_attr)
free(file->type_attr);
if (file->encoded_content)
free(file->encoded_content);
free(file);
}
void sc_file_dup(sc_file_t **dest, const sc_file_t *src)
{
sc_file_t *newf;
const sc_acl_entry_t *e;
unsigned int op;
*dest = NULL;
if (!sc_file_valid(src))
return;
newf = sc_file_new();
if (newf == NULL)
return;
*dest = newf;
memcpy(&newf->path, &src->path, sizeof(struct sc_path));
memcpy(&newf->name, &src->name, sizeof(src->name));
newf->namelen = src->namelen;
newf->type = src->type;
newf->shareable = src->shareable;
newf->ef_structure = src->ef_structure;
newf->size = src->size;
newf->id = src->id;
newf->status = src->status;
for (op = 0; op < SC_MAX_AC_OPS; op++) {
newf->acl[op] = NULL;
e = sc_file_get_acl_entry(src, op);
if (e != NULL) {
if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0)
goto err;
}
}
newf->record_length = src->record_length;
newf->record_count = src->record_count;
if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0)
goto err;
if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0)
goto err;
if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0)
goto err;
if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0)
goto err;
return;
err:
sc_file_free(newf);
*dest = NULL;
}
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr,
size_t prop_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (prop_attr == NULL) {
if (file->prop_attr != NULL)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->prop_attr, prop_attr_len);
if (!tmp) {
if (file->prop_attr)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->prop_attr = tmp;
memcpy(file->prop_attr, prop_attr, prop_attr_len);
file->prop_attr_len = prop_attr_len;
return SC_SUCCESS;
}
int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr,
size_t type_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (type_attr == NULL) {
if (file->type_attr != NULL)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->type_attr, type_attr_len);
if (!tmp) {
if (file->type_attr)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->type_attr = tmp;
memcpy(file->type_attr, type_attr, type_attr_len);
file->type_attr_len = type_attr_len;
return SC_SUCCESS;
}
int sc_file_set_content(sc_file_t *file, const u8 *content,
size_t content_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (content == NULL) {
if (file->encoded_content != NULL)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->encoded_content, content_len);
if (!tmp) {
if (file->encoded_content)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->encoded_content = tmp;
memcpy(file->encoded_content, content, content_len);
file->encoded_content_len = content_len;
return SC_SUCCESS;
}
int sc_file_valid(const sc_file_t *file) {
if (file == NULL)
return 0;
return file->magic == SC_FILE_MAGIC;
}
int _sc_parse_atr(sc_reader_t *reader)
{
u8 *p = reader->atr.value;
int atr_len = (int) reader->atr.len;
int n_hist, x;
int tx[4] = {-1, -1, -1, -1};
int i, FI, DI;
const int Fi_table[] = {
372, 372, 558, 744, 1116, 1488, 1860, -1,
-1, 512, 768, 1024, 1536, 2048, -1, -1 };
const int f_table[] = {
40, 50, 60, 80, 120, 160, 200, -1,
-1, 50, 75, 100, 150, 200, -1, -1 };
const int Di_table[] = {
-1, 1, 2, 4, 8, 16, 32, -1,
12, 20, -1, -1, -1, -1, -1, -1 };
reader->atr_info.hist_bytes_len = 0;
reader->atr_info.hist_bytes = NULL;
if (atr_len == 0) {
sc_log(reader->ctx, "empty ATR - card not present?\n");
return SC_ERROR_INTERNAL;
}
if (p[0] != 0x3B && p[0] != 0x3F) {
sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]);
return SC_ERROR_INTERNAL;
}
n_hist = p[1] & 0x0F;
x = p[1] >> 4;
p += 2;
atr_len -= 2;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
if (tx[0] >= 0) {
reader->atr_info.FI = FI = tx[0] >> 4;
reader->atr_info.DI = DI = tx[0] & 0x0F;
reader->atr_info.Fi = Fi_table[FI];
reader->atr_info.f = f_table[FI];
reader->atr_info.Di = Di_table[DI];
} else {
reader->atr_info.Fi = -1;
reader->atr_info.f = -1;
reader->atr_info.Di = -1;
}
if (tx[2] >= 0)
reader->atr_info.N = tx[3];
else
reader->atr_info.N = -1;
while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) {
x = tx[3] >> 4;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
}
if (atr_len <= 0)
return SC_SUCCESS;
if (n_hist > atr_len)
n_hist = atr_len;
reader->atr_info.hist_bytes_len = n_hist;
reader->atr_info.hist_bytes = p;
return SC_SUCCESS;
}
void sc_mem_clear(void *ptr, size_t len)
{
if (len > 0) {
#ifdef ENABLE_OPENSSL
OPENSSL_cleanse(ptr, len);
#else
memset(ptr, 0, len);
#endif
}
}
int sc_mem_reverse(unsigned char *buf, size_t len)
{
unsigned char ch;
size_t ii;
if (!buf || !len)
return SC_ERROR_INVALID_ARGUMENTS;
for (ii = 0; ii < len / 2; ii++) {
ch = *(buf + ii);
*(buf + ii) = *(buf + len - 1 - ii);
*(buf + len - 1 - ii) = ch;
}
return SC_SUCCESS;
}
static int
sc_remote_apdu_allocate(struct sc_remote_data *rdata,
struct sc_remote_apdu **new_rapdu)
{
struct sc_remote_apdu *rapdu = NULL, *rr;
if (!rdata)
return SC_ERROR_INVALID_ARGUMENTS;
rapdu = calloc(1, sizeof(struct sc_remote_apdu));
if (rapdu == NULL)
return SC_ERROR_OUT_OF_MEMORY;
rapdu->apdu.data = &rapdu->sbuf[0];
rapdu->apdu.resp = &rapdu->rbuf[0];
rapdu->apdu.resplen = sizeof(rapdu->rbuf);
if (new_rapdu)
*new_rapdu = rapdu;
if (rdata->data == NULL) {
rdata->data = rapdu;
rdata->length = 1;
return SC_SUCCESS;
}
for (rr = rdata->data; rr->next; rr = rr->next)
;
rr->next = rapdu;
rdata->length++;
return SC_SUCCESS;
}
static void
sc_remote_apdu_free (struct sc_remote_data *rdata)
{
struct sc_remote_apdu *rapdu = NULL;
if (!rdata)
return;
rapdu = rdata->data;
while(rapdu) {
struct sc_remote_apdu *rr = rapdu->next;
free(rapdu);
rapdu = rr;
}
}
void sc_remote_data_init(struct sc_remote_data *rdata)
{
if (!rdata)
return;
memset(rdata, 0, sizeof(struct sc_remote_data));
rdata->alloc = sc_remote_apdu_allocate;
rdata->free = sc_remote_apdu_free;
}
static unsigned long sc_CRC_tab32[256];
static int sc_CRC_tab32_initialized = 0;
unsigned sc_crc32(const unsigned char *value, size_t len)
{
size_t ii, jj;
unsigned long crc;
unsigned long index, long_c;
if (!sc_CRC_tab32_initialized) {
for (ii=0; ii<256; ii++) {
crc = (unsigned long) ii;
for (jj=0; jj<8; jj++) {
if ( crc & 0x00000001L )
crc = ( crc >> 1 ) ^ 0xEDB88320l;
else
crc = crc >> 1;
}
sc_CRC_tab32[ii] = crc;
}
sc_CRC_tab32_initialized = 1;
}
crc = 0xffffffffL;
for (ii=0; ii<len; ii++) {
long_c = 0x000000ffL & (unsigned long) (*(value + ii));
index = crc ^ long_c;
crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ];
}
crc ^= 0xffffffff;
return crc%0xffff;
}
const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen)
{
if (buf != NULL) {
size_t idx;
u8 plain_tag = tag & 0xF0;
size_t expected_len = tag & 0x0F;
for (idx = 0; idx < len; idx++) {
if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len &&
(expected_len == 0 || expected_len == (buf[idx] & 0x0F))) {
if (outlen != NULL)
*outlen = buf[idx] & 0x0F;
return buf + (idx + 1);
}
idx += (buf[idx] & 0x0F);
}
}
return NULL;
}
/**************************** mutex functions ************************/
int sc_mutex_create(const sc_context_t *ctx, void **mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL)
return ctx->thread_ctx->create_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_lock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL)
return ctx->thread_ctx->lock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_unlock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL)
return ctx->thread_ctx->unlock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_destroy(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL)
return ctx->thread_ctx->destroy_mutex(mutex);
else
return SC_SUCCESS;
}
unsigned long sc_thread_id(const sc_context_t *ctx)
{
if (ctx == NULL || ctx->thread_ctx == NULL ||
ctx->thread_ctx->thread_id == NULL)
return 0UL;
else
return ctx->thread_ctx->thread_id();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_344_7 |
crossvul-cpp_data_good_346_1 | /*
* Support for ePass2003 smart cards
*
* Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com>
* Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef ENABLE_SM /* empty file without SM enabled */
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include "internal.h"
#include "asn1.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table epass2003_atrs[] = {
/* This is a FIPS certified card using SCP01 security messaging. */
{"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e",
"FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00",
"FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL },
{NULL, NULL, NULL, 0, 0, NULL}
};
static struct sc_card_operations *iso_ops = NULL;
static struct sc_card_operations epass2003_ops;
static struct sc_card_driver epass2003_drv = {
"epass2003",
"epass2003",
&epass2003_ops,
NULL, 0, NULL
};
#define KEY_TYPE_AES 0x01 /* FIPS mode */
#define KEY_TYPE_DES 0x02 /* Non-FIPS mode */
#define KEY_LEN_AES 16
#define KEY_LEN_DES 8
#define KEY_LEN_DES3 24
#define HASH_LEN 24
static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID };
/*0x00:plain; 0x01:scp01 sm*/
#define SM_PLAIN 0x00
#define SM_SCP01 0x01
static unsigned char g_init_key_enc[16] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10
};
static unsigned char g_init_key_mac[16] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10
};
static unsigned char g_random[8] = {
0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40
};
typedef struct epass2003_exdata_st {
unsigned char sm; /* SM_PLAIN or SM_SCP01 */
unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */
unsigned char sk_enc[16]; /* encrypt session key */
unsigned char sk_mac[16]; /* mac session key */
unsigned char icv_mac[16]; /* instruction counter vector(for sm) */
unsigned char currAlg; /* current Alg */
unsigned int ecAlgFlags; /* Ec Alg mechanism type*/
} epass2003_exdata;
#define REVERSE_ORDER4(x) ( \
((unsigned long)x & 0xFF000000)>> 24 | \
((unsigned long)x & 0x00FF0000)>> 8 | \
((unsigned long)x & 0x0000FF00)<< 8 | \
((unsigned long)x & 0x000000FF)<< 24)
static const struct sc_card_error epass2003_errors[] = {
{ 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" },
{ 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" },
{ 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" },
{ 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" },
{ 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" },
{ 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"},
{ 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"},
{ 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" },
{ 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" },
{ 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" },
{ 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" },
{ 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" },
{ 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" },
{ 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" },
{ 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" },
{ 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" },
{ 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" },
{ 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" },
{ 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" },
{ 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" },
{ 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" },
{ 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" },
{ 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" },
{ 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" },
{ 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" },
{ 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" },
{ 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" },
{ 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" },
{ 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" },
{ 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" },
{ 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" },
{ 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" },
{ 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"},
{ 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"},
{ 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" },
{ 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" },
{ 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" },
{ 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" },
{ 0x9000,SC_SUCCESS, NULL }
};
static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu);
static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out);
int epass2003_refresh(struct sc_card *card);
static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType);
static int
epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)
{
const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]);
int i;
/* Handle special cases here */
if (sw1 == 0x6C) {
sc_log(card->ctx, "Wrong length; correct length is %d", sw2);
return SC_ERROR_WRONG_LENGTH;
}
for (i = 0; i < err_count; i++) {
if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) {
sc_log(card->ctx, "%s", epass2003_errors[i].errorstr);
return epass2003_errors[i].errorno;
}
}
sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2);
return SC_ERROR_CARD_CMD_FAILED;
}
static int
sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu)
{
int r = sc_transmit_apdu(card, apdu);
if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2)))
{
epass2003_refresh(card);
r = sc_transmit_apdu(card, apdu);
}
return r;
}
static int
openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv,
const unsigned char *input, size_t length, unsigned char *output)
{
int r = SC_ERROR_INTERNAL;
EVP_CIPHER_CTX * ctx = NULL;
int outl = 0;
int outl_tmp = 0;
unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 };
memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
goto out;
EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp);
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_EncryptUpdate(ctx, output, &outl, input, length))
goto out;
if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp))
goto out;
r = SC_SUCCESS;
out:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
return r;
}
static int
openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv,
const unsigned char *input, size_t length, unsigned char *output)
{
int r = SC_ERROR_INTERNAL;
EVP_CIPHER_CTX * ctx = NULL;
int outl = 0;
int outl_tmp = 0;
unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 };
memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
goto out;
EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp);
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_DecryptUpdate(ctx, output, &outl, input, length))
goto out;
if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp))
goto out;
r = SC_SUCCESS;
out:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
return r;
}
static int
aes128_encrypt_ecb(const unsigned char *key, int keysize,
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output);
}
static int
aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output);
}
static int
aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output);
}
static int
des3_encrypt_ecb(const unsigned char *key, int keysize,
const unsigned char *input, int length, unsigned char *output)
{
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output);
}
static int
des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output);
}
static int
des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output);
}
static int
des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_enc(EVP_des_cbc(), key, iv, input, length, output);
}
static int
des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dec(EVP_des_cbc(), key, iv, input, length, output);
}
static int
openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length,
unsigned char *output)
{
int r = 0;
EVP_MD_CTX *ctx = NULL;
unsigned outl = 0;
ctx = EVP_MD_CTX_create();
if (ctx == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
EVP_MD_CTX_init(ctx);
EVP_DigestInit_ex(ctx, digest, NULL);
if (!EVP_DigestUpdate(ctx, input, length)) {
r = SC_ERROR_INTERNAL;
goto err;
}
if (!EVP_DigestFinal_ex(ctx, output, &outl)) {
r = SC_ERROR_INTERNAL;
goto err;
}
r = SC_SUCCESS;
err:
if (ctx)
EVP_MD_CTX_destroy(ctx);
return r;
}
static int
sha1_digest(const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dig(EVP_sha1(), input, length, output);
}
static int
sha256_digest(const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dig(EVP_sha256(), input, length, output);
}
static int
gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac,
unsigned char *result, unsigned char key_type)
{
int r;
struct sc_apdu apdu;
unsigned char data[256] = { 0 };
unsigned char tmp_sm;
unsigned long blocksize = 0;
unsigned char cryptogram[256] = { 0 }; /* host cryptogram */
unsigned char iv[16] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = sizeof(g_random);
apdu.data = g_random; /* host random */
apdu.le = apdu.resplen = 28;
apdu.resp = result; /* card random is result[12~19] */
tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = epass2003_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "gen_init_key failed");
/* Step 1 - Generate Derivation data */
memcpy(data, &result[16], 4);
memcpy(&data[4], g_random, 4);
memcpy(&data[8], &result[12], 4);
memcpy(&data[12], &g_random[4], 4);
/* Step 2,3 - Create S-ENC/S-MAC Session Key */
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc);
aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac);
}
else {
des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc);
des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac);
}
memcpy(data, g_random, 8);
memcpy(&data[8], &result[12], 8);
data[16] = 0x80;
blocksize = (key_type == KEY_TYPE_AES ? 16 : 8);
memset(&data[17], 0x00, blocksize - 1);
/* calculate host cryptogram */
if (KEY_TYPE_AES == key_type)
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram);
else
des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram);
/* verify card cryptogram */
if (0 != memcmp(&cryptogram[16], &result[20], 8))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type)
{
int r;
struct sc_apdu apdu;
unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8);
unsigned char data[256] = { 0 };
unsigned char cryptogram[256] = { 0 }; /* host cryptogram */
unsigned char iv[16] = { 0 };
unsigned char mac[256] = { 0 };
unsigned long i;
unsigned char tmp_sm;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
memcpy(data, ran_key, 8);
memcpy(&data[8], g_random, 8);
data[16] = 0x80;
memset(&data[17], 0x00, blocksize - 1);
memset(iv, 0, 16);
/* calculate host cryptogram */
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize,
cryptogram);
} else {
des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize,
cryptogram);
}
memset(data, 0, sizeof(data));
memcpy(data, "\x84\x82\x03\x00\x10", 5);
memcpy(&data[5], &cryptogram[16], 8);
memcpy(&data[13], "\x80\x00\x00", 3);
/* calculate mac icv */
memset(iv, 0x00, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac);
i = 0;
} else {
des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac);
i = 8;
}
/* save mac icv */
memset(exdata->icv_mac, 0x00, 16);
memcpy(exdata->icv_mac, &mac[i], 8);
/* verify host cryptogram */
memcpy(data, &cryptogram[16], 8);
memcpy(&data[8], &mac[i], 8);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00);
apdu.cla = 0x84;
apdu.lc = apdu.datalen = 16;
apdu.data = data;
tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = epass2003_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
LOG_TEST_RET(card->ctx, r,
"APDU verify_init_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r,
"verify_init_key failed");
return r;
}
static int
mutual_auth(struct sc_card *card, unsigned char *key_enc,
unsigned char *key_mac)
{
struct sc_context *ctx = card->ctx;
int r;
unsigned char result[256] = { 0 };
unsigned char ran_key[8] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(ctx);
r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype);
LOG_TEST_RET(ctx, r, "gen_init_key failed");
memcpy(ran_key, &result[12], 8);
r = verify_init_key(card, ran_key, exdata->smtype);
LOG_TEST_RET(ctx, r, "verify_init_key failed");
LOG_FUNC_RETURN(ctx, r);
}
int
epass2003_refresh(struct sc_card *card)
{
int r = SC_SUCCESS;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (exdata->sm) {
card->sm_ctx.sm_mode = 0;
r = mutual_auth(card, g_init_key_enc, g_init_key_mac);
card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
LOG_TEST_RET(card->ctx, r, "mutual_auth failed");
}
return r;
}
/* Data(TLV)=0x87|L|0x01+Cipher */
static int
construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf,
unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char pad[4096] = { 0 };
size_t pad_len;
size_t tlv_more; /* increased tlv length */
unsigned char iv[16] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* padding */
apdu_buf[block_size] = 0x87;
memcpy(pad, apdu->data, apdu->lc);
pad[apdu->lc] = 0x80;
if ((apdu->lc + 1) % block_size)
pad_len = ((apdu->lc + 1) / block_size + 1) * block_size;
else
pad_len = apdu->lc + 1;
/* encode Lc' */
if (pad_len > 0x7E) {
/* Lc' > 0x7E, use extended APDU */
apdu_buf[block_size + 1] = 0x82;
apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100);
apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100);
apdu_buf[block_size + 4] = 0x01;
tlv_more = 5;
}
else {
apdu_buf[block_size + 1] = (unsigned char)pad_len + 1;
apdu_buf[block_size + 2] = 0x01;
tlv_more = 3;
}
memcpy(data_tlv, &apdu_buf[block_size], tlv_more);
/* encrypt Data */
if (KEY_TYPE_AES == key_type)
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more);
else
des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more);
memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len);
*data_tlv_len = tlv_more + pad_len;
return 0;
}
/* Le(TLV)=0x97|L|Le */
static int
construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len,
unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
*(apdu_buf + block_size + data_tlv_len) = 0x97;
if (apdu->le > 0x7F) {
/* Le' > 0x7E, use extended APDU */
*(apdu_buf + block_size + data_tlv_len + 1) = 2;
*(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100);
*(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100);
memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4);
*le_tlv_len = 4;
}
else {
*(apdu_buf + block_size + data_tlv_len + 1) = 1;
*(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le;
memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3);
*le_tlv_len = 3;
}
return 0;
}
/* MAC(TLV)=0x8e|0x08|MAC */
static int
construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len,
unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char mac[4096] = { 0 };
size_t mac_len;
unsigned char icv[16] = { 0 };
int i = (KEY_TYPE_AES == key_type ? 15 : 7);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (0 == data_tlv_len && 0 == le_tlv_len) {
mac_len = block_size;
}
else {
/* padding */
*(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80;
if ((data_tlv_len + le_tlv_len + 1) % block_size)
mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) +
1) * block_size + block_size;
else
mac_len = data_tlv_len + le_tlv_len + 1 + block_size;
memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1),
0, (mac_len - (data_tlv_len + le_tlv_len + 1)));
}
/* increase icv */
for (; i >= 0; i--) {
if (exdata->icv_mac[i] == 0xff) {
exdata->icv_mac[i] = 0;
}
else {
exdata->icv_mac[i]++;
break;
}
}
/* calculate MAC */
memset(icv, 0, sizeof(icv));
memcpy(icv, exdata->icv_mac, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac);
memcpy(mac_tlv + 2, &mac[mac_len - 16], 8);
}
else {
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char tmp[8] = { 0 };
des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac);
des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp);
memset(iv, 0x00, sizeof iv);
des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2);
}
*mac_tlv_len = 2 + 8;
return 0;
}
/* According to GlobalPlatform Card Specification's SCP01
* encode APDU from
* CLA INS P1 P2 [Lc] Data [Le]
* to
* CLA INS P1 P2 Lc' Data' [Le]
* where
* Data'=Data(TLV)+Le(TLV)+MAC(TLV) */
static int
encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm,
unsigned char *apdu_buf, size_t * apdu_buf_len)
{
size_t block_size = 0;
unsigned char dataTLV[4096] = { 0 };
size_t data_tlv_len = 0;
unsigned char le_tlv[256] = { 0 };
size_t le_tlv_len = 0;
size_t mac_tlv_len = 10;
size_t tmp_lc = 0;
size_t tmp_le = 0;
unsigned char mac_tlv[256] = { 0 };
epass2003_exdata *exdata = NULL;
mac_tlv[0] = 0x8E;
mac_tlv[1] = 8;
/* size_t plain_le = 0; */
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata*)card->drv_data;
block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8);
sm->cse = SC_APDU_CASE_4_SHORT;
apdu_buf[0] = (unsigned char)plain->cla;
apdu_buf[1] = (unsigned char)plain->ins;
apdu_buf[2] = (unsigned char)plain->p1;
apdu_buf[3] = (unsigned char)plain->p2;
/* plain_le = plain->le; */
/* padding */
apdu_buf[4] = 0x80;
memset(&apdu_buf[5], 0x00, block_size - 5);
/* Data -> Data' */
if (plain->lc != 0)
if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype))
return -1;
if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0))
if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv,
&le_tlv_len, exdata->smtype))
return -1;
if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype))
return -1;
memset(apdu_buf + 4, 0, *apdu_buf_len - 4);
sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len;
if (sm->lc > 0xFF) {
sm->cse = SC_APDU_CASE_4_EXT;
apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000);
apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100);
apdu_buf[6] = (unsigned char)((sm->lc) % 0x100);
tmp_lc = 3;
}
else {
apdu_buf[4] = (unsigned char)sm->lc;
tmp_lc = 1;
}
memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len);
memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len);
memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len);
memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen);
*apdu_buf_len = 0;
if (4 == le_tlv_len) {
sm->cse = SC_APDU_CASE_4_EXT;
*(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100);
*(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100);
tmp_le = 2;
}
else if (3 == le_tlv_len) {
*(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le;
tmp_le = 1;
}
*apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le;
/* sm->le = calc_le(plain_le); */
return 0;
}
static int
epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm)
{
unsigned char buf[4096] = { 0 }; /* APDU buffer */
size_t buf_len = sizeof(buf);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
if (exdata->sm)
plain->cla |= 0x0C;
sm->cse = plain->cse;
sm->cla = plain->cla;
sm->ins = plain->ins;
sm->p1 = plain->p1;
sm->p2 = plain->p2;
sm->lc = plain->lc;
sm->le = plain->le;
sm->control = plain->control;
sm->flags = plain->flags;
switch (sm->cla & 0x0C) {
case 0x00:
case 0x04:
sm->datalen = plain->datalen;
memcpy((void *)sm->data, plain->data, plain->datalen);
sm->resplen = plain->resplen;
memcpy(sm->resp, plain->resp, plain->resplen);
break;
case 0x0C:
memset(buf, 0, sizeof(buf));
if (0 != encode_apdu(card, plain, sm, buf, &buf_len))
return SC_ERROR_CARD_CMD_FAILED;
break;
default:
return SC_ERROR_INCORRECT_PARAMETERS;
}
return SC_SUCCESS;
}
/* According to GlobalPlatform Card Specification's SCP01
* decrypt APDU response from
* ResponseData' SW1 SW2
* to
* ResponseData SW1 SW2
* where
* ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV)
* where
* Data(TLV)=0x87|L|Cipher
* SW12(TLV)=0x99|0x02|SW1+SW2
* MAC(TLV)=0x8e|0x08|MAC */
static int
decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len)
{
size_t cipher_len;
size_t i;
unsigned char iv[16] = { 0 };
unsigned char plaintext[4096] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* no cipher */
if (in[0] == 0x99)
return 0;
/* parse cipher length */
if (0x01 == in[2] && 0x82 != in[1]) {
cipher_len = in[1];
i = 3;
}
else if (0x01 == in[3] && 0x81 == in[1]) {
cipher_len = in[2];
i = 4;
}
else if (0x01 == in[4] && 0x82 == in[1]) {
cipher_len = in[2] * 0x100;
cipher_len += in[3];
i = 5;
}
else {
return -1;
}
if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext)
return -1;
/* decrypt */
if (KEY_TYPE_AES == exdata->smtype)
aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
else
des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
/* unpadding */
while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))
cipher_len--;
if (2 == cipher_len || *out_len < cipher_len - 2)
return -1;
memcpy(out, plaintext, cipher_len - 2);
*out_len = cipher_len - 2;
return 0;
}
static int
epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
len = plain->resplen;
if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_sm_free_wrapped_apdu(struct sc_card *card,
struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
int rv = SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
if (!sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
if (!(*sm_apdu))
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
if (plain)
rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain);
if ((*sm_apdu)->data) {
unsigned char * p = (unsigned char *)((*sm_apdu)->data);
free(p);
}
if ((*sm_apdu)->resp) {
free((*sm_apdu)->resp);
}
free(*sm_apdu);
*sm_apdu = NULL;
LOG_FUNC_RETURN(ctx, rv);
}
static int
epass2003_sm_get_wrapped_apdu(struct sc_card *card,
struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu *apdu = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (!plain || !sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
*sm_apdu = NULL;
//construct new SM apdu from original apdu
apdu = calloc(1, sizeof(struct sc_apdu));
if (!apdu) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE);
if (!apdu->data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE);
if (!apdu->resp) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE;
apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE;
rv = epass2003_sm_wrap_apdu(card, plain, apdu);
if (rv) {
rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu);
if (rv < 0)
goto err;
}
*sm_apdu = apdu;
apdu = NULL;
err:
if (apdu) {
free((unsigned char *) apdu->data);
free(apdu->resp);
free(apdu);
apdu = NULL;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = sc_transmit_apdu_t(card, apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return r;
}
static int
get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen)
{
int r;
struct sc_apdu apdu;
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
size_t resplen = SC_MAX_APDU_BUFFER_SIZE;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type);
apdu.resp = resp;
apdu.le = 0;
apdu.resplen = resplen;
if (0x86 == type) {
/* No SM temporarily */
unsigned char tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = sc_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
}
else {
r = sc_transmit_apdu_t(card, &apdu);
}
LOG_TEST_RET(card->ctx, r, "APDU get_data failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "get_data failed");
memcpy(data, resp, datalen);
return r;
}
/* card driver functions */
static int epass2003_match_card(struct sc_card *card)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = _sc_match_atr(card, epass2003_atrs, &card->type);
if (r < 0)
return 0;
return 1;
}
static int
epass2003_init(struct sc_card *card)
{
unsigned int flags;
unsigned int ext_flags;
unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
size_t datalen = SC_MAX_APDU_BUFFER_SIZE;
epass2003_exdata *exdata = NULL;
LOG_FUNC_CALLED(card->ctx);
card->name = "epass2003";
card->cla = 0x00;
exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata));
if (!exdata)
return SC_ERROR_OUT_OF_MEMORY;
card->drv_data = exdata;
exdata->sm = SM_SCP01;
/* decide FIPS/Non-FIPS mode */
if (SC_SUCCESS != get_data(card, 0x86, data, datalen))
return SC_ERROR_INVALID_CARD;
if (0x01 == data[2])
exdata->smtype = KEY_TYPE_AES;
else
exdata->smtype = KEY_TYPE_DES;
if (0x84 == data[14]) {
if (0x00 == data[16]) {
exdata->sm = SM_PLAIN;
}
}
/* mutual authentication */
card->max_recv_size = 0xD8;
card->max_send_size = 0xE8;
card->sm_ctx.ops.open = epass2003_refresh;
card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu;
card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu;
/* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */
epass2003_refresh(card);
card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
//set EC Alg Flags
flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW;
ext_flags = 0;
_sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL);
card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_finish(sc_card_t *card)
{
epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data;
if (exdata)
free(exdata);
return SC_SUCCESS;
}
/* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the
* same DF, so use hook functions to increase/decrease FID by 0x20 */
static int
epass2003_hook_path(struct sc_path *path, int inc)
{
u8 fid_h = path->value[path->len - 2];
u8 fid_l = path->value[path->len - 1];
switch (fid_h) {
case 0x29:
case 0x30:
case 0x31:
case 0x32:
case 0x33:
case 0x34:
if (inc)
fid_l = fid_l * FID_STEP;
else
fid_l = fid_l / FID_STEP;
path->value[path->len - 1] = fid_l;
return 1;
default:
break;
}
return 0;
}
static void
epass2003_hook_file(struct sc_file *file, int inc)
{
int fidl = file->id & 0xff;
int fidh = file->id & 0xff00;
if (epass2003_hook_path(&file->path, inc)) {
if (inc)
file->id = fidh + fidl * FID_STEP;
else
file->id = fidh + fidl / FID_STEP;
}
}
static int
epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out)
{
struct sc_apdu apdu;
u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
int r, pathlen;
sc_file_t *file = NULL;
epass2003_hook_path(in_path, 1);
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
apdu.p1 = 0;
if (pathlen != 2)
return SC_ERROR_INVALID_ARGUMENTS;
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.p2 = 0; /* first record, return FCI */
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 0;
}
else {
apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */
/* Not allowed to select private key file, so fake fci. */
/* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */
apdu.resplen = 0x18;
memcpy(apdu.resp,
"\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff",
apdu.resplen);
apdu.resp[9] = path[1];
apdu.sw1 = 0x90;
apdu.sw2 = 0x00;
}
else {
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
}
if (file_out == NULL) {
if (apdu.sw1 == 0x61)
LOG_FUNC_RETURN(card->ctx, 0);
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(card->ctx, r);
if (apdu.resplen < 2)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
switch (apdu.resp[0]) {
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
if (card->ops->process_fci == NULL) {
sc_file_free(file);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
if ((size_t) apdu.resp[1] + 2 <= apdu.resplen)
card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]);
epass2003_hook_file(file, 0);
*file_out = file;
break;
case 0x00: /* proprietary coding */
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
return 0;
}
static int
epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo,
sc_file_t ** file_out)
{
int r;
sc_file_t *file = 0;
sc_path_t path;
memset(&path, 0, sizeof(path));
path.type = SC_PATH_TYPE_FILE_ID;
path.value[0] = id_hi;
path.value[1] = id_lo;
path.len = 2;
r = epass2003_select_fid_(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
/* update cache */
if (file && file->type == SC_FILE_TYPE_DF) {
card->cache.current_path.type = SC_PATH_TYPE_PATH;
card->cache.current_path.value[0] = 0x3f;
card->cache.current_path.value[1] = 0x00;
if (id_hi == 0x3f && id_lo == 0x00) {
card->cache.current_path.len = 2;
}
else {
card->cache.current_path.len = 4;
card->cache.current_path.value[2] = id_hi;
card->cache.current_path.value[3] = id_lo;
}
}
if (file_out)
*file_out = file;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out)
{
int r = 0;
if (card->cache.valid
&& card->cache.current_path.type == SC_PATH_TYPE_DF_NAME
&& card->cache.current_path.len == in_path->len
&& memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) {
if (file_out) {
*file_out = sc_file_new();
if (!file_out)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
}
else {
r = iso_ops->select_file(card, in_path, file_out);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
/* update cache */
card->cache.current_path.type = SC_PATH_TYPE_DF_NAME;
card->cache.current_path.len = in_path->len;
memcpy(card->cache.current_path.value, in_path->value, in_path->len);
}
if (file_out) {
sc_file_t *file = *file_out;
file->type = SC_FILE_TYPE_DF;
file->ef_structure = SC_FILE_EF_UNKNOWN;
file->path.len = 0;
file->size = 0;
/* AID */
memcpy(file->name, in_path->value, in_path->len);
file->namelen = in_path->len;
file->id = 0x0000;
}
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len,
sc_file_t ** file_out)
{
u8 n_pathbuf[SC_MAX_PATH_SIZE];
const u8 *path = pathbuf;
size_t pathlen = len;
int bMatch = -1;
unsigned int i;
int r;
if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
/* if pathlen == 6 then the first FID must be MF (== 3F00) */
if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
/* unify path (the first FID should be MF) */
if (path[0] != 0x3f || path[1] != 0x00) {
n_pathbuf[0] = 0x3f;
n_pathbuf[1] = 0x00;
for (i = 0; i < pathlen; i++)
n_pathbuf[i + 2] = pathbuf[i];
path = n_pathbuf;
pathlen += 2;
}
/* check current working directory */
if (card->cache.valid
&& card->cache.current_path.type == SC_PATH_TYPE_PATH
&& card->cache.current_path.len >= 2
&& card->cache.current_path.len <= pathlen) {
bMatch = 0;
for (i = 0; i < card->cache.current_path.len; i += 2)
if (card->cache.current_path.value[i] == path[i]
&& card->cache.current_path.value[i + 1] == path[i + 1])
bMatch += 2;
}
if (card->cache.valid && bMatch > 2) {
if (pathlen - bMatch == 2) {
/* we are in the right directory */
return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out);
}
else if (pathlen - bMatch > 2) {
/* two more steps to go */
sc_path_t new_path;
/* first step: change directory */
r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL);
LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed");
new_path.type = SC_PATH_TYPE_PATH;
new_path.len = pathlen - bMatch - 2;
memcpy(new_path.value, &(path[bMatch + 2]), new_path.len);
/* final step: select file */
return epass2003_select_file(card, &new_path, file_out);
}
else { /* if (bMatch - pathlen == 0) */
/* done: we are already in the
* requested directory */
sc_log(card->ctx, "cache hit\n");
/* copy file info (if necessary) */
if (file_out) {
sc_file_t *file = sc_file_new();
if (!file)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
file->id = (path[pathlen - 2] << 8) + path[pathlen - 1];
file->path = card->cache.current_path;
file->type = SC_FILE_TYPE_DF;
file->ef_structure = SC_FILE_EF_UNKNOWN;
file->size = 0;
file->namelen = 0;
file->magic = SC_FILE_MAGIC;
*file_out = file;
}
/* nothing left to do */
return SC_SUCCESS;
}
}
else {
/* no usable cache */
for (i = 0; i < pathlen - 2; i += 2) {
r = epass2003_select_fid(card, path[i], path[i + 1], NULL);
LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed");
}
return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out);
}
}
static int
epass2003_select_file(struct sc_card *card, const sc_path_t * in_path,
sc_file_t ** file_out)
{
int r;
char pbuf[SC_MAX_PATH_STRING_SIZE];
LOG_FUNC_CALLED(card->ctx);
r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path);
if (r != SC_SUCCESS)
pbuf[0] = '\0';
sc_log(card->ctx,
"current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n",
card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ?
"aid" : "path",
card->cache.valid ? "valid" : "invalid", pbuf,
card->cache.current_path.len);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (in_path->len != 2)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out);
case SC_PATH_TYPE_DF_NAME:
return epass2003_select_aid(card, in_path, file_out);
case SC_PATH_TYPE_PATH:
return epass2003_select_path(card, in_path->value, in_path->len, file_out);
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
}
static int
epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num)
{
struct sc_apdu apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 *p;
unsigned short fid = 0;
int r, locked = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0);
p = sbuf;
*p++ = 0x80; /* algorithm reference */
*p++ = 0x01;
*p++ = 0x84;
*p++ = 0x81;
*p++ = 0x02;
fid = 0x2900;
fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff));
*p++ = fid >> 8;
*p++ = fid & 0xff;
r = p - sbuf;
apdu.lc = r;
apdu.datalen = r;
apdu.data = sbuf;
if (env->algorithm == SC_ALGORITHM_EC)
{
apdu.p2 = 0xB6;
exdata->currAlg = SC_ALGORITHM_EC;
if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
sbuf[2] = 0x91;
exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1;
}
else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
sbuf[2] = 0x92;
exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256;
}
else
{
sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags);
goto err;
}
}
else if(env->algorithm == SC_ALGORITHM_RSA)
{
exdata->currAlg = SC_ALGORITHM_RSA;
apdu.p2 = 0xB8;
sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags);
}
else
{
sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm);
}
if (se_num > 0) {
r = sc_lock(card);
LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
locked = 1;
}
if (apdu.datalen != 0) {
r = sc_transmit_apdu_t(card, &apdu);
if (r) {
sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r));
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r) {
sc_log(card->ctx, "%s: Card returned error", sc_strerror(r));
goto err;
}
}
if (se_num <= 0)
return 0;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num);
r = sc_transmit_apdu_t(card, &apdu);
sc_unlock(card);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
err:
if (locked)
sc_unlock(card);
return r;
}
static int
epass2003_restore_security_env(struct sc_card *card, int se_num)
{
LOG_FUNC_CALLED(card->ctx);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
int r;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
epass2003_exdata *exdata = NULL;
LOG_FUNC_CALLED(card->ctx);
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if(exdata->currAlg == SC_ALGORITHM_EC)
{
if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash_data failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A);
apdu.data = sbuf;
apdu.lc = 0x14;
apdu.datalen = 0x14;
}
else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256);
LOG_TEST_RET(card->ctx, r, "hash_data failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A);
apdu.data = sbuf;
apdu.lc = 0x20;
apdu.datalen = 0x20;
}
else
{
return SC_ERROR_NOT_SUPPORTED;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
size_t len = apdu.resplen > outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
LOG_FUNC_RETURN(card->ctx, len);
}
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
else if(exdata->currAlg == SC_ALGORITHM_RSA)
{
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0;
memcpy(sbuf, data, datalen);
apdu.data = sbuf;
apdu.lc = datalen;
apdu.datalen = datalen;
}
else
{
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
memcpy(sbuf, data, datalen);
apdu.data = sbuf;
apdu.lc = datalen;
apdu.datalen = datalen;
}
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
size_t len = apdu.resplen > outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
LOG_FUNC_RETURN(card->ctx, len);
}
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int
acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e)
{
if (e == NULL)
return SC_ERROR_OBJECT_NOT_FOUND;
switch (e->method) {
case SC_AC_NONE:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE);
case SC_AC_NEVER:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE);
default:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER);
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
}
static int
epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen)
{
sc_context_t *ctx = card->ctx;
size_t taglen, len = buflen;
const u8 *tag = NULL, *p = buf;
sc_log(ctx, "processing FCI bytes");
tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen);
if (tag != NULL && taglen == 2) {
file->id = (tag[0] << 8) | tag[1];
sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]);
}
tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen);
if (tag != NULL && taglen > 0 && taglen < 3) {
file->size = tag[0];
if (taglen == 2)
file->size = (file->size << 8) + tag[1];
sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u",
file->size);
}
if (tag == NULL) {
tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen);
if (tag != NULL && taglen >= 2) {
int bytes = (tag[0] << 8) + tag[1];
sc_log(ctx, " bytes in file: %d", bytes);
file->size = bytes;
}
}
tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen);
if (tag != NULL) {
if (taglen > 0) {
unsigned char byte = tag[0];
const char *type;
if (byte == 0x38) {
type = "DF";
file->type = SC_FILE_TYPE_DF;
}
else if (0x01 <= byte && byte <= 0x07) {
type = "working EF";
file->type = SC_FILE_TYPE_WORKING_EF;
switch (byte) {
case 0x01:
file->ef_structure = SC_FILE_EF_TRANSPARENT;
break;
case 0x02:
file->ef_structure = SC_FILE_EF_LINEAR_FIXED;
break;
case 0x04:
file->ef_structure = SC_FILE_EF_LINEAR_FIXED;
break;
case 0x03:
case 0x05:
case 0x06:
case 0x07:
break;
default:
break;
}
}
else if (0x10 == byte) {
type = "BSO";
file->type = SC_FILE_TYPE_BSO;
}
else if (0x11 <= byte) {
type = "internal EF";
file->type = SC_FILE_TYPE_INTERNAL_EF;
switch (byte) {
case 0x11:
break;
case 0x12:
break;
default:
break;
}
}
else {
type = "unknown";
file->type = SC_FILE_TYPE_INTERNAL_EF;
}
sc_log(ctx, "type %s, EF structure %d", type, byte);
}
}
tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen);
if (tag != NULL && taglen > 0 && taglen <= 16) {
memcpy(file->name, tag, taglen);
file->namelen = taglen;
sc_log_hex(ctx, "File name", file->name, file->namelen);
if (!file->type)
file->type = SC_FILE_TYPE_DF;
}
tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen);
if (tag != NULL && taglen)
sc_file_set_prop_attr(file, tag, taglen);
else
file->prop_attr_len = 0;
tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen);
if (tag != NULL && taglen)
sc_file_set_prop_attr(file, tag, taglen);
tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen);
if (tag != NULL && taglen)
sc_file_set_sec_attr(file, tag, taglen);
tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen);
if (tag != NULL && taglen == 1) {
if (tag[0] == 0x01)
file->status = SC_FILE_STATUS_CREATION;
else if (tag[0] == 0x07 || tag[0] == 0x05)
file->status = SC_FILE_STATUS_ACTIVATED;
else if (tag[0] == 0x06 || tag[0] == 0x04)
file->status = SC_FILE_STATUS_INVALIDATED;
}
file->magic = SC_FILE_MAGIC;
return 0;
}
static int
epass2003_construct_fci(struct sc_card *card, const sc_file_t * file,
u8 * out, size_t * outlen)
{
u8 *p = out;
u8 buf[64];
unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
int rv;
unsigned ii;
if (*outlen < 2)
return SC_ERROR_BUFFER_TOO_SMALL;
*p++ = 0x62;
p++;
if (file->type == SC_FILE_TYPE_WORKING_EF) {
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p);
}
}
if (file->type == SC_FILE_TYPE_DF) {
buf[0] = 0x38;
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
buf[0] = file->ef_structure & 7;
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED
|| file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) {
buf[1] = 0x00;
buf[2] = 0x00;
buf[3] = 0x40; /* record length */
buf[4] = 0x00; /* record count */
sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p);
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) {
buf[0] = 0x11;
buf[1] = 0x00;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
buf[0] = 0x12;
buf[1] = 0x00;
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_BSO) {
buf[0] = 0x10;
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p);
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen != 0) {
sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p);
}
else {
return SC_ERROR_INVALID_ARGUMENTS;
}
}
if (file->type == SC_FILE_TYPE_DF) {
unsigned char data[2] = {0x00, 0x7F};
/* 127 files at most */
sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_BSO) {
buf[0] = file->size & 0xff;
sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p);
}
}
if (file->sec_attr_len) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p);
}
else {
sc_log(card->ctx, "SC_FILE_ACL");
if (file->type == SC_FILE_TYPE_DF) {
ops[0] = SC_AC_OP_LIST_FILES;
ops[1] = SC_AC_OP_CREATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED
|| file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_WRITE;
ops[3] = SC_AC_OP_DELETE;
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
}
else if (file->type == SC_FILE_TYPE_BSO) {
ops[0] = SC_AC_OP_UPDATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) {
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_CRYPTO;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_CRYPTO;
ops[3] = SC_AC_OP_DELETE;
}
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
for (ii = 0; ii < sizeof(ops); ii++) {
const struct sc_acl_entry *entry;
buf[ii] = 0xFF;
if (ops[ii] == 0xFF)
continue;
entry = sc_file_get_acl_entry(file, ops[ii]);
rv = acl_to_ac_byte(card, entry);
LOG_TEST_RET(card->ctx, rv, "Invalid ACL");
buf[ii] = rv;
}
sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p);
if(file->size == 256)
{
out[4]= 0x13;
}
}
/* VT ??? */
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
unsigned char data[2] = {0x00, 0x66};
sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p);
if(file->size == 256)
{
out[4]= 0x14;
}
}
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int
epass2003_create_file(struct sc_card *card, sc_file_t * file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
struct sc_apdu apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
epass2003_hook_file(file, 1);
if (card->ops->construct_fci == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
r = epass2003_construct_fci(card, file, sbuf, &len);
LOG_TEST_RET(card->ctx, r, "construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong");
epass2003_hook_file(file, 0);
return r;
}
static int
epass2003_delete_file(struct sc_card *card, const sc_path_t * path)
{
int r;
u8 sbuf[2];
struct sc_apdu apdu;
LOG_FUNC_CALLED(card->ctx);
r = sc_select_file(card, path, NULL);
epass2003_hook_path((struct sc_path *)path, 1);
if (r == SC_SUCCESS) {
sbuf[0] = path->value[path->len - 2];
sbuf[1] = path->value[path->len - 1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
}
else {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Delete file failed");
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen)
{
struct sc_apdu apdu;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00);
apdu.cla = 0x80;
apdu.le = 0;
apdu.resplen = sizeof(rbuf);
apdu.resp = rbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Card returned error");
if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0)
LOG_FUNC_RETURN(card->ctx, 0);
buflen = buflen < apdu.resplen ? buflen : apdu.resplen;
memcpy(buf, rbuf, buflen);
LOG_FUNC_RETURN(card->ctx, buflen);
}
static int
internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor,
sc_pkcs15_bignum_t data)
{
int r;
struct sc_apdu apdu;
u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
LOG_FUNC_CALLED(card->ctx);
sbuff[0] = ((fid & 0xff00) >> 8);
sbuff[1] = (fid & 0x00ff);
memcpy(&sbuff[2], data.data, data.len);
// sc_mem_reverse(&sbuff[2], data.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 2 + data.len;
apdu.data = sbuff;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus);
LOG_TEST_RET(card->ctx, r, "write n failed");
r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d);
LOG_TEST_RET(card->ctx, r, "write d failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType)
{
if ((NULL == data) || (NULL == hash))
return SC_ERROR_INVALID_ARGUMENTS;
if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
unsigned char data_hash[24] = { 0 };
size_t len = 0;
sha1_digest(data, datalen, data_hash);
len = REVERSE_ORDER4(datalen);
memcpy(&data_hash[20], &len, 4);
memcpy(hash, data_hash, 24);
}
else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
unsigned char data_hash[36] = { 0 };
size_t len = 0;
sha256_digest(data, datalen, data_hash);
len = REVERSE_ORDER4(datalen);
memcpy(&data_hash[32], &len, 4);
memcpy(hash, data_hash, 36);
}
else
{
return SC_ERROR_NOT_SUPPORTED;
}
return SC_SUCCESS;
}
static int
install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid,
unsigned char useac, unsigned char modifyac, unsigned char EC,
unsigned char *data, unsigned long dataLen)
{
int r;
struct sc_apdu apdu;
unsigned char isapp = 0x00; /* appendable */
unsigned char tmp_data[256] = { 0 };
tmp_data[0] = ktype;
tmp_data[1] = kid;
tmp_data[2] = useac;
tmp_data[3] = modifyac;
tmp_data[8] = 0xFF;
if (0x04 == ktype || 0x06 == ktype) {
tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO;
tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO;
tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO);
tmp_data[9] = (EC << 4) | EC;
}
memcpy(&tmp_data[10], data, dataLen);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 10 + dataLen;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "install_secret_key failed");
return r;
}
static int
internal_install_pre(struct sc_card *card)
{
int r;
/* init key for enc */
r = install_secret_key(card, 0x01, 0x00,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
0, g_init_key_enc, 16);
LOG_TEST_RET(card->ctx, r, "Install init key failed");
/* init key for mac */
r = install_secret_key(card, 0x02, 0x00,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
0, g_init_key_mac, 16);
LOG_TEST_RET(card->ctx, r, "Install init key failed");
return r;
}
/* use external auth secret as pin */
static int
internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin)
{
int r;
unsigned char hash[HASH_LEN] = { 0 };
r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid,
pin->key_data.es_secret.ac[0],
pin->key_data.es_secret.ac[1],
pin->key_data.es_secret.EC, hash, HASH_LEN);
LOG_TEST_RET(card->ctx, r, "Install failed");
return r;
}
static int
epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data)
{
LOG_FUNC_CALLED(card->ctx);
if (data->type & SC_EPASS2003_KEY) {
if (data->type == SC_EPASS2003_KEY_RSA)
return internal_write_rsa_key(card, data->key_data.es_key.fid,
data->key_data.es_key.rsa);
else
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
} else if (data->type & SC_EPASS2003_SECRET) {
if (data->type == SC_EPASS2003_SECRET_PRE)
return internal_install_pre(card);
else if (data->type == SC_EPASS2003_SECRET_PIN)
return internal_install_pin(card, data);
else
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
else {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data)
{
int r;
size_t len = data->key_length;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
LOG_FUNC_CALLED(card->ctx);
if(len == 256)
{
sbuf[0] = 0x02;
}
else
{
sbuf[0] = 0x01;
}
sbuf[1] = (u8) ((len >> 8) & 0xff);
sbuf[2] = (u8) (len & 0xff);
sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF);
sbuf[4] = (u8) ((data->prkey_id) & 0xFF);
sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF);
sbuf[6] = (u8) ((data->pukey_id) & 0xFF);
/* generate key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00);
apdu.lc = apdu.datalen = 7;
apdu.data = sbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "generate keypair failed");
/* read public key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00);
if(len == 256)
{
apdu.p1 = 0x00;
}
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 2;
apdu.data = &sbuf[5];
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x00;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "get pukey failed");
if (len < apdu.resplen)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
data->modulus = (u8 *) malloc(len);
if (!data->modulus)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(data->modulus, rbuf, len);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_erase_card(struct sc_card *card)
{
int r;
LOG_FUNC_CALLED(card->ctx);
sc_invalidate_cache(card);
r = sc_delete_file(card, sc_get_mf_path());
LOG_TEST_RET(card->ctx, r, "delete MF failed");
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial)
{
u8 rbuf[8];
size_t rbuf_len = sizeof(rbuf);
LOG_FUNC_CALLED(card->ctx);
if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len))
return SC_ERROR_CARD_CMD_FAILED;
card->serialnr.len = serial->len = 8;
memcpy(card->serialnr.value, rbuf, 8);
memcpy(serial->value, rbuf, 8);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr)
{
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "cmd is %0lx", cmd);
switch (cmd) {
case SC_CARDCTL_ENTERSAFE_WRITE_KEY:
return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr);
case SC_CARDCTL_ENTERSAFE_GENERATE_KEY:
return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr);
case SC_CARDCTL_ERASE_CARD:
return epass2003_erase_card(card);
case SC_CARDCTL_GET_SERIALNR:
return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static void
internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num)
{
pin->encoding = SC_PIN_ENCODING_ASCII;
pin->min_length = 4;
pin->max_length = 16;
pin->pad_length = 16;
pin->offset = 5 + num * 16;
pin->pad_char = 0x00;
}
static int
get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries)
{
unsigned char maxcounter[2] = { 0 };
static const sc_path_t file_path = {
{0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6,
0,
0,
SC_PATH_TYPE_PATH,
{{0}, 0}
};
int ret;
ret = sc_select_file(card, &file_path, NULL);
LOG_TEST_RET(card->ctx, ret, "select max counter file failed");
ret = sc_read_binary(card, 0, maxcounter, 2, 0);
LOG_TEST_RET(card->ctx, ret, "read max counter file failed");
*maxtries = maxcounter[0];
return SC_SUCCESS;
}
static int
get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries)
{
int r;
struct sc_apdu apdu;
unsigned char random[16] = { 0 };
r = sc_get_challenge(card, random, 8);
LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid);
apdu.resp = NULL;
apdu.resplen = 0;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed");
if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) {
*retries = (apdu.sw2 & 0x0f);
r = SC_SUCCESS;
}
else {
LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed");
r = SC_ERROR_CARD_CMD_FAILED;
}
return r;
}
static int
epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
u8 rbuf[16];
size_t out_len;
int r;
LOG_FUNC_CALLED(card->ctx);
r = iso_ops->get_challenge(card, rbuf, sizeof rbuf);
LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed");
if (len < (size_t) r) {
out_len = len;
} else {
out_len = (size_t) r;
}
memcpy(rnd, rbuf, out_len);
LOG_FUNC_RETURN(card->ctx, (int) out_len);
}
static int
external_key_auth(struct sc_card *card, unsigned char kid,
unsigned char *data, size_t datalen)
{
int r;
struct sc_apdu apdu;
unsigned char random[16] = { 0 };
unsigned char tmp_data[16] = { 0 };
unsigned char hash[HASH_LEN] = { 0 };
unsigned char iv[16] = { 0 };
r = sc_get_challenge(card, random, 8);
LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed");
r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid);
apdu.lc = apdu.datalen = 8;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "external_key_auth failed");
return r;
}
static int
update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid,
const unsigned char *data, unsigned long datalen)
{
int r;
struct sc_apdu apdu;
unsigned char hash[HASH_LEN] = { 0 };
unsigned char tmp_data[256] = { 0 };
unsigned char maxtries = 0;
r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
r = get_external_key_maxtries(card, &maxtries);
LOG_TEST_RET(card->ctx, r, "get max counter failed");
tmp_data[0] = (maxtries << 4) | maxtries;
memcpy(&tmp_data[1], hash, HASH_LEN);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 1 + HASH_LEN;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "update_secret_key failed");
return r;
}
/* use external auth secret as pin */
static int
epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
int r;
u8 kid;
u8 retries = 0;
u8 pin_low = 3;
unsigned char maxtries = 0;
LOG_FUNC_CALLED(card->ctx);
internal_sanitize_pin_info(&data->pin1, 0);
internal_sanitize_pin_info(&data->pin2, 1);
data->flags |= SC_PIN_CMD_NEED_PADDING;
kid = data->pin_reference;
/* get pin retries */
if (data->cmd == SC_PIN_CMD_GET_INFO) {
r = get_external_key_retries(card, 0x80 | kid, &retries);
if (r == SC_SUCCESS) {
data->pin1.tries_left = retries;
if (tries_left)
*tries_left = retries;
r = get_external_key_maxtries(card, &maxtries);
LOG_TEST_RET(card->ctx, r, "get max counter failed");
data->pin1.max_tries = maxtries;
}
//remove below code, because the old implement only return PIN retries, now modify the code and return PIN status
// return r;
}
else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */
r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data,
data->pin1.len);
LOG_TEST_RET(card->ctx, r, "verify pin failed");
}
else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */
r = update_secret_key(card, 0x04, kid, data->pin2.data,
(unsigned long)data->pin2.len);
LOG_TEST_RET(card->ctx, r, "verify pin failed");
}
else {
r = external_key_auth(card, kid, (unsigned char *)data->pin1.data,
data->pin1.len);
get_external_key_retries(card, 0x80 | kid, &retries);
if (retries < pin_low)
sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries);
}
LOG_TEST_RET(card->ctx, r, "verify pin failed");
if (r == SC_SUCCESS)
{
data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN;
}
return r;
}
static struct sc_card_driver *sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
epass2003_ops = *iso_ops;
epass2003_ops.match_card = epass2003_match_card;
epass2003_ops.init = epass2003_init;
epass2003_ops.finish = epass2003_finish;
epass2003_ops.write_binary = NULL;
epass2003_ops.write_record = NULL;
epass2003_ops.select_file = epass2003_select_file;
epass2003_ops.get_response = NULL;
epass2003_ops.restore_security_env = epass2003_restore_security_env;
epass2003_ops.set_security_env = epass2003_set_security_env;
epass2003_ops.decipher = epass2003_decipher;
epass2003_ops.compute_signature = epass2003_decipher;
epass2003_ops.create_file = epass2003_create_file;
epass2003_ops.delete_file = epass2003_delete_file;
epass2003_ops.list_files = epass2003_list_files;
epass2003_ops.card_ctl = epass2003_card_ctl;
epass2003_ops.process_fci = epass2003_process_fci;
epass2003_ops.construct_fci = epass2003_construct_fci;
epass2003_ops.pin_cmd = epass2003_pin_cmd;
epass2003_ops.check_sw = epass2003_check_sw;
epass2003_ops.get_challenge = epass2003_get_challenge;
return &epass2003_drv;
}
struct sc_card_driver *sc_get_epass2003_driver(void)
{
return sc_get_driver();
}
#endif /* #ifdef ENABLE_OPENSSL */
#endif /* #ifdef ENABLE_SM */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_346_1 |
crossvul-cpp_data_bad_1447_0 | /* ssl/d1_pkt.c */
/*
* DTLS implementation written by Nagendra Modadugu
* (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
*/
/* ====================================================================
* Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <errno.h>
#define USE_SOCKETS
#include "ssl_locl.h"
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <openssl/pqueue.h>
#include <openssl/rand.h>
/* mod 128 saturating subtract of two 64-bit values in big-endian order */
static int satsub64be(const unsigned char *v1,const unsigned char *v2)
{ int ret,sat,brw,i;
if (sizeof(long) == 8) do
{ const union { long one; char little; } is_endian = {1};
long l;
if (is_endian.little) break;
/* not reached on little-endians */
/* following test is redundant, because input is
* always aligned, but I take no chances... */
if (((size_t)v1|(size_t)v2)&0x7) break;
l = *((long *)v1);
l -= *((long *)v2);
if (l>128) return 128;
else if (l<-128) return -128;
else return (int)l;
} while (0);
ret = (int)v1[7]-(int)v2[7];
sat = 0;
brw = ret>>8; /* brw is either 0 or -1 */
if (ret & 0x80)
{ for (i=6;i>=0;i--)
{ brw += (int)v1[i]-(int)v2[i];
sat |= ~brw;
brw >>= 8;
}
}
else
{ for (i=6;i>=0;i--)
{ brw += (int)v1[i]-(int)v2[i];
sat |= brw;
brw >>= 8;
}
}
brw <<= 8; /* brw is either 0 or -256 */
if (sat&0xff) return brw | 0x80;
else return brw + (ret&0xFF);
}
static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
int len, int peek);
static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
unsigned int *is_next_epoch);
#if 0
static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
unsigned short *priority, unsigned long *offset);
#endif
static int dtls1_buffer_record(SSL *s, record_pqueue *q,
unsigned char *priority);
static int dtls1_process_record(SSL *s);
/* copy buffered record into SSL structure */
static int
dtls1_copy_record(SSL *s, pitem *item)
{
DTLS1_RECORD_DATA *rdata;
rdata = (DTLS1_RECORD_DATA *)item->data;
if (s->s3->rbuf.buf != NULL)
OPENSSL_free(s->s3->rbuf.buf);
s->packet = rdata->packet;
s->packet_length = rdata->packet_length;
memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
/* Set proper sequence number for mac calculation */
memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6);
return(1);
}
static int
dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
{
DTLS1_RECORD_DATA *rdata;
pitem *item;
/* Limit the size of the queue to prevent DOS attacks */
if (pqueue_size(queue->q) >= 100)
return 0;
rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
item = pitem_new(priority, rdata);
if (rdata == NULL || item == NULL)
{
if (rdata != NULL) OPENSSL_free(rdata);
if (item != NULL) pitem_free(item);
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
return(0);
}
rdata->packet = s->packet;
rdata->packet_length = s->packet_length;
memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
item->data = rdata;
#ifndef OPENSSL_NO_SCTP
/* Store bio_dgram_sctp_rcvinfo struct */
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
(s->state == SSL3_ST_SR_FINISHED_A || s->state == SSL3_ST_CR_FINISHED_A)) {
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo);
}
#endif
s->packet = NULL;
s->packet_length = 0;
memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
if (!ssl3_setup_buffers(s))
{
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
OPENSSL_free(rdata);
pitem_free(item);
return(0);
}
/* insert should not fail, since duplicates are dropped */
if (pqueue_insert(queue->q, item) == NULL)
{
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
OPENSSL_free(rdata);
pitem_free(item);
return(0);
}
return(1);
}
static int
dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
{
pitem *item;
item = pqueue_pop(queue->q);
if (item)
{
dtls1_copy_record(s, item);
OPENSSL_free(item->data);
pitem_free(item);
return(1);
}
return(0);
}
/* retrieve a buffered record that belongs to the new epoch, i.e., not processed
* yet */
#define dtls1_get_unprocessed_record(s) \
dtls1_retrieve_buffered_record((s), \
&((s)->d1->unprocessed_rcds))
/* retrieve a buffered record that belongs to the current epoch, ie, processed */
#define dtls1_get_processed_record(s) \
dtls1_retrieve_buffered_record((s), \
&((s)->d1->processed_rcds))
static int
dtls1_process_buffered_records(SSL *s)
{
pitem *item;
item = pqueue_peek(s->d1->unprocessed_rcds.q);
if (item)
{
/* Check if epoch is current. */
if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
return(1); /* Nothing to do. */
/* Process all the records. */
while (pqueue_peek(s->d1->unprocessed_rcds.q))
{
dtls1_get_unprocessed_record(s);
if ( ! dtls1_process_record(s))
return(0);
dtls1_buffer_record(s, &(s->d1->processed_rcds),
s->s3->rrec.seq_num);
}
}
/* sync epoch numbers once all the unprocessed records
* have been processed */
s->d1->processed_rcds.epoch = s->d1->r_epoch;
s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
return(1);
}
#if 0
static int
dtls1_get_buffered_record(SSL *s)
{
pitem *item;
PQ_64BIT priority =
(((PQ_64BIT)s->d1->handshake_read_seq) << 32) |
((PQ_64BIT)s->d1->r_msg_hdr.frag_off);
if ( ! SSL_in_init(s)) /* if we're not (re)negotiating,
nothing buffered */
return 0;
item = pqueue_peek(s->d1->rcvd_records);
if (item && item->priority == priority)
{
/* Check if we've received the record of interest. It must be
* a handshake record, since data records as passed up without
* buffering */
DTLS1_RECORD_DATA *rdata;
item = pqueue_pop(s->d1->rcvd_records);
rdata = (DTLS1_RECORD_DATA *)item->data;
if (s->s3->rbuf.buf != NULL)
OPENSSL_free(s->s3->rbuf.buf);
s->packet = rdata->packet;
s->packet_length = rdata->packet_length;
memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
OPENSSL_free(item->data);
pitem_free(item);
/* s->d1->next_expected_seq_num++; */
return(1);
}
return 0;
}
#endif
static int
dtls1_process_record(SSL *s)
{
int i,al;
int enc_err;
SSL_SESSION *sess;
SSL3_RECORD *rr;
unsigned int mac_size;
unsigned char md[EVP_MAX_MD_SIZE];
rr= &(s->s3->rrec);
sess = s->session;
/* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
* and we have that many bytes in s->packet
*/
rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]);
/* ok, we can now read from 's->packet' data into 'rr'
* rr->input points at rr->length bytes, which
* need to be copied into rr->data by either
* the decryption or by the decompression
* When the data is 'copied' into the rr->data buffer,
* rr->input will be pointed at the new buffer */
/* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
* rr->length bytes of encrypted compressed stuff. */
/* check is not needed I believe */
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
al=SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
goto f_err;
}
/* decrypt in place in 'rr->input' */
rr->data=rr->input;
rr->orig_len=rr->length;
enc_err = s->method->ssl3_enc->enc(s,0);
/* enc_err is:
* 0: (in non-constant time) if the record is publically invalid.
* 1: if the padding is valid
* -1: if the padding is invalid */
if (enc_err == 0)
{
/* For DTLS we simply ignore bad packets. */
rr->length = 0;
s->packet_length = 0;
goto err;
}
#ifdef TLS_DEBUG
printf("dec %d\n",rr->length);
{ unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
printf("\n");
#endif
/* r->length is now the compressed data plus mac */
if ((sess != NULL) &&
(s->enc_read_ctx != NULL) &&
(EVP_MD_CTX_md(s->read_hash) != NULL))
{
/* s->read_hash != NULL => mac_size != -1 */
unsigned char *mac = NULL;
unsigned char mac_tmp[EVP_MAX_MD_SIZE];
mac_size=EVP_MD_CTX_size(s->read_hash);
OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
/* orig_len is the length of the record before any padding was
* removed. This is public information, as is the MAC in use,
* therefore we can safely process the record in a different
* amount of time if it's too short to possibly contain a MAC.
*/
if (rr->orig_len < mac_size ||
/* CBC records must have a padding length byte too. */
(EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
rr->orig_len < mac_size+1))
{
al=SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE)
{
/* We update the length so that the TLS header bytes
* can be constructed correctly but we need to extract
* the MAC in constant time from within the record,
* without leaking the contents of the padding bytes.
* */
mac = mac_tmp;
ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
rr->length -= mac_size;
}
else
{
/* In this case there's no padding, so |rec->orig_len|
* equals |rec->length| and we checked that there's
* enough bytes for |mac_size| above. */
rr->length -= mac_size;
mac = &rr->data[rr->length];
}
i=s->method->ssl3_enc->mac(s,md,0 /* not send */);
if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
enc_err = -1;
if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size)
enc_err = -1;
}
if (enc_err < 0)
{
/* decryption failed, silently discard message */
rr->length = 0;
s->packet_length = 0;
goto err;
}
/* r->length is now just compressed */
if (s->expand != NULL)
{
if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH)
{
al=SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
goto f_err;
}
if (!ssl3_do_uncompress(s))
{
al=SSL_AD_DECOMPRESSION_FAILURE;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION);
goto f_err;
}
}
if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH)
{
al=SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
goto f_err;
}
rr->off=0;
/*-
* So at this point the following is true
* ssl->s3->rrec.type is the type of record
* ssl->s3->rrec.length == number of bytes in record
* ssl->s3->rrec.off == offset to first valid byte
* ssl->s3->rrec.data == where to take bytes from, increment
* after use :-).
*/
/* we have pulled in a full packet so zero things */
s->packet_length=0;
dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */
return(1);
f_err:
ssl3_send_alert(s,SSL3_AL_FATAL,al);
err:
return(0);
}
/*-
* Call this to get a new input record.
* It will return <= 0 if more data is needed, normally due to an error
* or non-blocking IO.
* When it finishes, one packet has been decoded and can be found in
* ssl->s3->rrec.type - is the type of record
* ssl->s3->rrec.data, - data
* ssl->s3->rrec.length, - number of bytes
*/
/* used only by dtls1_read_bytes */
int dtls1_get_record(SSL *s)
{
int ssl_major,ssl_minor;
int i,n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr= &(s->s3->rrec);
/* The epoch may have changed. If so, process all the
* pending records. This is a non-blocking operation. */
dtls1_process_buffered_records(s);
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
again:
/* check if we have the header */
if ( (s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH))
{
n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0) return(n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
{
s->packet_length = 0;
goto again;
}
s->rstate=SSL_ST_READ_BODY;
p=s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type= *(p++);
ssl_major= *(p++);
ssl_minor= *(p++);
version=(ssl_major<<8)|ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p,rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p+=6;
n2s(p,rr->length);
/* Lets check version */
if (!s->first_packet)
{
if (version != s->version)
{
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00))
{
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
{
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i=rr->length;
n=ssl3_read_n(s,i,i,1);
/* this packet contained a partial record, dump it */
if ( n != i)
{
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now n == rr->length,
* and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
}
s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if ( bitmap == NULL)
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
#endif
/* Check whether this is a repeat, or aged record.
* Don't check if we're listening and this message is
* a ClientHello. They can look as if they're replayed,
* since they arrive from different connections and
* would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
s->packet_length > DTLS1_RT_HEADER_LENGTH &&
s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap))
{
rr->length = 0;
s->packet_length=0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0) goto again;
/* If this record is from the next epoch (either HM or ALERT),
* and a handshake is currently in progress, buffer it since it
* cannot be processed at this time. However, do not buffer
* anything while listening.
*/
if (is_next_epoch)
{
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
{
dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s))
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
return(1);
}
/*-
* Return up to 'len' payload bytes received in 'type' records.
* 'type' is one of the following:
*
* - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
* - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
* - 0 (during a shutdown, no data has to be returned)
*
* If we don't have stored data to work from, read a SSL/TLS record first
* (possibly multiple records if we still don't have anything to return).
*
* This function must handle any surprises the peer may have for us, such as
* Alert records (e.g. close_notify), ChangeCipherSpec records (not really
* a surprise, but handled as if it were), or renegotiation requests.
* Also if record payloads contain fragments too small to process, we store
* them until there is enough for the respective protocol (the record protocol
* may use arbitrary fragmentation and even interleaving):
* Change cipher spec protocol
* just 1 byte needed, no need for keeping anything stored
* Alert protocol
* 2 bytes needed (AlertLevel, AlertDescription)
* Handshake protocol
* 4 bytes needed (HandshakeType, uint24 length) -- we just have
* to detect unexpected Client Hello and Hello Request messages
* here, anything else is handled by higher layers
* Application data protocol
* none of our business
*/
int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
{
int al,i,j,ret;
unsigned int n;
SSL3_RECORD *rr;
void (*cb)(const SSL *ssl,int type2,int val)=NULL;
if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
if (!ssl3_setup_buffers(s))
return(-1);
if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
(type != SSL3_RT_HANDSHAKE)) ||
(peek && (type != SSL3_RT_APPLICATION_DATA)))
{
SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
return -1;
}
/* check whether there's a handshake message (client hello?) waiting */
if ( (ret = have_handshake_fragment(s, type, buf, len, peek)))
return ret;
/* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
#ifndef OPENSSL_NO_SCTP
/* Continue handshake if it had to be interrupted to read
* app data with SCTP.
*/
if ((!s->in_handshake && SSL_in_init(s)) ||
(BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
(s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK) &&
s->s3->in_read_app_data != 2))
#else
if (!s->in_handshake && SSL_in_init(s))
#endif
{
/* type == SSL3_RT_APPLICATION_DATA */
i=s->handshake_func(s);
if (i < 0) return(i);
if (i == 0)
{
SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
return(-1);
}
}
start:
s->rwstate=SSL_NOTHING;
/*-
* s->s3->rrec.type - is the type of record
* s->s3->rrec.data, - data
* s->s3->rrec.off, - offset into 'data' for next read
* s->s3->rrec.length, - number of bytes.
*/
rr = &(s->s3->rrec);
/* We are not handshaking and have no data yet,
* so process data buffered during the last handshake
* in advance, if any.
*/
if (s->state == SSL_ST_OK && rr->length == 0)
{
pitem *item;
item = pqueue_pop(s->d1->buffered_app_data.q);
if (item)
{
#ifndef OPENSSL_NO_SCTP
/* Restore bio_dgram_sctp_rcvinfo struct */
if (BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *) item->data;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo);
}
#endif
dtls1_copy_record(s, item);
OPENSSL_free(item->data);
pitem_free(item);
}
}
/* Check for timeout */
if (dtls1_handle_timeout(s) > 0)
goto start;
/* get new packet if necessary */
if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
{
ret=dtls1_get_record(s);
if (ret <= 0)
{
ret = dtls1_read_failed(s, ret);
/* anything other than a timeout is an error */
if (ret <= 0)
return(ret);
else
goto start;
}
}
if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE)
{
rr->length = 0;
goto start;
}
/* we now have a packet which can be read and processed */
if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
* reset by ssl3_get_finished */
&& (rr->type != SSL3_RT_HANDSHAKE))
{
/* We now have application data between CCS and Finished.
* Most likely the packets were reordered on their way, so
* buffer the application data for later processing rather
* than dropping the connection.
*/
dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num);
rr->length = 0;
goto start;
}
/* If the other end has shut down, throw anything we read away
* (even in 'peek' mode) */
if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
{
rr->length=0;
s->rwstate=SSL_NOTHING;
return(0);
}
if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
{
/* make sure that we are not getting application data when we
* are doing a handshake for the first time */
if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
(s->enc_read_ctx == NULL))
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);
goto f_err;
}
if (len <= 0) return(len);
if ((unsigned int)len > rr->length)
n = rr->length;
else
n = (unsigned int)len;
memcpy(buf,&(rr->data[rr->off]),n);
if (!peek)
{
rr->length-=n;
rr->off+=n;
if (rr->length == 0)
{
s->rstate=SSL_ST_READ_HEADER;
rr->off=0;
}
}
#ifndef OPENSSL_NO_SCTP
/* We were about to renegotiate but had to read
* belated application data first, so retry.
*/
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
rr->type == SSL3_RT_APPLICATION_DATA &&
(s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK))
{
s->rwstate=SSL_READING;
BIO_clear_retry_flags(SSL_get_rbio(s));
BIO_set_retry_read(SSL_get_rbio(s));
}
/* We might had to delay a close_notify alert because
* of reordered app data. If there was an alert and there
* is no message to read anymore, finally set shutdown.
*/
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
s->d1->shutdown_received && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)))
{
s->shutdown |= SSL_RECEIVED_SHUTDOWN;
return(0);
}
#endif
return(n);
}
/* If we get here, then type != rr->type; if we have a handshake
* message, then it was unexpected (Hello Request or Client Hello). */
/* In case of record types for which we have 'fragment' storage,
* fill that so that we can process the data at a fixed place.
*/
{
unsigned int k, dest_maxlen = 0;
unsigned char *dest = NULL;
unsigned int *dest_len = NULL;
if (rr->type == SSL3_RT_HANDSHAKE)
{
dest_maxlen = sizeof s->d1->handshake_fragment;
dest = s->d1->handshake_fragment;
dest_len = &s->d1->handshake_fragment_len;
}
else if (rr->type == SSL3_RT_ALERT)
{
dest_maxlen = sizeof(s->d1->alert_fragment);
dest = s->d1->alert_fragment;
dest_len = &s->d1->alert_fragment_len;
}
#ifndef OPENSSL_NO_HEARTBEATS
else if (rr->type == TLS1_RT_HEARTBEAT)
{
dtls1_process_heartbeat(s);
/* Exit and notify application to read again */
rr->length = 0;
s->rwstate=SSL_READING;
BIO_clear_retry_flags(SSL_get_rbio(s));
BIO_set_retry_read(SSL_get_rbio(s));
return(-1);
}
#endif
/* else it's a CCS message, or application data or wrong */
else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC)
{
/* Application data while renegotiating
* is allowed. Try again reading.
*/
if (rr->type == SSL3_RT_APPLICATION_DATA)
{
BIO *bio;
s->s3->in_read_app_data=2;
bio=SSL_get_rbio(s);
s->rwstate=SSL_READING;
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return(-1);
}
/* Not certain if this is the right error handling */
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
goto f_err;
}
if (dest_maxlen > 0)
{
/* XDTLS: In a pathalogical case, the Client Hello
* may be fragmented--don't always expect dest_maxlen bytes */
if ( rr->length < dest_maxlen)
{
#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
/*
* for normal alerts rr->length is 2, while
* dest_maxlen is 7 if we were to handle this
* non-existing alert...
*/
FIX ME
#endif
s->rstate=SSL_ST_READ_HEADER;
rr->length = 0;
goto start;
}
/* now move 'n' bytes: */
for ( k = 0; k < dest_maxlen; k++)
{
dest[k] = rr->data[rr->off++];
rr->length--;
}
*dest_len = dest_maxlen;
}
}
/* s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE;
* s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT.
* (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
/* If we are a client, check for an incoming 'Hello Request': */
if ((!s->server) &&
(s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
(s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
(s->session != NULL) && (s->session->cipher != NULL))
{
s->d1->handshake_fragment_len = 0;
if ((s->d1->handshake_fragment[1] != 0) ||
(s->d1->handshake_fragment[2] != 0) ||
(s->d1->handshake_fragment[3] != 0))
{
al=SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_HELLO_REQUEST);
goto err;
}
/* no need to check sequence number on HELLO REQUEST messages */
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
s->d1->handshake_fragment, 4, s, s->msg_callback_arg);
if (SSL_is_init_finished(s) &&
!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
!s->s3->renegotiate)
{
s->d1->handshake_read_seq++;
s->new_session = 1;
ssl3_renegotiate(s);
if (ssl3_renegotiate_check(s))
{
i=s->handshake_func(s);
if (i < 0) return(i);
if (i == 0)
{
SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
return(-1);
}
if (!(s->mode & SSL_MODE_AUTO_RETRY))
{
if (s->s3->rbuf.left == 0) /* no read-ahead left? */
{
BIO *bio;
/* In the case where we try to read application data,
* but we trigger an SSL handshake, we return -1 with
* the retry option set. Otherwise renegotiation may
* cause nasty problems in the blocking world */
s->rwstate=SSL_READING;
bio=SSL_get_rbio(s);
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return(-1);
}
}
}
}
/* we either finished a handshake or ignored the request,
* now try again to obtain the (application) data we were asked for */
goto start;
}
if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH)
{
int alert_level = s->d1->alert_fragment[0];
int alert_descr = s->d1->alert_fragment[1];
s->d1->alert_fragment_len = 0;
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_ALERT,
s->d1->alert_fragment, 2, s, s->msg_callback_arg);
if (s->info_callback != NULL)
cb=s->info_callback;
else if (s->ctx->info_callback != NULL)
cb=s->ctx->info_callback;
if (cb != NULL)
{
j = (alert_level << 8) | alert_descr;
cb(s, SSL_CB_READ_ALERT, j);
}
if (alert_level == 1) /* warning */
{
s->s3->warn_alert = alert_descr;
if (alert_descr == SSL_AD_CLOSE_NOTIFY)
{
#ifndef OPENSSL_NO_SCTP
/* With SCTP and streams the socket may deliver app data
* after a close_notify alert. We have to check this
* first so that nothing gets discarded.
*/
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)))
{
s->d1->shutdown_received = 1;
s->rwstate=SSL_READING;
BIO_clear_retry_flags(SSL_get_rbio(s));
BIO_set_retry_read(SSL_get_rbio(s));
return -1;
}
#endif
s->shutdown |= SSL_RECEIVED_SHUTDOWN;
return(0);
}
#if 0
/* XXX: this is a possible improvement in the future */
/* now check if it's a missing record */
if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
{
unsigned short seq;
unsigned int frag_off;
unsigned char *p = &(s->d1->alert_fragment[2]);
n2s(p, seq);
n2l3(p, frag_off);
dtls1_retransmit_message(s,
dtls1_get_queue_priority(frag->msg_header.seq, 0),
frag_off, &found);
if ( ! found && SSL_in_init(s))
{
/* fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */
/* requested a message not yet sent,
send an alert ourselves */
ssl3_send_alert(s,SSL3_AL_WARNING,
DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
}
}
#endif
}
else if (alert_level == 2) /* fatal */
{
char tmp[16];
s->rwstate=SSL_NOTHING;
s->s3->fatal_alert = alert_descr;
SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
ERR_add_error_data(2,"SSL alert number ",tmp);
s->shutdown|=SSL_RECEIVED_SHUTDOWN;
SSL_CTX_remove_session(s->ctx,s->session);
return(0);
}
else
{
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);
goto f_err;
}
goto start;
}
if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
{
s->rwstate=SSL_NOTHING;
rr->length=0;
return(0);
}
if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
{
struct ccs_header_st ccs_hdr;
unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
dtls1_get_ccs_header(rr->data, &ccs_hdr);
if (s->version == DTLS1_BAD_VER)
ccs_hdr_len = 3;
/* 'Change Cipher Spec' is just a single byte, so we know
* exactly what the record payload has to look like */
/* XDTLS: check that epoch is consistent */
if ( (rr->length != ccs_hdr_len) ||
(rr->off != 0) || (rr->data[0] != SSL3_MT_CCS))
{
i=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);
goto err;
}
rr->length=0;
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
rr->data, 1, s, s->msg_callback_arg);
/* We can't process a CCS now, because previous handshake
* messages are still missing, so just drop it.
*/
if (!s->d1->change_cipher_spec_ok)
{
goto start;
}
s->d1->change_cipher_spec_ok = 0;
s->s3->change_cipher_spec=1;
if (!ssl3_do_change_cipher_spec(s))
goto err;
/* do this whenever CCS is processed */
dtls1_reset_seq_numbers(s, SSL3_CC_READ);
if (s->version == DTLS1_BAD_VER)
s->d1->handshake_read_seq++;
#ifndef OPENSSL_NO_SCTP
/* Remember that a CCS has been received,
* so that an old key of SCTP-Auth can be
* deleted when a CCS is sent. Will be ignored
* if no SCTP is used
*/
BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
#endif
goto start;
}
/* Unexpected handshake message (Client Hello, or protocol violation) */
if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
!s->in_handshake)
{
struct hm_header_st msg_hdr;
/* this may just be a stale retransmit */
dtls1_get_message_header(rr->data, &msg_hdr);
if( rr->epoch != s->d1->r_epoch)
{
rr->length = 0;
goto start;
}
/* If we are server, we may have a repeated FINISHED of the
* client here, then retransmit our CCS and FINISHED.
*/
if (msg_hdr.type == SSL3_MT_FINISHED)
{
if (dtls1_check_timeout_num(s) < 0)
return -1;
dtls1_retransmit_buffered_messages(s);
rr->length = 0;
goto start;
}
if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
{
#if 0 /* worked only because C operator preferences are not as expected (and
* because this is not really needed for clients except for detecting
* protocol violations): */
s->state=SSL_ST_BEFORE|(s->server)
?SSL_ST_ACCEPT
:SSL_ST_CONNECT;
#else
s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
#endif
s->renegotiate=1;
s->new_session=1;
}
i=s->handshake_func(s);
if (i < 0) return(i);
if (i == 0)
{
SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
return(-1);
}
if (!(s->mode & SSL_MODE_AUTO_RETRY))
{
if (s->s3->rbuf.left == 0) /* no read-ahead left? */
{
BIO *bio;
/* In the case where we try to read application data,
* but we trigger an SSL handshake, we return -1 with
* the retry option set. Otherwise renegotiation may
* cause nasty problems in the blocking world */
s->rwstate=SSL_READING;
bio=SSL_get_rbio(s);
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return(-1);
}
}
goto start;
}
switch (rr->type)
{
default:
#ifndef OPENSSL_NO_TLS
/* TLS just ignores unknown message types */
if (s->version == TLS1_VERSION)
{
rr->length = 0;
goto start;
}
#endif
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
goto f_err;
case SSL3_RT_CHANGE_CIPHER_SPEC:
case SSL3_RT_ALERT:
case SSL3_RT_HANDSHAKE:
/* we already handled all of these, with the possible exception
* of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
* should not happen when type != rr->type */
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_READ_BYTES,ERR_R_INTERNAL_ERROR);
goto f_err;
case SSL3_RT_APPLICATION_DATA:
/* At this point, we were expecting handshake data,
* but have application data. If the library was
* running inside ssl3_read() (i.e. in_read_app_data
* is set) and it makes sense to read application data
* at this point (session renegotiation not yet started),
* we will indulge it.
*/
if (s->s3->in_read_app_data &&
(s->s3->total_renegotiations != 0) &&
((
(s->state & SSL_ST_CONNECT) &&
(s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
(s->state <= SSL3_ST_CR_SRVR_HELLO_A)
) || (
(s->state & SSL_ST_ACCEPT) &&
(s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
(s->state >= SSL3_ST_SR_CLNT_HELLO_A)
)
))
{
s->s3->in_read_app_data=2;
return(-1);
}
else
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
goto f_err;
}
}
/* not reached */
f_err:
ssl3_send_alert(s,SSL3_AL_FATAL,al);
err:
return(-1);
}
int
dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
{
int i;
#ifndef OPENSSL_NO_SCTP
/* Check if we have to continue an interrupted handshake
* for reading belated app data with SCTP.
*/
if ((SSL_in_init(s) && !s->in_handshake) ||
(BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
(s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)))
#else
if (SSL_in_init(s) && !s->in_handshake)
#endif
{
i=s->handshake_func(s);
if (i < 0) return(i);
if (i == 0)
{
SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
return -1;
}
}
if (len > SSL3_RT_MAX_PLAIN_LENGTH)
{
SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_DTLS_MESSAGE_TOO_BIG);
return -1;
}
i = dtls1_write_bytes(s, type, buf_, len);
return i;
}
/* this only happens when a client hello is received and a handshake
* is started. */
static int
have_handshake_fragment(SSL *s, int type, unsigned char *buf,
int len, int peek)
{
if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
/* (partially) satisfy request from storage */
{
unsigned char *src = s->d1->handshake_fragment;
unsigned char *dst = buf;
unsigned int k,n;
/* peek == 0 */
n = 0;
while ((len > 0) && (s->d1->handshake_fragment_len > 0))
{
*dst++ = *src++;
len--; s->d1->handshake_fragment_len--;
n++;
}
/* move any remaining fragment bytes: */
for (k = 0; k < s->d1->handshake_fragment_len; k++)
s->d1->handshake_fragment[k] = *src++;
return n;
}
return 0;
}
/* Call this to write data in records of type 'type'
* It will return <= 0 if not all data has been sent or non-blocking IO.
*/
int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
{
int i;
OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
s->rwstate=SSL_NOTHING;
i=do_dtls1_write(s, type, buf, len, 0);
return i;
}
int do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len, int create_empty_fragment)
{
unsigned char *p,*pseq;
int i,mac_size,clear=0;
int prefix_len = 0;
int eivlen;
SSL3_RECORD *wr;
SSL3_BUFFER *wb;
SSL_SESSION *sess;
/* first check if there is a SSL3_BUFFER still being written
* out. This will happen with non blocking IO */
if (s->s3->wbuf.left != 0)
{
OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */
return(ssl3_write_pending(s,type,buf,len));
}
/* If we have an alert to send, lets send it */
if (s->s3->alert_dispatch)
{
i=s->method->ssl_dispatch_alert(s);
if (i <= 0)
return(i);
/* if it went, fall through and send more stuff */
}
if (len == 0 && !create_empty_fragment)
return 0;
wr= &(s->s3->wrec);
wb= &(s->s3->wbuf);
sess=s->session;
if ( (sess == NULL) ||
(s->enc_write_ctx == NULL) ||
(EVP_MD_CTX_md(s->write_hash) == NULL))
clear=1;
if (clear)
mac_size=0;
else
{
mac_size=EVP_MD_CTX_size(s->write_hash);
if (mac_size < 0)
goto err;
}
/* DTLS implements explicit IV, so no need for empty fragments */
#if 0
/* 'create_empty_fragment' is true only when this function calls itself */
if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done
&& SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
{
/* countermeasure against known-IV weakness in CBC ciphersuites
* (see http://www.openssl.org/~bodo/tls-cbc.txt)
*/
if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA)
{
/* recursive function call with 'create_empty_fragment' set;
* this prepares and buffers the data for an empty fragment
* (these 'prefix_len' bytes are sent out later
* together with the actual payload) */
prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1);
if (prefix_len <= 0)
goto err;
if (s->s3->wbuf.len < (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE)
{
/* insufficient space */
SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR);
goto err;
}
}
s->s3->empty_fragment_done = 1;
}
#endif
p = wb->buf + prefix_len;
/* write the header */
*(p++)=type&0xff;
wr->type=type;
/* Special case: for hello verify request, client version 1.0 and
* we haven't decided which version to use yet send back using
* version 1.0 header: otherwise some clients will ignore it.
*/
if (s->method->version == DTLS_ANY_VERSION)
{
*(p++)=DTLS1_VERSION>>8;
*(p++)=DTLS1_VERSION&0xff;
}
else
{
*(p++)=s->version>>8;
*(p++)=s->version&0xff;
}
/* field where we are to write out packet epoch, seq num and len */
pseq=p;
p+=10;
/* Explicit IV length, block ciphers appropriate version flag */
if (s->enc_write_ctx)
{
int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
if (mode == EVP_CIPH_CBC_MODE)
{
eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
if (eivlen <= 1)
eivlen = 0;
}
/* Need explicit part of IV for GCM mode */
else if (mode == EVP_CIPH_GCM_MODE)
eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
else
eivlen = 0;
}
else
eivlen = 0;
/* lets setup the record stuff. */
wr->data=p + eivlen; /* make room for IV in case of CBC */
wr->length=(int)len;
wr->input=(unsigned char *)buf;
/* we now 'read' from wr->input, wr->length bytes into
* wr->data */
/* first we compress */
if (s->compress != NULL)
{
if (!ssl3_do_compress(s))
{
SSLerr(SSL_F_DO_DTLS1_WRITE,SSL_R_COMPRESSION_FAILURE);
goto err;
}
}
else
{
memcpy(wr->data,wr->input,wr->length);
wr->input=wr->data;
}
/* we should still have the output to wr->data and the input
* from wr->input. Length should be wr->length.
* wr->data still points in the wb->buf */
if (mac_size != 0)
{
if(s->method->ssl3_enc->mac(s,&(p[wr->length + eivlen]),1) < 0)
goto err;
wr->length+=mac_size;
}
/* this is true regardless of mac size */
wr->input=p;
wr->data=p;
if (eivlen)
wr->length += eivlen;
if(s->method->ssl3_enc->enc(s,1) < 1) goto err;
/* record length after mac and block padding */
/* if (type == SSL3_RT_APPLICATION_DATA ||
(type == SSL3_RT_ALERT && ! SSL_in_init(s))) */
/* there's only one epoch between handshake and app data */
s2n(s->d1->w_epoch, pseq);
/* XDTLS: ?? */
/* else
s2n(s->d1->handshake_epoch, pseq); */
memcpy(pseq, &(s->s3->write_sequence[2]), 6);
pseq+=6;
s2n(wr->length,pseq);
if (s->msg_callback)
s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* we should now have
* wr->data pointing to the encrypted data, which is
* wr->length long */
wr->type=type; /* not needed but helps for debugging */
wr->length+=DTLS1_RT_HEADER_LENGTH;
#if 0 /* this is now done at the message layer */
/* buffer the record, making it easy to handle retransmits */
if ( type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
dtls1_buffer_record(s, wr->data, wr->length,
*((PQ_64BIT *)&(s->s3->write_sequence[0])));
#endif
ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
if (create_empty_fragment)
{
/* we are in a recursive call;
* just return the length, don't write out anything here
*/
return wr->length;
}
/* now let's set up wb */
wb->left = prefix_len + wr->length;
wb->offset = 0;
/* memorize arguments so that ssl3_write_pending can detect bad write retries later */
s->s3->wpend_tot=len;
s->s3->wpend_buf=buf;
s->s3->wpend_type=type;
s->s3->wpend_ret=len;
/* we now just need to write the buffer */
return ssl3_write_pending(s,type,buf,len);
err:
return -1;
}
static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
{
int cmp;
unsigned int shift;
const unsigned char *seq = s->s3->read_sequence;
cmp = satsub64be(seq,bitmap->max_seq_num);
if (cmp > 0)
{
memcpy (s->s3->rrec.seq_num,seq,8);
return 1; /* this record in new */
}
shift = -cmp;
if (shift >= sizeof(bitmap->map)*8)
return 0; /* stale, outside the window */
else if (bitmap->map & (1UL<<shift))
return 0; /* record previously received */
memcpy (s->s3->rrec.seq_num,seq,8);
return 1;
}
static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
{
int cmp;
unsigned int shift;
const unsigned char *seq = s->s3->read_sequence;
cmp = satsub64be(seq,bitmap->max_seq_num);
if (cmp > 0)
{
shift = cmp;
if (shift < sizeof(bitmap->map)*8)
bitmap->map <<= shift, bitmap->map |= 1UL;
else
bitmap->map = 1UL;
memcpy(bitmap->max_seq_num,seq,8);
}
else {
shift = -cmp;
if (shift < sizeof(bitmap->map)*8)
bitmap->map |= 1UL<<shift;
}
}
int dtls1_dispatch_alert(SSL *s)
{
int i,j;
void (*cb)(const SSL *ssl,int type,int val)=NULL;
unsigned char buf[DTLS1_AL_HEADER_LENGTH];
unsigned char *ptr = &buf[0];
s->s3->alert_dispatch=0;
memset(buf, 0x00, sizeof(buf));
*ptr++ = s->s3->send_alert[0];
*ptr++ = s->s3->send_alert[1];
#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
{
s2n(s->d1->handshake_read_seq, ptr);
#if 0
if ( s->d1->r_msg_hdr.frag_off == 0) /* waiting for a new msg */
else
s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
#endif
#if 0
fprintf(stderr, "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",s->d1->handshake_read_seq,s->d1->r_msg_hdr.seq);
#endif
l2n3(s->d1->r_msg_hdr.frag_off, ptr);
}
#endif
i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
if (i <= 0)
{
s->s3->alert_dispatch=1;
/* fprintf( stderr, "not done with alert\n" ); */
}
else
{
if (s->s3->send_alert[0] == SSL3_AL_FATAL
#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
|| s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
#endif
)
(void)BIO_flush(s->wbio);
if (s->msg_callback)
s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
2, s, s->msg_callback_arg);
if (s->info_callback != NULL)
cb=s->info_callback;
else if (s->ctx->info_callback != NULL)
cb=s->ctx->info_callback;
if (cb != NULL)
{
j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
cb(s,SSL_CB_WRITE_ALERT,j);
}
}
return(i);
}
static DTLS1_BITMAP *
dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch)
{
*is_next_epoch = 0;
/* In current epoch, accept HM, CCS, DATA, & ALERT */
if (rr->epoch == s->d1->r_epoch)
return &s->d1->bitmap;
/* Only HM and ALERT messages can be from the next epoch */
else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
(rr->type == SSL3_RT_HANDSHAKE ||
rr->type == SSL3_RT_ALERT))
{
*is_next_epoch = 1;
return &s->d1->next_bitmap;
}
return NULL;
}
#if 0
static int
dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, unsigned short *priority,
unsigned long *offset)
{
/* alerts are passed up immediately */
if ( rr->type == SSL3_RT_APPLICATION_DATA ||
rr->type == SSL3_RT_ALERT)
return 0;
/* Only need to buffer if a handshake is underway.
* (this implies that Hello Request and Client Hello are passed up
* immediately) */
if ( SSL_in_init(s))
{
unsigned char *data = rr->data;
/* need to extract the HM/CCS sequence number here */
if ( rr->type == SSL3_RT_HANDSHAKE ||
rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
{
unsigned short seq_num;
struct hm_header_st msg_hdr;
struct ccs_header_st ccs_hdr;
if ( rr->type == SSL3_RT_HANDSHAKE)
{
dtls1_get_message_header(data, &msg_hdr);
seq_num = msg_hdr.seq;
*offset = msg_hdr.frag_off;
}
else
{
dtls1_get_ccs_header(data, &ccs_hdr);
seq_num = ccs_hdr.seq;
*offset = 0;
}
/* this is either a record we're waiting for, or a
* retransmit of something we happened to previously
* receive (higher layers will drop the repeat silently */
if ( seq_num < s->d1->handshake_read_seq)
return 0;
if (rr->type == SSL3_RT_HANDSHAKE &&
seq_num == s->d1->handshake_read_seq &&
msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
return 0;
else if ( seq_num == s->d1->handshake_read_seq &&
(rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
return 0;
else
{
*priority = seq_num;
return 1;
}
}
else /* unknown record type */
return 0;
}
return 0;
}
#endif
void
dtls1_reset_seq_numbers(SSL *s, int rw)
{
unsigned char *seq;
unsigned int seq_bytes = sizeof(s->s3->read_sequence);
if ( rw & SSL3_CC_READ)
{
seq = s->s3->read_sequence;
s->d1->r_epoch++;
memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
}
else
{
seq = s->s3->write_sequence;
memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence));
s->d1->w_epoch++;
}
memset(seq, 0x00, seq_bytes);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1447_0 |
crossvul-cpp_data_good_5815_0 | /*
* FFV1 decoder
*
* Copyright (c) 2003-2013 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* FF Video Codec 1 (a lossless codec) decoder
*/
#include "libavutil/avassert.h"
#include "libavutil/crc.h"
#include "libavutil/opt.h"
#include "libavutil/imgutils.h"
#include "libavutil/pixdesc.h"
#include "libavutil/timer.h"
#include "avcodec.h"
#include "internal.h"
#include "get_bits.h"
#include "rangecoder.h"
#include "golomb.h"
#include "mathops.h"
#include "ffv1.h"
static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state,
int is_signed)
{
if (get_rac(c, state + 0))
return 0;
else {
int i, e, a;
e = 0;
while (get_rac(c, state + 1 + FFMIN(e, 9))) // 1..10
e++;
a = 1;
for (i = e - 1; i >= 0; i--)
a += a + get_rac(c, state + 22 + FFMIN(i, 9)); // 22..31
e = -(is_signed && get_rac(c, state + 11 + FFMIN(e, 10))); // 11..21
return (a ^ e) - e;
}
}
static av_noinline int get_symbol(RangeCoder *c, uint8_t *state, int is_signed)
{
return get_symbol_inline(c, state, is_signed);
}
static inline int get_vlc_symbol(GetBitContext *gb, VlcState *const state,
int bits)
{
int k, i, v, ret;
i = state->count;
k = 0;
while (i < state->error_sum) { // FIXME: optimize
k++;
i += i;
}
v = get_sr_golomb(gb, k, 12, bits);
av_dlog(NULL, "v:%d bias:%d error:%d drift:%d count:%d k:%d",
v, state->bias, state->error_sum, state->drift, state->count, k);
#if 0 // JPEG LS
if (k == 0 && 2 * state->drift <= -state->count)
v ^= (-1);
#else
v ^= ((2 * state->drift + state->count) >> 31);
#endif
ret = fold(v + state->bias, bits);
update_vlc_state(state, v);
return ret;
}
static av_always_inline void decode_line(FFV1Context *s, int w,
int16_t *sample[2],
int plane_index, int bits)
{
PlaneContext *const p = &s->plane[plane_index];
RangeCoder *const c = &s->c;
int x;
int run_count = 0;
int run_mode = 0;
int run_index = s->run_index;
for (x = 0; x < w; x++) {
int diff, context, sign;
context = get_context(p, sample[1] + x, sample[0] + x, sample[1] + x);
if (context < 0) {
context = -context;
sign = 1;
} else
sign = 0;
av_assert2(context < p->context_count);
if (s->ac) {
diff = get_symbol_inline(c, p->state[context], 1);
} else {
if (context == 0 && run_mode == 0)
run_mode = 1;
if (run_mode) {
if (run_count == 0 && run_mode == 1) {
if (get_bits1(&s->gb)) {
run_count = 1 << ff_log2_run[run_index];
if (x + run_count <= w)
run_index++;
} else {
if (ff_log2_run[run_index])
run_count = get_bits(&s->gb, ff_log2_run[run_index]);
else
run_count = 0;
if (run_index)
run_index--;
run_mode = 2;
}
}
run_count--;
if (run_count < 0) {
run_mode = 0;
run_count = 0;
diff = get_vlc_symbol(&s->gb, &p->vlc_state[context],
bits);
if (diff >= 0)
diff++;
} else
diff = 0;
} else
diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
run_count, run_index, run_mode, x, get_bits_count(&s->gb));
}
if (sign)
diff = -diff;
sample[1][x] = (predict(sample[1] + x, sample[0] + x) + diff) &
((1 << bits) - 1);
}
s->run_index = run_index;
}
static void decode_plane(FFV1Context *s, uint8_t *src,
int w, int h, int stride, int plane_index)
{
int x, y;
int16_t *sample[2];
sample[0] = s->sample_buffer + 3;
sample[1] = s->sample_buffer + w + 6 + 3;
s->run_index = 0;
memset(s->sample_buffer, 0, 2 * (w + 6) * sizeof(*s->sample_buffer));
for (y = 0; y < h; y++) {
int16_t *temp = sample[0]; // FIXME: try a normal buffer
sample[0] = sample[1];
sample[1] = temp;
sample[1][-1] = sample[0][0];
sample[0][w] = sample[0][w - 1];
// { START_TIMER
if (s->avctx->bits_per_raw_sample <= 8) {
decode_line(s, w, sample, plane_index, 8);
for (x = 0; x < w; x++)
src[x + stride * y] = sample[1][x];
} else {
decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
if (s->packed_at_lsb) {
for (x = 0; x < w; x++) {
((uint16_t*)(src + stride*y))[x] = sample[1][x];
}
} else {
for (x = 0; x < w; x++) {
((uint16_t*)(src + stride*y))[x] = sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
}
}
}
// STOP_TIMER("decode-line") }
}
}
static void decode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])
{
int x, y, p;
int16_t *sample[4][2];
int lbd = s->avctx->bits_per_raw_sample <= 8;
int bits = s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
int offset = 1 << bits;
for (x = 0; x < 4; x++) {
sample[x][0] = s->sample_buffer + x * 2 * (w + 6) + 3;
sample[x][1] = s->sample_buffer + (x * 2 + 1) * (w + 6) + 3;
}
s->run_index = 0;
memset(s->sample_buffer, 0, 8 * (w + 6) * sizeof(*s->sample_buffer));
for (y = 0; y < h; y++) {
for (p = 0; p < 3 + s->transparency; p++) {
int16_t *temp = sample[p][0]; // FIXME: try a normal buffer
sample[p][0] = sample[p][1];
sample[p][1] = temp;
sample[p][1][-1]= sample[p][0][0 ];
sample[p][0][ w]= sample[p][0][w-1];
if (lbd)
decode_line(s, w, sample[p], (p + 1)/2, 9);
else
decode_line(s, w, sample[p], (p + 1)/2, bits + 1);
}
for (x = 0; x < w; x++) {
int g = sample[0][1][x];
int b = sample[1][1][x];
int r = sample[2][1][x];
int a = sample[3][1][x];
b -= offset;
r -= offset;
g -= (b + r) >> 2;
b += g;
r += g;
if (lbd)
*((uint32_t*)(src[0] + x*4 + stride[0]*y)) = b + (g<<8) + (r<<16) + (a<<24);
else {
*((uint16_t*)(src[0] + x*2 + stride[0]*y)) = b;
*((uint16_t*)(src[1] + x*2 + stride[1]*y)) = g;
*((uint16_t*)(src[2] + x*2 + stride[2]*y)) = r;
}
}
}
}
static int decode_slice_header(FFV1Context *f, FFV1Context *fs)
{
RangeCoder *c = &fs->c;
uint8_t state[CONTEXT_SIZE];
unsigned ps, i, context_count;
memset(state, 128, sizeof(state));
av_assert0(f->version > 2);
fs->slice_x = get_symbol(c, state, 0) * f->width ;
fs->slice_y = get_symbol(c, state, 0) * f->height;
fs->slice_width = (get_symbol(c, state, 0) + 1) * f->width + fs->slice_x;
fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
fs->slice_x /= f->num_h_slices;
fs->slice_y /= f->num_v_slices;
fs->slice_width = fs->slice_width /f->num_h_slices - fs->slice_x;
fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y;
if ((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height)
return -1;
if ( (unsigned)fs->slice_x + (uint64_t)fs->slice_width > f->width
|| (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
return -1;
for (i = 0; i < f->plane_count; i++) {
PlaneContext * const p = &fs->plane[i];
int idx = get_symbol(c, state, 0);
if (idx > (unsigned)f->quant_table_count) {
av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");
return -1;
}
p->quant_table_index = idx;
memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));
context_count = f->context_count[idx];
if (p->context_count < context_count) {
av_freep(&p->state);
av_freep(&p->vlc_state);
}
p->context_count = context_count;
}
ps = get_symbol(c, state, 0);
if (ps == 1) {
f->cur->interlaced_frame = 1;
f->cur->top_field_first = 1;
} else if (ps == 2) {
f->cur->interlaced_frame = 1;
f->cur->top_field_first = 0;
} else if (ps == 3) {
f->cur->interlaced_frame = 0;
}
f->cur->sample_aspect_ratio.num = get_symbol(c, state, 0);
f->cur->sample_aspect_ratio.den = get_symbol(c, state, 0);
return 0;
}
static int decode_slice(AVCodecContext *c, void *arg)
{
FFV1Context *fs = *(void **)arg;
FFV1Context *f = fs->avctx->priv_data;
int width, height, x, y, ret;
const int ps = av_pix_fmt_desc_get(c->pix_fmt)->comp[0].step_minus1 + 1;
AVFrame * const p = f->cur;
int i, si;
for( si=0; fs != f->slice_context[si]; si ++)
;
if(f->fsrc && !p->key_frame)
ff_thread_await_progress(&f->last_picture, si, 0);
if(f->fsrc && !p->key_frame) {
FFV1Context *fssrc = f->fsrc->slice_context[si];
FFV1Context *fsdst = f->slice_context[si];
av_assert1(fsdst->plane_count == fssrc->plane_count);
av_assert1(fsdst == fs);
if (!p->key_frame)
fsdst->slice_damaged |= fssrc->slice_damaged;
for (i = 0; i < f->plane_count; i++) {
PlaneContext *psrc = &fssrc->plane[i];
PlaneContext *pdst = &fsdst->plane[i];
av_free(pdst->state);
av_free(pdst->vlc_state);
memcpy(pdst, psrc, sizeof(*pdst));
pdst->state = NULL;
pdst->vlc_state = NULL;
if (fssrc->ac) {
pdst->state = av_malloc(CONTEXT_SIZE * psrc->context_count);
memcpy(pdst->state, psrc->state, CONTEXT_SIZE * psrc->context_count);
} else {
pdst->vlc_state = av_malloc(sizeof(*pdst->vlc_state) * psrc->context_count);
memcpy(pdst->vlc_state, psrc->vlc_state, sizeof(*pdst->vlc_state) * psrc->context_count);
}
}
}
if (f->version > 2) {
if (ffv1_init_slice_state(f, fs) < 0)
return AVERROR(ENOMEM);
if (decode_slice_header(f, fs) < 0) {
fs->slice_damaged = 1;
return AVERROR_INVALIDDATA;
}
}
if ((ret = ffv1_init_slice_state(f, fs)) < 0)
return ret;
if (f->cur->key_frame)
ffv1_clear_slice_state(f, fs);
width = fs->slice_width;
height = fs->slice_height;
x = fs->slice_x;
y = fs->slice_y;
if (!fs->ac) {
if (f->version == 3 && f->micro_version > 1 || f->version > 3)
get_rac(&fs->c, (uint8_t[]) { 129 });
fs->ac_byte_count = f->version > 2 || (!x && !y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;
init_get_bits(&fs->gb,
fs->c.bytestream_start + fs->ac_byte_count,
(fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8);
}
av_assert1(width && height);
if (f->colorspace == 0) {
const int chroma_width = FF_CEIL_RSHIFT(width, f->chroma_h_shift);
const int chroma_height = FF_CEIL_RSHIFT(height, f->chroma_v_shift);
const int cx = x >> f->chroma_h_shift;
const int cy = y >> f->chroma_v_shift;
decode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
if (f->chroma_planes) {
decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
}
if (fs->transparency)
decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
} else {
uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0],
p->data[1] + ps * x + y * p->linesize[1],
p->data[2] + ps * x + y * p->linesize[2] };
decode_rgb_frame(fs, planes, width, height, p->linesize);
}
if (fs->ac && f->version > 2) {
int v;
get_rac(&fs->c, (uint8_t[]) { 129 });
v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5*f->ec;
if (v) {
av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n", v);
fs->slice_damaged = 1;
}
}
emms_c();
ff_thread_report_progress(&f->picture, si, 0);
return 0;
}
static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale)
{
int v;
int i = 0;
uint8_t state[CONTEXT_SIZE];
memset(state, 128, sizeof(state));
for (v = 0; i < 128; v++) {
unsigned len = get_symbol(c, state, 0) + 1;
if (len > 128 - i)
return AVERROR_INVALIDDATA;
while (len--) {
quant_table[i] = scale * v;
i++;
}
}
for (i = 1; i < 128; i++)
quant_table[256 - i] = -quant_table[i];
quant_table[128] = -quant_table[127];
return 2 * v - 1;
}
static int read_quant_tables(RangeCoder *c,
int16_t quant_table[MAX_CONTEXT_INPUTS][256])
{
int i;
int context_count = 1;
for (i = 0; i < 5; i++) {
context_count *= read_quant_table(c, quant_table[i], context_count);
if (context_count > 32768U) {
return AVERROR_INVALIDDATA;
}
}
return (context_count + 1) / 2;
}
static int read_extra_header(FFV1Context *f)
{
RangeCoder *const c = &f->c;
uint8_t state[CONTEXT_SIZE];
int i, j, k, ret;
uint8_t state2[32][CONTEXT_SIZE];
memset(state2, 128, sizeof(state2));
memset(state, 128, sizeof(state));
ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);
ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
f->version = get_symbol(c, state, 0);
if (f->version < 2) {
av_log(f->avctx, AV_LOG_ERROR, "Invalid version in global header\n");
return AVERROR_INVALIDDATA;
}
if (f->version > 2) {
c->bytestream_end -= 4;
f->micro_version = get_symbol(c, state, 0);
}
f->ac = f->avctx->coder_type = get_symbol(c, state, 0);
if (f->ac > 1) {
for (i = 1; i < 256; i++)
f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
}
f->colorspace = get_symbol(c, state, 0); //YUV cs type
f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
f->chroma_planes = get_rac(c, state);
f->chroma_h_shift = get_symbol(c, state, 0);
f->chroma_v_shift = get_symbol(c, state, 0);
f->transparency = get_rac(c, state);
f->plane_count = 1 + (f->chroma_planes || f->version<4) + f->transparency;
f->num_h_slices = 1 + get_symbol(c, state, 0);
f->num_v_slices = 1 + get_symbol(c, state, 0);
if (f->num_h_slices > (unsigned)f->width || !f->num_h_slices ||
f->num_v_slices > (unsigned)f->height || !f->num_v_slices
) {
av_log(f->avctx, AV_LOG_ERROR, "slice count invalid\n");
return AVERROR_INVALIDDATA;
}
f->quant_table_count = get_symbol(c, state, 0);
if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
return AVERROR_INVALIDDATA;
for (i = 0; i < f->quant_table_count; i++) {
f->context_count[i] = read_quant_tables(c, f->quant_tables[i]);
if (f->context_count[i] < 0) {
av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
return AVERROR_INVALIDDATA;
}
}
if ((ret = ffv1_allocate_initial_states(f)) < 0)
return ret;
for (i = 0; i < f->quant_table_count; i++)
if (get_rac(c, state)) {
for (j = 0; j < f->context_count[i]; j++)
for (k = 0; k < CONTEXT_SIZE; k++) {
int pred = j ? f->initial_states[i][j - 1][k] : 128;
f->initial_states[i][j][k] =
(pred + get_symbol(c, state2[k], 1)) & 0xFF;
}
}
if (f->version > 2) {
f->ec = get_symbol(c, state, 0);
if (f->micro_version > 2)
f->intra = get_symbol(c, state, 0);
}
if (f->version > 2) {
unsigned v;
v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0,
f->avctx->extradata, f->avctx->extradata_size);
if (v) {
av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
return AVERROR_INVALIDDATA;
}
}
if (f->avctx->debug & FF_DEBUG_PICT_INFO)
av_log(f->avctx, AV_LOG_DEBUG,
"global: ver:%d.%d, coder:%d, colorspace: %d bpr:%d chroma:%d(%d:%d), alpha:%d slices:%dx%d qtabs:%d ec:%d intra:%d\n",
f->version, f->micro_version,
f->ac,
f->colorspace,
f->avctx->bits_per_raw_sample,
f->chroma_planes, f->chroma_h_shift, f->chroma_v_shift,
f->transparency,
f->num_h_slices, f->num_v_slices,
f->quant_table_count,
f->ec,
f->intra
);
return 0;
}
static int read_header(FFV1Context *f)
{
uint8_t state[CONTEXT_SIZE];
int i, j, context_count = -1; //-1 to avoid warning
RangeCoder *const c = &f->slice_context[0]->c;
memset(state, 128, sizeof(state));
if (f->version < 2) {
int chroma_planes, chroma_h_shift, chroma_v_shift, transparency;
unsigned v= get_symbol(c, state, 0);
if (v >= 2) {
av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v);
return AVERROR_INVALIDDATA;
}
f->version = v;
f->ac = f->avctx->coder_type = get_symbol(c, state, 0);
if (f->ac > 1) {
for (i = 1; i < 256; i++)
f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
}
f->colorspace = get_symbol(c, state, 0); //YUV cs type
if (f->version > 0)
f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
chroma_planes = get_rac(c, state);
chroma_h_shift = get_symbol(c, state, 0);
chroma_v_shift = get_symbol(c, state, 0);
transparency = get_rac(c, state);
if (f->plane_count) {
if ( chroma_planes != f->chroma_planes
|| chroma_h_shift!= f->chroma_h_shift
|| chroma_v_shift!= f->chroma_v_shift
|| transparency != f->transparency) {
av_log(f->avctx, AV_LOG_ERROR, "Invalid change of global parameters\n");
return AVERROR_INVALIDDATA;
}
}
f->chroma_planes = chroma_planes;
f->chroma_h_shift = chroma_h_shift;
f->chroma_v_shift = chroma_v_shift;
f->transparency = transparency;
f->plane_count = 2 + f->transparency;
}
if (f->colorspace == 0) {
if (!f->transparency && !f->chroma_planes) {
if (f->avctx->bits_per_raw_sample <= 8)
f->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
else
f->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
} else if (f->avctx->bits_per_raw_sample<=8 && !f->transparency) {
switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P; break;
case 0x01: f->avctx->pix_fmt = AV_PIX_FMT_YUV440P; break;
case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P; break;
case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P; break;
case 0x20: f->avctx->pix_fmt = AV_PIX_FMT_YUV411P; break;
case 0x22: f->avctx->pix_fmt = AV_PIX_FMT_YUV410P; break;
default:
av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
return AVERROR(ENOSYS);
}
} else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) {
switch(16*f->chroma_h_shift + f->chroma_v_shift) {
case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P; break;
case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P; break;
case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P; break;
default:
av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
return AVERROR(ENOSYS);
}
} else if (f->avctx->bits_per_raw_sample == 9) {
f->packed_at_lsb = 1;
switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9; break;
case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9; break;
case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9; break;
default:
av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
return AVERROR(ENOSYS);
}
} else if (f->avctx->bits_per_raw_sample == 10) {
f->packed_at_lsb = 1;
switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10; break;
case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10; break;
case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10; break;
default:
av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
return AVERROR(ENOSYS);
}
} else {
switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16; break;
case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16; break;
case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16; break;
default:
av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
return AVERROR(ENOSYS);
}
}
} else if (f->colorspace == 1) {
if (f->chroma_h_shift || f->chroma_v_shift) {
av_log(f->avctx, AV_LOG_ERROR,
"chroma subsampling not supported in this colorspace\n");
return AVERROR(ENOSYS);
}
if ( f->avctx->bits_per_raw_sample == 9)
f->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
else if (f->avctx->bits_per_raw_sample == 10)
f->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
else if (f->avctx->bits_per_raw_sample == 12)
f->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
else if (f->avctx->bits_per_raw_sample == 14)
f->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
else
if (f->transparency) f->avctx->pix_fmt = AV_PIX_FMT_RGB32;
else f->avctx->pix_fmt = AV_PIX_FMT_0RGB32;
} else {
av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
return AVERROR(ENOSYS);
}
av_dlog(f->avctx, "%d %d %d\n",
f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt);
if (f->version < 2) {
context_count = read_quant_tables(c, f->quant_table);
if (context_count < 0) {
av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
return AVERROR_INVALIDDATA;
}
} else if (f->version < 3) {
f->slice_count = get_symbol(c, state, 0);
} else {
const uint8_t *p = c->bytestream_end;
for (f->slice_count = 0;
f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start;
f->slice_count++) {
int trailer = 3 + 5*!!f->ec;
int size = AV_RB24(p-trailer);
if (size + trailer > p - c->bytestream_start)
break;
p -= size + trailer;
}
}
if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) {
av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count);
return AVERROR_INVALIDDATA;
}
for (j = 0; j < f->slice_count; j++) {
FFV1Context *fs = f->slice_context[j];
fs->ac = f->ac;
fs->packed_at_lsb = f->packed_at_lsb;
fs->slice_damaged = 0;
if (f->version == 2) {
fs->slice_x = get_symbol(c, state, 0) * f->width ;
fs->slice_y = get_symbol(c, state, 0) * f->height;
fs->slice_width = (get_symbol(c, state, 0) + 1) * f->width + fs->slice_x;
fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
fs->slice_x /= f->num_h_slices;
fs->slice_y /= f->num_v_slices;
fs->slice_width = fs->slice_width / f->num_h_slices - fs->slice_x;
fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y;
if ((unsigned)fs->slice_width > f->width ||
(unsigned)fs->slice_height > f->height)
return AVERROR_INVALIDDATA;
if ( (unsigned)fs->slice_x + (uint64_t)fs->slice_width > f->width
|| (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
return AVERROR_INVALIDDATA;
}
for (i = 0; i < f->plane_count; i++) {
PlaneContext *const p = &fs->plane[i];
if (f->version == 2) {
int idx = get_symbol(c, state, 0);
if (idx > (unsigned)f->quant_table_count) {
av_log(f->avctx, AV_LOG_ERROR,
"quant_table_index out of range\n");
return AVERROR_INVALIDDATA;
}
p->quant_table_index = idx;
memcpy(p->quant_table, f->quant_tables[idx],
sizeof(p->quant_table));
context_count = f->context_count[idx];
} else {
memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
}
if (f->version <= 2) {
av_assert0(context_count >= 0);
if (p->context_count < context_count) {
av_freep(&p->state);
av_freep(&p->vlc_state);
}
p->context_count = context_count;
}
}
}
return 0;
}
static av_cold int decode_init(AVCodecContext *avctx)
{
FFV1Context *f = avctx->priv_data;
int ret;
if ((ret = ffv1_common_init(avctx)) < 0)
return ret;
if (avctx->extradata && (ret = read_extra_header(f)) < 0)
return ret;
if ((ret = ffv1_init_slice_contexts(f)) < 0)
return ret;
avctx->internal->allocate_progress = 1;
return 0;
}
static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
FFV1Context *f = avctx->priv_data;
RangeCoder *const c = &f->slice_context[0]->c;
int i, ret;
uint8_t keystate = 128;
const uint8_t *buf_p;
AVFrame *p;
if (f->last_picture.f)
ff_thread_release_buffer(avctx, &f->last_picture);
FFSWAP(ThreadFrame, f->picture, f->last_picture);
f->cur = p = f->picture.f;
if (f->version < 3 && avctx->field_order > AV_FIELD_PROGRESSIVE) {
/* we have interlaced material flagged in container */
p->interlaced_frame = 1;
if (avctx->field_order == AV_FIELD_TT || avctx->field_order == AV_FIELD_TB)
p->top_field_first = 1;
}
f->avctx = avctx;
ff_init_range_decoder(c, buf, buf_size);
ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
p->pict_type = AV_PICTURE_TYPE_I; //FIXME I vs. P
if (get_rac(c, &keystate)) {
p->key_frame = 1;
f->key_frame_ok = 0;
if ((ret = read_header(f)) < 0)
return ret;
f->key_frame_ok = 1;
} else {
if (!f->key_frame_ok) {
av_log(avctx, AV_LOG_ERROR,
"Cannot decode non-keyframe without valid keyframe\n");
return AVERROR_INVALIDDATA;
}
p->key_frame = 0;
}
if ((ret = ff_thread_get_buffer(avctx, &f->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
return ret;
if (avctx->debug & FF_DEBUG_PICT_INFO)
av_log(avctx, AV_LOG_DEBUG, "ver:%d keyframe:%d coder:%d ec:%d slices:%d bps:%d\n",
f->version, p->key_frame, f->ac, f->ec, f->slice_count, f->avctx->bits_per_raw_sample);
ff_thread_finish_setup(avctx);
buf_p = buf + buf_size;
for (i = f->slice_count - 1; i >= 0; i--) {
FFV1Context *fs = f->slice_context[i];
int trailer = 3 + 5*!!f->ec;
int v;
if (i || f->version > 2) v = AV_RB24(buf_p-trailer) + trailer;
else v = buf_p - c->bytestream_start;
if (buf_p - c->bytestream_start < v) {
av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
return AVERROR_INVALIDDATA;
}
buf_p -= v;
if (f->ec) {
unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v);
if (crc) {
int64_t ts = avpkt->pts != AV_NOPTS_VALUE ? avpkt->pts : avpkt->dts;
av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!", crc);
if (ts != AV_NOPTS_VALUE && avctx->pkt_timebase.num) {
av_log(f->avctx, AV_LOG_ERROR, "at %f seconds\n", ts*av_q2d(avctx->pkt_timebase));
} else if (ts != AV_NOPTS_VALUE) {
av_log(f->avctx, AV_LOG_ERROR, "at %"PRId64"\n", ts);
} else {
av_log(f->avctx, AV_LOG_ERROR, "\n");
}
fs->slice_damaged = 1;
}
}
if (i) {
ff_init_range_decoder(&fs->c, buf_p, v);
} else
fs->c.bytestream_end = (uint8_t *)(buf_p + v);
fs->avctx = avctx;
fs->cur = p;
}
avctx->execute(avctx,
decode_slice,
&f->slice_context[0],
NULL,
f->slice_count,
sizeof(void*));
for (i = f->slice_count - 1; i >= 0; i--) {
FFV1Context *fs = f->slice_context[i];
int j;
if (fs->slice_damaged && f->last_picture.f->data[0]) {
const uint8_t *src[4];
uint8_t *dst[4];
ff_thread_await_progress(&f->last_picture, INT_MAX, 0);
for (j = 0; j < 4; j++) {
int sh = (j==1 || j==2) ? f->chroma_h_shift : 0;
int sv = (j==1 || j==2) ? f->chroma_v_shift : 0;
dst[j] = p->data[j] + p->linesize[j]*
(fs->slice_y>>sv) + (fs->slice_x>>sh);
src[j] = f->last_picture.f->data[j] + f->last_picture.f->linesize[j]*
(fs->slice_y>>sv) + (fs->slice_x>>sh);
}
av_image_copy(dst, p->linesize, (const uint8_t **)src,
f->last_picture.f->linesize,
avctx->pix_fmt,
fs->slice_width,
fs->slice_height);
}
}
ff_thread_report_progress(&f->picture, INT_MAX, 0);
f->picture_number++;
if (f->last_picture.f)
ff_thread_release_buffer(avctx, &f->last_picture);
f->cur = NULL;
if ((ret = av_frame_ref(data, f->picture.f)) < 0)
return ret;
*got_frame = 1;
return buf_size;
}
static int init_thread_copy(AVCodecContext *avctx)
{
FFV1Context *f = avctx->priv_data;
f->picture.f = NULL;
f->last_picture.f = NULL;
f->sample_buffer = NULL;
f->quant_table_count = 0;
f->slice_count = 0;
return 0;
}
static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
{
FFV1Context *fsrc = src->priv_data;
FFV1Context *fdst = dst->priv_data;
int i, ret;
if (dst == src)
return 0;
if (!fdst->picture.f) {
memcpy(fdst, fsrc, sizeof(*fdst));
for (i = 0; i < fdst->quant_table_count; i++) {
fdst->initial_states[i] = av_malloc(fdst->context_count[i] * sizeof(*fdst->initial_states[i]));
memcpy(fdst->initial_states[i], fsrc->initial_states[i], fdst->context_count[i] * sizeof(*fdst->initial_states[i]));
}
fdst->picture.f = av_frame_alloc();
fdst->last_picture.f = av_frame_alloc();
if ((ret = ffv1_init_slice_contexts(fdst)) < 0)
return ret;
}
av_assert1(fdst->slice_count == fsrc->slice_count);
fdst->key_frame_ok = fsrc->key_frame_ok;
ff_thread_release_buffer(dst, &fdst->picture);
if (fsrc->picture.f->data[0]) {
if ((ret = ff_thread_ref_frame(&fdst->picture, &fsrc->picture)) < 0)
return ret;
}
for (i = 0; i < fdst->slice_count; i++) {
FFV1Context *fsdst = fdst->slice_context[i];
FFV1Context *fssrc = fsrc->slice_context[i];
fsdst->slice_damaged = fssrc->slice_damaged;
}
fdst->fsrc = fsrc;
return 0;
}
AVCodec ff_ffv1_decoder = {
.name = "ffv1",
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_FFV1,
.priv_data_size = sizeof(FFV1Context),
.init = decode_init,
.close = ffv1_close,
.decode = decode_frame,
.init_thread_copy = ONLY_IF_THREADS_ENABLED(init_thread_copy),
.update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
.capabilities = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/ |
CODEC_CAP_FRAME_THREADS | CODEC_CAP_SLICE_THREADS,
.long_name = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5815_0 |
crossvul-cpp_data_bad_939_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP N N M M %
% P P NN N MM MM %
% PPPP N N N M M M %
% P N NN M M %
% P N N M M %
% %
% %
% Read/Write PBMPlus Portable Anymap Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
/*
Typedef declarations.
*/
typedef struct _CommentInfo
{
char
*comment;
size_t
extent;
} CommentInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePNMImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P N M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPNM() returns MagickTrue if the image format type, identified by the
% magick string, is PNM.
%
% The format of the IsPNM method is:
%
% MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o extent: Specifies the extent of the magick string.
%
*/
static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
{
if (extent < 2)
return(MagickFalse);
if ((*magick == (unsigned char) 'P') &&
((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') ||
(magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') ||
(magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f')))
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPNMImage() reads a Portable Anymap image file and returns it.
% It allocates the memory necessary for the new Image structure and returns
% a pointer to the new image.
%
% The format of the ReadPNMImage method is:
%
% Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static int PNMComment(Image *image,CommentInfo *comment_info)
{
int
c;
register char
*p;
/*
Read comment.
*/
p=comment_info->comment+strlen(comment_info->comment);
for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++)
{
if ((size_t) (p-comment_info->comment+1) >= comment_info->extent)
{
comment_info->extent<<=1;
comment_info->comment=(char *) ResizeQuantumMemory(
comment_info->comment,comment_info->extent,
sizeof(*comment_info->comment));
if (comment_info->comment == (char *) NULL)
return(-1);
p=comment_info->comment+strlen(comment_info->comment);
}
c=ReadBlobByte(image);
if (c != EOF)
{
*p=(char) c;
*(p+1)='\0';
}
}
return(c);
}
static unsigned int PNMInteger(Image *image,CommentInfo *comment_info,
const unsigned int base)
{
int
c;
unsigned int
value;
/*
Skip any leading whitespace.
*/
do
{
c=ReadBlobByte(image);
if (c == EOF)
return(0);
if (c == (int) '#')
c=PNMComment(image,comment_info);
} while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'));
if (base == 2)
return((unsigned int) (c-(int) '0'));
/*
Evaluate number.
*/
value=0;
while (isdigit(c) != 0)
{
if (value <= (unsigned int) (INT_MAX/10))
{
value*=10;
if (value <= (unsigned int) (INT_MAX-(c-(int) '0')))
value+=c-(int) '0';
}
c=ReadBlobByte(image);
if (c == EOF)
return(0);
}
if (c == (int) '#')
c=PNMComment(image,comment_info);
return(value);
}
static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowPNMException(exception,message) \
{ \
if (comment_info.comment != (char *) NULL) \
comment_info.comment=DestroyString(comment_info.comment); \
ThrowReaderException((exception),(message)); \
}
char
format;
CommentInfo
comment_info;
double
quantum_scale;
Image
*image;
MagickBooleanType
status;
QuantumAny
max_value;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
depth,
extent,
packet_size;
ssize_t
count,
row,
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PNM image.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
do
{
/*
Initialize image structure.
*/
comment_info.comment=AcquireString(NULL);
comment_info.extent=MagickPathExtent;
if ((count != 1) || (format != 'P'))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
max_value=1;
quantum_type=RGBQuantum;
quantum_scale=1.0;
format=(char) ReadBlobByte(image);
if (format != '7')
{
/*
PBM, PGM, PPM, and PNM.
*/
image->columns=PNMInteger(image,&comment_info,10);
image->rows=PNMInteger(image,&comment_info,10);
if ((format == 'f') || (format == 'F'))
{
char
scale[MaxTextExtent];
if (ReadBlobString(image,scale) != (char *) NULL)
quantum_scale=StringToDouble(scale,(char **) NULL);
}
else
{
if ((format == '1') || (format == '4'))
max_value=1; /* bitmap */
else
max_value=PNMInteger(image,&comment_info,10);
}
}
else
{
char
keyword[MaxTextExtent],
value[MaxTextExtent];
int
c;
register char
*p;
/*
PAM.
*/
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == '#')
{
/*
Comment.
*/
c=PNMComment(image,&comment_info);
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c));
*p='\0';
if (LocaleCompare(keyword,"endhdr") == 0)
break;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
p=value;
while (isalnum(c) || (c == '_'))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"depth") == 0)
packet_size=StringToUnsignedLong(value);
(void) packet_size;
if (LocaleCompare(keyword,"height") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"maxval") == 0)
max_value=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"TUPLTYPE") == 0)
{
if (LocaleCompare(value,"BLACKANDWHITE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
image->matte=MagickTrue;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"GRAYSCALE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
image->matte=MagickTrue;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"RGB_ALPHA") == 0)
{
quantum_type=RGBAQuantum;
image->matte=MagickTrue;
}
if (LocaleCompare(value,"CMYK") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace);
quantum_type=CMYKQuantum;
}
if (LocaleCompare(value,"CMYK_ALPHA") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace);
image->matte=MagickTrue;
quantum_type=CMYKAQuantum;
}
}
if (LocaleCompare(keyword,"width") == 0)
image->columns=StringToUnsignedLong(value);
}
}
if ((image->columns == 0) || (image->rows == 0))
ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize");
if ((max_value == 0) || (max_value > 4294967295U))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
for (depth=1; GetQuantumRange(depth) < max_value; depth++) ;
image->depth=depth;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image))
ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile");
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
(void) ResetImagePixels(image,exception);
/*
Convert PNM pixels.
*/
row=0;
switch (format)
{
case '1':
{
/*
Convert PBM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,PNMInteger(image,&comment_info,2) == 0 ?
QuantumRange : 0);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=BilevelType;
break;
}
case '2':
{
size_t
intensity;
/*
Convert PGM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelRed(q,intensity);
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=GrayscaleType;
break;
}
case '3':
{
/*
Convert PNM image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
QuantumAny
pixel;
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelRed(q,pixel);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
SetPixelGreen(q,pixel);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
SetPixelBlue(q,pixel);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
break;
}
case '4':
{
/*
Convert PBM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
if (image->storage_class == PseudoClass)
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumMinIsWhite(quantum_info,MagickTrue);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '5':
{
/*
Convert PGM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '6':
{
/*
Convert PNM raster image to pixel packets.
*/
quantum_type=RGBQuantum;
extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
{
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
q->opacity=OpaqueOpacity;
q++;
}
break;
}
case 16:
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleShortToQuantum(pixel));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleShortToQuantum(pixel));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleShortToQuantum(pixel));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
case 32:
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleLongToQuantum(pixel));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleLongToQuantum(pixel));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleLongToQuantum(pixel));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
break;
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register IndexPacket
*indexes;
size_t
channels;
/*
Convert PAM raster image to pixel packets.
*/
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
channels=1;
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
channels=4;
break;
}
default:
{
channels=3;
break;
}
}
if (image->matte != MagickFalse)
channels++;
extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
if (image->depth != 1)
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
else
SetPixelOpacity(q,QuantumRange-ScaleAnyToQuantum(
pixel,max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,
max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,
max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case 'F':
case 'f':
{
/*
Convert PFM raster image to pixel packets.
*/
if (format == 'f')
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian;
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumDepth(image,quantum_info,32);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumScale(quantum_info,(MagickRealType) QuantumRange*
fabs(quantum_scale));
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if ((size_t) count != extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1),
image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
default:
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
}
if (*comment_info.comment != '\0')
(void) SetImageProperty(image,"comment",comment_info.comment);
comment_info.comment=DestroyString(comment_info.comment);
if (y < (ssize_t) image->rows)
ThrowPNMException(CorruptImageError,"UnableToReadImageData");
if (EOFBlob(image) != MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((format == '1') || (format == '2') || (format == '3'))
do
{
/*
Skip to end of line.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
if (count != 1)
break;
if (format == 'P')
break;
} while (format != '\n');
count=ReadBlob(image,1,(unsigned char *) &format);
if ((count == 1) && (format == 'P'))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count == 1) && (format == 'P'));
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPNMImage() adds properties for the PNM image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPNMImage method is:
%
% size_t RegisterPNMImage(void)
%
*/
ModuleExport size_t RegisterPNMImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("PAM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Common 2-dimensional bitmap format");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PBM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable bitmap format (black and white)");
entry->mime_type=ConstantString("image/x-portable-bitmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PFM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Portable float format");
entry->module=ConstantString("PFM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PGM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable graymap format (gray scale)");
entry->mime_type=ConstantString("image/x-portable-greymap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->magick=(IsImageFormatHandler *) IsPNM;
entry->description=ConstantString("Portable anymap");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PPM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable pixmap format (color)");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPNMImage() removes format registrations made by the
% PNM module from the list of supported formats.
%
% The format of the UnregisterPNMImage method is:
%
% UnregisterPNMImage(void)
%
*/
ModuleExport void UnregisterPNMImage(void)
{
(void) UnregisterMagickInfo("PAM");
(void) UnregisterMagickInfo("PBM");
(void) UnregisterMagickInfo("PGM");
(void) UnregisterMagickInfo("PNM");
(void) UnregisterMagickInfo("PPM");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePNMImage() writes an image to a file in the PNM rasterfile format.
%
% The format of the WritePNMImage method is:
%
% MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
format,
magick[MaxTextExtent];
const char
*value;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*pixels,
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
max_value=GetQuantumRange(image->depth);
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MaxTextExtent);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,&image->exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MaxTextExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,&image->exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MaxTextExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent);
if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MaxTextExtent);
break;
}
}
if (image->matte != MagickFalse)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n",
type);
(void) WriteBlobString(image,buffer);
}
/*
Convert to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)),
ScaleQuantumToChar(GetPixelGreen(p)),
ScaleQuantumToChar(GetPixelBlue(p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)),
ScaleQuantumToShort(GetPixelGreen(p)),
ScaleQuantumToShort(GetPixelBlue(p)));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)),
ScaleQuantumToLong(GetPixelGreen(p)),
ScaleQuantumToLong(GetPixelBlue(p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 32)
pixel=ScaleQuantumToLong(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_939_0 |
crossvul-cpp_data_bad_5484_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS GGGG IIIII %
% SS G I %
% SSS G GG I %
% SS G G I %
% SSSSS GGG IIIII %
% %
% %
% Read/Write Irix RGB Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
Typedef declaractions.
*/
typedef struct _SGIInfo
{
unsigned short
magic;
unsigned char
storage,
bytes_per_pixel;
unsigned short
dimension,
columns,
rows,
depth;
size_t
minimum_value,
maximum_value,
sans;
char
name[80];
size_t
pixel_format;
unsigned char
filler[404];
} SGIInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WriteSGIImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s S G I %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsSGI() returns MagickTrue if the image format type, identified by the
% magick string, is SGI.
%
% The format of the IsSGI method is:
%
% MagickBooleanType IsSGI(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsSGI(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\001\332",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadSGIImage() reads a SGI RGB image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadSGIImage method is:
%
% Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType SGIDecode(const size_t bytes_per_pixel,
ssize_t number_packets,unsigned char *packets,ssize_t number_pixels,
unsigned char *pixels)
{
register unsigned char
*p,
*q;
size_t
pixel;
ssize_t
count;
p=packets;
q=pixels;
if (bytes_per_pixel == 2)
{
for ( ; number_pixels > 0; )
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++) << 8;
pixel|=(*p++);
count=(ssize_t) (pixel & 0x7f);
if (count == 0)
break;
if (count > (ssize_t) number_pixels)
return(MagickFalse);
number_pixels-=count;
if ((pixel & 0x80) != 0)
for ( ; count != 0; count--)
{
if (number_packets-- == 0)
return(MagickFalse);
*q=(*p++);
*(q+1)=(*p++);
q+=8;
}
else
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++) << 8;
pixel|=(*p++);
for ( ; count != 0; count--)
{
*q=(unsigned char) (pixel >> 8);
*(q+1)=(unsigned char) pixel;
q+=8;
}
}
}
return(MagickTrue);
}
for ( ; number_pixels > 0; )
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++);
count=(ssize_t) (pixel & 0x7f);
if (count == 0)
break;
if (count > (ssize_t) number_pixels)
return(MagickFalse);
number_pixels-=count;
if ((pixel & 0x80) != 0)
for ( ; count != 0; count--)
{
if (number_packets-- == 0)
return(MagickFalse);
*q=(*p++);
q+=4;
}
else
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++);
for ( ; count != 0; count--)
{
*q=(unsigned char) pixel;
q+=4;
}
}
}
return(MagickTrue);
}
static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SGI raster header.
*/
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
count=ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
if ((size_t) count != sizeof(iris_info.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name,exception);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
if ((size_t) count != sizeof(iris_info.filler))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,
MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=(size_t) (iris_info.bytes_per_pixel > 1 ? 65535 : 256);
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (EOFBlob(image) != MagickFalse)
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets == (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength == (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info == (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=(ssize_t) ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset,
SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
(ssize_t) iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
p+=(iris_info.columns*4*bytes_per_pixel);
}
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset,
SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
(ssize_t) iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Initialize image structure.
*/
image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))),q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(image,(Quantum) quantum,q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p,q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterSGIImage() adds properties for the SGI image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterSGIImage method is:
%
% size_t RegisterSGIImage(void)
%
*/
ModuleExport size_t RegisterSGIImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("SGI","SGI","Irix RGB image");
entry->decoder=(DecodeImageHandler *) ReadSGIImage;
entry->encoder=(EncodeImageHandler *) WriteSGIImage;
entry->magick=(IsImageFormatHandler *) IsSGI;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterSGIImage() removes format registrations made by the
% SGI module from the list of supported formats.
%
% The format of the UnregisterSGIImage method is:
%
% UnregisterSGIImage(void)
%
*/
ModuleExport void UnregisterSGIImage(void)
{
(void) UnregisterMagickInfo("SGI");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteSGIImage() writes an image in SGI RGB encoded image format.
%
% The format of the WriteSGIImage method is:
%
% MagickBooleanType WriteSGIImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static size_t SGIEncode(unsigned char *pixels,size_t length,
unsigned char *packets)
{
short
runlength;
register unsigned char
*p,
*q;
unsigned char
*limit,
*mark;
p=pixels;
limit=p+length*4;
q=packets;
while (p < limit)
{
mark=p;
p+=8;
while ((p < limit) && ((*(p-8) != *(p-4)) || (*(p-4) != *p)))
p+=4;
p-=8;
length=(size_t) (p-mark) >> 2;
while (length != 0)
{
runlength=(short) (length > 126 ? 126 : length);
length-=runlength;
*q++=(unsigned char) (0x80 | runlength);
for ( ; runlength > 0; runlength--)
{
*q++=(*mark);
mark+=4;
}
}
mark=p;
p+=4;
while ((p < limit) && (*p == *mark))
p+=4;
length=(size_t) (p-mark) >> 2;
while (length != 0)
{
runlength=(short) (length > 126 ? 126 : length);
length-=runlength;
*q++=(unsigned char) runlength;
*q++=(*mark);
}
}
*q++='\0';
return((size_t) (q-packets));
}
static MagickBooleanType WriteSGIImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
CompressionType
compression;
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
SGIInfo
iris_info;
register const Quantum
*p;
register ssize_t
i,
x;
register unsigned char
*q;
ssize_t
y,
z;
unsigned char
*pixels,
*packets;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns > 65535UL) || (image->rows > 65535UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
/*
Initialize SGI raster file header.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) ResetMagickMemory(&iris_info,0,sizeof(iris_info));
iris_info.magic=0x01DA;
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
if (image->depth > 8)
compression=NoCompression;
if (compression == NoCompression)
iris_info.storage=(unsigned char) 0x00;
else
iris_info.storage=(unsigned char) 0x01;
iris_info.bytes_per_pixel=(unsigned char) (image->depth > 8 ? 2 : 1);
iris_info.dimension=3;
iris_info.columns=(unsigned short) image->columns;
iris_info.rows=(unsigned short) image->rows;
if (image->alpha_trait != UndefinedPixelTrait)
iris_info.depth=4;
else
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
iris_info.dimension=2;
iris_info.depth=1;
}
else
iris_info.depth=3;
}
iris_info.minimum_value=0;
iris_info.maximum_value=(size_t) (image->depth <= 8 ?
1UL*ScaleQuantumToChar(QuantumRange) :
1UL*ScaleQuantumToShort(QuantumRange));
/*
Write SGI header.
*/
(void) WriteBlobMSBShort(image,iris_info.magic);
(void) WriteBlobByte(image,iris_info.storage);
(void) WriteBlobByte(image,iris_info.bytes_per_pixel);
(void) WriteBlobMSBShort(image,iris_info.dimension);
(void) WriteBlobMSBShort(image,iris_info.columns);
(void) WriteBlobMSBShort(image,iris_info.rows);
(void) WriteBlobMSBShort(image,iris_info.depth);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.minimum_value);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.maximum_value);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.sans);
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(iris_info.name,value,sizeof(iris_info.name));
(void) WriteBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.pixel_format);
(void) WriteBlob(image,sizeof(iris_info.filler),iris_info.filler);
/*
Allocate SGI pixels.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*iris_info.bytes_per_pixel*number_pixels) !=
((MagickSizeType) (size_t) (4*iris_info.bytes_per_pixel*number_pixels)))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory((size_t) number_pixels,4*
iris_info.bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Convert image pixels to uncompressed SGI pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (image->depth <= 8)
for (x=0; x < (ssize_t) image->columns; x++)
{
register unsigned char
*q;
q=(unsigned char *) pixels;
q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
register unsigned short
*q;
q=(unsigned short *) pixels;
q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;
*q++=ScaleQuantumToShort(GetPixelRed(image,p));
*q++=ScaleQuantumToShort(GetPixelGreen(image,p));
*q++=ScaleQuantumToShort(GetPixelBlue(image,p));
*q++=ScaleQuantumToShort(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
switch (compression)
{
case NoCompression:
{
/*
Write uncompressed SGI pixels.
*/
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (image->depth <= 8)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
register unsigned char
*q;
q=(unsigned char *) pixels;
q+=y*(4*iris_info.columns)+4*x+z;
(void) WriteBlobByte(image,*q);
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
register unsigned short
*q;
q=(unsigned short *) pixels;
q+=y*(4*iris_info.columns)+4*x+z;
(void) WriteBlobMSBShort(image,*q);
}
}
}
break;
}
default:
{
MemoryInfo
*packet_info;
size_t
length,
number_packets,
*runlength;
ssize_t
offset,
*offsets;
/*
Convert SGI uncompressed pixels.
*/
offsets=(ssize_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((2*(size_t) iris_info.columns+10)*
image->rows,4*sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets != (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength != (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info != (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
offset=512+4*2*((ssize_t) iris_info.rows*iris_info.depth);
number_packets=0;
q=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
length=SGIEncode(q+z,(size_t) iris_info.columns,packets+
number_packets);
number_packets+=length;
offsets[y+z*iris_info.rows]=offset;
runlength[y+z*iris_info.rows]=(size_t) length;
offset+=(ssize_t) length;
}
q+=(iris_info.columns*4);
}
/*
Write out line start and length tables and runlength-encoded pixels.
*/
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
(void) WriteBlobMSBLong(image,(unsigned int) offsets[i]);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
(void) WriteBlobMSBLong(image,(unsigned int) runlength[i]);
(void) WriteBlob(image,number_packets,packets);
/*
Relinquish resources.
*/
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
runlength=(size_t *) RelinquishMagickMemory(runlength);
packet_info=RelinquishVirtualMemory(packet_info);
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5484_0 |
crossvul-cpp_data_good_340_2 | /*
* card-muscle.c: Support for MuscleCard Applet from musclecard.com
*
* Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include "internal.h"
#include "cardctl.h"
#include "muscle.h"
#include "muscle-filesystem.h"
#include "types.h"
#include "opensc.h"
static struct sc_card_operations muscle_ops;
static const struct sc_card_operations *iso_ops = NULL;
static struct sc_card_driver muscle_drv = {
"MuscleApplet",
"muscle",
&muscle_ops,
NULL, 0, NULL
};
static struct sc_atr_table muscle_atrs[] = {
/* Tyfone JCOP 242R2 cards */
{ "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL },
/* Aladdin eToken PRO USB 72K Java */
{ "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL },
/* JCOP31 v2.4.1 contact interface */
{ "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL },
/* JCOP31 v2.4.1 RF interface */
{ "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
#define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data )
#define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs )
typedef struct muscle_private {
sc_security_env_t env;
unsigned short verifiedPins;
mscfs_t *fs;
int rsa_key_ref;
} muscle_private_t;
static int muscle_finish(sc_card_t *card)
{
muscle_private_t *priv = MUSCLE_DATA(card);
mscfs_free(priv->fs);
free(priv);
return 0;
}
static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 };
static int muscle_match_card(sc_card_t *card)
{
sc_apdu_t apdu;
u8 response[64];
int r;
/* Since we send an APDU, the card's logout function may be called...
* however it's not always properly nulled out... */
card->ops->logout = NULL;
if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) {
/* Muscle applet is present, check the protocol version to be sure */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00);
apdu.cla = 0xB0;
apdu.le = 64;
apdu.resplen = 64;
apdu.resp = response;
r = sc_transmit_apdu(card, &apdu);
if (r == SC_SUCCESS && response[0] == 0x01) {
card->type = SC_CARD_TYPE_MUSCLE_V1;
} else {
card->type = SC_CARD_TYPE_MUSCLE_GENERIC;
}
return 1;
}
return 0;
}
/* Since Musclecard has a different ACL system then PKCS15
* objects need to have their READ/UPDATE/DELETE permissions mapped for files
* and directory ACLS need to be set
* For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here
*/
static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl)
{
unsigned short acl_entry = 0;
while(acl) {
int key = acl->key_ref;
int method = acl->method;
switch(method) {
case SC_AC_NEVER:
return 0xFFFF;
/* Ignore... other items overwrite these */
case SC_AC_NONE:
case SC_AC_UNKNOWN:
break;
case SC_AC_CHV:
acl_entry |= (1 << key); /* Assuming key 0 == SO */
break;
case SC_AC_AUT:
case SC_AC_TERM:
case SC_AC_PRO:
default:
/* Ignored */
break;
}
acl = acl->next;
}
return acl_entry;
}
static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm)
{
assert(read_perm && write_perm && delete_perm);
*read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ));
*write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE));
*delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE));
}
static int muscle_create_directory(sc_card_t *card, sc_file_t *file)
{
mscfs_t *fs = MUSCLE_FS(card);
msc_id objectId;
u8* oid = objectId.id;
unsigned id = file->id;
unsigned short read_perm = 0, write_perm = 0, delete_perm = 0;
int objectSize;
int r;
if(id == 0) /* No null name files */
return SC_ERROR_INVALID_ARGUMENTS;
/* No nesting directories */
if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00)
return SC_ERROR_NOT_SUPPORTED;
oid[0] = ((id & 0xFF00) >> 8) & 0xFF;
oid[1] = id & 0xFF;
oid[2] = oid[3] = 0;
objectSize = file->size;
muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm);
r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm);
mscfs_clear_cache(fs);
if(r >= 0) return 0;
return r;
}
static int muscle_create_file(sc_card_t *card, sc_file_t *file)
{
mscfs_t *fs = MUSCLE_FS(card);
int objectSize = file->size;
unsigned short read_perm = 0, write_perm = 0, delete_perm = 0;
msc_id objectId;
int r;
if(file->type == SC_FILE_TYPE_DF)
return muscle_create_directory(card, file);
if(file->type != SC_FILE_TYPE_WORKING_EF)
return SC_ERROR_NOT_SUPPORTED;
if(file->id == 0) /* No null name files */
return SC_ERROR_INVALID_ARGUMENTS;
muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm);
mscfs_lookup_local(fs, file->id, &objectId);
r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm);
mscfs_clear_cache(fs);
if(r >= 0) return 0;
return r;
}
static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags)
{
mscfs_t *fs = MUSCLE_FS(card);
int r;
msc_id objectId;
u8* oid = objectId.id;
mscfs_file_t *file;
r = mscfs_check_selection(fs, -1);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
file = &fs->cache.array[fs->currentFileIndex];
objectId = file->objectId;
/* memcpy(objectId.id, file->objectId.id, 4); */
if(!file->ef) {
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
}
r = msc_read_object(card, objectId, idx, buf, count);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags)
{
mscfs_t *fs = MUSCLE_FS(card);
int r;
mscfs_file_t *file;
msc_id objectId;
u8* oid = objectId.id;
r = mscfs_check_selection(fs, -1);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
file = &fs->cache.array[fs->currentFileIndex];
objectId = file->objectId;
/* memcpy(objectId.id, file->objectId.id, 4); */
if(!file->ef) {
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
}
if(file->size < idx + count) {
int newFileSize = idx + count;
u8* buffer = malloc(newFileSize);
if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
r = msc_read_object(card, objectId, 0, buffer, file->size);
/* TODO: RETRIEVE ACLS */
if(r < 0) goto update_bin_free_buffer;
r = msc_delete_object(card, objectId, 0);
if(r < 0) goto update_bin_free_buffer;
r = msc_create_object(card, objectId, newFileSize, 0,0,0);
if(r < 0) goto update_bin_free_buffer;
memcpy(buffer + idx, buf, count);
r = msc_update_object(card, objectId, 0, buffer, newFileSize);
if(r < 0) goto update_bin_free_buffer;
file->size = newFileSize;
update_bin_free_buffer:
free(buffer);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
} else {
r = msc_update_object(card, objectId, idx, buf, count);
}
/* mscfs_clear_cache(fs); */
return r;
}
/* TODO: Evaluate correctness */
static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data)
{
mscfs_t *fs = MUSCLE_FS(card);
msc_id id = file_data->objectId;
u8* oid = id.id;
int r;
if(!file_data->ef) {
int x;
mscfs_file_t *childFile;
/* Delete children */
mscfs_check_cache(fs);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"DELETING Children of: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
for(x = 0; x < fs->cache.size; x++) {
msc_id objectId;
childFile = &fs->cache.array[x];
objectId = childFile->objectId;
if(0 == memcmp(oid + 2, objectId.id, 2)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"DELETING: %02X%02X%02X%02X\n",
objectId.id[0],objectId.id[1],
objectId.id[2],objectId.id[3]);
r = muscle_delete_mscfs_file(card, childFile);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
}
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
/* ??? objectId = objectId >> 16; */
}
if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4))
|| (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) {
}
r = msc_delete_object(card, id, 1);
/* Check if its the root... this file generally is virtual
* So don't return an error if it fails */
if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4))
|| (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4)))
return 0;
if(r < 0) {
printf("ID: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
return 0;
}
static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in)
{
mscfs_t *fs = MUSCLE_FS(card);
mscfs_file_t *file_data = NULL;
int r = 0;
r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
r = muscle_delete_mscfs_file(card, file_data);
mscfs_clear_cache(fs);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
return 0;
}
static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl)
{
int key;
/* Everybody by default.... */
sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0);
if(acl == 0xFFFF) {
sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0);
return;
}
for(key = 0; key < 16; key++) {
if(acl >> key & 1) {
sc_file_add_acl_entry(file, operation, SC_AC_CHV, key);
}
}
}
static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data)
{
muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read);
muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write);
muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write);
muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete);
}
static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data)
{
muscle_load_single_acl(file, SC_AC_OP_SELECT, 0);
muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0);
muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF);
muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete);
muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write);
}
/* Required type = -1 for don't care, 1 for EF, 0 for DF */
static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType)
{
mscfs_t *fs = MUSCLE_FS(card);
mscfs_file_t *file_data = NULL;
int pathlen = path_in->len;
int r = 0;
int objectIndex;
u8* oid;
mscfs_check_cache(fs);
r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
/* Check if its the right type */
if(requiredType >= 0 && requiredType != file_data->ef) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
oid = file_data->objectId.id;
/* Is it a file or directory */
if(file_data->ef) {
fs->currentPath[0] = oid[0];
fs->currentPath[1] = oid[1];
fs->currentFile[0] = oid[2];
fs->currentFile[1] = oid[3];
} else {
fs->currentPath[0] = oid[pathlen - 2];
fs->currentPath[1] = oid[pathlen - 1];
fs->currentFile[0] = 0;
fs->currentFile[1] = 0;
}
fs->currentFileIndex = objectIndex;
if(file_out) {
sc_file_t *file;
file = sc_file_new();
file->path = *path_in;
file->size = file_data->size;
file->id = (oid[2] << 8) | oid[3];
if(!file_data->ef) {
file->type = SC_FILE_TYPE_DF;
} else {
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
}
/* Setup ACLS */
if(file_data->ef) {
muscle_load_file_acls(file, file_data);
} else {
muscle_load_dir_acls(file, file_data);
/* Setup directory acls... */
}
file->magic = SC_FILE_MAGIC;
*file_out = file;
}
return 0;
}
static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in,
sc_file_t **file_out)
{
int r;
assert(card != NULL && path_in != NULL);
switch (path_in->type) {
case SC_PATH_TYPE_FILE_ID:
r = select_item(card, path_in, file_out, 1);
break;
case SC_PATH_TYPE_DF_NAME:
r = select_item(card, path_in, file_out, 0);
break;
case SC_PATH_TYPE_PATH:
r = select_item(card, path_in, file_out, -1);
break;
default:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if(r > 0) r = 0;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
static int _listFile(mscfs_file_t *file, int reset, void *udata)
{
int next = reset ? 0x00 : 0x01;
return msc_list_objects( (sc_card_t*)udata, next, file);
}
static int muscle_init(sc_card_t *card)
{
muscle_private_t *priv;
card->name = "MuscleApplet";
card->drv_data = malloc(sizeof(muscle_private_t));
if(!card->drv_data) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
memset(card->drv_data, 0, sizeof(muscle_private_t));
priv = MUSCLE_DATA(card);
priv->verifiedPins = 0;
priv->fs = mscfs_new();
if(!priv->fs) {
free(card->drv_data);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
priv->fs->udata = card;
priv->fs->listFile = _listFile;
card->cla = 0xB0;
card->flags |= SC_CARD_FLAG_RNG;
card->caps |= SC_CARD_CAP_RNG;
/* Card type detection */
_sc_match_atr(card, muscle_atrs, &card->type);
if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) {
card->caps |= SC_CARD_CAP_APDU_EXT;
}
if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) {
card->caps |= SC_CARD_CAP_APDU_EXT;
}
if (!(card->caps & SC_CARD_CAP_APDU_EXT)) {
card->max_recv_size = 255;
card->max_send_size = 255;
}
if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) {
/* Tyfone JCOP v242R2 card that doesn't support extended APDUs */
}
/* FIXME: Card type detection */
if (1) {
unsigned long flags;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
flags |= SC_ALGORITHM_ONBOARD_KEY_GEN;
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return SC_SUCCESS;
}
static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid = fs->cache.array[x].objectId.id;
if (bufLen < 2)
break;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count += 2;
bufLen -= 2;
}
}
return count;
}
static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd,
int *tries_left)
{
muscle_private_t* priv = MUSCLE_DATA(card);
const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH;
u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH];
switch(cmd->cmd) {
case SC_PIN_CMD_VERIFY:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
int r;
msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len);
cmd->apdu = &apdu;
cmd->pin1.offset = 5;
r = iso_ops->pin_cmd(card, cmd, tries_left);
if(r >= 0)
priv->verifiedPins |= (1 << cmd->pin_reference);
return r;
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
case SC_PIN_CMD_CHANGE:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len);
cmd->apdu = &apdu;
return iso_ops->pin_cmd(card, cmd, tries_left);
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
case SC_PIN_CMD_UNBLOCK:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len);
cmd->apdu = &apdu;
return iso_ops->pin_cmd(card, cmd, tries_left);
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n");
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info)
{
/* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */
switch(info->keyType) {
case 1: /* RSA */
return msc_extract_rsa_public_key(card,
info->keyLocation,
&info->modLength,
&info->modValue,
&info->expLength,
&info->expValue);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info)
{
/* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */
switch(info->keyType) {
case 0x02: /* RSA_PRIVATE */
case 0x03: /* RSA_PRIVATE_CRT */
return msc_import_key(card,
info->keyLocation,
info);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info)
{
return msc_generate_keypair(card,
info->privateKeyLocation,
info->publicKeyLocation,
info->keyType,
info->keySize,
0);
}
static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info)
{
muscle_private_t* priv = MUSCLE_DATA(card);
info->verifiedPins = priv->verifiedPins;
return 0;
}
static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data)
{
switch(request) {
case SC_CARDCTL_MUSCLE_GENERATE_KEY:
return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data);
case SC_CARDCTL_MUSCLE_EXTRACT_KEY:
return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data);
case SC_CARDCTL_MUSCLE_IMPORT_KEY:
return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data);
case SC_CARDCTL_MUSCLE_VERIFIED_PINS:
return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data);
default:
return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */
}
}
static int muscle_set_security_env(sc_card_t *card,
const sc_security_env_t *env,
int se_num)
{
muscle_private_t* priv = MUSCLE_DATA(card);
if (env->operation != SC_SEC_OPERATION_SIGN &&
env->operation != SC_SEC_OPERATION_DECIPHER) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (env->algorithm != SC_ALGORITHM_RSA) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* ADJUST FOR PKCS1 padding support for decryption only */
if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) ||
(env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
if (env->key_ref_len != 1 ||
(env->key_ref[0] > 0x0F)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
priv->rsa_key_ref = env->key_ref[0];
}
if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT)
if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n");
return SC_ERROR_NOT_SUPPORTED;
} */
priv->env = *env;
return 0;
}
static int muscle_restore_security_env(sc_card_t *card, int se_num)
{
muscle_private_t* priv = MUSCLE_DATA(card);
memset(&priv->env, 0, sizeof(priv->env));
return 0;
}
static int muscle_decipher(sc_card_t * card,
const u8 * crgram, size_t crgram_len, u8 * out,
size_t out_len)
{
muscle_private_t* priv = MUSCLE_DATA(card);
u8 key_id;
int r;
/* sanity check */
if (priv->env.operation != SC_SEC_OPERATION_DECIPHER)
return SC_ERROR_INVALID_ARGUMENTS;
key_id = priv->rsa_key_ref * 2; /* Private key */
if (out_len < crgram_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small");
return SC_ERROR_BUFFER_TOO_SMALL;
}
r = msc_compute_crypt(card,
key_id,
0x00, /* RSA NO PADDING */
0x04, /* decrypt */
crgram,
out,
crgram_len,
out_len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed");
return r;
}
static int muscle_compute_signature(sc_card_t *card, const u8 *data,
size_t data_len, u8 * out, size_t outlen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
u8 key_id;
int r;
key_id = priv->rsa_key_ref * 2; /* Private key */
if (outlen < data_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small");
return SC_ERROR_BUFFER_TOO_SMALL;
}
r = msc_compute_crypt(card,
key_id,
0x00, /* RSA NO PADDING */
0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */
data,
out,
data_len,
outlen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed");
return r;
}
static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
if (len == 0)
return SC_SUCCESS;
else {
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL,
msc_get_challenge(card, len, 0, NULL, rnd),
"GET CHALLENGE cmd failed");
return (int) len;
}
}
static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) {
if(sw1 == 0x9C) {
switch(sw2) {
case 0x01: /* SW_NO_MEMORY_LEFT */
return SC_ERROR_NOT_ENOUGH_MEMORY;
case 0x02: /* SW_AUTH_FAILED */
return SC_ERROR_PIN_CODE_INCORRECT;
case 0x03: /* SW_OPERATION_NOT_ALLOWED */
return SC_ERROR_NOT_ALLOWED;
case 0x05: /* SW_UNSUPPORTED_FEATURE */
return SC_ERROR_NO_CARD_SUPPORT;
case 0x06: /* SW_UNAUTHORIZED */
return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
case 0x07: /* SW_OBJECT_NOT_FOUND */
return SC_ERROR_FILE_NOT_FOUND;
case 0x08: /* SW_OBJECT_EXISTS */
return SC_ERROR_FILE_ALREADY_EXISTS;
case 0x09: /* SW_INCORRECT_ALG */
return SC_ERROR_INCORRECT_PARAMETERS;
case 0x0B: /* SW_SIGNATURE_INVALID */
return SC_ERROR_CARD_CMD_FAILED;
case 0x0C: /* SW_IDENTITY_BLOCKED */
return SC_ERROR_AUTH_METHOD_BLOCKED;
case 0x0F: /* SW_INVALID_PARAMETER */
case 0x10: /* SW_INCORRECT_P1 */
case 0x11: /* SW_INCORRECT_P2 */
return SC_ERROR_INCORRECT_PARAMETERS;
}
}
return iso_ops->check_sw(card, sw1, sw2);
}
static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (was_reset > 0) {
if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) {
r = SC_ERROR_INVALID_CARD;
}
}
LOG_FUNC_RETURN(card->ctx, r);
}
static struct sc_card_driver * sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
muscle_ops = *iso_drv->ops;
muscle_ops.check_sw = muscle_check_sw;
muscle_ops.pin_cmd = muscle_pin_cmd;
muscle_ops.match_card = muscle_match_card;
muscle_ops.init = muscle_init;
muscle_ops.finish = muscle_finish;
muscle_ops.get_challenge = muscle_get_challenge;
muscle_ops.set_security_env = muscle_set_security_env;
muscle_ops.restore_security_env = muscle_restore_security_env;
muscle_ops.compute_signature = muscle_compute_signature;
muscle_ops.decipher = muscle_decipher;
muscle_ops.card_ctl = muscle_card_ctl;
muscle_ops.read_binary = muscle_read_binary;
muscle_ops.update_binary = muscle_update_binary;
muscle_ops.create_file = muscle_create_file;
muscle_ops.select_file = muscle_select_file;
muscle_ops.delete_file = muscle_delete_file;
muscle_ops.list_files = muscle_list_files;
muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained;
return &muscle_drv;
}
struct sc_card_driver * sc_get_muscle_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_340_2 |
crossvul-cpp_data_bad_2560_0 | /*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2002,2003,2004,2006,2007,2008,2009,2010 Free Software Foundation, Inc.
*
* GRUB 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.
*
* GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <grub/disk.h>
#include <grub/err.h>
#include <grub/mm.h>
#include <grub/types.h>
#include <grub/partition.h>
#include <grub/misc.h>
#include <grub/time.h>
#include <grub/file.h>
GRUB_EXPORT(grub_disk_dev_register);
GRUB_EXPORT(grub_disk_dev_unregister);
GRUB_EXPORT(grub_disk_dev_iterate);
GRUB_EXPORT(grub_disk_open);
GRUB_EXPORT(grub_disk_close);
GRUB_EXPORT(grub_disk_read);
GRUB_EXPORT(grub_disk_read_ex);
GRUB_EXPORT(grub_disk_write);
GRUB_EXPORT(grub_disk_get_size);
GRUB_EXPORT(grub_disk_firmware_fini);
GRUB_EXPORT(grub_disk_firmware_is_tainted);
GRUB_EXPORT(grub_disk_ata_pass_through);
#define GRUB_CACHE_TIMEOUT 2
/* The last time the disk was used. */
static grub_uint64_t grub_last_time = 0;
/* Disk cache. */
struct grub_disk_cache
{
enum grub_disk_dev_id dev_id;
unsigned long disk_id;
grub_disk_addr_t sector;
char *data;
int lock;
};
static struct grub_disk_cache grub_disk_cache_table[GRUB_DISK_CACHE_NUM];
void (*grub_disk_firmware_fini) (void);
int grub_disk_firmware_is_tainted;
grub_err_t (* grub_disk_ata_pass_through) (grub_disk_t,
struct grub_disk_ata_pass_through_parms *);
#if 0
static unsigned long grub_disk_cache_hits;
static unsigned long grub_disk_cache_misses;
void
grub_disk_cache_get_performance (unsigned long *hits, unsigned long *misses)
{
*hits = grub_disk_cache_hits;
*misses = grub_disk_cache_misses;
}
#endif
static unsigned
grub_disk_cache_get_index (unsigned long dev_id, unsigned long disk_id,
grub_disk_addr_t sector)
{
return ((dev_id * 524287UL + disk_id * 2606459UL
+ ((unsigned) (sector >> GRUB_DISK_CACHE_BITS)))
% GRUB_DISK_CACHE_NUM);
}
static void
grub_disk_cache_invalidate (unsigned long dev_id, unsigned long disk_id,
grub_disk_addr_t sector)
{
unsigned index;
struct grub_disk_cache *cache;
sector &= ~(GRUB_DISK_CACHE_SIZE - 1);
index = grub_disk_cache_get_index (dev_id, disk_id, sector);
cache = grub_disk_cache_table + index;
if (cache->dev_id == dev_id && cache->disk_id == disk_id
&& cache->sector == sector && cache->data)
{
cache->lock = 1;
grub_free (cache->data);
cache->data = 0;
cache->lock = 0;
}
}
void
grub_disk_cache_invalidate_all (void)
{
unsigned i;
for (i = 0; i < GRUB_DISK_CACHE_NUM; i++)
{
struct grub_disk_cache *cache = grub_disk_cache_table + i;
if (cache->data && ! cache->lock)
{
grub_free (cache->data);
cache->data = 0;
}
}
}
static char *
grub_disk_cache_fetch (unsigned long dev_id, unsigned long disk_id,
grub_disk_addr_t sector)
{
struct grub_disk_cache *cache;
unsigned index;
index = grub_disk_cache_get_index (dev_id, disk_id, sector);
cache = grub_disk_cache_table + index;
if (cache->dev_id == dev_id && cache->disk_id == disk_id
&& cache->sector == sector)
{
cache->lock = 1;
#if 0
grub_disk_cache_hits++;
#endif
return cache->data;
}
#if 0
grub_disk_cache_misses++;
#endif
return 0;
}
static void
grub_disk_cache_unlock (unsigned long dev_id, unsigned long disk_id,
grub_disk_addr_t sector)
{
struct grub_disk_cache *cache;
unsigned index;
index = grub_disk_cache_get_index (dev_id, disk_id, sector);
cache = grub_disk_cache_table + index;
if (cache->dev_id == dev_id && cache->disk_id == disk_id
&& cache->sector == sector)
cache->lock = 0;
}
static grub_err_t
grub_disk_cache_store (unsigned long dev_id, unsigned long disk_id,
grub_disk_addr_t sector, const char *data)
{
unsigned index;
struct grub_disk_cache *cache;
index = grub_disk_cache_get_index (dev_id, disk_id, sector);
cache = grub_disk_cache_table + index;
cache->lock = 1;
grub_free (cache->data);
cache->data = 0;
cache->lock = 0;
cache->data = grub_malloc (GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS);
if (! cache->data)
return grub_errno;
grub_memcpy (cache->data, data,
GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS);
cache->dev_id = dev_id;
cache->disk_id = disk_id;
cache->sector = sector;
return GRUB_ERR_NONE;
}
static grub_disk_dev_t grub_disk_dev_list;
void
grub_disk_dev_register (grub_disk_dev_t dev)
{
dev->next = grub_disk_dev_list;
grub_disk_dev_list = dev;
}
void
grub_disk_dev_unregister (grub_disk_dev_t dev)
{
grub_disk_dev_t *p, q;
for (p = &grub_disk_dev_list, q = *p; q; p = &(q->next), q = q->next)
if (q == dev)
{
*p = q->next;
break;
}
}
int
grub_disk_dev_iterate (int (*hook) (const char *name, void *closure),
void *closure)
{
grub_disk_dev_t p;
for (p = grub_disk_dev_list; p; p = p->next)
if (p->iterate && (p->iterate) (hook, closure))
return 1;
return 0;
}
/* Return the location of the first ',', if any, which is not
escaped by a '\'. */
static const char *
find_part_sep (const char *name)
{
const char *p = name;
char c;
while ((c = *p++) != '\0')
{
if (c == '\\' && *p == ',')
p++;
else if (c == ',')
return p - 1;
}
return NULL;
}
grub_disk_t
grub_disk_open (const char *name)
{
const char *p;
grub_disk_t disk;
grub_disk_dev_t dev;
char *raw = (char *) name;
grub_uint64_t current_time;
grub_dprintf ("disk", "Opening `%s'...\n", name);
disk = (grub_disk_t) grub_zalloc (sizeof (*disk));
if (! disk)
return 0;
disk->name = grub_strdup (name);
if (! disk->name)
goto fail;
p = find_part_sep (name);
if (p)
{
grub_size_t len = p - name;
raw = grub_malloc (len + 1);
if (! raw)
goto fail;
grub_memcpy (raw, name, len);
raw[len] = '\0';
}
for (dev = grub_disk_dev_list; dev; dev = dev->next)
{
if ((dev->open) (raw, disk) == GRUB_ERR_NONE)
break;
else if (grub_errno == GRUB_ERR_UNKNOWN_DEVICE)
grub_errno = GRUB_ERR_NONE;
else
goto fail;
}
if (! dev)
{
grub_error (GRUB_ERR_UNKNOWN_DEVICE, "no such disk");
goto fail;
}
if (p && ! disk->has_partitions)
{
grub_error (GRUB_ERR_BAD_DEVICE, "no partition on this disk");
goto fail;
}
disk->dev = dev;
if (p)
{
disk->partition = grub_partition_probe (disk, p + 1);
if (! disk->partition)
{
grub_error (GRUB_ERR_UNKNOWN_DEVICE, "no such partition");
goto fail;
}
}
/* The cache will be invalidated about 2 seconds after a device was
closed. */
current_time = grub_get_time_ms ();
if (current_time > (grub_last_time
+ GRUB_CACHE_TIMEOUT * 1000))
grub_disk_cache_invalidate_all ();
grub_last_time = current_time;
fail:
if (raw && raw != name)
grub_free (raw);
if (grub_errno != GRUB_ERR_NONE)
{
grub_error_push ();
grub_dprintf ("disk", "Opening `%s' failed.\n", name);
grub_error_pop ();
grub_disk_close (disk);
return 0;
}
return disk;
}
void
grub_disk_close (grub_disk_t disk)
{
grub_partition_t part;
grub_dprintf ("disk", "Closing `%s'.\n", disk->name);
if (disk->dev && disk->dev->close)
(disk->dev->close) (disk);
/* Reset the timer. */
grub_last_time = grub_get_time_ms ();
while (disk->partition)
{
part = disk->partition->parent;
grub_free (disk->partition);
disk->partition = part;
}
grub_free ((void *) disk->name);
grub_free (disk);
}
/* This function performs three tasks:
- Make sectors disk relative from partition relative.
- Normalize offset to be less than the sector size.
- Verify that the range is inside the partition. */
static grub_err_t
grub_disk_adjust_range (grub_disk_t disk, grub_disk_addr_t *sector,
grub_off_t *offset, grub_size_t size)
{
*sector += *offset >> GRUB_DISK_SECTOR_BITS;
*offset &= GRUB_DISK_SECTOR_SIZE - 1;
/*
grub_partition_t part;
for (part = disk->partition; part; part = part->parent)
{
grub_disk_addr_t start;
grub_uint64_t len;
start = part->start;
len = part->len;
if (*sector >= len
|| len - *sector < ((*offset + size + GRUB_DISK_SECTOR_SIZE - 1)
>> GRUB_DISK_SECTOR_BITS))
return grub_error (GRUB_ERR_OUT_OF_RANGE, "out of partition");
*sector += start;
}
if (disk->total_sectors <= *sector
|| ((*offset + size + GRUB_DISK_SECTOR_SIZE - 1)
>> GRUB_DISK_SECTOR_BITS) > disk->total_sectors - *sector)
return grub_error (GRUB_ERR_OUT_OF_RANGE, "out of disk");
*/
return GRUB_ERR_NONE;
}
/* Read data from the disk. */
grub_err_t
grub_disk_read (grub_disk_t disk, grub_disk_addr_t sector,
grub_off_t offset, grub_size_t size, void *buf)
{
char *tmp_buf;
unsigned real_offset;
/* First of all, check if the region is within the disk. */
if (grub_disk_adjust_range (disk, §or, &offset, size) != GRUB_ERR_NONE)
{
grub_error_push ();
grub_dprintf ("disk", "Read out of range: sector 0x%llx (%s).\n",
(unsigned long long) sector, grub_errmsg);
grub_error_pop ();
return grub_errno;
}
real_offset = offset;
/* Allocate a temporary buffer. */
tmp_buf = grub_malloc (GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS);
if (! tmp_buf)
return grub_errno;
/* Until SIZE is zero... */
while (size)
{
char *data;
grub_disk_addr_t start_sector;
grub_size_t len;
grub_size_t pos;
/* For reading bulk data. */
start_sector = sector & ~(GRUB_DISK_CACHE_SIZE - 1);
pos = (sector - start_sector) << GRUB_DISK_SECTOR_BITS;
len = ((GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS)
- pos - real_offset);
if (len > size)
len = size;
/* Fetch the cache. */
data = grub_disk_cache_fetch (disk->dev->id, disk->id, start_sector);
if (data)
{
/* Just copy it! */
if (buf)
grub_memcpy (buf, data + pos + real_offset, len);
grub_disk_cache_unlock (disk->dev->id, disk->id, start_sector);
}
else
{
/* Otherwise read data from the disk actually. */
if (start_sector + GRUB_DISK_CACHE_SIZE > disk->total_sectors
|| (disk->dev->read) (disk, start_sector,
GRUB_DISK_CACHE_SIZE, tmp_buf)
!= GRUB_ERR_NONE)
{
/* Uggh... Failed. Instead, just read necessary data. */
unsigned num;
char *p;
grub_errno = GRUB_ERR_NONE;
num = ((size + real_offset + GRUB_DISK_SECTOR_SIZE - 1)
>> GRUB_DISK_SECTOR_BITS);
p = grub_realloc (tmp_buf, num << GRUB_DISK_SECTOR_BITS);
if (!p)
goto finish;
tmp_buf = p;
if ((disk->dev->read) (disk, sector, num, tmp_buf))
{
grub_error_push ();
grub_dprintf ("disk", "%s read failed\n", disk->name);
grub_error_pop ();
goto finish;
}
if (buf)
grub_memcpy (buf, tmp_buf + real_offset, size);
/* Call the read hook, if any. */
if (disk->read_hook)
while (size)
{
grub_size_t to_read;
to_read = size;
if (real_offset + to_read > GRUB_DISK_SECTOR_SIZE)
to_read = GRUB_DISK_SECTOR_SIZE - real_offset;
(disk->read_hook) (sector, real_offset,
to_read, disk->closure);
if (grub_errno != GRUB_ERR_NONE)
goto finish;
sector++;
size -= to_read;
real_offset = 0;
}
/* This must be the end. */
goto finish;
}
/* Copy it and store it in the disk cache. */
if (buf)
grub_memcpy (buf, tmp_buf + pos + real_offset, len);
grub_disk_cache_store (disk->dev->id, disk->id,
start_sector, tmp_buf);
}
/* Call the read hook, if any. */
if (disk->read_hook)
{
grub_disk_addr_t s = sector;
grub_size_t l = len;
while (l)
{
(disk->read_hook) (s, real_offset,
((l > GRUB_DISK_SECTOR_SIZE)
? GRUB_DISK_SECTOR_SIZE
: l), disk->closure);
if (l < GRUB_DISK_SECTOR_SIZE - real_offset)
break;
s++;
l -= GRUB_DISK_SECTOR_SIZE - real_offset;
real_offset = 0;
}
}
sector = start_sector + GRUB_DISK_CACHE_SIZE;
if (buf)
buf = (char *) buf + len;
size -= len;
real_offset = 0;
}
finish:
grub_free (tmp_buf);
return grub_errno;
}
grub_err_t
grub_disk_read_ex (grub_disk_t disk, grub_disk_addr_t sector,
grub_off_t offset, grub_size_t size, void *buf, int flags)
{
unsigned real_offset;
if (! flags)
return grub_disk_read (disk, sector, offset, size, buf);
if (grub_disk_adjust_range (disk, §or, &offset, size) != GRUB_ERR_NONE)
return grub_errno;
real_offset = offset;
while (size)
{
char tmp_buf[GRUB_DISK_SECTOR_SIZE];
grub_size_t len;
if ((real_offset != 0) || (size < GRUB_DISK_SECTOR_SIZE))
{
len = GRUB_DISK_SECTOR_SIZE - real_offset;
if (len > size)
len = size;
if (buf)
{
if ((disk->dev->read) (disk, sector, 1, tmp_buf) != GRUB_ERR_NONE)
break;
grub_memcpy (buf, tmp_buf + real_offset, len);
}
if (disk->read_hook)
(disk->read_hook) (sector, real_offset, len, disk->closure);
sector++;
real_offset = 0;
}
else
{
grub_size_t n;
len = size & ~(GRUB_DISK_SECTOR_SIZE - 1);
n = size >> GRUB_DISK_SECTOR_BITS;
if ((buf) &&
((disk->dev->read) (disk, sector, n, buf) != GRUB_ERR_NONE))
break;
if (disk->read_hook)
{
while (n)
{
(disk->read_hook) (sector++, 0, GRUB_DISK_SECTOR_SIZE,
disk->closure);
n--;
}
}
else
sector += n;
}
if (buf)
buf = (char *) buf + len;
size -= len;
}
return grub_errno;
}
grub_err_t
grub_disk_write (grub_disk_t disk, grub_disk_addr_t sector,
grub_off_t offset, grub_size_t size, const void *buf)
{
unsigned real_offset;
grub_dprintf ("disk", "Writing `%s'...\n", disk->name);
if (grub_disk_adjust_range (disk, §or, &offset, size) != GRUB_ERR_NONE)
return grub_errno;
real_offset = offset;
while (size)
{
if (real_offset != 0 || (size < GRUB_DISK_SECTOR_SIZE && size != 0))
{
char tmp_buf[GRUB_DISK_SECTOR_SIZE];
grub_size_t len;
grub_partition_t part;
part = disk->partition;
disk->partition = 0;
if (grub_disk_read (disk, sector, 0, GRUB_DISK_SECTOR_SIZE, tmp_buf)
!= GRUB_ERR_NONE)
{
disk->partition = part;
goto finish;
}
disk->partition = part;
len = GRUB_DISK_SECTOR_SIZE - real_offset;
if (len > size)
len = size;
grub_memcpy (tmp_buf + real_offset, buf, len);
grub_disk_cache_invalidate (disk->dev->id, disk->id, sector);
if ((disk->dev->write) (disk, sector, 1, tmp_buf) != GRUB_ERR_NONE)
goto finish;
sector++;
buf = (char *) buf + len;
size -= len;
real_offset = 0;
}
else
{
grub_size_t len;
grub_size_t n;
len = size & ~(GRUB_DISK_SECTOR_SIZE - 1);
n = size >> GRUB_DISK_SECTOR_BITS;
if ((disk->dev->write) (disk, sector, n, buf) != GRUB_ERR_NONE)
goto finish;
while (n--)
grub_disk_cache_invalidate (disk->dev->id, disk->id, sector++);
buf = (char *) buf + len;
size -= len;
}
}
finish:
return grub_errno;
}
grub_uint64_t
grub_disk_get_size (grub_disk_t disk)
{
if (disk->partition)
return grub_partition_get_len (disk->partition);
else
return disk->total_sectors;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2560_0 |
crossvul-cpp_data_good_5740_2 | /*
* NET3: Garbage Collector For AF_UNIX sockets
*
* Garbage Collector:
* Copyright (C) Barak A. Pearlmutter.
* Released under the GPL version 2 or later.
*
* Chopped about by Alan Cox 22/3/96 to make it fit the AF_UNIX socket problem.
* If it doesn't work blame me, it worked when Barak sent it.
*
* Assumptions:
*
* - object w/ a bit
* - free list
*
* Current optimizations:
*
* - explicit stack instead of recursion
* - tail recurse on first born instead of immediate push/pop
* - we gather the stuff that should not be killed into tree
* and stack is just a path from root to the current pointer.
*
* Future optimizations:
*
* - don't just push entire root set; process in place
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Fixes:
* Alan Cox 07 Sept 1997 Vmalloc internal stack as needed.
* Cope with changing max_files.
* Al Viro 11 Oct 1998
* Graph may have cycles. That is, we can send the descriptor
* of foo to bar and vice versa. Current code chokes on that.
* Fix: move SCM_RIGHTS ones into the separate list and then
* skb_free() them all instead of doing explicit fput's.
* Another problem: since fput() may block somebody may
* create a new unix_socket when we are in the middle of sweep
* phase. Fix: revert the logic wrt MARKED. Mark everything
* upon the beginning and unmark non-junk ones.
*
* [12 Oct 1998] AAARGH! New code purges all SCM_RIGHTS
* sent to connect()'ed but still not accept()'ed sockets.
* Fixed. Old code had slightly different problem here:
* extra fput() in situation when we passed the descriptor via
* such socket and closed it (descriptor). That would happen on
* each unix_gc() until the accept(). Since the struct file in
* question would go to the free list and might be reused...
* That might be the reason of random oopses on filp_close()
* in unrelated processes.
*
* AV 28 Feb 1999
* Kill the explicit allocation of stack. Now we keep the tree
* with root in dummy + pointer (gc_current) to one of the nodes.
* Stack is represented as path from gc_current to dummy. Unmark
* now means "add to tree". Push == "make it a son of gc_current".
* Pop == "move gc_current to parent". We keep only pointers to
* parents (->gc_tree).
* AV 1 Mar 1999
* Damn. Added missing check for ->dead in listen queues scanning.
*
* Miklos Szeredi 25 Jun 2007
* Reimplement with a cycle collecting algorithm. This should
* solve several problems with the previous code, like being racy
* wrt receive and holding up unrelated socket operations.
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/un.h>
#include <linux/net.h>
#include <linux/fs.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/file.h>
#include <linux/proc_fs.h>
#include <linux/mutex.h>
#include <linux/wait.h>
#include <net/sock.h>
#include <net/af_unix.h>
#include <net/scm.h>
#include <net/tcp_states.h>
/* Internal data structures and random procedures: */
static LIST_HEAD(gc_inflight_list);
static LIST_HEAD(gc_candidates);
static DEFINE_SPINLOCK(unix_gc_lock);
static DECLARE_WAIT_QUEUE_HEAD(unix_gc_wait);
unsigned int unix_tot_inflight;
struct sock *unix_get_socket(struct file *filp)
{
struct sock *u_sock = NULL;
struct inode *inode = file_inode(filp);
/* Socket ? */
if (S_ISSOCK(inode->i_mode) && !(filp->f_mode & FMODE_PATH)) {
struct socket *sock = SOCKET_I(inode);
struct sock *s = sock->sk;
/* PF_UNIX ? */
if (s && sock->ops && sock->ops->family == PF_UNIX)
u_sock = s;
}
return u_sock;
}
/* Keep the number of times in flight count for the file
* descriptor if it is for an AF_UNIX socket.
*/
void unix_inflight(struct file *fp)
{
struct sock *s = unix_get_socket(fp);
spin_lock(&unix_gc_lock);
if (s) {
struct unix_sock *u = unix_sk(s);
if (atomic_long_inc_return(&u->inflight) == 1) {
BUG_ON(!list_empty(&u->link));
list_add_tail(&u->link, &gc_inflight_list);
} else {
BUG_ON(list_empty(&u->link));
}
unix_tot_inflight++;
}
fp->f_cred->user->unix_inflight++;
spin_unlock(&unix_gc_lock);
}
void unix_notinflight(struct file *fp)
{
struct sock *s = unix_get_socket(fp);
spin_lock(&unix_gc_lock);
if (s) {
struct unix_sock *u = unix_sk(s);
BUG_ON(list_empty(&u->link));
if (atomic_long_dec_and_test(&u->inflight))
list_del_init(&u->link);
unix_tot_inflight--;
}
fp->f_cred->user->unix_inflight--;
spin_unlock(&unix_gc_lock);
}
static void scan_inflight(struct sock *x, void (*func)(struct unix_sock *),
struct sk_buff_head *hitlist)
{
struct sk_buff *skb;
struct sk_buff *next;
spin_lock(&x->sk_receive_queue.lock);
skb_queue_walk_safe(&x->sk_receive_queue, skb, next) {
/* Do we have file descriptors ? */
if (UNIXCB(skb).fp) {
bool hit = false;
/* Process the descriptors of this socket */
int nfd = UNIXCB(skb).fp->count;
struct file **fp = UNIXCB(skb).fp->fp;
while (nfd--) {
/* Get the socket the fd matches if it indeed does so */
struct sock *sk = unix_get_socket(*fp++);
if (sk) {
struct unix_sock *u = unix_sk(sk);
/* Ignore non-candidates, they could
* have been added to the queues after
* starting the garbage collection
*/
if (test_bit(UNIX_GC_CANDIDATE, &u->gc_flags)) {
hit = true;
func(u);
}
}
}
if (hit && hitlist != NULL) {
__skb_unlink(skb, &x->sk_receive_queue);
__skb_queue_tail(hitlist, skb);
}
}
}
spin_unlock(&x->sk_receive_queue.lock);
}
static void scan_children(struct sock *x, void (*func)(struct unix_sock *),
struct sk_buff_head *hitlist)
{
if (x->sk_state != TCP_LISTEN) {
scan_inflight(x, func, hitlist);
} else {
struct sk_buff *skb;
struct sk_buff *next;
struct unix_sock *u;
LIST_HEAD(embryos);
/* For a listening socket collect the queued embryos
* and perform a scan on them as well.
*/
spin_lock(&x->sk_receive_queue.lock);
skb_queue_walk_safe(&x->sk_receive_queue, skb, next) {
u = unix_sk(skb->sk);
/* An embryo cannot be in-flight, so it's safe
* to use the list link.
*/
BUG_ON(!list_empty(&u->link));
list_add_tail(&u->link, &embryos);
}
spin_unlock(&x->sk_receive_queue.lock);
while (!list_empty(&embryos)) {
u = list_entry(embryos.next, struct unix_sock, link);
scan_inflight(&u->sk, func, hitlist);
list_del_init(&u->link);
}
}
}
static void dec_inflight(struct unix_sock *usk)
{
atomic_long_dec(&usk->inflight);
}
static void inc_inflight(struct unix_sock *usk)
{
atomic_long_inc(&usk->inflight);
}
static void inc_inflight_move_tail(struct unix_sock *u)
{
atomic_long_inc(&u->inflight);
/* If this still might be part of a cycle, move it to the end
* of the list, so that it's checked even if it was already
* passed over
*/
if (test_bit(UNIX_GC_MAYBE_CYCLE, &u->gc_flags))
list_move_tail(&u->link, &gc_candidates);
}
static bool gc_in_progress;
#define UNIX_INFLIGHT_TRIGGER_GC 16000
void wait_for_unix_gc(void)
{
/* If number of inflight sockets is insane,
* force a garbage collect right now.
*/
if (unix_tot_inflight > UNIX_INFLIGHT_TRIGGER_GC && !gc_in_progress)
unix_gc();
wait_event(unix_gc_wait, gc_in_progress == false);
}
/* The external entry point: unix_gc() */
void unix_gc(void)
{
struct unix_sock *u;
struct unix_sock *next;
struct sk_buff_head hitlist;
struct list_head cursor;
LIST_HEAD(not_cycle_list);
spin_lock(&unix_gc_lock);
/* Avoid a recursive GC. */
if (gc_in_progress)
goto out;
gc_in_progress = true;
/* First, select candidates for garbage collection. Only
* in-flight sockets are considered, and from those only ones
* which don't have any external reference.
*
* Holding unix_gc_lock will protect these candidates from
* being detached, and hence from gaining an external
* reference. Since there are no possible receivers, all
* buffers currently on the candidates' queues stay there
* during the garbage collection.
*
* We also know that no new candidate can be added onto the
* receive queues. Other, non candidate sockets _can_ be
* added to queue, so we must make sure only to touch
* candidates.
*/
list_for_each_entry_safe(u, next, &gc_inflight_list, link) {
long total_refs;
long inflight_refs;
total_refs = file_count(u->sk.sk_socket->file);
inflight_refs = atomic_long_read(&u->inflight);
BUG_ON(inflight_refs < 1);
BUG_ON(total_refs < inflight_refs);
if (total_refs == inflight_refs) {
list_move_tail(&u->link, &gc_candidates);
__set_bit(UNIX_GC_CANDIDATE, &u->gc_flags);
__set_bit(UNIX_GC_MAYBE_CYCLE, &u->gc_flags);
}
}
/* Now remove all internal in-flight reference to children of
* the candidates.
*/
list_for_each_entry(u, &gc_candidates, link)
scan_children(&u->sk, dec_inflight, NULL);
/* Restore the references for children of all candidates,
* which have remaining references. Do this recursively, so
* only those remain, which form cyclic references.
*
* Use a "cursor" link, to make the list traversal safe, even
* though elements might be moved about.
*/
list_add(&cursor, &gc_candidates);
while (cursor.next != &gc_candidates) {
u = list_entry(cursor.next, struct unix_sock, link);
/* Move cursor to after the current position. */
list_move(&cursor, &u->link);
if (atomic_long_read(&u->inflight) > 0) {
list_move_tail(&u->link, ¬_cycle_list);
__clear_bit(UNIX_GC_MAYBE_CYCLE, &u->gc_flags);
scan_children(&u->sk, inc_inflight_move_tail, NULL);
}
}
list_del(&cursor);
/* not_cycle_list contains those sockets which do not make up a
* cycle. Restore these to the inflight list.
*/
while (!list_empty(¬_cycle_list)) {
u = list_entry(not_cycle_list.next, struct unix_sock, link);
__clear_bit(UNIX_GC_CANDIDATE, &u->gc_flags);
list_move_tail(&u->link, &gc_inflight_list);
}
/* Now gc_candidates contains only garbage. Restore original
* inflight counters for these as well, and remove the skbuffs
* which are creating the cycle(s).
*/
skb_queue_head_init(&hitlist);
list_for_each_entry(u, &gc_candidates, link)
scan_children(&u->sk, inc_inflight, &hitlist);
spin_unlock(&unix_gc_lock);
/* Here we are. Hitlist is filled. Die. */
__skb_queue_purge(&hitlist);
spin_lock(&unix_gc_lock);
/* All candidates should have been detached by now. */
BUG_ON(!list_empty(&gc_candidates));
gc_in_progress = false;
wake_up(&unix_gc_wait);
out:
spin_unlock(&unix_gc_lock);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5740_2 |
crossvul-cpp_data_good_3316_0 | /*
* Copyright (C) 2006, 2007, 2009 Rusty Russell, IBM Corporation
* Copyright (C) 2009, 2010, 2011 Red Hat, Inc.
* Copyright (C) 2009, 2010, 2011 Amit Shah <amit.shah@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/cdev.h>
#include <linux/debugfs.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/freezer.h>
#include <linux/fs.h>
#include <linux/splice.h>
#include <linux/pagemap.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/poll.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/virtio.h>
#include <linux/virtio_console.h>
#include <linux/wait.h>
#include <linux/workqueue.h>
#include <linux/module.h>
#include <linux/dma-mapping.h>
#include "../tty/hvc/hvc_console.h"
#define is_rproc_enabled IS_ENABLED(CONFIG_REMOTEPROC)
/*
* This is a global struct for storing common data for all the devices
* this driver handles.
*
* Mainly, it has a linked list for all the consoles in one place so
* that callbacks from hvc for get_chars(), put_chars() work properly
* across multiple devices and multiple ports per device.
*/
struct ports_driver_data {
/* Used for registering chardevs */
struct class *class;
/* Used for exporting per-port information to debugfs */
struct dentry *debugfs_dir;
/* List of all the devices we're handling */
struct list_head portdevs;
/*
* This is used to keep track of the number of hvc consoles
* spawned by this driver. This number is given as the first
* argument to hvc_alloc(). To correctly map an initial
* console spawned via hvc_instantiate to the console being
* hooked up via hvc_alloc, we need to pass the same vtermno.
*
* We also just assume the first console being initialised was
* the first one that got used as the initial console.
*/
unsigned int next_vtermno;
/* All the console devices handled by this driver */
struct list_head consoles;
};
static struct ports_driver_data pdrvdata;
static DEFINE_SPINLOCK(pdrvdata_lock);
static DECLARE_COMPLETION(early_console_added);
/* This struct holds information that's relevant only for console ports */
struct console {
/* We'll place all consoles in a list in the pdrvdata struct */
struct list_head list;
/* The hvc device associated with this console port */
struct hvc_struct *hvc;
/* The size of the console */
struct winsize ws;
/*
* This number identifies the number that we used to register
* with hvc in hvc_instantiate() and hvc_alloc(); this is the
* number passed on by the hvc callbacks to us to
* differentiate between the other console ports handled by
* this driver
*/
u32 vtermno;
};
struct port_buffer {
char *buf;
/* size of the buffer in *buf above */
size_t size;
/* used length of the buffer */
size_t len;
/* offset in the buf from which to consume data */
size_t offset;
/* DMA address of buffer */
dma_addr_t dma;
/* Device we got DMA memory from */
struct device *dev;
/* List of pending dma buffers to free */
struct list_head list;
/* If sgpages == 0 then buf is used */
unsigned int sgpages;
/* sg is used if spages > 0. sg must be the last in is struct */
struct scatterlist sg[0];
};
/*
* This is a per-device struct that stores data common to all the
* ports for that device (vdev->priv).
*/
struct ports_device {
/* Next portdev in the list, head is in the pdrvdata struct */
struct list_head list;
/*
* Workqueue handlers where we process deferred work after
* notification
*/
struct work_struct control_work;
struct work_struct config_work;
struct list_head ports;
/* To protect the list of ports */
spinlock_t ports_lock;
/* To protect the vq operations for the control channel */
spinlock_t c_ivq_lock;
spinlock_t c_ovq_lock;
/* max. number of ports this device can hold */
u32 max_nr_ports;
/* The virtio device we're associated with */
struct virtio_device *vdev;
/*
* A couple of virtqueues for the control channel: one for
* guest->host transfers, one for host->guest transfers
*/
struct virtqueue *c_ivq, *c_ovq;
/*
* A control packet buffer for guest->host requests, protected
* by c_ovq_lock.
*/
struct virtio_console_control cpkt;
/* Array of per-port IO virtqueues */
struct virtqueue **in_vqs, **out_vqs;
/* Major number for this device. Ports will be created as minors. */
int chr_major;
};
struct port_stats {
unsigned long bytes_sent, bytes_received, bytes_discarded;
};
/* This struct holds the per-port data */
struct port {
/* Next port in the list, head is in the ports_device */
struct list_head list;
/* Pointer to the parent virtio_console device */
struct ports_device *portdev;
/* The current buffer from which data has to be fed to readers */
struct port_buffer *inbuf;
/*
* To protect the operations on the in_vq associated with this
* port. Has to be a spinlock because it can be called from
* interrupt context (get_char()).
*/
spinlock_t inbuf_lock;
/* Protect the operations on the out_vq. */
spinlock_t outvq_lock;
/* The IO vqs for this port */
struct virtqueue *in_vq, *out_vq;
/* File in the debugfs directory that exposes this port's information */
struct dentry *debugfs_file;
/*
* Keep count of the bytes sent, received and discarded for
* this port for accounting and debugging purposes. These
* counts are not reset across port open / close events.
*/
struct port_stats stats;
/*
* The entries in this struct will be valid if this port is
* hooked up to an hvc console
*/
struct console cons;
/* Each port associates with a separate char device */
struct cdev *cdev;
struct device *dev;
/* Reference-counting to handle port hot-unplugs and file operations */
struct kref kref;
/* A waitqueue for poll() or blocking read operations */
wait_queue_head_t waitqueue;
/* The 'name' of the port that we expose via sysfs properties */
char *name;
/* We can notify apps of host connect / disconnect events via SIGIO */
struct fasync_struct *async_queue;
/* The 'id' to identify the port with the Host */
u32 id;
bool outvq_full;
/* Is the host device open */
bool host_connected;
/* We should allow only one process to open a port */
bool guest_connected;
};
/* This is the very early arch-specified put chars function. */
static int (*early_put_chars)(u32, const char *, int);
static struct port *find_port_by_vtermno(u32 vtermno)
{
struct port *port;
struct console *cons;
unsigned long flags;
spin_lock_irqsave(&pdrvdata_lock, flags);
list_for_each_entry(cons, &pdrvdata.consoles, list) {
if (cons->vtermno == vtermno) {
port = container_of(cons, struct port, cons);
goto out;
}
}
port = NULL;
out:
spin_unlock_irqrestore(&pdrvdata_lock, flags);
return port;
}
static struct port *find_port_by_devt_in_portdev(struct ports_device *portdev,
dev_t dev)
{
struct port *port;
unsigned long flags;
spin_lock_irqsave(&portdev->ports_lock, flags);
list_for_each_entry(port, &portdev->ports, list) {
if (port->cdev->dev == dev) {
kref_get(&port->kref);
goto out;
}
}
port = NULL;
out:
spin_unlock_irqrestore(&portdev->ports_lock, flags);
return port;
}
static struct port *find_port_by_devt(dev_t dev)
{
struct ports_device *portdev;
struct port *port;
unsigned long flags;
spin_lock_irqsave(&pdrvdata_lock, flags);
list_for_each_entry(portdev, &pdrvdata.portdevs, list) {
port = find_port_by_devt_in_portdev(portdev, dev);
if (port)
goto out;
}
port = NULL;
out:
spin_unlock_irqrestore(&pdrvdata_lock, flags);
return port;
}
static struct port *find_port_by_id(struct ports_device *portdev, u32 id)
{
struct port *port;
unsigned long flags;
spin_lock_irqsave(&portdev->ports_lock, flags);
list_for_each_entry(port, &portdev->ports, list)
if (port->id == id)
goto out;
port = NULL;
out:
spin_unlock_irqrestore(&portdev->ports_lock, flags);
return port;
}
static struct port *find_port_by_vq(struct ports_device *portdev,
struct virtqueue *vq)
{
struct port *port;
unsigned long flags;
spin_lock_irqsave(&portdev->ports_lock, flags);
list_for_each_entry(port, &portdev->ports, list)
if (port->in_vq == vq || port->out_vq == vq)
goto out;
port = NULL;
out:
spin_unlock_irqrestore(&portdev->ports_lock, flags);
return port;
}
static bool is_console_port(struct port *port)
{
if (port->cons.hvc)
return true;
return false;
}
static bool is_rproc_serial(const struct virtio_device *vdev)
{
return is_rproc_enabled && vdev->id.device == VIRTIO_ID_RPROC_SERIAL;
}
static inline bool use_multiport(struct ports_device *portdev)
{
/*
* This condition can be true when put_chars is called from
* early_init
*/
if (!portdev->vdev)
return false;
return __virtio_test_bit(portdev->vdev, VIRTIO_CONSOLE_F_MULTIPORT);
}
static DEFINE_SPINLOCK(dma_bufs_lock);
static LIST_HEAD(pending_free_dma_bufs);
static void free_buf(struct port_buffer *buf, bool can_sleep)
{
unsigned int i;
for (i = 0; i < buf->sgpages; i++) {
struct page *page = sg_page(&buf->sg[i]);
if (!page)
break;
put_page(page);
}
if (!buf->dev) {
kfree(buf->buf);
} else if (is_rproc_enabled) {
unsigned long flags;
/* dma_free_coherent requires interrupts to be enabled. */
if (!can_sleep) {
/* queue up dma-buffers to be freed later */
spin_lock_irqsave(&dma_bufs_lock, flags);
list_add_tail(&buf->list, &pending_free_dma_bufs);
spin_unlock_irqrestore(&dma_bufs_lock, flags);
return;
}
dma_free_coherent(buf->dev, buf->size, buf->buf, buf->dma);
/* Release device refcnt and allow it to be freed */
put_device(buf->dev);
}
kfree(buf);
}
static void reclaim_dma_bufs(void)
{
unsigned long flags;
struct port_buffer *buf, *tmp;
LIST_HEAD(tmp_list);
if (list_empty(&pending_free_dma_bufs))
return;
/* Create a copy of the pending_free_dma_bufs while holding the lock */
spin_lock_irqsave(&dma_bufs_lock, flags);
list_cut_position(&tmp_list, &pending_free_dma_bufs,
pending_free_dma_bufs.prev);
spin_unlock_irqrestore(&dma_bufs_lock, flags);
/* Release the dma buffers, without irqs enabled */
list_for_each_entry_safe(buf, tmp, &tmp_list, list) {
list_del(&buf->list);
free_buf(buf, true);
}
}
static struct port_buffer *alloc_buf(struct virtqueue *vq, size_t buf_size,
int pages)
{
struct port_buffer *buf;
reclaim_dma_bufs();
/*
* Allocate buffer and the sg list. The sg list array is allocated
* directly after the port_buffer struct.
*/
buf = kmalloc(sizeof(*buf) + sizeof(struct scatterlist) * pages,
GFP_KERNEL);
if (!buf)
goto fail;
buf->sgpages = pages;
if (pages > 0) {
buf->dev = NULL;
buf->buf = NULL;
return buf;
}
if (is_rproc_serial(vq->vdev)) {
/*
* Allocate DMA memory from ancestor. When a virtio
* device is created by remoteproc, the DMA memory is
* associated with the grandparent device:
* vdev => rproc => platform-dev.
* The code here would have been less quirky if
* DMA_MEMORY_INCLUDES_CHILDREN had been supported
* in dma-coherent.c
*/
if (!vq->vdev->dev.parent || !vq->vdev->dev.parent->parent)
goto free_buf;
buf->dev = vq->vdev->dev.parent->parent;
/* Increase device refcnt to avoid freeing it */
get_device(buf->dev);
buf->buf = dma_alloc_coherent(buf->dev, buf_size, &buf->dma,
GFP_KERNEL);
} else {
buf->dev = NULL;
buf->buf = kmalloc(buf_size, GFP_KERNEL);
}
if (!buf->buf)
goto free_buf;
buf->len = 0;
buf->offset = 0;
buf->size = buf_size;
return buf;
free_buf:
kfree(buf);
fail:
return NULL;
}
/* Callers should take appropriate locks */
static struct port_buffer *get_inbuf(struct port *port)
{
struct port_buffer *buf;
unsigned int len;
if (port->inbuf)
return port->inbuf;
buf = virtqueue_get_buf(port->in_vq, &len);
if (buf) {
buf->len = len;
buf->offset = 0;
port->stats.bytes_received += len;
}
return buf;
}
/*
* Create a scatter-gather list representing our input buffer and put
* it in the queue.
*
* Callers should take appropriate locks.
*/
static int add_inbuf(struct virtqueue *vq, struct port_buffer *buf)
{
struct scatterlist sg[1];
int ret;
sg_init_one(sg, buf->buf, buf->size);
ret = virtqueue_add_inbuf(vq, sg, 1, buf, GFP_ATOMIC);
virtqueue_kick(vq);
if (!ret)
ret = vq->num_free;
return ret;
}
/* Discard any unread data this port has. Callers lockers. */
static void discard_port_data(struct port *port)
{
struct port_buffer *buf;
unsigned int err;
if (!port->portdev) {
/* Device has been unplugged. vqs are already gone. */
return;
}
buf = get_inbuf(port);
err = 0;
while (buf) {
port->stats.bytes_discarded += buf->len - buf->offset;
if (add_inbuf(port->in_vq, buf) < 0) {
err++;
free_buf(buf, false);
}
port->inbuf = NULL;
buf = get_inbuf(port);
}
if (err)
dev_warn(port->dev, "Errors adding %d buffers back to vq\n",
err);
}
static bool port_has_data(struct port *port)
{
unsigned long flags;
bool ret;
ret = false;
spin_lock_irqsave(&port->inbuf_lock, flags);
port->inbuf = get_inbuf(port);
if (port->inbuf)
ret = true;
spin_unlock_irqrestore(&port->inbuf_lock, flags);
return ret;
}
static ssize_t __send_control_msg(struct ports_device *portdev, u32 port_id,
unsigned int event, unsigned int value)
{
struct scatterlist sg[1];
struct virtqueue *vq;
unsigned int len;
if (!use_multiport(portdev))
return 0;
vq = portdev->c_ovq;
spin_lock(&portdev->c_ovq_lock);
portdev->cpkt.id = cpu_to_virtio32(portdev->vdev, port_id);
portdev->cpkt.event = cpu_to_virtio16(portdev->vdev, event);
portdev->cpkt.value = cpu_to_virtio16(portdev->vdev, value);
sg_init_one(sg, &portdev->cpkt, sizeof(struct virtio_console_control));
if (virtqueue_add_outbuf(vq, sg, 1, &portdev->cpkt, GFP_ATOMIC) == 0) {
virtqueue_kick(vq);
while (!virtqueue_get_buf(vq, &len)
&& !virtqueue_is_broken(vq))
cpu_relax();
}
spin_unlock(&portdev->c_ovq_lock);
return 0;
}
static ssize_t send_control_msg(struct port *port, unsigned int event,
unsigned int value)
{
/* Did the port get unplugged before userspace closed it? */
if (port->portdev)
return __send_control_msg(port->portdev, port->id, event, value);
return 0;
}
/* Callers must take the port->outvq_lock */
static void reclaim_consumed_buffers(struct port *port)
{
struct port_buffer *buf;
unsigned int len;
if (!port->portdev) {
/* Device has been unplugged. vqs are already gone. */
return;
}
while ((buf = virtqueue_get_buf(port->out_vq, &len))) {
free_buf(buf, false);
port->outvq_full = false;
}
}
static ssize_t __send_to_port(struct port *port, struct scatterlist *sg,
int nents, size_t in_count,
void *data, bool nonblock)
{
struct virtqueue *out_vq;
int err;
unsigned long flags;
unsigned int len;
out_vq = port->out_vq;
spin_lock_irqsave(&port->outvq_lock, flags);
reclaim_consumed_buffers(port);
err = virtqueue_add_outbuf(out_vq, sg, nents, data, GFP_ATOMIC);
/* Tell Host to go! */
virtqueue_kick(out_vq);
if (err) {
in_count = 0;
goto done;
}
if (out_vq->num_free == 0)
port->outvq_full = true;
if (nonblock)
goto done;
/*
* Wait till the host acknowledges it pushed out the data we
* sent. This is done for data from the hvc_console; the tty
* operations are performed with spinlocks held so we can't
* sleep here. An alternative would be to copy the data to a
* buffer and relax the spinning requirement. The downside is
* we need to kmalloc a GFP_ATOMIC buffer each time the
* console driver writes something out.
*/
while (!virtqueue_get_buf(out_vq, &len)
&& !virtqueue_is_broken(out_vq))
cpu_relax();
done:
spin_unlock_irqrestore(&port->outvq_lock, flags);
port->stats.bytes_sent += in_count;
/*
* We're expected to return the amount of data we wrote -- all
* of it
*/
return in_count;
}
/*
* Give out the data that's requested from the buffer that we have
* queued up.
*/
static ssize_t fill_readbuf(struct port *port, char __user *out_buf,
size_t out_count, bool to_user)
{
struct port_buffer *buf;
unsigned long flags;
if (!out_count || !port_has_data(port))
return 0;
buf = port->inbuf;
out_count = min(out_count, buf->len - buf->offset);
if (to_user) {
ssize_t ret;
ret = copy_to_user(out_buf, buf->buf + buf->offset, out_count);
if (ret)
return -EFAULT;
} else {
memcpy((__force char *)out_buf, buf->buf + buf->offset,
out_count);
}
buf->offset += out_count;
if (buf->offset == buf->len) {
/*
* We're done using all the data in this buffer.
* Re-queue so that the Host can send us more data.
*/
spin_lock_irqsave(&port->inbuf_lock, flags);
port->inbuf = NULL;
if (add_inbuf(port->in_vq, buf) < 0)
dev_warn(port->dev, "failed add_buf\n");
spin_unlock_irqrestore(&port->inbuf_lock, flags);
}
/* Return the number of bytes actually copied */
return out_count;
}
/* The condition that must be true for polling to end */
static bool will_read_block(struct port *port)
{
if (!port->guest_connected) {
/* Port got hot-unplugged. Let's exit. */
return false;
}
return !port_has_data(port) && port->host_connected;
}
static bool will_write_block(struct port *port)
{
bool ret;
if (!port->guest_connected) {
/* Port got hot-unplugged. Let's exit. */
return false;
}
if (!port->host_connected)
return true;
spin_lock_irq(&port->outvq_lock);
/*
* Check if the Host has consumed any buffers since we last
* sent data (this is only applicable for nonblocking ports).
*/
reclaim_consumed_buffers(port);
ret = port->outvq_full;
spin_unlock_irq(&port->outvq_lock);
return ret;
}
static ssize_t port_fops_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *offp)
{
struct port *port;
ssize_t ret;
port = filp->private_data;
/* Port is hot-unplugged. */
if (!port->guest_connected)
return -ENODEV;
if (!port_has_data(port)) {
/*
* If nothing's connected on the host just return 0 in
* case of list_empty; this tells the userspace app
* that there's no connection
*/
if (!port->host_connected)
return 0;
if (filp->f_flags & O_NONBLOCK)
return -EAGAIN;
ret = wait_event_freezable(port->waitqueue,
!will_read_block(port));
if (ret < 0)
return ret;
}
/* Port got hot-unplugged while we were waiting above. */
if (!port->guest_connected)
return -ENODEV;
/*
* We could've received a disconnection message while we were
* waiting for more data.
*
* This check is not clubbed in the if() statement above as we
* might receive some data as well as the host could get
* disconnected after we got woken up from our wait. So we
* really want to give off whatever data we have and only then
* check for host_connected.
*/
if (!port_has_data(port) && !port->host_connected)
return 0;
return fill_readbuf(port, ubuf, count, true);
}
static int wait_port_writable(struct port *port, bool nonblock)
{
int ret;
if (will_write_block(port)) {
if (nonblock)
return -EAGAIN;
ret = wait_event_freezable(port->waitqueue,
!will_write_block(port));
if (ret < 0)
return ret;
}
/* Port got hot-unplugged. */
if (!port->guest_connected)
return -ENODEV;
return 0;
}
static ssize_t port_fops_write(struct file *filp, const char __user *ubuf,
size_t count, loff_t *offp)
{
struct port *port;
struct port_buffer *buf;
ssize_t ret;
bool nonblock;
struct scatterlist sg[1];
/* Userspace could be out to fool us */
if (!count)
return 0;
port = filp->private_data;
nonblock = filp->f_flags & O_NONBLOCK;
ret = wait_port_writable(port, nonblock);
if (ret < 0)
return ret;
count = min((size_t)(32 * 1024), count);
buf = alloc_buf(port->out_vq, count, 0);
if (!buf)
return -ENOMEM;
ret = copy_from_user(buf->buf, ubuf, count);
if (ret) {
ret = -EFAULT;
goto free_buf;
}
/*
* We now ask send_buf() to not spin for generic ports -- we
* can re-use the same code path that non-blocking file
* descriptors take for blocking file descriptors since the
* wait is already done and we're certain the write will go
* through to the host.
*/
nonblock = true;
sg_init_one(sg, buf->buf, count);
ret = __send_to_port(port, sg, 1, count, buf, nonblock);
if (nonblock && ret > 0)
goto out;
free_buf:
free_buf(buf, true);
out:
return ret;
}
struct sg_list {
unsigned int n;
unsigned int size;
size_t len;
struct scatterlist *sg;
};
static int pipe_to_sg(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
struct splice_desc *sd)
{
struct sg_list *sgl = sd->u.data;
unsigned int offset, len;
if (sgl->n == sgl->size)
return 0;
/* Try lock this page */
if (pipe_buf_steal(pipe, buf) == 0) {
/* Get reference and unlock page for moving */
get_page(buf->page);
unlock_page(buf->page);
len = min(buf->len, sd->len);
sg_set_page(&(sgl->sg[sgl->n]), buf->page, len, buf->offset);
} else {
/* Failback to copying a page */
struct page *page = alloc_page(GFP_KERNEL);
char *src;
if (!page)
return -ENOMEM;
offset = sd->pos & ~PAGE_MASK;
len = sd->len;
if (len + offset > PAGE_SIZE)
len = PAGE_SIZE - offset;
src = kmap_atomic(buf->page);
memcpy(page_address(page) + offset, src + buf->offset, len);
kunmap_atomic(src);
sg_set_page(&(sgl->sg[sgl->n]), page, len, offset);
}
sgl->n++;
sgl->len += len;
return len;
}
/* Faster zero-copy write by splicing */
static ssize_t port_fops_splice_write(struct pipe_inode_info *pipe,
struct file *filp, loff_t *ppos,
size_t len, unsigned int flags)
{
struct port *port = filp->private_data;
struct sg_list sgl;
ssize_t ret;
struct port_buffer *buf;
struct splice_desc sd = {
.total_len = len,
.flags = flags,
.pos = *ppos,
.u.data = &sgl,
};
/*
* Rproc_serial does not yet support splice. To support splice
* pipe_to_sg() must allocate dma-buffers and copy content from
* regular pages to dma pages. And alloc_buf and free_buf must
* support allocating and freeing such a list of dma-buffers.
*/
if (is_rproc_serial(port->out_vq->vdev))
return -EINVAL;
/*
* pipe->nrbufs == 0 means there are no data to transfer,
* so this returns just 0 for no data.
*/
pipe_lock(pipe);
if (!pipe->nrbufs) {
ret = 0;
goto error_out;
}
ret = wait_port_writable(port, filp->f_flags & O_NONBLOCK);
if (ret < 0)
goto error_out;
buf = alloc_buf(port->out_vq, 0, pipe->nrbufs);
if (!buf) {
ret = -ENOMEM;
goto error_out;
}
sgl.n = 0;
sgl.len = 0;
sgl.size = pipe->nrbufs;
sgl.sg = buf->sg;
sg_init_table(sgl.sg, sgl.size);
ret = __splice_from_pipe(pipe, &sd, pipe_to_sg);
pipe_unlock(pipe);
if (likely(ret > 0))
ret = __send_to_port(port, buf->sg, sgl.n, sgl.len, buf, true);
if (unlikely(ret <= 0))
free_buf(buf, true);
return ret;
error_out:
pipe_unlock(pipe);
return ret;
}
static unsigned int port_fops_poll(struct file *filp, poll_table *wait)
{
struct port *port;
unsigned int ret;
port = filp->private_data;
poll_wait(filp, &port->waitqueue, wait);
if (!port->guest_connected) {
/* Port got unplugged */
return POLLHUP;
}
ret = 0;
if (!will_read_block(port))
ret |= POLLIN | POLLRDNORM;
if (!will_write_block(port))
ret |= POLLOUT;
if (!port->host_connected)
ret |= POLLHUP;
return ret;
}
static void remove_port(struct kref *kref);
static int port_fops_release(struct inode *inode, struct file *filp)
{
struct port *port;
port = filp->private_data;
/* Notify host of port being closed */
send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 0);
spin_lock_irq(&port->inbuf_lock);
port->guest_connected = false;
discard_port_data(port);
spin_unlock_irq(&port->inbuf_lock);
spin_lock_irq(&port->outvq_lock);
reclaim_consumed_buffers(port);
spin_unlock_irq(&port->outvq_lock);
reclaim_dma_bufs();
/*
* Locks aren't necessary here as a port can't be opened after
* unplug, and if a port isn't unplugged, a kref would already
* exist for the port. Plus, taking ports_lock here would
* create a dependency on other locks taken by functions
* inside remove_port if we're the last holder of the port,
* creating many problems.
*/
kref_put(&port->kref, remove_port);
return 0;
}
static int port_fops_open(struct inode *inode, struct file *filp)
{
struct cdev *cdev = inode->i_cdev;
struct port *port;
int ret;
/* We get the port with a kref here */
port = find_port_by_devt(cdev->dev);
if (!port) {
/* Port was unplugged before we could proceed */
return -ENXIO;
}
filp->private_data = port;
/*
* Don't allow opening of console port devices -- that's done
* via /dev/hvc
*/
if (is_console_port(port)) {
ret = -ENXIO;
goto out;
}
/* Allow only one process to open a particular port at a time */
spin_lock_irq(&port->inbuf_lock);
if (port->guest_connected) {
spin_unlock_irq(&port->inbuf_lock);
ret = -EBUSY;
goto out;
}
port->guest_connected = true;
spin_unlock_irq(&port->inbuf_lock);
spin_lock_irq(&port->outvq_lock);
/*
* There might be a chance that we missed reclaiming a few
* buffers in the window of the port getting previously closed
* and opening now.
*/
reclaim_consumed_buffers(port);
spin_unlock_irq(&port->outvq_lock);
nonseekable_open(inode, filp);
/* Notify host of port being opened */
send_control_msg(filp->private_data, VIRTIO_CONSOLE_PORT_OPEN, 1);
return 0;
out:
kref_put(&port->kref, remove_port);
return ret;
}
static int port_fops_fasync(int fd, struct file *filp, int mode)
{
struct port *port;
port = filp->private_data;
return fasync_helper(fd, filp, mode, &port->async_queue);
}
/*
* The file operations that we support: programs in the guest can open
* a console device, read from it, write to it, poll for data and
* close it. The devices are at
* /dev/vport<device number>p<port number>
*/
static const struct file_operations port_fops = {
.owner = THIS_MODULE,
.open = port_fops_open,
.read = port_fops_read,
.write = port_fops_write,
.splice_write = port_fops_splice_write,
.poll = port_fops_poll,
.release = port_fops_release,
.fasync = port_fops_fasync,
.llseek = no_llseek,
};
/*
* The put_chars() callback is pretty straightforward.
*
* We turn the characters into a scatter-gather list, add it to the
* output queue and then kick the Host. Then we sit here waiting for
* it to finish: inefficient in theory, but in practice
* implementations will do it immediately (lguest's Launcher does).
*/
static int put_chars(u32 vtermno, const char *buf, int count)
{
struct port *port;
struct scatterlist sg[1];
void *data;
int ret;
if (unlikely(early_put_chars))
return early_put_chars(vtermno, buf, count);
port = find_port_by_vtermno(vtermno);
if (!port)
return -EPIPE;
data = kmemdup(buf, count, GFP_ATOMIC);
if (!data)
return -ENOMEM;
sg_init_one(sg, data, count);
ret = __send_to_port(port, sg, 1, count, data, false);
kfree(data);
return ret;
}
/*
* get_chars() is the callback from the hvc_console infrastructure
* when an interrupt is received.
*
* We call out to fill_readbuf that gets us the required data from the
* buffers that are queued up.
*/
static int get_chars(u32 vtermno, char *buf, int count)
{
struct port *port;
/* If we've not set up the port yet, we have no input to give. */
if (unlikely(early_put_chars))
return 0;
port = find_port_by_vtermno(vtermno);
if (!port)
return -EPIPE;
/* If we don't have an input queue yet, we can't get input. */
BUG_ON(!port->in_vq);
return fill_readbuf(port, (__force char __user *)buf, count, false);
}
static void resize_console(struct port *port)
{
struct virtio_device *vdev;
/* The port could have been hot-unplugged */
if (!port || !is_console_port(port))
return;
vdev = port->portdev->vdev;
/* Don't test F_SIZE at all if we're rproc: not a valid feature! */
if (!is_rproc_serial(vdev) &&
virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE))
hvc_resize(port->cons.hvc, port->cons.ws);
}
/* We set the configuration at this point, since we now have a tty */
static int notifier_add_vio(struct hvc_struct *hp, int data)
{
struct port *port;
port = find_port_by_vtermno(hp->vtermno);
if (!port)
return -EINVAL;
hp->irq_requested = 1;
resize_console(port);
return 0;
}
static void notifier_del_vio(struct hvc_struct *hp, int data)
{
hp->irq_requested = 0;
}
/* The operations for console ports. */
static const struct hv_ops hv_ops = {
.get_chars = get_chars,
.put_chars = put_chars,
.notifier_add = notifier_add_vio,
.notifier_del = notifier_del_vio,
.notifier_hangup = notifier_del_vio,
};
/*
* Console drivers are initialized very early so boot messages can go
* out, so we do things slightly differently from the generic virtio
* initialization of the net and block drivers.
*
* At this stage, the console is output-only. It's too early to set
* up a virtqueue, so we let the drivers do some boutique early-output
* thing.
*/
int __init virtio_cons_early_init(int (*put_chars)(u32, const char *, int))
{
early_put_chars = put_chars;
return hvc_instantiate(0, 0, &hv_ops);
}
static int init_port_console(struct port *port)
{
int ret;
/*
* The Host's telling us this port is a console port. Hook it
* up with an hvc console.
*
* To set up and manage our virtual console, we call
* hvc_alloc().
*
* The first argument of hvc_alloc() is the virtual console
* number. The second argument is the parameter for the
* notification mechanism (like irq number). We currently
* leave this as zero, virtqueues have implicit notifications.
*
* The third argument is a "struct hv_ops" containing the
* put_chars() get_chars(), notifier_add() and notifier_del()
* pointers. The final argument is the output buffer size: we
* can do any size, so we put PAGE_SIZE here.
*/
port->cons.vtermno = pdrvdata.next_vtermno;
port->cons.hvc = hvc_alloc(port->cons.vtermno, 0, &hv_ops, PAGE_SIZE);
if (IS_ERR(port->cons.hvc)) {
ret = PTR_ERR(port->cons.hvc);
dev_err(port->dev,
"error %d allocating hvc for port\n", ret);
port->cons.hvc = NULL;
return ret;
}
spin_lock_irq(&pdrvdata_lock);
pdrvdata.next_vtermno++;
list_add_tail(&port->cons.list, &pdrvdata.consoles);
spin_unlock_irq(&pdrvdata_lock);
port->guest_connected = true;
/*
* Start using the new console output if this is the first
* console to come up.
*/
if (early_put_chars)
early_put_chars = NULL;
/* Notify host of port being opened */
send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
return 0;
}
static ssize_t show_port_name(struct device *dev,
struct device_attribute *attr, char *buffer)
{
struct port *port;
port = dev_get_drvdata(dev);
return sprintf(buffer, "%s\n", port->name);
}
static DEVICE_ATTR(name, S_IRUGO, show_port_name, NULL);
static struct attribute *port_sysfs_entries[] = {
&dev_attr_name.attr,
NULL
};
static struct attribute_group port_attribute_group = {
.name = NULL, /* put in device directory */
.attrs = port_sysfs_entries,
};
static ssize_t debugfs_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *offp)
{
struct port *port;
char *buf;
ssize_t ret, out_offset, out_count;
out_count = 1024;
buf = kmalloc(out_count, GFP_KERNEL);
if (!buf)
return -ENOMEM;
port = filp->private_data;
out_offset = 0;
out_offset += snprintf(buf + out_offset, out_count,
"name: %s\n", port->name ? port->name : "");
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"guest_connected: %d\n", port->guest_connected);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"host_connected: %d\n", port->host_connected);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"outvq_full: %d\n", port->outvq_full);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"bytes_sent: %lu\n", port->stats.bytes_sent);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"bytes_received: %lu\n",
port->stats.bytes_received);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"bytes_discarded: %lu\n",
port->stats.bytes_discarded);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"is_console: %s\n",
is_console_port(port) ? "yes" : "no");
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"console_vtermno: %u\n", port->cons.vtermno);
ret = simple_read_from_buffer(ubuf, count, offp, buf, out_offset);
kfree(buf);
return ret;
}
static const struct file_operations port_debugfs_ops = {
.owner = THIS_MODULE,
.open = simple_open,
.read = debugfs_read,
};
static void set_console_size(struct port *port, u16 rows, u16 cols)
{
if (!port || !is_console_port(port))
return;
port->cons.ws.ws_row = rows;
port->cons.ws.ws_col = cols;
}
static unsigned int fill_queue(struct virtqueue *vq, spinlock_t *lock)
{
struct port_buffer *buf;
unsigned int nr_added_bufs;
int ret;
nr_added_bufs = 0;
do {
buf = alloc_buf(vq, PAGE_SIZE, 0);
if (!buf)
break;
spin_lock_irq(lock);
ret = add_inbuf(vq, buf);
if (ret < 0) {
spin_unlock_irq(lock);
free_buf(buf, true);
break;
}
nr_added_bufs++;
spin_unlock_irq(lock);
} while (ret > 0);
return nr_added_bufs;
}
static void send_sigio_to_port(struct port *port)
{
if (port->async_queue && port->guest_connected)
kill_fasync(&port->async_queue, SIGIO, POLL_OUT);
}
static int add_port(struct ports_device *portdev, u32 id)
{
char debugfs_name[16];
struct port *port;
struct port_buffer *buf;
dev_t devt;
unsigned int nr_added_bufs;
int err;
port = kmalloc(sizeof(*port), GFP_KERNEL);
if (!port) {
err = -ENOMEM;
goto fail;
}
kref_init(&port->kref);
port->portdev = portdev;
port->id = id;
port->name = NULL;
port->inbuf = NULL;
port->cons.hvc = NULL;
port->async_queue = NULL;
port->cons.ws.ws_row = port->cons.ws.ws_col = 0;
port->host_connected = port->guest_connected = false;
port->stats = (struct port_stats) { 0 };
port->outvq_full = false;
port->in_vq = portdev->in_vqs[port->id];
port->out_vq = portdev->out_vqs[port->id];
port->cdev = cdev_alloc();
if (!port->cdev) {
dev_err(&port->portdev->vdev->dev, "Error allocating cdev\n");
err = -ENOMEM;
goto free_port;
}
port->cdev->ops = &port_fops;
devt = MKDEV(portdev->chr_major, id);
err = cdev_add(port->cdev, devt, 1);
if (err < 0) {
dev_err(&port->portdev->vdev->dev,
"Error %d adding cdev for port %u\n", err, id);
goto free_cdev;
}
port->dev = device_create(pdrvdata.class, &port->portdev->vdev->dev,
devt, port, "vport%up%u",
port->portdev->vdev->index, id);
if (IS_ERR(port->dev)) {
err = PTR_ERR(port->dev);
dev_err(&port->portdev->vdev->dev,
"Error %d creating device for port %u\n",
err, id);
goto free_cdev;
}
spin_lock_init(&port->inbuf_lock);
spin_lock_init(&port->outvq_lock);
init_waitqueue_head(&port->waitqueue);
/* Fill the in_vq with buffers so the host can send us data. */
nr_added_bufs = fill_queue(port->in_vq, &port->inbuf_lock);
if (!nr_added_bufs) {
dev_err(port->dev, "Error allocating inbufs\n");
err = -ENOMEM;
goto free_device;
}
if (is_rproc_serial(port->portdev->vdev))
/*
* For rproc_serial assume remote processor is connected.
* rproc_serial does not want the console port, only
* the generic port implementation.
*/
port->host_connected = true;
else if (!use_multiport(port->portdev)) {
/*
* If we're not using multiport support,
* this has to be a console port.
*/
err = init_port_console(port);
if (err)
goto free_inbufs;
}
spin_lock_irq(&portdev->ports_lock);
list_add_tail(&port->list, &port->portdev->ports);
spin_unlock_irq(&portdev->ports_lock);
/*
* Tell the Host we're set so that it can send us various
* configuration parameters for this port (eg, port name,
* caching, whether this is a console port, etc.)
*/
send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
if (pdrvdata.debugfs_dir) {
/*
* Finally, create the debugfs file that we can use to
* inspect a port's state at any time
*/
snprintf(debugfs_name, sizeof(debugfs_name), "vport%up%u",
port->portdev->vdev->index, id);
port->debugfs_file = debugfs_create_file(debugfs_name, 0444,
pdrvdata.debugfs_dir,
port,
&port_debugfs_ops);
}
return 0;
free_inbufs:
while ((buf = virtqueue_detach_unused_buf(port->in_vq)))
free_buf(buf, true);
free_device:
device_destroy(pdrvdata.class, port->dev->devt);
free_cdev:
cdev_del(port->cdev);
free_port:
kfree(port);
fail:
/* The host might want to notify management sw about port add failure */
__send_control_msg(portdev, id, VIRTIO_CONSOLE_PORT_READY, 0);
return err;
}
/* No users remain, remove all port-specific data. */
static void remove_port(struct kref *kref)
{
struct port *port;
port = container_of(kref, struct port, kref);
kfree(port);
}
static void remove_port_data(struct port *port)
{
struct port_buffer *buf;
spin_lock_irq(&port->inbuf_lock);
/* Remove unused data this port might have received. */
discard_port_data(port);
spin_unlock_irq(&port->inbuf_lock);
/* Remove buffers we queued up for the Host to send us data in. */
do {
spin_lock_irq(&port->inbuf_lock);
buf = virtqueue_detach_unused_buf(port->in_vq);
spin_unlock_irq(&port->inbuf_lock);
if (buf)
free_buf(buf, true);
} while (buf);
spin_lock_irq(&port->outvq_lock);
reclaim_consumed_buffers(port);
spin_unlock_irq(&port->outvq_lock);
/* Free pending buffers from the out-queue. */
do {
spin_lock_irq(&port->outvq_lock);
buf = virtqueue_detach_unused_buf(port->out_vq);
spin_unlock_irq(&port->outvq_lock);
if (buf)
free_buf(buf, true);
} while (buf);
}
/*
* Port got unplugged. Remove port from portdev's list and drop the
* kref reference. If no userspace has this port opened, it will
* result in immediate removal the port.
*/
static void unplug_port(struct port *port)
{
spin_lock_irq(&port->portdev->ports_lock);
list_del(&port->list);
spin_unlock_irq(&port->portdev->ports_lock);
spin_lock_irq(&port->inbuf_lock);
if (port->guest_connected) {
/* Let the app know the port is going down. */
send_sigio_to_port(port);
/* Do this after sigio is actually sent */
port->guest_connected = false;
port->host_connected = false;
wake_up_interruptible(&port->waitqueue);
}
spin_unlock_irq(&port->inbuf_lock);
if (is_console_port(port)) {
spin_lock_irq(&pdrvdata_lock);
list_del(&port->cons.list);
spin_unlock_irq(&pdrvdata_lock);
hvc_remove(port->cons.hvc);
}
remove_port_data(port);
/*
* We should just assume the device itself has gone off --
* else a close on an open port later will try to send out a
* control message.
*/
port->portdev = NULL;
sysfs_remove_group(&port->dev->kobj, &port_attribute_group);
device_destroy(pdrvdata.class, port->dev->devt);
cdev_del(port->cdev);
debugfs_remove(port->debugfs_file);
kfree(port->name);
/*
* Locks around here are not necessary - a port can't be
* opened after we removed the port struct from ports_list
* above.
*/
kref_put(&port->kref, remove_port);
}
/* Any private messages that the Host and Guest want to share */
static void handle_control_message(struct virtio_device *vdev,
struct ports_device *portdev,
struct port_buffer *buf)
{
struct virtio_console_control *cpkt;
struct port *port;
size_t name_size;
int err;
cpkt = (struct virtio_console_control *)(buf->buf + buf->offset);
port = find_port_by_id(portdev, virtio32_to_cpu(vdev, cpkt->id));
if (!port &&
cpkt->event != cpu_to_virtio16(vdev, VIRTIO_CONSOLE_PORT_ADD)) {
/* No valid header at start of buffer. Drop it. */
dev_dbg(&portdev->vdev->dev,
"Invalid index %u in control packet\n", cpkt->id);
return;
}
switch (virtio16_to_cpu(vdev, cpkt->event)) {
case VIRTIO_CONSOLE_PORT_ADD:
if (port) {
dev_dbg(&portdev->vdev->dev,
"Port %u already added\n", port->id);
send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
break;
}
if (virtio32_to_cpu(vdev, cpkt->id) >=
portdev->max_nr_ports) {
dev_warn(&portdev->vdev->dev,
"Request for adding port with "
"out-of-bound id %u, max. supported id: %u\n",
cpkt->id, portdev->max_nr_ports - 1);
break;
}
add_port(portdev, virtio32_to_cpu(vdev, cpkt->id));
break;
case VIRTIO_CONSOLE_PORT_REMOVE:
unplug_port(port);
break;
case VIRTIO_CONSOLE_CONSOLE_PORT:
if (!cpkt->value)
break;
if (is_console_port(port))
break;
init_port_console(port);
complete(&early_console_added);
/*
* Could remove the port here in case init fails - but
* have to notify the host first.
*/
break;
case VIRTIO_CONSOLE_RESIZE: {
struct {
__u16 rows;
__u16 cols;
} size;
if (!is_console_port(port))
break;
memcpy(&size, buf->buf + buf->offset + sizeof(*cpkt),
sizeof(size));
set_console_size(port, size.rows, size.cols);
port->cons.hvc->irq_requested = 1;
resize_console(port);
break;
}
case VIRTIO_CONSOLE_PORT_OPEN:
port->host_connected = virtio16_to_cpu(vdev, cpkt->value);
wake_up_interruptible(&port->waitqueue);
/*
* If the host port got closed and the host had any
* unconsumed buffers, we'll be able to reclaim them
* now.
*/
spin_lock_irq(&port->outvq_lock);
reclaim_consumed_buffers(port);
spin_unlock_irq(&port->outvq_lock);
/*
* If the guest is connected, it'll be interested in
* knowing the host connection state changed.
*/
spin_lock_irq(&port->inbuf_lock);
send_sigio_to_port(port);
spin_unlock_irq(&port->inbuf_lock);
break;
case VIRTIO_CONSOLE_PORT_NAME:
/*
* If we woke up after hibernation, we can get this
* again. Skip it in that case.
*/
if (port->name)
break;
/*
* Skip the size of the header and the cpkt to get the size
* of the name that was sent
*/
name_size = buf->len - buf->offset - sizeof(*cpkt) + 1;
port->name = kmalloc(name_size, GFP_KERNEL);
if (!port->name) {
dev_err(port->dev,
"Not enough space to store port name\n");
break;
}
strncpy(port->name, buf->buf + buf->offset + sizeof(*cpkt),
name_size - 1);
port->name[name_size - 1] = 0;
/*
* Since we only have one sysfs attribute, 'name',
* create it only if we have a name for the port.
*/
err = sysfs_create_group(&port->dev->kobj,
&port_attribute_group);
if (err) {
dev_err(port->dev,
"Error %d creating sysfs device attributes\n",
err);
} else {
/*
* Generate a udev event so that appropriate
* symlinks can be created based on udev
* rules.
*/
kobject_uevent(&port->dev->kobj, KOBJ_CHANGE);
}
break;
}
}
static void control_work_handler(struct work_struct *work)
{
struct ports_device *portdev;
struct virtqueue *vq;
struct port_buffer *buf;
unsigned int len;
portdev = container_of(work, struct ports_device, control_work);
vq = portdev->c_ivq;
spin_lock(&portdev->c_ivq_lock);
while ((buf = virtqueue_get_buf(vq, &len))) {
spin_unlock(&portdev->c_ivq_lock);
buf->len = len;
buf->offset = 0;
handle_control_message(vq->vdev, portdev, buf);
spin_lock(&portdev->c_ivq_lock);
if (add_inbuf(portdev->c_ivq, buf) < 0) {
dev_warn(&portdev->vdev->dev,
"Error adding buffer to queue\n");
free_buf(buf, false);
}
}
spin_unlock(&portdev->c_ivq_lock);
}
static void out_intr(struct virtqueue *vq)
{
struct port *port;
port = find_port_by_vq(vq->vdev->priv, vq);
if (!port)
return;
wake_up_interruptible(&port->waitqueue);
}
static void in_intr(struct virtqueue *vq)
{
struct port *port;
unsigned long flags;
port = find_port_by_vq(vq->vdev->priv, vq);
if (!port)
return;
spin_lock_irqsave(&port->inbuf_lock, flags);
port->inbuf = get_inbuf(port);
/*
* Normally the port should not accept data when the port is
* closed. For generic serial ports, the host won't (shouldn't)
* send data till the guest is connected. But this condition
* can be reached when a console port is not yet connected (no
* tty is spawned) and the other side sends out data over the
* vring, or when a remote devices start sending data before
* the ports are opened.
*
* A generic serial port will discard data if not connected,
* while console ports and rproc-serial ports accepts data at
* any time. rproc-serial is initiated with guest_connected to
* false because port_fops_open expects this. Console ports are
* hooked up with an HVC console and is initialized with
* guest_connected to true.
*/
if (!port->guest_connected && !is_rproc_serial(port->portdev->vdev))
discard_port_data(port);
/* Send a SIGIO indicating new data in case the process asked for it */
send_sigio_to_port(port);
spin_unlock_irqrestore(&port->inbuf_lock, flags);
wake_up_interruptible(&port->waitqueue);
if (is_console_port(port) && hvc_poll(port->cons.hvc))
hvc_kick();
}
static void control_intr(struct virtqueue *vq)
{
struct ports_device *portdev;
portdev = vq->vdev->priv;
schedule_work(&portdev->control_work);
}
static void config_intr(struct virtio_device *vdev)
{
struct ports_device *portdev;
portdev = vdev->priv;
if (!use_multiport(portdev))
schedule_work(&portdev->config_work);
}
static void config_work_handler(struct work_struct *work)
{
struct ports_device *portdev;
portdev = container_of(work, struct ports_device, config_work);
if (!use_multiport(portdev)) {
struct virtio_device *vdev;
struct port *port;
u16 rows, cols;
vdev = portdev->vdev;
virtio_cread(vdev, struct virtio_console_config, cols, &cols);
virtio_cread(vdev, struct virtio_console_config, rows, &rows);
port = find_port_by_id(portdev, 0);
set_console_size(port, rows, cols);
/*
* We'll use this way of resizing only for legacy
* support. For newer userspace
* (VIRTIO_CONSOLE_F_MULTPORT+), use control messages
* to indicate console size changes so that it can be
* done per-port.
*/
resize_console(port);
}
}
static int init_vqs(struct ports_device *portdev)
{
vq_callback_t **io_callbacks;
char **io_names;
struct virtqueue **vqs;
u32 i, j, nr_ports, nr_queues;
int err;
nr_ports = portdev->max_nr_ports;
nr_queues = use_multiport(portdev) ? (nr_ports + 1) * 2 : 2;
vqs = kmalloc(nr_queues * sizeof(struct virtqueue *), GFP_KERNEL);
io_callbacks = kmalloc(nr_queues * sizeof(vq_callback_t *), GFP_KERNEL);
io_names = kmalloc(nr_queues * sizeof(char *), GFP_KERNEL);
portdev->in_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
GFP_KERNEL);
portdev->out_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
GFP_KERNEL);
if (!vqs || !io_callbacks || !io_names || !portdev->in_vqs ||
!portdev->out_vqs) {
err = -ENOMEM;
goto free;
}
/*
* For backward compat (newer host but older guest), the host
* spawns a console port first and also inits the vqs for port
* 0 before others.
*/
j = 0;
io_callbacks[j] = in_intr;
io_callbacks[j + 1] = out_intr;
io_names[j] = "input";
io_names[j + 1] = "output";
j += 2;
if (use_multiport(portdev)) {
io_callbacks[j] = control_intr;
io_callbacks[j + 1] = NULL;
io_names[j] = "control-i";
io_names[j + 1] = "control-o";
for (i = 1; i < nr_ports; i++) {
j += 2;
io_callbacks[j] = in_intr;
io_callbacks[j + 1] = out_intr;
io_names[j] = "input";
io_names[j + 1] = "output";
}
}
/* Find the queues. */
err = portdev->vdev->config->find_vqs(portdev->vdev, nr_queues, vqs,
io_callbacks,
(const char **)io_names, NULL);
if (err)
goto free;
j = 0;
portdev->in_vqs[0] = vqs[0];
portdev->out_vqs[0] = vqs[1];
j += 2;
if (use_multiport(portdev)) {
portdev->c_ivq = vqs[j];
portdev->c_ovq = vqs[j + 1];
for (i = 1; i < nr_ports; i++) {
j += 2;
portdev->in_vqs[i] = vqs[j];
portdev->out_vqs[i] = vqs[j + 1];
}
}
kfree(io_names);
kfree(io_callbacks);
kfree(vqs);
return 0;
free:
kfree(portdev->out_vqs);
kfree(portdev->in_vqs);
kfree(io_names);
kfree(io_callbacks);
kfree(vqs);
return err;
}
static const struct file_operations portdev_fops = {
.owner = THIS_MODULE,
};
static void remove_vqs(struct ports_device *portdev)
{
portdev->vdev->config->del_vqs(portdev->vdev);
kfree(portdev->in_vqs);
kfree(portdev->out_vqs);
}
static void remove_controlq_data(struct ports_device *portdev)
{
struct port_buffer *buf;
unsigned int len;
if (!use_multiport(portdev))
return;
while ((buf = virtqueue_get_buf(portdev->c_ivq, &len)))
free_buf(buf, true);
while ((buf = virtqueue_detach_unused_buf(portdev->c_ivq)))
free_buf(buf, true);
}
/*
* Once we're further in boot, we get probed like any other virtio
* device.
*
* If the host also supports multiple console ports, we check the
* config space to see how many ports the host has spawned. We
* initialize each port found.
*/
static int virtcons_probe(struct virtio_device *vdev)
{
struct ports_device *portdev;
int err;
bool multiport;
bool early = early_put_chars != NULL;
/* We only need a config space if features are offered */
if (!vdev->config->get &&
(virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE)
|| virtio_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT))) {
dev_err(&vdev->dev, "%s failure: config access disabled\n",
__func__);
return -EINVAL;
}
/* Ensure to read early_put_chars now */
barrier();
portdev = kmalloc(sizeof(*portdev), GFP_KERNEL);
if (!portdev) {
err = -ENOMEM;
goto fail;
}
/* Attach this portdev to this virtio_device, and vice-versa. */
portdev->vdev = vdev;
vdev->priv = portdev;
portdev->chr_major = register_chrdev(0, "virtio-portsdev",
&portdev_fops);
if (portdev->chr_major < 0) {
dev_err(&vdev->dev,
"Error %d registering chrdev for device %u\n",
portdev->chr_major, vdev->index);
err = portdev->chr_major;
goto free;
}
multiport = false;
portdev->max_nr_ports = 1;
/* Don't test MULTIPORT at all if we're rproc: not a valid feature! */
if (!is_rproc_serial(vdev) &&
virtio_cread_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT,
struct virtio_console_config, max_nr_ports,
&portdev->max_nr_ports) == 0) {
multiport = true;
}
err = init_vqs(portdev);
if (err < 0) {
dev_err(&vdev->dev, "Error %d initializing vqs\n", err);
goto free_chrdev;
}
spin_lock_init(&portdev->ports_lock);
INIT_LIST_HEAD(&portdev->ports);
virtio_device_ready(portdev->vdev);
INIT_WORK(&portdev->config_work, &config_work_handler);
INIT_WORK(&portdev->control_work, &control_work_handler);
if (multiport) {
unsigned int nr_added_bufs;
spin_lock_init(&portdev->c_ivq_lock);
spin_lock_init(&portdev->c_ovq_lock);
nr_added_bufs = fill_queue(portdev->c_ivq,
&portdev->c_ivq_lock);
if (!nr_added_bufs) {
dev_err(&vdev->dev,
"Error allocating buffers for control queue\n");
err = -ENOMEM;
goto free_vqs;
}
} else {
/*
* For backward compatibility: Create a console port
* if we're running on older host.
*/
add_port(portdev, 0);
}
spin_lock_irq(&pdrvdata_lock);
list_add_tail(&portdev->list, &pdrvdata.portdevs);
spin_unlock_irq(&pdrvdata_lock);
__send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
VIRTIO_CONSOLE_DEVICE_READY, 1);
/*
* If there was an early virtio console, assume that there are no
* other consoles. We need to wait until the hvc_alloc matches the
* hvc_instantiate, otherwise tty_open will complain, resulting in
* a "Warning: unable to open an initial console" boot failure.
* Without multiport this is done in add_port above. With multiport
* this might take some host<->guest communication - thus we have to
* wait.
*/
if (multiport && early)
wait_for_completion(&early_console_added);
return 0;
free_vqs:
/* The host might want to notify mgmt sw about device add failure */
__send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
VIRTIO_CONSOLE_DEVICE_READY, 0);
remove_vqs(portdev);
free_chrdev:
unregister_chrdev(portdev->chr_major, "virtio-portsdev");
free:
kfree(portdev);
fail:
return err;
}
static void virtcons_remove(struct virtio_device *vdev)
{
struct ports_device *portdev;
struct port *port, *port2;
portdev = vdev->priv;
spin_lock_irq(&pdrvdata_lock);
list_del(&portdev->list);
spin_unlock_irq(&pdrvdata_lock);
/* Disable interrupts for vqs */
vdev->config->reset(vdev);
/* Finish up work that's lined up */
if (use_multiport(portdev))
cancel_work_sync(&portdev->control_work);
else
cancel_work_sync(&portdev->config_work);
list_for_each_entry_safe(port, port2, &portdev->ports, list)
unplug_port(port);
unregister_chrdev(portdev->chr_major, "virtio-portsdev");
/*
* When yanking out a device, we immediately lose the
* (device-side) queues. So there's no point in keeping the
* guest side around till we drop our final reference. This
* also means that any ports which are in an open state will
* have to just stop using the port, as the vqs are going
* away.
*/
remove_controlq_data(portdev);
remove_vqs(portdev);
kfree(portdev);
}
static struct virtio_device_id id_table[] = {
{ VIRTIO_ID_CONSOLE, VIRTIO_DEV_ANY_ID },
{ 0 },
};
static unsigned int features[] = {
VIRTIO_CONSOLE_F_SIZE,
VIRTIO_CONSOLE_F_MULTIPORT,
};
static struct virtio_device_id rproc_serial_id_table[] = {
#if IS_ENABLED(CONFIG_REMOTEPROC)
{ VIRTIO_ID_RPROC_SERIAL, VIRTIO_DEV_ANY_ID },
#endif
{ 0 },
};
static unsigned int rproc_serial_features[] = {
};
#ifdef CONFIG_PM_SLEEP
static int virtcons_freeze(struct virtio_device *vdev)
{
struct ports_device *portdev;
struct port *port;
portdev = vdev->priv;
vdev->config->reset(vdev);
virtqueue_disable_cb(portdev->c_ivq);
cancel_work_sync(&portdev->control_work);
cancel_work_sync(&portdev->config_work);
/*
* Once more: if control_work_handler() was running, it would
* enable the cb as the last step.
*/
virtqueue_disable_cb(portdev->c_ivq);
remove_controlq_data(portdev);
list_for_each_entry(port, &portdev->ports, list) {
virtqueue_disable_cb(port->in_vq);
virtqueue_disable_cb(port->out_vq);
/*
* We'll ask the host later if the new invocation has
* the port opened or closed.
*/
port->host_connected = false;
remove_port_data(port);
}
remove_vqs(portdev);
return 0;
}
static int virtcons_restore(struct virtio_device *vdev)
{
struct ports_device *portdev;
struct port *port;
int ret;
portdev = vdev->priv;
ret = init_vqs(portdev);
if (ret)
return ret;
virtio_device_ready(portdev->vdev);
if (use_multiport(portdev))
fill_queue(portdev->c_ivq, &portdev->c_ivq_lock);
list_for_each_entry(port, &portdev->ports, list) {
port->in_vq = portdev->in_vqs[port->id];
port->out_vq = portdev->out_vqs[port->id];
fill_queue(port->in_vq, &port->inbuf_lock);
/* Get port open/close status on the host */
send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
/*
* If a port was open at the time of suspending, we
* have to let the host know that it's still open.
*/
if (port->guest_connected)
send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
}
return 0;
}
#endif
static struct virtio_driver virtio_console = {
.feature_table = features,
.feature_table_size = ARRAY_SIZE(features),
.driver.name = KBUILD_MODNAME,
.driver.owner = THIS_MODULE,
.id_table = id_table,
.probe = virtcons_probe,
.remove = virtcons_remove,
.config_changed = config_intr,
#ifdef CONFIG_PM_SLEEP
.freeze = virtcons_freeze,
.restore = virtcons_restore,
#endif
};
static struct virtio_driver virtio_rproc_serial = {
.feature_table = rproc_serial_features,
.feature_table_size = ARRAY_SIZE(rproc_serial_features),
.driver.name = "virtio_rproc_serial",
.driver.owner = THIS_MODULE,
.id_table = rproc_serial_id_table,
.probe = virtcons_probe,
.remove = virtcons_remove,
};
static int __init init(void)
{
int err;
pdrvdata.class = class_create(THIS_MODULE, "virtio-ports");
if (IS_ERR(pdrvdata.class)) {
err = PTR_ERR(pdrvdata.class);
pr_err("Error %d creating virtio-ports class\n", err);
return err;
}
pdrvdata.debugfs_dir = debugfs_create_dir("virtio-ports", NULL);
if (!pdrvdata.debugfs_dir)
pr_warning("Error creating debugfs dir for virtio-ports\n");
INIT_LIST_HEAD(&pdrvdata.consoles);
INIT_LIST_HEAD(&pdrvdata.portdevs);
err = register_virtio_driver(&virtio_console);
if (err < 0) {
pr_err("Error %d registering virtio driver\n", err);
goto free;
}
err = register_virtio_driver(&virtio_rproc_serial);
if (err < 0) {
pr_err("Error %d registering virtio rproc serial driver\n",
err);
goto unregister;
}
return 0;
unregister:
unregister_virtio_driver(&virtio_console);
free:
debugfs_remove_recursive(pdrvdata.debugfs_dir);
class_destroy(pdrvdata.class);
return err;
}
static void __exit fini(void)
{
reclaim_dma_bufs();
unregister_virtio_driver(&virtio_console);
unregister_virtio_driver(&virtio_rproc_serial);
class_destroy(pdrvdata.class);
debugfs_remove_recursive(pdrvdata.debugfs_dir);
}
module_init(init);
module_exit(fini);
MODULE_DEVICE_TABLE(virtio, id_table);
MODULE_DESCRIPTION("Virtio console driver");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3316_0 |
crossvul-cpp_data_bad_5824_0 | /*
* FFV1 decoder
*
* Copyright (c) 2003-2013 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* FF Video Codec 1 (a lossless codec) decoder
*/
#include "libavutil/avassert.h"
#include "libavutil/crc.h"
#include "libavutil/opt.h"
#include "libavutil/imgutils.h"
#include "libavutil/pixdesc.h"
#include "libavutil/timer.h"
#include "avcodec.h"
#include "internal.h"
#include "get_bits.h"
#include "rangecoder.h"
#include "golomb.h"
#include "mathops.h"
#include "ffv1.h"
static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state,
int is_signed)
{
if (get_rac(c, state + 0))
return 0;
else {
int i, e, a;
e = 0;
while (get_rac(c, state + 1 + FFMIN(e, 9))) // 1..10
e++;
a = 1;
for (i = e - 1; i >= 0; i--)
a += a + get_rac(c, state + 22 + FFMIN(i, 9)); // 22..31
e = -(is_signed && get_rac(c, state + 11 + FFMIN(e, 10))); // 11..21
return (a ^ e) - e;
}
}
static av_noinline int get_symbol(RangeCoder *c, uint8_t *state, int is_signed)
{
return get_symbol_inline(c, state, is_signed);
}
static inline int get_vlc_symbol(GetBitContext *gb, VlcState *const state,
int bits)
{
int k, i, v, ret;
i = state->count;
k = 0;
while (i < state->error_sum) { // FIXME: optimize
k++;
i += i;
}
v = get_sr_golomb(gb, k, 12, bits);
av_dlog(NULL, "v:%d bias:%d error:%d drift:%d count:%d k:%d",
v, state->bias, state->error_sum, state->drift, state->count, k);
#if 0 // JPEG LS
if (k == 0 && 2 * state->drift <= -state->count)
v ^= (-1);
#else
v ^= ((2 * state->drift + state->count) >> 31);
#endif
ret = fold(v + state->bias, bits);
update_vlc_state(state, v);
return ret;
}
static av_always_inline void decode_line(FFV1Context *s, int w,
int16_t *sample[2],
int plane_index, int bits)
{
PlaneContext *const p = &s->plane[plane_index];
RangeCoder *const c = &s->c;
int x;
int run_count = 0;
int run_mode = 0;
int run_index = s->run_index;
for (x = 0; x < w; x++) {
int diff, context, sign;
context = get_context(p, sample[1] + x, sample[0] + x, sample[1] + x);
if (context < 0) {
context = -context;
sign = 1;
} else
sign = 0;
av_assert2(context < p->context_count);
if (s->ac) {
diff = get_symbol_inline(c, p->state[context], 1);
} else {
if (context == 0 && run_mode == 0)
run_mode = 1;
if (run_mode) {
if (run_count == 0 && run_mode == 1) {
if (get_bits1(&s->gb)) {
run_count = 1 << ff_log2_run[run_index];
if (x + run_count <= w)
run_index++;
} else {
if (ff_log2_run[run_index])
run_count = get_bits(&s->gb, ff_log2_run[run_index]);
else
run_count = 0;
if (run_index)
run_index--;
run_mode = 2;
}
}
run_count--;
if (run_count < 0) {
run_mode = 0;
run_count = 0;
diff = get_vlc_symbol(&s->gb, &p->vlc_state[context],
bits);
if (diff >= 0)
diff++;
} else
diff = 0;
} else
diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
run_count, run_index, run_mode, x, get_bits_count(&s->gb));
}
if (sign)
diff = -diff;
sample[1][x] = (predict(sample[1] + x, sample[0] + x) + diff) &
((1 << bits) - 1);
}
s->run_index = run_index;
}
static void decode_plane(FFV1Context *s, uint8_t *src,
int w, int h, int stride, int plane_index)
{
int x, y;
int16_t *sample[2];
sample[0] = s->sample_buffer + 3;
sample[1] = s->sample_buffer + w + 6 + 3;
s->run_index = 0;
memset(s->sample_buffer, 0, 2 * (w + 6) * sizeof(*s->sample_buffer));
for (y = 0; y < h; y++) {
int16_t *temp = sample[0]; // FIXME: try a normal buffer
sample[0] = sample[1];
sample[1] = temp;
sample[1][-1] = sample[0][0];
sample[0][w] = sample[0][w - 1];
// { START_TIMER
if (s->avctx->bits_per_raw_sample <= 8) {
decode_line(s, w, sample, plane_index, 8);
for (x = 0; x < w; x++)
src[x + stride * y] = sample[1][x];
} else {
decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
if (s->packed_at_lsb) {
for (x = 0; x < w; x++) {
((uint16_t*)(src + stride*y))[x] = sample[1][x];
}
} else {
for (x = 0; x < w; x++) {
((uint16_t*)(src + stride*y))[x] = sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
}
}
}
// STOP_TIMER("decode-line") }
}
}
static void decode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])
{
int x, y, p;
int16_t *sample[4][2];
int lbd = s->avctx->bits_per_raw_sample <= 8;
int bits = s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
int offset = 1 << bits;
for (x = 0; x < 4; x++) {
sample[x][0] = s->sample_buffer + x * 2 * (w + 6) + 3;
sample[x][1] = s->sample_buffer + (x * 2 + 1) * (w + 6) + 3;
}
s->run_index = 0;
memset(s->sample_buffer, 0, 8 * (w + 6) * sizeof(*s->sample_buffer));
for (y = 0; y < h; y++) {
for (p = 0; p < 3 + s->transparency; p++) {
int16_t *temp = sample[p][0]; // FIXME: try a normal buffer
sample[p][0] = sample[p][1];
sample[p][1] = temp;
sample[p][1][-1]= sample[p][0][0 ];
sample[p][0][ w]= sample[p][0][w-1];
if (lbd)
decode_line(s, w, sample[p], (p + 1)/2, 9);
else
decode_line(s, w, sample[p], (p + 1)/2, bits + 1);
}
for (x = 0; x < w; x++) {
int g = sample[0][1][x];
int b = sample[1][1][x];
int r = sample[2][1][x];
int a = sample[3][1][x];
b -= offset;
r -= offset;
g -= (b + r) >> 2;
b += g;
r += g;
if (lbd)
*((uint32_t*)(src[0] + x*4 + stride[0]*y)) = b + (g<<8) + (r<<16) + (a<<24);
else {
*((uint16_t*)(src[0] + x*2 + stride[0]*y)) = b;
*((uint16_t*)(src[1] + x*2 + stride[1]*y)) = g;
*((uint16_t*)(src[2] + x*2 + stride[2]*y)) = r;
}
}
}
}
static int decode_slice_header(FFV1Context *f, FFV1Context *fs)
{
RangeCoder *c = &fs->c;
uint8_t state[CONTEXT_SIZE];
unsigned ps, i, context_count;
memset(state, 128, sizeof(state));
av_assert0(f->version > 2);
fs->slice_x = get_symbol(c, state, 0) * f->width ;
fs->slice_y = get_symbol(c, state, 0) * f->height;
fs->slice_width = (get_symbol(c, state, 0) + 1) * f->width + fs->slice_x;
fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
fs->slice_x /= f->num_h_slices;
fs->slice_y /= f->num_v_slices;
fs->slice_width = fs->slice_width /f->num_h_slices - fs->slice_x;
fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y;
if ((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height)
return -1;
if ( (unsigned)fs->slice_x + (uint64_t)fs->slice_width > f->width
|| (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
return -1;
for (i = 0; i < f->plane_count; i++) {
PlaneContext * const p = &fs->plane[i];
int idx = get_symbol(c, state, 0);
if (idx > (unsigned)f->quant_table_count) {
av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");
return -1;
}
p->quant_table_index = idx;
memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));
context_count = f->context_count[idx];
if (p->context_count < context_count) {
av_freep(&p->state);
av_freep(&p->vlc_state);
}
p->context_count = context_count;
}
ps = get_symbol(c, state, 0);
if (ps == 1) {
f->cur->interlaced_frame = 1;
f->cur->top_field_first = 1;
} else if (ps == 2) {
f->cur->interlaced_frame = 1;
f->cur->top_field_first = 0;
} else if (ps == 3) {
f->cur->interlaced_frame = 0;
}
f->cur->sample_aspect_ratio.num = get_symbol(c, state, 0);
f->cur->sample_aspect_ratio.den = get_symbol(c, state, 0);
return 0;
}
static int decode_slice(AVCodecContext *c, void *arg)
{
FFV1Context *fs = *(void **)arg;
FFV1Context *f = fs->avctx->priv_data;
int width, height, x, y, ret;
const int ps = av_pix_fmt_desc_get(c->pix_fmt)->comp[0].step_minus1 + 1;
AVFrame * const p = f->cur;
int i, si;
for( si=0; fs != f->slice_context[si]; si ++)
;
if(f->fsrc && !p->key_frame)
ff_thread_await_progress(&f->last_picture, si, 0);
if(f->fsrc && !p->key_frame) {
FFV1Context *fssrc = f->fsrc->slice_context[si];
FFV1Context *fsdst = f->slice_context[si];
av_assert1(fsdst->plane_count == fssrc->plane_count);
av_assert1(fsdst == fs);
if (!p->key_frame)
fsdst->slice_damaged |= fssrc->slice_damaged;
for (i = 0; i < f->plane_count; i++) {
PlaneContext *psrc = &fssrc->plane[i];
PlaneContext *pdst = &fsdst->plane[i];
av_free(pdst->state);
av_free(pdst->vlc_state);
memcpy(pdst, psrc, sizeof(*pdst));
pdst->state = NULL;
pdst->vlc_state = NULL;
if (fssrc->ac) {
pdst->state = av_malloc(CONTEXT_SIZE * psrc->context_count);
memcpy(pdst->state, psrc->state, CONTEXT_SIZE * psrc->context_count);
} else {
pdst->vlc_state = av_malloc(sizeof(*pdst->vlc_state) * psrc->context_count);
memcpy(pdst->vlc_state, psrc->vlc_state, sizeof(*pdst->vlc_state) * psrc->context_count);
}
}
}
if (f->version > 2) {
if (ffv1_init_slice_state(f, fs) < 0)
return AVERROR(ENOMEM);
if (decode_slice_header(f, fs) < 0) {
fs->slice_damaged = 1;
return AVERROR_INVALIDDATA;
}
}
if ((ret = ffv1_init_slice_state(f, fs)) < 0)
return ret;
if (f->cur->key_frame)
ffv1_clear_slice_state(f, fs);
width = fs->slice_width;
height = fs->slice_height;
x = fs->slice_x;
y = fs->slice_y;
if (!fs->ac) {
if (f->version == 3 && f->micro_version > 1 || f->version > 3)
get_rac(&fs->c, (uint8_t[]) { 129 });
fs->ac_byte_count = f->version > 2 || (!x && !y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;
init_get_bits(&fs->gb,
fs->c.bytestream_start + fs->ac_byte_count,
(fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8);
}
av_assert1(width && height);
if (f->colorspace == 0) {
const int chroma_width = FF_CEIL_RSHIFT(width, f->chroma_h_shift);
const int chroma_height = FF_CEIL_RSHIFT(height, f->chroma_v_shift);
const int cx = x >> f->chroma_h_shift;
const int cy = y >> f->chroma_v_shift;
decode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
if (f->chroma_planes) {
decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
}
if (fs->transparency)
decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
} else {
uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0],
p->data[1] + ps * x + y * p->linesize[1],
p->data[2] + ps * x + y * p->linesize[2] };
decode_rgb_frame(fs, planes, width, height, p->linesize);
}
if (fs->ac && f->version > 2) {
int v;
get_rac(&fs->c, (uint8_t[]) { 129 });
v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5*f->ec;
if (v) {
av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n", v);
fs->slice_damaged = 1;
}
}
emms_c();
ff_thread_report_progress(&f->picture, si, 0);
return 0;
}
static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale)
{
int v;
int i = 0;
uint8_t state[CONTEXT_SIZE];
memset(state, 128, sizeof(state));
for (v = 0; i < 128; v++) {
unsigned len = get_symbol(c, state, 0) + 1;
if (len > 128 - i)
return AVERROR_INVALIDDATA;
while (len--) {
quant_table[i] = scale * v;
i++;
}
}
for (i = 1; i < 128; i++)
quant_table[256 - i] = -quant_table[i];
quant_table[128] = -quant_table[127];
return 2 * v - 1;
}
static int read_quant_tables(RangeCoder *c,
int16_t quant_table[MAX_CONTEXT_INPUTS][256])
{
int i;
int context_count = 1;
for (i = 0; i < 5; i++) {
context_count *= read_quant_table(c, quant_table[i], context_count);
if (context_count > 32768U) {
return AVERROR_INVALIDDATA;
}
}
return (context_count + 1) / 2;
}
static int read_extra_header(FFV1Context *f)
{
RangeCoder *const c = &f->c;
uint8_t state[CONTEXT_SIZE];
int i, j, k, ret;
uint8_t state2[32][CONTEXT_SIZE];
memset(state2, 128, sizeof(state2));
memset(state, 128, sizeof(state));
ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);
ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
f->version = get_symbol(c, state, 0);
if (f->version < 2) {
av_log(f->avctx, AV_LOG_ERROR, "Invalid version in global header\n");
return AVERROR_INVALIDDATA;
}
if (f->version > 2) {
c->bytestream_end -= 4;
f->micro_version = get_symbol(c, state, 0);
}
f->ac = f->avctx->coder_type = get_symbol(c, state, 0);
if (f->ac > 1) {
for (i = 1; i < 256; i++)
f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
}
f->colorspace = get_symbol(c, state, 0); //YUV cs type
f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
f->chroma_planes = get_rac(c, state);
f->chroma_h_shift = get_symbol(c, state, 0);
f->chroma_v_shift = get_symbol(c, state, 0);
f->transparency = get_rac(c, state);
f->plane_count = 1 + (f->chroma_planes || f->version<4) + f->transparency;
f->num_h_slices = 1 + get_symbol(c, state, 0);
f->num_v_slices = 1 + get_symbol(c, state, 0);
if (f->num_h_slices > (unsigned)f->width || !f->num_h_slices ||
f->num_v_slices > (unsigned)f->height || !f->num_v_slices
) {
av_log(f->avctx, AV_LOG_ERROR, "slice count invalid\n");
return AVERROR_INVALIDDATA;
}
f->quant_table_count = get_symbol(c, state, 0);
if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
return AVERROR_INVALIDDATA;
for (i = 0; i < f->quant_table_count; i++) {
f->context_count[i] = read_quant_tables(c, f->quant_tables[i]);
if (f->context_count[i] < 0) {
av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
return AVERROR_INVALIDDATA;
}
}
if ((ret = ffv1_allocate_initial_states(f)) < 0)
return ret;
for (i = 0; i < f->quant_table_count; i++)
if (get_rac(c, state)) {
for (j = 0; j < f->context_count[i]; j++)
for (k = 0; k < CONTEXT_SIZE; k++) {
int pred = j ? f->initial_states[i][j - 1][k] : 128;
f->initial_states[i][j][k] =
(pred + get_symbol(c, state2[k], 1)) & 0xFF;
}
}
if (f->version > 2) {
f->ec = get_symbol(c, state, 0);
if (f->micro_version > 2)
f->intra = get_symbol(c, state, 0);
}
if (f->version > 2) {
unsigned v;
v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0,
f->avctx->extradata, f->avctx->extradata_size);
if (v) {
av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
return AVERROR_INVALIDDATA;
}
}
if (f->avctx->debug & FF_DEBUG_PICT_INFO)
av_log(f->avctx, AV_LOG_DEBUG,
"global: ver:%d.%d, coder:%d, colorspace: %d bpr:%d chroma:%d(%d:%d), alpha:%d slices:%dx%d qtabs:%d ec:%d intra:%d\n",
f->version, f->micro_version,
f->ac,
f->colorspace,
f->avctx->bits_per_raw_sample,
f->chroma_planes, f->chroma_h_shift, f->chroma_v_shift,
f->transparency,
f->num_h_slices, f->num_v_slices,
f->quant_table_count,
f->ec,
f->intra
);
return 0;
}
static int read_header(FFV1Context *f)
{
uint8_t state[CONTEXT_SIZE];
int i, j, context_count = -1; //-1 to avoid warning
RangeCoder *const c = &f->slice_context[0]->c;
memset(state, 128, sizeof(state));
if (f->version < 2) {
int chroma_planes, chroma_h_shift, chroma_v_shift, transparency;
unsigned v= get_symbol(c, state, 0);
if (v >= 2) {
av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v);
return AVERROR_INVALIDDATA;
}
f->version = v;
f->ac = f->avctx->coder_type = get_symbol(c, state, 0);
if (f->ac > 1) {
for (i = 1; i < 256; i++)
f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
}
f->colorspace = get_symbol(c, state, 0); //YUV cs type
if (f->version > 0)
f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
chroma_planes = get_rac(c, state);
chroma_h_shift = get_symbol(c, state, 0);
chroma_v_shift = get_symbol(c, state, 0);
transparency = get_rac(c, state);
if (f->plane_count) {
if ( chroma_planes != f->chroma_planes
|| chroma_h_shift!= f->chroma_h_shift
|| chroma_v_shift!= f->chroma_v_shift
|| transparency != f->transparency) {
av_log(f->avctx, AV_LOG_ERROR, "Invalid change of global parameters\n");
return AVERROR_INVALIDDATA;
}
}
f->chroma_planes = chroma_planes;
f->chroma_h_shift = chroma_h_shift;
f->chroma_v_shift = chroma_v_shift;
f->transparency = transparency;
f->plane_count = 2 + f->transparency;
}
if (f->colorspace == 0) {
if (!f->transparency && !f->chroma_planes) {
if (f->avctx->bits_per_raw_sample <= 8)
f->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
else
f->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
} else if (f->avctx->bits_per_raw_sample<=8 && !f->transparency) {
switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P; break;
case 0x01: f->avctx->pix_fmt = AV_PIX_FMT_YUV440P; break;
case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P; break;
case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P; break;
case 0x20: f->avctx->pix_fmt = AV_PIX_FMT_YUV411P; break;
case 0x22: f->avctx->pix_fmt = AV_PIX_FMT_YUV410P; break;
default:
av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
return AVERROR(ENOSYS);
}
} else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) {
switch(16*f->chroma_h_shift + f->chroma_v_shift) {
case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P; break;
case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P; break;
case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P; break;
default:
av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
return AVERROR(ENOSYS);
}
} else if (f->avctx->bits_per_raw_sample == 9) {
f->packed_at_lsb = 1;
switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9; break;
case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9; break;
case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9; break;
default:
av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
return AVERROR(ENOSYS);
}
} else if (f->avctx->bits_per_raw_sample == 10) {
f->packed_at_lsb = 1;
switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10; break;
case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10; break;
case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10; break;
default:
av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
return AVERROR(ENOSYS);
}
} else {
switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16; break;
case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16; break;
case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16; break;
default:
av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
return AVERROR(ENOSYS);
}
}
} else if (f->colorspace == 1) {
if (f->chroma_h_shift || f->chroma_v_shift) {
av_log(f->avctx, AV_LOG_ERROR,
"chroma subsampling not supported in this colorspace\n");
return AVERROR(ENOSYS);
}
if ( f->avctx->bits_per_raw_sample == 9)
f->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
else if (f->avctx->bits_per_raw_sample == 10)
f->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
else if (f->avctx->bits_per_raw_sample == 12)
f->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
else if (f->avctx->bits_per_raw_sample == 14)
f->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
else
if (f->transparency) f->avctx->pix_fmt = AV_PIX_FMT_RGB32;
else f->avctx->pix_fmt = AV_PIX_FMT_0RGB32;
} else {
av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
return AVERROR(ENOSYS);
}
av_dlog(f->avctx, "%d %d %d\n",
f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt);
if (f->version < 2) {
context_count = read_quant_tables(c, f->quant_table);
if (context_count < 0) {
av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
return AVERROR_INVALIDDATA;
}
} else if (f->version < 3) {
f->slice_count = get_symbol(c, state, 0);
} else {
const uint8_t *p = c->bytestream_end;
for (f->slice_count = 0;
f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start;
f->slice_count++) {
int trailer = 3 + 5*!!f->ec;
int size = AV_RB24(p-trailer);
if (size + trailer > p - c->bytestream_start)
break;
p -= size + trailer;
}
}
if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) {
av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count);
return AVERROR_INVALIDDATA;
}
for (j = 0; j < f->slice_count; j++) {
FFV1Context *fs = f->slice_context[j];
fs->ac = f->ac;
fs->packed_at_lsb = f->packed_at_lsb;
fs->slice_damaged = 0;
if (f->version == 2) {
fs->slice_x = get_symbol(c, state, 0) * f->width ;
fs->slice_y = get_symbol(c, state, 0) * f->height;
fs->slice_width = (get_symbol(c, state, 0) + 1) * f->width + fs->slice_x;
fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
fs->slice_x /= f->num_h_slices;
fs->slice_y /= f->num_v_slices;
fs->slice_width = fs->slice_width / f->num_h_slices - fs->slice_x;
fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y;
if ((unsigned)fs->slice_width > f->width ||
(unsigned)fs->slice_height > f->height)
return AVERROR_INVALIDDATA;
if ( (unsigned)fs->slice_x + (uint64_t)fs->slice_width > f->width
|| (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
return AVERROR_INVALIDDATA;
}
for (i = 0; i < f->plane_count; i++) {
PlaneContext *const p = &fs->plane[i];
if (f->version == 2) {
int idx = get_symbol(c, state, 0);
if (idx > (unsigned)f->quant_table_count) {
av_log(f->avctx, AV_LOG_ERROR,
"quant_table_index out of range\n");
return AVERROR_INVALIDDATA;
}
p->quant_table_index = idx;
memcpy(p->quant_table, f->quant_tables[idx],
sizeof(p->quant_table));
context_count = f->context_count[idx];
} else {
memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
}
if (f->version <= 2) {
av_assert0(context_count >= 0);
if (p->context_count < context_count) {
av_freep(&p->state);
av_freep(&p->vlc_state);
}
p->context_count = context_count;
}
}
}
return 0;
}
static av_cold int decode_init(AVCodecContext *avctx)
{
FFV1Context *f = avctx->priv_data;
int ret;
if ((ret = ffv1_common_init(avctx)) < 0)
return ret;
if (avctx->extradata && (ret = read_extra_header(f)) < 0)
return ret;
if ((ret = ffv1_init_slice_contexts(f)) < 0)
return ret;
avctx->internal->allocate_progress = 1;
return 0;
}
static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
FFV1Context *f = avctx->priv_data;
RangeCoder *const c = &f->slice_context[0]->c;
int i, ret;
uint8_t keystate = 128;
const uint8_t *buf_p;
AVFrame *p;
if (f->last_picture.f)
ff_thread_release_buffer(avctx, &f->last_picture);
FFSWAP(ThreadFrame, f->picture, f->last_picture);
f->cur = p = f->picture.f;
if (f->version < 3 && avctx->field_order > AV_FIELD_PROGRESSIVE) {
/* we have interlaced material flagged in container */
p->interlaced_frame = 1;
if (avctx->field_order == AV_FIELD_TT || avctx->field_order == AV_FIELD_TB)
p->top_field_first = 1;
}
f->avctx = avctx;
ff_init_range_decoder(c, buf, buf_size);
ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
p->pict_type = AV_PICTURE_TYPE_I; //FIXME I vs. P
if (get_rac(c, &keystate)) {
p->key_frame = 1;
f->key_frame_ok = 0;
if ((ret = read_header(f)) < 0)
return ret;
f->key_frame_ok = 1;
} else {
if (!f->key_frame_ok) {
av_log(avctx, AV_LOG_ERROR,
"Cannot decode non-keyframe without valid keyframe\n");
return AVERROR_INVALIDDATA;
}
p->key_frame = 0;
}
if ((ret = ff_thread_get_buffer(avctx, &f->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
return ret;
if (avctx->debug & FF_DEBUG_PICT_INFO)
av_log(avctx, AV_LOG_DEBUG, "ver:%d keyframe:%d coder:%d ec:%d slices:%d bps:%d\n",
f->version, p->key_frame, f->ac, f->ec, f->slice_count, f->avctx->bits_per_raw_sample);
ff_thread_finish_setup(avctx);
buf_p = buf + buf_size;
for (i = f->slice_count - 1; i >= 0; i--) {
FFV1Context *fs = f->slice_context[i];
int trailer = 3 + 5*!!f->ec;
int v;
if (i || f->version > 2) v = AV_RB24(buf_p-trailer) + trailer;
else v = buf_p - c->bytestream_start;
if (buf_p - c->bytestream_start < v) {
av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
return AVERROR_INVALIDDATA;
}
buf_p -= v;
if (f->ec) {
unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v);
if (crc) {
int64_t ts = avpkt->pts != AV_NOPTS_VALUE ? avpkt->pts : avpkt->dts;
av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!", crc);
if (ts != AV_NOPTS_VALUE && avctx->pkt_timebase.num) {
av_log(f->avctx, AV_LOG_ERROR, "at %f seconds\n", ts*av_q2d(avctx->pkt_timebase));
} else if (ts != AV_NOPTS_VALUE) {
av_log(f->avctx, AV_LOG_ERROR, "at %"PRId64"\n", ts);
} else {
av_log(f->avctx, AV_LOG_ERROR, "\n");
}
fs->slice_damaged = 1;
}
}
if (i) {
ff_init_range_decoder(&fs->c, buf_p, v);
} else
fs->c.bytestream_end = (uint8_t *)(buf_p + v);
fs->avctx = avctx;
fs->cur = p;
}
avctx->execute(avctx,
decode_slice,
&f->slice_context[0],
NULL,
f->slice_count,
sizeof(void*));
for (i = f->slice_count - 1; i >= 0; i--) {
FFV1Context *fs = f->slice_context[i];
int j;
if (fs->slice_damaged && f->last_picture.f->data[0]) {
const uint8_t *src[4];
uint8_t *dst[4];
ff_thread_await_progress(&f->last_picture, INT_MAX, 0);
for (j = 0; j < 4; j++) {
int sh = (j==1 || j==2) ? f->chroma_h_shift : 0;
int sv = (j==1 || j==2) ? f->chroma_v_shift : 0;
dst[j] = p->data[j] + p->linesize[j]*
(fs->slice_y>>sv) + (fs->slice_x>>sh);
src[j] = f->last_picture.f->data[j] + f->last_picture.f->linesize[j]*
(fs->slice_y>>sv) + (fs->slice_x>>sh);
}
av_image_copy(dst, p->linesize, (const uint8_t **)src,
f->last_picture.f->linesize,
avctx->pix_fmt,
fs->slice_width,
fs->slice_height);
}
}
ff_thread_report_progress(&f->picture, INT_MAX, 0);
f->picture_number++;
if (f->last_picture.f)
ff_thread_release_buffer(avctx, &f->last_picture);
f->cur = NULL;
if ((ret = av_frame_ref(data, f->picture.f)) < 0)
return ret;
*got_frame = 1;
return buf_size;
}
static int init_thread_copy(AVCodecContext *avctx)
{
FFV1Context *f = avctx->priv_data;
f->picture.f = NULL;
f->last_picture.f = NULL;
f->sample_buffer = NULL;
f->quant_table_count = 0;
f->slice_count = 0;
return 0;
}
static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
{
FFV1Context *fsrc = src->priv_data;
FFV1Context *fdst = dst->priv_data;
int i, ret;
if (dst == src)
return 0;
if (!fdst->picture.f) {
memcpy(fdst, fsrc, sizeof(*fdst));
for (i = 0; i < fdst->quant_table_count; i++) {
fdst->initial_states[i] = av_malloc(fdst->context_count[i] * sizeof(*fdst->initial_states[i]));
memcpy(fdst->initial_states[i], fsrc->initial_states[i], fdst->context_count[i] * sizeof(*fdst->initial_states[i]));
}
fdst->picture.f = av_frame_alloc();
fdst->last_picture.f = av_frame_alloc();
if ((ret = ffv1_init_slice_contexts(fdst)) < 0)
return ret;
}
av_assert1(fdst->slice_count == fsrc->slice_count);
fdst->key_frame_ok = fsrc->key_frame_ok;
ff_thread_release_buffer(dst, &fdst->picture);
if (fsrc->picture.f->data[0]) {
if ((ret = ff_thread_ref_frame(&fdst->picture, &fsrc->picture)) < 0)
return ret;
}
for (i = 0; i < fdst->slice_count; i++) {
FFV1Context *fsdst = fdst->slice_context[i];
FFV1Context *fssrc = fsrc->slice_context[i];
fsdst->slice_damaged = fssrc->slice_damaged;
}
fdst->fsrc = fsrc;
return 0;
}
AVCodec ff_ffv1_decoder = {
.name = "ffv1",
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_FFV1,
.priv_data_size = sizeof(FFV1Context),
.init = decode_init,
.close = ffv1_close,
.decode = decode_frame,
.init_thread_copy = ONLY_IF_THREADS_ENABLED(init_thread_copy),
.update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
.capabilities = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/ |
CODEC_CAP_FRAME_THREADS | CODEC_CAP_SLICE_THREADS,
.long_name = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5824_0 |
crossvul-cpp_data_good_341_5 | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Initially written by David Mattes <david.mattes@boeing.com> */
/* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "internal.h"
#include "pkcs15.h"
#define MANU_ID "Gemplus"
#define APPLET_NAME "GemSAFE V1"
#define DRIVER_SERIAL_NUMBER "v0.9"
#define GEMSAFE_APP_PATH "3F001600"
#define GEMSAFE_PATH "3F0016000004"
/* Apparently, the Applet max read "quanta" is 248 bytes
* Gemalto ClassicClient reads files in chunks of 238 bytes
*/
#define GEMSAFE_READ_QUANTUM 248
#define GEMSAFE_MAX_OBJLEN 28672
int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *);
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags);
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags);
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags);
typedef struct cdata_st {
char *label;
int authority;
const char *path;
size_t index;
size_t count;
const char *id;
int obj_flags;
} cdata;
const unsigned int gemsafe_cert_max = 12;
cdata gemsafe_cert[] = {
{"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE},
};
typedef struct pdata_st {
const u8 atr[SC_MAX_ATR_SIZE];
const size_t atr_len;
const char *id;
const char *label;
const char *path;
const int ref;
const int type;
const unsigned int maxlen;
const unsigned int minlen;
const int flags;
const int tries_left;
const char pad_char;
const int obj_flags;
} pindata;
const unsigned int gemsafe_pin_max = 2;
const pindata gemsafe_pin[] = {
/* ATR-specific PIN policies, first match found is used: */
{ {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65,
0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC,
8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE },
/* default PIN policy comes last: */
{ { 0 }, 0,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD,
16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }
};
typedef struct prdata_st {
const char *id;
char *label;
unsigned int modulus_len;
int usage;
const char *path;
int ref;
const char *auth_id;
int obj_flags;
} prdata;
#define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION
#define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP
#define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP | \
SC_PKCS15_PRKEY_USAGE_SIGN
prdata gemsafe_prkeys[] = {
{ "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE},
};
static int gemsafe_get_cert_len(sc_card_t *card)
{
int r;
u8 ibuf[GEMSAFE_MAX_OBJLEN];
u8 *iptr;
struct sc_path path;
struct sc_file *file;
size_t objlen, certlen;
unsigned int ind, i=0;
sc_format_path(GEMSAFE_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* Initial read */
r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0);
if (r < 0)
return SC_ERROR_INTERNAL;
/* Actual stored object size is encoded in first 2 bytes
* (allocated EF space is much greater!)
*/
objlen = (((size_t) ibuf[0]) << 8) | ibuf[1];
sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) {
sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
return SC_ERROR_INTERNAL;
}
/* It looks like the first thing in the block is a table of
* which keys are allocated. The table is small and is in the
* first 248 bytes. Example for a card with 10 key containers:
* 01 f0 00 03 03 b0 00 03 <= 1st key unallocated
* 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated
* 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated
* 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated
* 01 f0 00 07 03 b0 00 07 <= 5th key unallocated
* ...
* 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated
* For allocated keys, the fourth byte seems to indicate the
* default key and the fifth byte indicates the key_ref of
* the private key.
*/
ind = 2; /* skip length */
while (ibuf[ind] == 0x01 && i < gemsafe_cert_max) {
if (ibuf[ind+1] == 0xFE) {
gemsafe_prkeys[i].ref = ibuf[ind+4];
sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d",
i+1, gemsafe_prkeys[i].ref);
ind += 9;
}
else {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
sc_log(card->ctx, "Key container %d is unallocated", i+1);
ind += 8;
}
i++;
}
/* Delete additional key containers from the data structures if
* this card can't accommodate them.
*/
for (; i < gemsafe_cert_max; i++) {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
/* Read entire file, then dissect in memory.
* Gemalto ClassicClient seems to do it the same way.
*/
iptr = ibuf + GEMSAFE_READ_QUANTUM;
while ((size_t)(iptr - ibuf) < objlen) {
r = sc_read_binary(card, iptr - ibuf, iptr,
MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0);
if (r < 0) {
sc_log(card->ctx, "Could not read cert object");
return SC_ERROR_INTERNAL;
}
iptr += GEMSAFE_READ_QUANTUM;
}
/* Search buffer for certificates, they start with 0x3082. */
i = 0;
while (ind < objlen - 1) {
if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) {
/* Find next allocated key container */
while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL)
i++;
if (i == gemsafe_cert_max) {
sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind);
return SC_SUCCESS;
}
/* DER cert len is encoded this way */
if (ind+3 >= sizeof ibuf)
return SC_ERROR_INVALID_DATA;
certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4;
sc_log(card->ctx,
"Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u",
i+1, ind, certlen);
gemsafe_cert[i].index = ind;
gemsafe_cert[i].count = certlen;
ind += certlen;
i++;
} else
ind++;
}
/* Delete additional key containers from the data structures if
* they're missing on the card.
*/
for (; i < gemsafe_cert_max; i++) {
if (gemsafe_cert[i].label) {
sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1);
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
}
return SC_SUCCESS;
}
static int gemsafe_detect_card( sc_pkcs15_card_t *p15card)
{
if (strcmp(p15card->card->name, "GemSAFE V1"))
return SC_ERROR_WRONG_CARD;
return SC_SUCCESS;
}
static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card)
{
int r;
unsigned int i;
struct sc_path path;
struct sc_file *file = NULL;
struct sc_card *card = p15card->card;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_log(p15card->card->ctx, "Setting pkcs15 parameters");
if (p15card->tokeninfo->label)
free(p15card->tokeninfo->label);
p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1);
if (!p15card->tokeninfo->label)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->label, APPLET_NAME);
if (p15card->tokeninfo->serial_number)
free(p15card->tokeninfo->serial_number);
p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1);
if (!p15card->tokeninfo->serial_number)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER);
/* the GemSAFE applet version number */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
/* Manual says Le=0x05, but should be 0x08 to return full version number */
apdu.le = 0x08;
apdu.lc = 0;
apdu.datalen = 0;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return SC_ERROR_INTERNAL;
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* the manufacturer ID, in this case GemPlus */
if (p15card->tokeninfo->manufacturer_id)
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1);
if (!p15card->tokeninfo->manufacturer_id)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID);
/* determine allocated key containers and length of certificates */
r = gemsafe_get_cert_len(card);
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* set certs */
sc_log(p15card->card->ctx, "Setting certificates");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
if (gemsafe_cert[i].label == NULL)
continue;
sc_format_path(gemsafe_cert[i].path, &path);
sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id);
path.index = gemsafe_cert[i].index;
path.count = gemsafe_cert[i].count;
sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509,
gemsafe_cert[i].authority, &path, &p15Id,
gemsafe_cert[i].label, gemsafe_cert[i].obj_flags);
}
/* set gemsafe_pin */
sc_log(p15card->card->ctx, "Setting PIN");
for (i=0; i < gemsafe_pin_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id);
sc_format_path(gemsafe_pin[i].path, &path);
if (gemsafe_pin[i].atr_len == 0 ||
(gemsafe_pin[i].atr_len == p15card->card->atr.len &&
memcmp(p15card->card->atr.value, gemsafe_pin[i].atr,
p15card->card->atr.len) == 0)) {
sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label,
&path, gemsafe_pin[i].ref, gemsafe_pin[i].type,
gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen,
gemsafe_pin[i].flags, gemsafe_pin[i].tries_left,
gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags);
break;
}
};
/* set private keys */
sc_log(p15card->card->ctx, "Setting private keys");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id, authId, *pauthId;
struct sc_path path;
int key_ref = 0x03;
if (gemsafe_prkeys[i].label == NULL)
continue;
sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id);
if (gemsafe_prkeys[i].auth_id) {
sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId);
pauthId = &authId;
} else
pauthId = NULL;
sc_format_path(gemsafe_prkeys[i].path, &path);
/*
* The key ref may be different for different sites;
* by adding flags=n where the low order 4 bits can be
* the key ref we can force it.
*/
if ( p15card->card->flags & 0x0F) {
key_ref = p15card->card->flags & 0x0F;
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Overriding key_ref %d with %d\n",
gemsafe_prkeys[i].ref, key_ref);
} else
key_ref = gemsafe_prkeys[i].ref;
sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label,
SC_PKCS15_TYPE_PRKEY_RSA,
gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage,
&path, key_ref, pauthId,
gemsafe_prkeys[i].obj_flags);
}
/* select the application DF */
sc_log(p15card->card->ctx, "Selecting application DF");
sc_format_path(GEMSAFE_APP_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* set the application DF */
if (p15card->file_app)
free(p15card->file_app);
p15card->file_app = file;
return SC_SUCCESS;
}
int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)
return sc_pkcs15emu_gemsafeV1_init(p15card);
else {
int r = gemsafe_detect_card(p15card);
if (r)
return SC_ERROR_WRONG_CARD;
return sc_pkcs15emu_gemsafeV1_init(p15card);
}
}
static sc_pkcs15_df_t *
sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type)
{
sc_pkcs15_df_t *df;
sc_file_t *file;
int created = 0;
while (1) {
for (df = p15card->df_list; df; df = df->next) {
if (df->type == type) {
if (created)
df->enumerated = 1;
return df;
}
}
assert(created == 0);
file = sc_file_new();
if (!file)
return NULL;
sc_format_path("11001101", &file->path);
sc_pkcs15_add_df(p15card, type, &file->path);
sc_file_free(file);
created++;
}
}
static int
sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type,
const char *label, void *data,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_object_t *obj;
int df_type;
obj = calloc(1, sizeof(*obj));
obj->type = type;
obj->data = data;
if (label)
strncpy(obj->label, label, sizeof(obj->label)-1);
obj->flags = obj_flags;
if (auth_id)
obj->auth_id = *auth_id;
switch (type & SC_PKCS15_TYPE_CLASS_MASK) {
case SC_PKCS15_TYPE_AUTH:
df_type = SC_PKCS15_AODF;
break;
case SC_PKCS15_TYPE_PRKEY:
df_type = SC_PKCS15_PRKDF;
break;
case SC_PKCS15_TYPE_PUBKEY:
df_type = SC_PKCS15_PUKDF;
break;
case SC_PKCS15_TYPE_CERT:
df_type = SC_PKCS15_CDF;
break;
default:
sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type);
free(obj);
return SC_ERROR_INVALID_ARGUMENTS;
}
obj->df = sc_pkcs15emu_get_df(p15card, df_type);
sc_pkcs15_add_object(p15card, obj);
return 0;
}
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags)
{
sc_pkcs15_auth_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
info->auth_method = SC_AC_CHV;
info->auth_id = *id;
info->attrs.pin.min_length = min_length;
info->attrs.pin.max_length = max_length;
info->attrs.pin.stored_length = max_length;
info->attrs.pin.type = type;
info->attrs.pin.reference = ref;
info->attrs.pin.flags = flags;
info->attrs.pin.pad_char = pad_char;
info->tries_left = tries_left;
info->logged_in = SC_PIN_STATE_UNKNOWN;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags)
{
sc_pkcs15_cert_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->authority = authority;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_prkey_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->modulus_length = modulus_length;
info->usage = usage;
info->native = 1;
info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE
| SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE
| SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE
| SC_PKCS15_PRKEY_ACCESS_LOCAL;
info->key_reference = ref;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label,
info, auth_id, obj_flags);
}
/* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_341_5 |
crossvul-cpp_data_good_5127_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC AAA CCCC H H EEEEE %
% C A A C H H E %
% C AAAAA C HHHHH EEE %
% C A A C H H E %
% CCCC A A CCCC H H EEEEE %
% %
% %
% MagickCore Pixel Cache Methods %
% %
% Software Design %
% Cristy %
% July 1999 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/distribute-cache-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/nt-base-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/policy.h"
#include "MagickCore/quantum.h"
#include "MagickCore/random_.h"
#include "MagickCore/registry.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#if defined(MAGICKCORE_ZLIB_DELEGATE)
#include "zlib.h"
#endif
/*
Define declarations.
*/
#define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent)
#define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \
GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse)
/*
Typedef declarations.
*/
typedef struct _MagickModulo
{
ssize_t
quotient,
remainder;
} MagickModulo;
/*
Forward declarations.
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static Cache
GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *)
magick_hot_spot;
static const Quantum
*GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t,
const ssize_t,const size_t,const size_t,ExceptionInfo *),
*GetVirtualPixelsCache(const Image *);
static const void
*GetVirtualMetacontentFromCache(const Image *);
static MagickBooleanType
GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t,Quantum *,
ExceptionInfo *),
GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod,
const ssize_t,const ssize_t,Quantum *,ExceptionInfo *),
OpenPixelCache(Image *,const MapMode,ExceptionInfo *),
OpenPixelCacheOnDisk(CacheInfo *,const MapMode),
ReadPixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict,
ExceptionInfo *),
ReadPixelCacheMetacontent(CacheInfo *magick_restrict,
NexusInfo *magick_restrict,ExceptionInfo *),
SyncAuthenticPixelsCache(Image *,ExceptionInfo *),
WritePixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict,
ExceptionInfo *),
WritePixelCacheMetacontent(CacheInfo *,NexusInfo *magick_restrict,
ExceptionInfo *);
static Quantum
*GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t,
const size_t,ExceptionInfo *),
*QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t,
const size_t,ExceptionInfo *),
*SetPixelCacheNexusPixels(const CacheInfo *,const MapMode,
const RectangleInfo *,NexusInfo *,ExceptionInfo *) magick_hot_spot;
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
/*
Global declarations.
*/
static volatile MagickBooleanType
instantiate_cache = MagickFalse;
static SemaphoreInfo
*cache_semaphore = (SemaphoreInfo *) NULL;
static time_t
cache_epoch = 0;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquirePixelCache() acquires a pixel cache.
%
% The format of the AcquirePixelCache() method is:
%
% Cache AcquirePixelCache(const size_t number_threads)
%
% A description of each parameter follows:
%
% o number_threads: the number of nexus threads.
%
*/
MagickPrivate Cache AcquirePixelCache(const size_t number_threads)
{
CacheInfo
*magick_restrict cache_info;
char
*synchronize;
cache_info=(CacheInfo *) AcquireQuantumMemory(1,sizeof(*cache_info));
if (cache_info == (CacheInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(cache_info,0,sizeof(*cache_info));
cache_info->type=UndefinedCache;
cache_info->mode=IOMode;
cache_info->colorspace=sRGBColorspace;
cache_info->file=(-1);
cache_info->id=GetMagickThreadId();
cache_info->number_threads=number_threads;
if (GetOpenMPMaximumThreads() > cache_info->number_threads)
cache_info->number_threads=GetOpenMPMaximumThreads();
if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads)
cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
if (cache_info->number_threads == 0)
cache_info->number_threads=1;
cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads);
if (cache_info->nexus_info == (NexusInfo **) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE");
if (synchronize != (const char *) NULL)
{
cache_info->synchronize=IsStringTrue(synchronize);
synchronize=DestroyString(synchronize);
}
cache_info->semaphore=AcquireSemaphoreInfo();
cache_info->reference_count=1;
cache_info->file_semaphore=AcquireSemaphoreInfo();
cache_info->debug=IsEventLogging();
cache_info->signature=MagickCoreSignature;
return((Cache ) cache_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquirePixelCacheNexus() allocates the NexusInfo structure.
%
% The format of the AcquirePixelCacheNexus method is:
%
% NexusInfo **AcquirePixelCacheNexus(const size_t number_threads)
%
% A description of each parameter follows:
%
% o number_threads: the number of nexus threads.
%
*/
MagickPrivate NexusInfo **AcquirePixelCacheNexus(const size_t number_threads)
{
NexusInfo
**magick_restrict nexus_info;
register ssize_t
i;
nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory(
number_threads,sizeof(*nexus_info)));
if (nexus_info == (NexusInfo **) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
nexus_info[0]=(NexusInfo *) AcquireQuantumMemory(number_threads,
sizeof(**nexus_info));
if (nexus_info[0] == (NexusInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(nexus_info[0],0,number_threads*sizeof(**nexus_info));
for (i=0; i < (ssize_t) number_threads; i++)
{
nexus_info[i]=(&nexus_info[0][i]);
nexus_info[i]->signature=MagickCoreSignature;
}
return(nexus_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e P i x e l C a c h e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquirePixelCachePixels() returns the pixels associated with the specified
% image.
%
% The format of the AcquirePixelCachePixels() method is:
%
% const void *AcquirePixelCachePixels(const Image *image,
% MagickSizeType *length,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o length: the pixel cache length.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickPrivate const void *AcquirePixelCachePixels(const Image *image,
MagickSizeType *length,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
*length=0;
if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache))
return((const void *) NULL);
*length=cache_info->length;
return((const void *) cache_info->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C a c h e C o m p o n e n t G e n e s i s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CacheComponentGenesis() instantiates the cache component.
%
% The format of the CacheComponentGenesis method is:
%
% MagickBooleanType CacheComponentGenesis(void)
%
*/
MagickPrivate MagickBooleanType CacheComponentGenesis(void)
{
if (cache_semaphore == (SemaphoreInfo *) NULL)
cache_semaphore=AcquireSemaphoreInfo();
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C a c h e C o m p o n e n t T e r m i n u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CacheComponentTerminus() destroys the cache component.
%
% The format of the CacheComponentTerminus() method is:
%
% CacheComponentTerminus(void)
%
*/
MagickPrivate void CacheComponentTerminus(void)
{
if (cache_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&cache_semaphore);
LockSemaphoreInfo(cache_semaphore);
instantiate_cache=MagickFalse;
UnlockSemaphoreInfo(cache_semaphore);
RelinquishSemaphoreInfo(&cache_semaphore);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l o n e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClonePixelCache() clones a pixel cache.
%
% The format of the ClonePixelCache() method is:
%
% Cache ClonePixelCache(const Cache cache)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
*/
MagickPrivate Cache ClonePixelCache(const Cache cache)
{
CacheInfo
*magick_restrict clone_info;
const CacheInfo
*magick_restrict cache_info;
assert(cache != NULL);
cache_info=(const CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads);
if (clone_info == (Cache) NULL)
return((Cache) NULL);
clone_info->virtual_pixel_method=cache_info->virtual_pixel_method;
return((Cache ) clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l o n e P i x e l C a c h e M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClonePixelCacheMethods() clones the pixel cache methods from one cache to
% another.
%
% The format of the ClonePixelCacheMethods() method is:
%
% void ClonePixelCacheMethods(Cache clone,const Cache cache)
%
% A description of each parameter follows:
%
% o clone: Specifies a pointer to a Cache structure.
%
% o cache: the pixel cache.
%
*/
MagickPrivate void ClonePixelCacheMethods(Cache clone,const Cache cache)
{
CacheInfo
*magick_restrict cache_info,
*magick_restrict source_info;
assert(clone != (Cache) NULL);
source_info=(CacheInfo *) clone;
assert(source_info->signature == MagickCoreSignature);
if (source_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
source_info->filename);
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
source_info->methods=cache_info->methods;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l o n e P i x e l C a c h e R e p o s i t o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ClonePixelCacheRepository() clones the source pixel cache to the destination
% cache.
%
% The format of the ClonePixelCacheRepository() method is:
%
% MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info,
% CacheInfo *source_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o source_info: the source pixel cache.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType ClonePixelCacheOnDisk(
CacheInfo *magick_restrict cache_info,CacheInfo *magick_restrict clone_info)
{
MagickSizeType
extent;
size_t
quantum;
ssize_t
count;
struct stat
file_stats;
unsigned char
*buffer;
/*
Clone pixel cache on disk with identifcal morphology.
*/
if ((OpenPixelCacheOnDisk(cache_info,ReadMode) == MagickFalse) ||
(OpenPixelCacheOnDisk(clone_info,IOMode) == MagickFalse))
return(MagickFalse);
quantum=(size_t) MagickMaxBufferExtent;
if ((fstat(cache_info->file,&file_stats) == 0) && (file_stats.st_size > 0))
quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent);
buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
extent=0;
while ((count=read(cache_info->file,buffer,quantum)) > 0)
{
ssize_t
number_bytes;
number_bytes=write(clone_info->file,buffer,(size_t) count);
if (number_bytes != count)
break;
extent+=number_bytes;
}
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
if (extent != cache_info->length)
return(MagickFalse);
return(MagickTrue);
}
static MagickBooleanType ClonePixelCacheRepository(
CacheInfo *magick_restrict clone_info,CacheInfo *magick_restrict cache_info,
ExceptionInfo *exception)
{
#define MaxCacheThreads 2
#define cache_threads(source,destination) \
num_threads(((source)->type == DiskCache) || \
((destination)->type == DiskCache) || (((source)->rows) < \
(16*GetMagickResourceLimit(ThreadResource))) ? 1 : \
GetMagickResourceLimit(ThreadResource) < MaxCacheThreads ? \
GetMagickResourceLimit(ThreadResource) : MaxCacheThreads)
MagickBooleanType
optimize,
status;
NexusInfo
**magick_restrict cache_nexus,
**magick_restrict clone_nexus;
size_t
length;
ssize_t
y;
assert(cache_info != (CacheInfo *) NULL);
assert(clone_info != (CacheInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
if (cache_info->type == PingCache)
return(MagickTrue);
length=cache_info->number_channels*sizeof(*cache_info->channel_map);
if ((cache_info->columns == clone_info->columns) &&
(cache_info->rows == clone_info->rows) &&
(cache_info->number_channels == clone_info->number_channels) &&
(memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) &&
(cache_info->metacontent_extent == clone_info->metacontent_extent))
{
/*
Identical pixel cache morphology.
*/
if (((cache_info->type == MemoryCache) ||
(cache_info->type == MapCache)) &&
((clone_info->type == MemoryCache) ||
(clone_info->type == MapCache)))
{
(void) memcpy(clone_info->pixels,cache_info->pixels,
cache_info->columns*cache_info->number_channels*cache_info->rows*
sizeof(*cache_info->pixels));
if ((cache_info->metacontent_extent != 0) &&
(clone_info->metacontent_extent != 0))
(void) memcpy(clone_info->metacontent,cache_info->metacontent,
cache_info->columns*cache_info->rows*
clone_info->metacontent_extent*sizeof(unsigned char));
return(MagickTrue);
}
if ((cache_info->type == DiskCache) && (clone_info->type == DiskCache))
return(ClonePixelCacheOnDisk(cache_info,clone_info));
}
/*
Mismatched pixel cache morphology.
*/
cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads);
clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads);
if ((cache_nexus == (NexusInfo **) NULL) ||
(clone_nexus == (NexusInfo **) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
length=cache_info->number_channels*sizeof(*cache_info->channel_map);
optimize=(cache_info->number_channels == clone_info->number_channels) &&
(memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) ?
MagickTrue : MagickFalse;
length=(size_t) MagickMin(cache_info->columns*cache_info->number_channels,
clone_info->columns*clone_info->number_channels);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
cache_threads(cache_info,clone_info)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
Quantum
*pixels;
RectangleInfo
region;
register ssize_t
x;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
region.width=cache_info->columns;
region.height=1;
region.x=0;
region.y=y;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,
cache_nexus[id],exception);
if (pixels == (Quantum *) NULL)
continue;
status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
region.width=clone_info->columns;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,
clone_nexus[id],exception);
if (pixels == (Quantum *) NULL)
continue;
(void) ResetMagickMemory(clone_nexus[id]->pixels,0,(size_t)
clone_nexus[id]->length);
if (optimize != MagickFalse)
(void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length*
sizeof(Quantum));
else
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
/*
Mismatched pixel channel map.
*/
p=cache_nexus[id]->pixels;
q=clone_nexus[id]->pixels;
for (x=0; x < (ssize_t) cache_info->columns; x++)
{
register ssize_t
i;
if (x == (ssize_t) clone_info->columns)
break;
for (i=0; i < (ssize_t) clone_info->number_channels; i++)
{
PixelChannel
channel;
PixelTrait
traits;
channel=clone_info->channel_map[i].channel;
traits=cache_info->channel_map[channel].traits;
if (traits != UndefinedPixelTrait)
*q=*(p+cache_info->channel_map[channel].offset);
q++;
}
p+=cache_info->number_channels;
}
}
status=WritePixelCachePixels(clone_info,clone_nexus[id],exception);
}
if ((cache_info->metacontent_extent != 0) &&
(clone_info->metacontent_extent != 0))
{
/*
Clone metacontent.
*/
length=(size_t) MagickMin(cache_info->metacontent_extent,
clone_info->metacontent_extent);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
cache_threads(cache_info,clone_info)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
Quantum
*pixels;
RectangleInfo
region;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
region.width=cache_info->columns;
region.height=1;
region.x=0;
region.y=y;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,
cache_nexus[id],exception);
if (pixels == (Quantum *) NULL)
continue;
status=ReadPixelCacheMetacontent(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
region.width=clone_info->columns;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,
clone_nexus[id],exception);
if (pixels == (Quantum *) NULL)
continue;
if ((clone_nexus[id]->metacontent != (void *) NULL) &&
(cache_nexus[id]->metacontent != (void *) NULL))
(void) memcpy(clone_nexus[id]->metacontent,
cache_nexus[id]->metacontent,length*sizeof(unsigned char));
status=WritePixelCacheMetacontent(clone_info,clone_nexus[id],exception);
}
}
cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads);
clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads);
if (cache_info->debug != MagickFalse)
{
char
message[MagickPathExtent];
(void) FormatLocaleString(message,MagickPathExtent,"%s => %s",
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type),
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type));
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y I m a g e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImagePixelCache() deallocates memory associated with the pixel cache.
%
% The format of the DestroyImagePixelCache() method is:
%
% void DestroyImagePixelCache(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static void DestroyImagePixelCache(Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->cache == (void *) NULL)
return;
image->cache=DestroyPixelCache(image->cache);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y I m a g e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImagePixels() deallocates memory associated with the pixel cache.
%
% The format of the DestroyImagePixels() method is:
%
% void DestroyImagePixels(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DestroyImagePixels(Image *image)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL)
{
cache_info->methods.destroy_pixel_handler(image);
return;
}
image->cache=DestroyPixelCache(image->cache);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyPixelCache() deallocates memory associated with the pixel cache.
%
% The format of the DestroyPixelCache() method is:
%
% Cache DestroyPixelCache(Cache cache)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
*/
static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info)
{
int
status;
status=(-1);
if (cache_info->file != -1)
{
status=close(cache_info->file);
cache_info->file=(-1);
RelinquishMagickResource(FileResource,1);
}
return(status == -1 ? MagickFalse : MagickTrue);
}
static inline void RelinquishPixelCachePixels(CacheInfo *cache_info)
{
switch (cache_info->type)
{
case MemoryCache:
{
if (cache_info->mapped == MagickFalse)
cache_info->pixels=(Quantum *) RelinquishAlignedMemory(
cache_info->pixels);
else
{
(void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length);
cache_info->pixels=(Quantum *) NULL;
}
RelinquishMagickResource(MemoryResource,cache_info->length);
break;
}
case MapCache:
{
(void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length);
cache_info->pixels=(Quantum *) NULL;
if (cache_info->mode != ReadMode)
(void) RelinquishUniqueFileResource(cache_info->cache_filename);
*cache_info->cache_filename='\0';
RelinquishMagickResource(MapResource,cache_info->length);
}
case DiskCache:
{
if (cache_info->file != -1)
(void) ClosePixelCacheOnDisk(cache_info);
if (cache_info->mode != ReadMode)
(void) RelinquishUniqueFileResource(cache_info->cache_filename);
*cache_info->cache_filename='\0';
RelinquishMagickResource(DiskResource,cache_info->length);
break;
}
case DistributedCache:
{
*cache_info->cache_filename='\0';
(void) RelinquishDistributePixelCache((DistributeCacheInfo *)
cache_info->server_info);
break;
}
default:
break;
}
cache_info->type=UndefinedCache;
cache_info->mapped=MagickFalse;
cache_info->metacontent=(void *) NULL;
}
MagickPrivate Cache DestroyPixelCache(Cache cache)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
LockSemaphoreInfo(cache_info->semaphore);
cache_info->reference_count--;
if (cache_info->reference_count != 0)
{
UnlockSemaphoreInfo(cache_info->semaphore);
return((Cache) NULL);
}
UnlockSemaphoreInfo(cache_info->semaphore);
if (cache_info->debug != MagickFalse)
{
char
message[MagickPathExtent];
(void) FormatLocaleString(message,MagickPathExtent,"destroy %s",
cache_info->filename);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
RelinquishPixelCachePixels(cache_info);
if (cache_info->server_info != (DistributeCacheInfo *) NULL)
cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *)
cache_info->server_info);
if (cache_info->nexus_info != (NexusInfo **) NULL)
cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info,
cache_info->number_threads);
if (cache_info->random_info != (RandomInfo *) NULL)
cache_info->random_info=DestroyRandomInfo(cache_info->random_info);
if (cache_info->file_semaphore != (SemaphoreInfo *) NULL)
RelinquishSemaphoreInfo(&cache_info->file_semaphore);
if (cache_info->semaphore != (SemaphoreInfo *) NULL)
RelinquishSemaphoreInfo(&cache_info->semaphore);
cache_info->signature=(~MagickCoreSignature);
cache_info=(CacheInfo *) RelinquishMagickMemory(cache_info);
cache=(Cache) NULL;
return(cache);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyPixelCacheNexus() destroys a pixel cache nexus.
%
% The format of the DestroyPixelCacheNexus() method is:
%
% NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info,
% const size_t number_threads)
%
% A description of each parameter follows:
%
% o nexus_info: the nexus to destroy.
%
% o number_threads: the number of nexus threads.
%
*/
static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info)
{
if (nexus_info->mapped == MagickFalse)
(void) RelinquishAlignedMemory(nexus_info->cache);
else
(void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length);
nexus_info->cache=(Quantum *) NULL;
nexus_info->pixels=(Quantum *) NULL;
nexus_info->metacontent=(void *) NULL;
nexus_info->length=0;
nexus_info->mapped=MagickFalse;
}
MagickPrivate NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info,
const size_t number_threads)
{
register ssize_t
i;
assert(nexus_info != (NexusInfo **) NULL);
for (i=0; i < (ssize_t) number_threads; i++)
{
if (nexus_info[i]->cache != (Quantum *) NULL)
RelinquishCacheNexusPixels(nexus_info[i]);
nexus_info[i]->signature=(~MagickCoreSignature);
}
nexus_info[0]=(NexusInfo *) RelinquishMagickMemory(nexus_info[0]);
nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info);
return(nexus_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A u t h e n t i c M e t a c o n t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticMetacontent() returns the authentic metacontent corresponding
% with the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is
% returned if the associated pixels are not available.
%
% The format of the GetAuthenticMetacontent() method is:
%
% void *GetAuthenticMetacontent(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void *GetAuthenticMetacontent(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_authentic_metacontent_from_handler !=
(GetAuthenticMetacontentFromHandler) NULL)
{
void
*metacontent;
metacontent=cache_info->methods.
get_authentic_metacontent_from_handler(image);
return(metacontent);
}
assert(id < (int) cache_info->number_threads);
return(cache_info->nexus_info[id]->metacontent);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t A u t h e n t i c M e t a c o n t e n t F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticMetacontentFromCache() returns the meta-content corresponding
% with the last call to QueueAuthenticPixelsCache() or
% GetAuthenticPixelsCache().
%
% The format of the GetAuthenticMetacontentFromCache() method is:
%
% void *GetAuthenticMetacontentFromCache(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static void *GetAuthenticMetacontentFromCache(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(cache_info->nexus_info[id]->metacontent);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t A u t h e n t i c P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or
% disk pixel cache as defined by the geometry parameters. A pointer to the
% pixels is returned if the pixels are transferred, otherwise a NULL is
% returned.
%
% The format of the GetAuthenticPixelCacheNexus() method is:
%
% Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o nexus_info: the cache nexus to return.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickPrivate Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,NexusInfo *nexus_info,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
Quantum
*magick_restrict pixels;
/*
Transfer pixels from the cache.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue,
nexus_info,exception);
if (pixels == (Quantum *) NULL)
return((Quantum *) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(pixels);
if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse)
return((Quantum *) NULL);
if (cache_info->metacontent_extent != 0)
if (ReadPixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse)
return((Quantum *) NULL);
return(pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t A u t h e n t i c P i x e l s F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticPixelsFromCache() returns the pixels associated with the last
% call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods.
%
% The format of the GetAuthenticPixelsFromCache() method is:
%
% Quantum *GetAuthenticPixelsFromCache(const Image image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static Quantum *GetAuthenticPixelsFromCache(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(cache_info->nexus_info[id]->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A u t h e n t i c P i x e l Q u e u e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticPixelQueue() returns the authentic pixels associated
% corresponding with the last call to QueueAuthenticPixels() or
% GetAuthenticPixels().
%
% The format of the GetAuthenticPixelQueue() method is:
%
% Quantum *GetAuthenticPixelQueue(const Image image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport Quantum *GetAuthenticPixelQueue(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_authentic_pixels_from_handler !=
(GetAuthenticPixelsFromHandler) NULL)
return(cache_info->methods.get_authentic_pixels_from_handler(image));
assert(id < (int) cache_info->number_threads);
return(cache_info->nexus_info[id]->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A u t h e n t i c P i x e l s %
% %
% %
% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticPixels() obtains a pixel region for read/write access. If the
% region is successfully accessed, a pointer to a Quantum array
% representing the region is returned, otherwise NULL is returned.
%
% The returned pointer may point to a temporary working copy of the pixels
% or it may point to the original pixels in memory. Performance is maximized
% if the selected region is part of one row, or one or more full rows, since
% then there is opportunity to access the pixels in-place (without a copy)
% if the image is in memory, or in a memory-mapped file. The returned pointer
% must *never* be deallocated by the user.
%
% Pixels accessed via the returned pointer represent a simple array of type
% Quantum. If the image has corresponding metacontent,call
% GetAuthenticMetacontent() after invoking GetAuthenticPixels() to obtain the
% meta-content corresponding to the region. Once the Quantum array has
% been updated, the changes must be saved back to the underlying image using
% SyncAuthenticPixels() or they may be lost.
%
% The format of the GetAuthenticPixels() method is:
%
% Quantum *GetAuthenticPixels(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Quantum *GetAuthenticPixels(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
Quantum
*pixels;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_authentic_pixels_handler !=
(GetAuthenticPixelsHandler) NULL)
{
pixels=cache_info->methods.get_authentic_pixels_handler(image,x,y,columns,
rows,exception);
return(pixels);
}
assert(id < (int) cache_info->number_threads);
pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows,
cache_info->nexus_info[id],exception);
return(pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t A u t h e n t i c P i x e l s C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache
% as defined by the geometry parameters. A pointer to the pixels is returned
% if the pixels are transferred, otherwise a NULL is returned.
%
% The format of the GetAuthenticPixelsCache() method is:
%
% Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
Quantum
*magick_restrict pixels;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
if (cache_info == (Cache) NULL)
return((Quantum *) NULL);
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows,
cache_info->nexus_info[id],exception);
return(pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageExtent() returns the extent of the pixels associated corresponding
% with the last call to QueueAuthenticPixels() or GetAuthenticPixels().
%
% The format of the GetImageExtent() method is:
%
% MagickSizeType GetImageExtent(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickSizeType GetImageExtent(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id]));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImagePixelCache() ensures that there is only a single reference to the
% pixel cache to be modified, updating the provided cache pointer to point to
% a clone of the original pixel cache if necessary.
%
% The format of the GetImagePixelCache method is:
%
% Cache GetImagePixelCache(Image *image,const MagickBooleanType clone,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o clone: any value other than MagickFalse clones the cache pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline MagickBooleanType ValidatePixelCacheMorphology(
const Image *magick_restrict image)
{
const CacheInfo
*magick_restrict cache_info;
const PixelChannelMap
*magick_restrict p,
*magick_restrict q;
/*
Does the image match the pixel cache morphology?
*/
cache_info=(CacheInfo *) image->cache;
p=image->channel_map;
q=cache_info->channel_map;
if ((image->storage_class != cache_info->storage_class) ||
(image->colorspace != cache_info->colorspace) ||
(image->alpha_trait != cache_info->alpha_trait) ||
(image->read_mask != cache_info->read_mask) ||
(image->write_mask != cache_info->write_mask) ||
(image->columns != cache_info->columns) ||
(image->rows != cache_info->rows) ||
(image->number_channels != cache_info->number_channels) ||
(memcmp(p,q,image->number_channels*sizeof(*p)) != 0) ||
(image->metacontent_extent != cache_info->metacontent_extent) ||
(cache_info->nexus_info == (NexusInfo **) NULL))
return(MagickFalse);
return(MagickTrue);
}
static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
MagickBooleanType
destroy,
status;
static MagickSizeType
cache_timelimit = 0,
cpu_throttle = MagickResourceInfinity,
cycles = 0;
status=MagickTrue;
if (cpu_throttle == MagickResourceInfinity)
cpu_throttle=GetMagickResourceLimit(ThrottleResource);
if ((cpu_throttle != 0) && ((cycles++ % 32) == 0))
MagickDelay(cpu_throttle);
if (cache_epoch == 0)
{
/*
Set the expire time in seconds.
*/
cache_timelimit=GetMagickResourceLimit(TimeResource);
cache_epoch=time((time_t *) NULL);
}
if ((cache_timelimit != MagickResourceInfinity) &&
((MagickSizeType) (time((time_t *) NULL)-cache_epoch) >= cache_timelimit))
{
#if defined(ECANCELED)
errno=ECANCELED;
#endif
ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded");
}
LockSemaphoreInfo(image->semaphore);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
destroy=MagickFalse;
if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode))
{
LockSemaphoreInfo(cache_info->semaphore);
if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode))
{
CacheInfo
*clone_info;
Image
clone_image;
/*
Clone pixel cache.
*/
clone_image=(*image);
clone_image.semaphore=AcquireSemaphoreInfo();
clone_image.reference_count=1;
clone_image.cache=ClonePixelCache(cache_info);
clone_info=(CacheInfo *) clone_image.cache;
status=OpenPixelCache(&clone_image,IOMode,exception);
if (status != MagickFalse)
{
if (clone != MagickFalse)
status=ClonePixelCacheRepository(clone_info,cache_info,
exception);
if (status != MagickFalse)
{
if (cache_info->reference_count == 1)
cache_info->nexus_info=(NexusInfo **) NULL;
destroy=MagickTrue;
image->cache=clone_image.cache;
}
}
RelinquishSemaphoreInfo(&clone_image.semaphore);
}
UnlockSemaphoreInfo(cache_info->semaphore);
}
if (destroy != MagickFalse)
cache_info=(CacheInfo *) DestroyPixelCache(cache_info);
if (status != MagickFalse)
{
/*
Ensure the image matches the pixel cache morphology.
*/
image->type=UndefinedType;
if (ValidatePixelCacheMorphology(image) == MagickFalse)
{
status=OpenPixelCache(image,IOMode,exception);
cache_info=(CacheInfo *) image->cache;
if (cache_info->type == DiskCache)
(void) ClosePixelCacheOnDisk(cache_info);
}
}
UnlockSemaphoreInfo(image->semaphore);
if (status == MagickFalse)
return((Cache) NULL);
return(image->cache);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e P i x e l C a c h e T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImagePixelCacheType() returns the pixel cache type: UndefinedCache,
% DiskCache, MemoryCache, MapCache, or PingCache.
%
% The format of the GetImagePixelCacheType() method is:
%
% CacheType GetImagePixelCacheType(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport CacheType GetImagePixelCacheType(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
return(cache_info->type);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t O n e A u t h e n t i c P i x e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOneAuthenticPixel() returns a single pixel at the specified (x,y)
% location. The image background color is returned if an error occurs.
%
% The format of the GetOneAuthenticPixel() method is:
%
% MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x,
% const ssize_t y,Quantum *pixel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y: These values define the location of the pixel to return.
%
% o pixel: return a pixel at the specified (x,y) location.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline MagickBooleanType CopyPixel(const Image *image,const Quantum *source,
Quantum *destination)
{
register ssize_t
i;
if (source == (const Quantum *) NULL)
{
destination[RedPixelChannel]=ClampToQuantum(image->background_color.red);
destination[GreenPixelChannel]=ClampToQuantum(image->background_color.green);
destination[BluePixelChannel]=ClampToQuantum(image->background_color.blue);
destination[BlackPixelChannel]=ClampToQuantum(image->background_color.black);
destination[AlphaPixelChannel]=ClampToQuantum(image->background_color.alpha);
return(MagickFalse);
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
destination[channel]=source[i];
}
return(MagickTrue);
}
MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image,
const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
register Quantum
*magick_restrict q;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
(void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel));
if (cache_info->methods.get_one_authentic_pixel_from_handler !=
(GetOneAuthenticPixelFromHandler) NULL)
return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y,
pixel,exception));
q=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception);
return(CopyPixel(image,q,pixel));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t O n e A u t h e n t i c P i x e l F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y)
% location. The image background color is returned if an error occurs.
%
% The format of the GetOneAuthenticPixelFromCache() method is:
%
% MagickBooleanType GetOneAuthenticPixelFromCache(const Image image,
% const ssize_t x,const ssize_t y,Quantum *pixel,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y: These values define the location of the pixel to return.
%
% o pixel: return a pixel at the specified (x,y) location.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image,
const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
register Quantum
*magick_restrict q;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
(void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel));
q=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL,cache_info->nexus_info[id],
exception);
return(CopyPixel(image,q,pixel));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t O n e V i r t u a l P i x e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOneVirtualPixel() returns a single virtual pixel at the specified
% (x,y) location. The image background color is returned if an error occurs.
% If you plan to modify the pixel, use GetOneAuthenticPixel() instead.
%
% The format of the GetOneVirtualPixel() method is:
%
% MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x,
% const ssize_t y,Quantum *pixel,ExceptionInfo exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y: These values define the location of the pixel to return.
%
% o pixel: return a pixel at the specified (x,y) location.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image,
const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
const Quantum
*p;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
(void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel));
if (cache_info->methods.get_one_virtual_pixel_from_handler !=
(GetOneVirtualPixelFromHandler) NULL)
return(cache_info->methods.get_one_virtual_pixel_from_handler(image,
GetPixelCacheVirtualMethod(image),x,y,pixel,exception));
assert(id < (int) cache_info->number_threads);
p=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y,
1UL,1UL,cache_info->nexus_info[id],exception);
return(CopyPixel(image,p,pixel));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t O n e V i r t u a l P i x e l F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOneVirtualPixelFromCache() returns a single virtual pixel at the
% specified (x,y) location. The image background color is returned if an
% error occurs.
%
% The format of the GetOneVirtualPixelFromCache() method is:
%
% MagickBooleanType GetOneVirtualPixelFromCache(const Image image,
% const VirtualPixelMethod method,const ssize_t x,const ssize_t y,
% Quantum *pixel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: the virtual pixel method.
%
% o x,y: These values define the location of the pixel to return.
%
% o pixel: return a pixel at the specified (x,y) location.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image,
const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y,
Quantum *pixel,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
const Quantum
*p;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
(void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel));
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL,
cache_info->nexus_info[id],exception);
return(CopyPixel(image,p,pixel));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t O n e V i r t u a l P i x e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOneVirtualPixelInfo() returns a single pixel at the specified (x,y)
% location. The image background color is returned if an error occurs. If
% you plan to modify the pixel, use GetOneAuthenticPixel() instead.
%
% The format of the GetOneVirtualPixelInfo() method is:
%
% MagickBooleanType GetOneVirtualPixelInfo(const Image image,
% const VirtualPixelMethod virtual_pixel_method,const ssize_t x,
% const ssize_t y,PixelInfo *pixel,ExceptionInfo exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: the virtual pixel method.
%
% o x,y: these values define the location of the pixel to return.
%
% o pixel: return a pixel at the specified (x,y) location.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetOneVirtualPixelInfo(const Image *image,
const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y,
PixelInfo *pixel,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
register const Quantum
*magick_restrict p;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
GetPixelInfo(image,pixel);
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL,
cache_info->nexus_info[id],exception);
if (p == (const Quantum *) NULL)
return(MagickFalse);
GetPixelInfoPixel(image,p,pixel);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e C o l o r s p a c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheColorspace() returns the class type of the pixel cache.
%
% The format of the GetPixelCacheColorspace() method is:
%
% Colorspace GetPixelCacheColorspace(Cache cache)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
*/
MagickPrivate ColorspaceType GetPixelCacheColorspace(const Cache cache)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
return(cache_info->colorspace);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheMethods() initializes the CacheMethods structure.
%
% The format of the GetPixelCacheMethods() method is:
%
% void GetPixelCacheMethods(CacheMethods *cache_methods)
%
% A description of each parameter follows:
%
% o cache_methods: Specifies a pointer to a CacheMethods structure.
%
*/
MagickPrivate void GetPixelCacheMethods(CacheMethods *cache_methods)
{
assert(cache_methods != (CacheMethods *) NULL);
(void) ResetMagickMemory(cache_methods,0,sizeof(*cache_methods));
cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache;
cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache;
cache_methods->get_virtual_metacontent_from_handler=
GetVirtualMetacontentFromCache;
cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache;
cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache;
cache_methods->get_authentic_metacontent_from_handler=
GetAuthenticMetacontentFromCache;
cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache;
cache_methods->get_one_authentic_pixel_from_handler=
GetOneAuthenticPixelFromCache;
cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache;
cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache;
cache_methods->destroy_pixel_handler=DestroyImagePixelCache;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e N e x u s E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheNexusExtent() returns the extent of the pixels associated
% corresponding with the last call to SetPixelCacheNexusPixels() or
% GetPixelCacheNexusPixels().
%
% The format of the GetPixelCacheNexusExtent() method is:
%
% MagickSizeType GetPixelCacheNexusExtent(const Cache cache,
% NexusInfo *nexus_info)
%
% A description of each parameter follows:
%
% o nexus_info: the nexus info.
%
*/
MagickPrivate MagickSizeType GetPixelCacheNexusExtent(const Cache cache,
NexusInfo *magick_restrict nexus_info)
{
CacheInfo
*magick_restrict cache_info;
MagickSizeType
extent;
assert(cache != NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height;
if (extent == 0)
return((MagickSizeType) cache_info->columns*cache_info->rows);
return(extent);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCachePixels() returns the pixels associated with the specified image.
%
% The format of the GetPixelCachePixels() method is:
%
% void *GetPixelCachePixels(Image *image,MagickSizeType *length,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o length: the pixel cache length.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickPrivate void *GetPixelCachePixels(Image *image,MagickSizeType *length,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
assert(length != (MagickSizeType *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
*length=0;
if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache))
return((void *) NULL);
*length=cache_info->length;
return((void *) cache_info->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e S t o r a g e C l a s s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheStorageClass() returns the class type of the pixel cache.
%
% The format of the GetPixelCacheStorageClass() method is:
%
% ClassType GetPixelCacheStorageClass(Cache cache)
%
% A description of each parameter follows:
%
% o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass.
%
% o cache: the pixel cache.
%
*/
MagickPrivate ClassType GetPixelCacheStorageClass(const Cache cache)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
return(cache_info->storage_class);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e T i l e S i z e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheTileSize() returns the pixel cache tile size.
%
% The format of the GetPixelCacheTileSize() method is:
%
% void GetPixelCacheTileSize(const Image *image,size_t *width,
% size_t *height)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the optimize cache tile width in pixels.
%
% o height: the optimize cache tile height in pixels.
%
*/
MagickPrivate void GetPixelCacheTileSize(const Image *image,size_t *width,
size_t *height)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
*width=2048UL/(cache_info->number_channels*sizeof(Quantum));
if (GetImagePixelCacheType(image) == DiskCache)
*width=8192UL/(cache_info->number_channels*sizeof(Quantum));
*height=(*width);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e V i r t u a l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the
% pixel cache. A virtual pixel is any pixel access that is outside the
% boundaries of the image cache.
%
% The format of the GetPixelCacheVirtualMethod() method is:
%
% VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickPrivate VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
return(cache_info->virtual_pixel_method);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l M e t a c o n t e n t F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualMetacontentFromCache() returns the meta-content corresponding with
% the last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache().
%
% The format of the GetVirtualMetacontentFromCache() method is:
%
% void *GetVirtualMetacontentFromCache(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static const void *GetVirtualMetacontentFromCache(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
const void
*magick_restrict metacontent;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
metacontent=GetVirtualMetacontentFromNexus(cache_info,
cache_info->nexus_info[id]);
return(metacontent);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l M e t a c o n t e n t F r o m N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualMetacontentFromNexus() returns the meta-content for the specified
% cache nexus.
%
% The format of the GetVirtualMetacontentFromNexus() method is:
%
% const void *GetVirtualMetacontentFromNexus(const Cache cache,
% NexusInfo *nexus_info)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
% o nexus_info: the cache nexus to return the meta-content.
%
*/
MagickPrivate const void *GetVirtualMetacontentFromNexus(const Cache cache,
NexusInfo *magick_restrict nexus_info)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->storage_class == UndefinedClass)
return((void *) NULL);
return(nexus_info->metacontent);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t V i r t u a l M e t a c o n t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualMetacontent() returns the virtual metacontent corresponding with
% the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is
% returned if the meta-content are not available.
%
% The format of the GetVirtualMetacontent() method is:
%
% const void *GetVirtualMetacontent(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport const void *GetVirtualMetacontent(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
const void
*magick_restrict metacontent;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
metacontent=cache_info->methods.get_virtual_metacontent_from_handler(image);
if (metacontent != (void *) NULL)
return(metacontent);
assert(id < (int) cache_info->number_threads);
metacontent=GetVirtualMetacontentFromNexus(cache_info,
cache_info->nexus_info[id]);
return(metacontent);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l P i x e l s F r o m N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixelsFromNexus() gets virtual pixels from the in-memory or disk
% pixel cache as defined by the geometry parameters. A pointer to the pixels
% is returned if the pixels are transferred, otherwise a NULL is returned.
%
% The format of the GetVirtualPixelsFromNexus() method is:
%
% Quantum *GetVirtualPixelsFromNexus(const Image *image,
% const VirtualPixelMethod method,const ssize_t x,const ssize_t y,
% const size_t columns,const size_t rows,NexusInfo *nexus_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: the virtual pixel method.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o nexus_info: the cache nexus to acquire.
%
% o exception: return any errors or warnings in this structure.
%
*/
static ssize_t
DitherMatrix[64] =
{
0, 48, 12, 60, 3, 51, 15, 63,
32, 16, 44, 28, 35, 19, 47, 31,
8, 56, 4, 52, 11, 59, 7, 55,
40, 24, 36, 20, 43, 27, 39, 23,
2, 50, 14, 62, 1, 49, 13, 61,
34, 18, 46, 30, 33, 17, 45, 29,
10, 58, 6, 54, 9, 57, 5, 53,
42, 26, 38, 22, 41, 25, 37, 21
};
static inline ssize_t DitherX(const ssize_t x,const size_t columns)
{
ssize_t
index;
index=x+DitherMatrix[x & 0x07]-32L;
if (index < 0L)
return(0L);
if (index >= (ssize_t) columns)
return((ssize_t) columns-1L);
return(index);
}
static inline ssize_t DitherY(const ssize_t y,const size_t rows)
{
ssize_t
index;
index=y+DitherMatrix[y & 0x07]-32L;
if (index < 0L)
return(0L);
if (index >= (ssize_t) rows)
return((ssize_t) rows-1L);
return(index);
}
static inline ssize_t EdgeX(const ssize_t x,const size_t columns)
{
if (x < 0L)
return(0L);
if (x >= (ssize_t) columns)
return((ssize_t) (columns-1));
return(x);
}
static inline ssize_t EdgeY(const ssize_t y,const size_t rows)
{
if (y < 0L)
return(0L);
if (y >= (ssize_t) rows)
return((ssize_t) (rows-1));
return(y);
}
static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns)
{
return((ssize_t) (columns*GetPseudoRandomValue(random_info)));
}
static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows)
{
return((ssize_t) (rows*GetPseudoRandomValue(random_info)));
}
static inline MagickModulo VirtualPixelModulo(const ssize_t offset,
const size_t extent)
{
MagickModulo
modulo;
/*
Compute the remainder of dividing offset by extent. It returns not only
the quotient (tile the offset falls in) but also the positive remainer
within that tile such that 0 <= remainder < extent. This method is
essentially a ldiv() using a floored modulo division rather than the
normal default truncated modulo division.
*/
modulo.quotient=offset/(ssize_t) extent;
if (offset < 0L)
modulo.quotient--;
modulo.remainder=offset-modulo.quotient*(ssize_t) extent;
return(modulo);
}
MagickPrivate const Quantum *GetVirtualPixelsFromNexus(const Image *image,
const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y,
const size_t columns,const size_t rows,NexusInfo *nexus_info,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
MagickOffsetType
offset;
MagickSizeType
length,
number_pixels;
NexusInfo
**magick_restrict virtual_nexus;
Quantum
*magick_restrict pixels,
virtual_pixel[MaxPixelChannels];
RectangleInfo
region;
register const Quantum
*magick_restrict p;
register const void
*magick_restrict r;
register Quantum
*magick_restrict q;
register ssize_t
i,
u;
register unsigned char
*magick_restrict s;
ssize_t
v;
void
*magick_restrict virtual_metacontent;
/*
Acquire pixels.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->type == UndefinedCache)
return((const Quantum *) NULL);
region.x=x;
region.y=y;
region.width=columns;
region.height=rows;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,nexus_info,
exception);
if (pixels == (Quantum *) NULL)
return((const Quantum *) NULL);
q=pixels;
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+
nexus_info->region.x;
length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+
nexus_info->region.width-1L;
number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows;
if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels))
if ((x >= 0) && ((ssize_t) (x+columns) <= (ssize_t) cache_info->columns) &&
(y >= 0) && ((ssize_t) (y+rows) <= (ssize_t) cache_info->rows))
{
MagickBooleanType
status;
/*
Pixel request is inside cache extents.
*/
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(q);
status=ReadPixelCachePixels(cache_info,nexus_info,exception);
if (status == MagickFalse)
return((const Quantum *) NULL);
if (cache_info->metacontent_extent != 0)
{
status=ReadPixelCacheMetacontent(cache_info,nexus_info,exception);
if (status == MagickFalse)
return((const Quantum *) NULL);
}
return(q);
}
/*
Pixel request is outside cache extents.
*/
s=(unsigned char *) nexus_info->metacontent;
virtual_nexus=AcquirePixelCacheNexus(1);
if (virtual_nexus == (NexusInfo **) NULL)
{
if (virtual_nexus != (NexusInfo **) NULL)
virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1);
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"UnableToGetCacheNexus","`%s'",image->filename);
return((const Quantum *) NULL);
}
(void) ResetMagickMemory(virtual_pixel,0,cache_info->number_channels*
sizeof(*virtual_pixel));
virtual_metacontent=(void *) NULL;
switch (virtual_pixel_method)
{
case BackgroundVirtualPixelMethod:
case BlackVirtualPixelMethod:
case GrayVirtualPixelMethod:
case TransparentVirtualPixelMethod:
case MaskVirtualPixelMethod:
case WhiteVirtualPixelMethod:
case EdgeVirtualPixelMethod:
case CheckerTileVirtualPixelMethod:
case HorizontalTileVirtualPixelMethod:
case VerticalTileVirtualPixelMethod:
{
if (cache_info->metacontent_extent != 0)
{
/*
Acquire a metacontent buffer.
*/
virtual_metacontent=(void *) AcquireQuantumMemory(1,
cache_info->metacontent_extent);
if (virtual_metacontent == (void *) NULL)
{
virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1);
(void) ThrowMagickException(exception,GetMagickModule(),
CacheError,"UnableToGetCacheNexus","`%s'",image->filename);
return((const Quantum *) NULL);
}
(void) ResetMagickMemory(virtual_metacontent,0,
cache_info->metacontent_extent);
}
switch (virtual_pixel_method)
{
case BlackVirtualPixelMethod:
{
for (i=0; i < (ssize_t) cache_info->number_channels; i++)
SetPixelChannel(image,(PixelChannel) i,0,virtual_pixel);
SetPixelAlpha(image,OpaqueAlpha,virtual_pixel);
break;
}
case GrayVirtualPixelMethod:
{
for (i=0; i < (ssize_t) cache_info->number_channels; i++)
SetPixelChannel(image,(PixelChannel) i,QuantumRange/2,
virtual_pixel);
SetPixelAlpha(image,OpaqueAlpha,virtual_pixel);
break;
}
case TransparentVirtualPixelMethod:
{
for (i=0; i < (ssize_t) cache_info->number_channels; i++)
SetPixelChannel(image,(PixelChannel) i,0,virtual_pixel);
SetPixelAlpha(image,TransparentAlpha,virtual_pixel);
break;
}
case MaskVirtualPixelMethod:
case WhiteVirtualPixelMethod:
{
for (i=0; i < (ssize_t) cache_info->number_channels; i++)
SetPixelChannel(image,(PixelChannel) i,QuantumRange,virtual_pixel);
SetPixelAlpha(image,OpaqueAlpha,virtual_pixel);
break;
}
default:
{
SetPixelRed(image,ClampToQuantum(image->background_color.red),
virtual_pixel);
SetPixelGreen(image,ClampToQuantum(image->background_color.green),
virtual_pixel);
SetPixelBlue(image,ClampToQuantum(image->background_color.blue),
virtual_pixel);
SetPixelBlack(image,ClampToQuantum(image->background_color.black),
virtual_pixel);
SetPixelAlpha(image,ClampToQuantum(image->background_color.alpha),
virtual_pixel);
break;
}
}
break;
}
default:
break;
}
for (v=0; v < (ssize_t) rows; v++)
{
ssize_t
y_offset;
y_offset=y+v;
if ((virtual_pixel_method == EdgeVirtualPixelMethod) ||
(virtual_pixel_method == UndefinedVirtualPixelMethod))
y_offset=EdgeY(y_offset,cache_info->rows);
for (u=0; u < (ssize_t) columns; u+=length)
{
ssize_t
x_offset;
x_offset=x+u;
length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u);
if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) ||
((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) ||
(length == 0))
{
MagickModulo
x_modulo,
y_modulo;
/*
Transfer a single pixel.
*/
length=(MagickSizeType) 1;
switch (virtual_pixel_method)
{
case EdgeVirtualPixelMethod:
default:
{
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,
EdgeX(x_offset,cache_info->columns),
EdgeY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus,
exception);
r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus);
break;
}
case RandomVirtualPixelMethod:
{
if (cache_info->random_info == (RandomInfo *) NULL)
cache_info->random_info=AcquireRandomInfo();
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,
RandomX(cache_info->random_info,cache_info->columns),
RandomY(cache_info->random_info,cache_info->rows),1UL,1UL,
*virtual_nexus,exception);
r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus);
break;
}
case DitherVirtualPixelMethod:
{
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,
DitherX(x_offset,cache_info->columns),
DitherY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus,
exception);
r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus);
break;
}
case TileVirtualPixelMethod:
{
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,
x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus,
exception);
r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus);
break;
}
case MirrorVirtualPixelMethod:
{
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
if ((x_modulo.quotient & 0x01) == 1L)
x_modulo.remainder=(ssize_t) cache_info->columns-
x_modulo.remainder-1L;
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
if ((y_modulo.quotient & 0x01) == 1L)
y_modulo.remainder=(ssize_t) cache_info->rows-
y_modulo.remainder-1L;
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,
x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus,
exception);
r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus);
break;
}
case HorizontalTileEdgeVirtualPixelMethod:
{
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,
x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL,
*virtual_nexus,exception);
r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus);
break;
}
case VerticalTileEdgeVirtualPixelMethod:
{
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,
EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL,
*virtual_nexus,exception);
r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus);
break;
}
case BackgroundVirtualPixelMethod:
case BlackVirtualPixelMethod:
case GrayVirtualPixelMethod:
case TransparentVirtualPixelMethod:
case MaskVirtualPixelMethod:
case WhiteVirtualPixelMethod:
{
p=virtual_pixel;
r=virtual_metacontent;
break;
}
case CheckerTileVirtualPixelMethod:
{
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L)
{
p=virtual_pixel;
r=virtual_metacontent;
break;
}
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,
x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus,
exception);
r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus);
break;
}
case HorizontalTileVirtualPixelMethod:
{
if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows))
{
p=virtual_pixel;
r=virtual_metacontent;
break;
}
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,
x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus,
exception);
r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus);
break;
}
case VerticalTileVirtualPixelMethod:
{
if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns))
{
p=virtual_pixel;
r=virtual_metacontent;
break;
}
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,
x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus,
exception);
r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus);
break;
}
}
if (p == (const Quantum *) NULL)
break;
(void) memcpy(q,p,(size_t) length*cache_info->number_channels*
sizeof(*p));
q+=cache_info->number_channels;
if ((s != (void *) NULL) && (r != (const void *) NULL))
{
(void) memcpy(s,r,(size_t) cache_info->metacontent_extent);
s+=cache_info->metacontent_extent;
}
continue;
}
/*
Transfer a run of pixels.
*/
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x_offset,y_offset,
(size_t) length,1UL,*virtual_nexus,exception);
if (p == (const Quantum *) NULL)
break;
r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus);
(void) memcpy(q,p,(size_t) length*cache_info->number_channels*sizeof(*p));
q+=length*cache_info->number_channels;
if ((r != (void *) NULL) && (s != (const void *) NULL))
{
(void) memcpy(s,r,(size_t) length);
s+=length*cache_info->metacontent_extent;
}
}
if (u < (ssize_t) columns)
break;
}
/*
Free resources.
*/
if (virtual_metacontent != (void *) NULL)
virtual_metacontent=(void *) RelinquishMagickMemory(virtual_metacontent);
virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1);
if (v < (ssize_t) rows)
return((const Quantum *) NULL);
return(pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel
% cache as defined by the geometry parameters. A pointer to the pixels
% is returned if the pixels are transferred, otherwise a NULL is returned.
%
% The format of the GetVirtualPixelCache() method is:
%
% const Quantum *GetVirtualPixelCache(const Image *image,
% const VirtualPixelMethod virtual_pixel_method,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: the virtual pixel method.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static const Quantum *GetVirtualPixelCache(const Image *image,
const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y,
const size_t columns,const size_t rows,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
const Quantum
*magick_restrict p;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,columns,rows,
cache_info->nexus_info[id],exception);
return(p);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t V i r t u a l P i x e l Q u e u e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixelQueue() returns the virtual pixels associated corresponding
% with the last call to QueueAuthenticPixels() or GetVirtualPixels().
%
% The format of the GetVirtualPixelQueue() method is:
%
% const Quantum *GetVirtualPixelQueue(const Image image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport const Quantum *GetVirtualPixelQueue(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_virtual_pixels_handler !=
(GetVirtualPixelsHandler) NULL)
return(cache_info->methods.get_virtual_pixels_handler(image));
assert(id < (int) cache_info->number_threads);
return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id]));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t V i r t u a l P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixels() returns an immutable pixel region. If the
% region is successfully accessed, a pointer to it is returned, otherwise
% NULL is returned. The returned pointer may point to a temporary working
% copy of the pixels or it may point to the original pixels in memory.
% Performance is maximized if the selected region is part of one row, or one
% or more full rows, since there is opportunity to access the pixels in-place
% (without a copy) if the image is in memory, or in a memory-mapped file. The
% returned pointer must *never* be deallocated by the user.
%
% Pixels accessed via the returned pointer represent a simple array of type
% Quantum. If the image type is CMYK or the storage class is PseudoClass,
% call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to
% access the meta-content (of type void) corresponding to the the
% region.
%
% If you plan to modify the pixels, use GetAuthenticPixels() instead.
%
% Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread-
% safe. In a threaded environment, use GetCacheViewVirtualPixels() or
% GetCacheViewAuthenticPixels() instead.
%
% The format of the GetVirtualPixels() method is:
%
% const Quantum *GetVirtualPixels(const Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport const Quantum *GetVirtualPixels(const Image *image,
const ssize_t x,const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
const Quantum
*magick_restrict p;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_virtual_pixel_handler !=
(GetVirtualPixelHandler) NULL)
return(cache_info->methods.get_virtual_pixel_handler(image,
GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception));
assert(id < (int) cache_info->number_threads);
p=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y,
columns,rows,cache_info->nexus_info[id],exception);
return(p);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l P i x e l s F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixelsCache() returns the pixels associated corresponding with the
% last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache().
%
% The format of the GetVirtualPixelsCache() method is:
%
% Quantum *GetVirtualPixelsCache(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static const Quantum *GetVirtualPixelsCache(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id]));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l P i x e l s N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixelsNexus() returns the pixels associated with the specified
% cache nexus.
%
% The format of the GetVirtualPixelsNexus() method is:
%
% const Quantum *GetVirtualPixelsNexus(const Cache cache,
% NexusInfo *nexus_info)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
% o nexus_info: the cache nexus to return the colormap pixels.
%
*/
MagickPrivate const Quantum *GetVirtualPixelsNexus(const Cache cache,
NexusInfo *magick_restrict nexus_info)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->storage_class == UndefinedClass)
return((Quantum *) NULL);
return((const Quantum *) nexus_info->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ O p e n P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OpenPixelCache() allocates the pixel cache. This includes defining the cache
% dimensions, allocating space for the image pixels and optionally the
% metacontent, and memory mapping the cache if it is disk based. The cache
% nexus array is initialized as well.
%
% The format of the OpenPixelCache() method is:
%
% MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o mode: ReadMode, WriteMode, or IOMode.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
#if defined(SIGBUS)
static void CacheSignalHandler(int status)
{
ThrowFatalException(CacheFatalError,"UnableToExtendPixelCache");
}
#endif
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info,
const MapMode mode)
{
int
file;
/*
Open pixel cache on disk.
*/
if ((cache_info->file != -1) && (cache_info->mode == mode))
return(MagickTrue); /* cache already open and in the proper mode */
if (*cache_info->cache_filename == '\0')
file=AcquireUniqueFileResource(cache_info->cache_filename);
else
switch (mode)
{
case ReadMode:
{
file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0);
break;
}
case WriteMode:
{
file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT |
O_BINARY | O_EXCL,S_MODE);
if (file == -1)
file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE);
break;
}
case IOMode:
default:
{
file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY |
O_EXCL,S_MODE);
if (file == -1)
file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE);
break;
}
}
if (file == -1)
return(MagickFalse);
(void) AcquireMagickResource(FileResource,1);
if (cache_info->file != -1)
(void) ClosePixelCacheOnDisk(cache_info);
cache_info->file=file;
cache_info->mode=mode;
return(MagickTrue);
}
static inline MagickOffsetType WritePixelCacheRegion(
const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset,
const MagickSizeType length,const unsigned char *magick_restrict buffer)
{
register MagickOffsetType
i;
ssize_t
count;
#if !defined(MAGICKCORE_HAVE_PWRITE)
if (lseek(cache_info->file,offset,SEEK_SET) < 0)
return((MagickOffsetType) -1);
#endif
count=0;
for (i=0; i < (MagickOffsetType) length; i+=count)
{
#if !defined(MAGICKCORE_HAVE_PWRITE)
count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t)
SSIZE_MAX));
#else
count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t)
SSIZE_MAX),(off_t) (offset+i));
#endif
if (count <= 0)
{
count=0;
if (errno != EINTR)
break;
}
}
return(i);
}
static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length)
{
CacheInfo
*magick_restrict cache_info;
MagickOffsetType
count,
extent,
offset;
cache_info=(CacheInfo *) image->cache;
if (image->debug != MagickFalse)
{
char
format[MagickPathExtent],
message[MagickPathExtent];
(void) FormatMagickSize(length,MagickFalse,"B",MagickPathExtent,format);
(void) FormatLocaleString(message,MagickPathExtent,
"extend %s (%s[%d], disk, %s)",cache_info->filename,
cache_info->cache_filename,cache_info->file,format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
if (length != (MagickSizeType) ((MagickOffsetType) length))
return(MagickFalse);
offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END);
if (offset < 0)
return(MagickFalse);
if ((MagickSizeType) offset >= length)
count=(MagickOffsetType) 1;
else
{
extent=(MagickOffsetType) length-1;
count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *)
"");
#if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE)
if (cache_info->synchronize != MagickFalse)
(void) posix_fallocate(cache_info->file,offset+1,extent-offset);
#endif
#if defined(SIGBUS)
(void) signal(SIGBUS,CacheSignalHandler);
#endif
}
offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_SET);
if (offset < 0)
return(MagickFalse);
return(count != (MagickOffsetType) 1 ? MagickFalse : MagickTrue);
}
static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info,
source_info;
char
format[MagickPathExtent],
message[MagickPathExtent];
const char
*type;
MagickBooleanType
status;
MagickSizeType
length,
number_pixels;
size_t
columns,
packet_size;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns == 0) || (image->rows == 0))
ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) ||
(AcquireMagickResource(HeightResource,image->rows) == MagickFalse))
ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit",
image->filename);
source_info=(*cache_info);
source_info.file=(-1);
(void) FormatLocaleString(cache_info->filename,MagickPathExtent,"%s[%.20g]",
image->filename,(double) GetImageIndexInList(image));
cache_info->storage_class=image->storage_class;
cache_info->colorspace=image->colorspace;
cache_info->alpha_trait=image->alpha_trait;
cache_info->read_mask=image->read_mask;
cache_info->write_mask=image->write_mask;
cache_info->rows=image->rows;
cache_info->columns=image->columns;
InitializePixelChannelMap(image);
cache_info->number_channels=GetPixelChannels(image);
(void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels*
sizeof(*image->channel_map));
cache_info->metacontent_extent=image->metacontent_extent;
cache_info->mode=mode;
number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows;
packet_size=cache_info->number_channels*sizeof(Quantum);
if (image->metacontent_extent != 0)
packet_size+=cache_info->metacontent_extent;
length=number_pixels*packet_size;
columns=(size_t) (length/cache_info->rows/packet_size);
if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) ||
((ssize_t) cache_info->rows < 0))
ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed",
image->filename);
cache_info->length=length;
if (image->ping != MagickFalse)
{
cache_info->storage_class=image->storage_class;
cache_info->colorspace=image->colorspace;
cache_info->type=PingCache;
return(MagickTrue);
}
status=AcquireMagickResource(AreaResource,cache_info->length);
length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+
cache_info->metacontent_extent);
if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length)))
{
status=AcquireMagickResource(MemoryResource,cache_info->length);
if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) ||
(cache_info->type == MemoryCache))
{
cache_info->mapped=MagickFalse;
cache_info->pixels=(Quantum *) MagickAssumeAligned(
AcquireAlignedMemory(1,(size_t) cache_info->length));
if (cache_info->pixels == (Quantum *) NULL)
cache_info->pixels=source_info.pixels;
else
{
/*
Create memory pixel cache.
*/
status=MagickTrue;
cache_info->type=MemoryCache;
cache_info->metacontent=(void *) NULL;
if (cache_info->metacontent_extent != 0)
cache_info->metacontent=(void *) (cache_info->pixels+
number_pixels*cache_info->number_channels);
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickTrue,"B",
MagickPathExtent,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MagickPathExtent,
"open %s (%s %s, %.20gx%.20gx%.20g %s)",
cache_info->filename,cache_info->mapped != MagickFalse ?
"Anonymous" : "Heap",type,(double) cache_info->columns,
(double) cache_info->rows,(double)
cache_info->number_channels,format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
return(status);
}
}
RelinquishMagickResource(MemoryResource,cache_info->length);
}
/*
Create pixel cache on disk.
*/
status=AcquireMagickResource(DiskResource,cache_info->length);
if ((status == MagickFalse) || (cache_info->type == DistributedCache))
{
DistributeCacheInfo
*server_info;
if (cache_info->type == DistributedCache)
RelinquishMagickResource(DiskResource,cache_info->length);
server_info=AcquireDistributeCacheInfo(exception);
if (server_info != (DistributeCacheInfo *) NULL)
{
status=OpenDistributePixelCache(server_info,image);
if (status == MagickFalse)
{
ThrowFileException(exception,CacheError,"UnableToOpenPixelCache",
GetDistributeCacheHostname(server_info));
server_info=DestroyDistributeCacheInfo(server_info);
}
else
{
/*
Create a distributed pixel cache.
*/
cache_info->type=DistributedCache;
cache_info->server_info=server_info;
(void) FormatLocaleString(cache_info->cache_filename,
MagickPathExtent,"%s:%d",GetDistributeCacheHostname(
(DistributeCacheInfo *) cache_info->server_info),
GetDistributeCachePort((DistributeCacheInfo *)
cache_info->server_info));
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickFalse,"B",
MagickPathExtent,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MagickPathExtent,
"open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",
cache_info->filename,cache_info->cache_filename,
GetDistributeCacheFile((DistributeCacheInfo *)
cache_info->server_info),type,(double) cache_info->columns,
(double) cache_info->rows,(double)
cache_info->number_channels,format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
return(MagickTrue);
}
}
RelinquishMagickResource(DiskResource,cache_info->length);
cache_info->type=UndefinedCache;
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"CacheResourcesExhausted","`%s'",image->filename);
return(MagickFalse);
}
if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode))
{
(void) ClosePixelCacheOnDisk(cache_info);
*cache_info->cache_filename='\0';
}
if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse)
{
RelinquishMagickResource(DiskResource,cache_info->length);
cache_info->type=UndefinedCache;
ThrowFileException(exception,CacheError,"UnableToOpenPixelCache",
image->filename);
return(MagickFalse);
}
status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+
cache_info->length);
if (status == MagickFalse)
{
cache_info->type=UndefinedCache;
ThrowFileException(exception,CacheError,"UnableToExtendCache",
image->filename);
return(MagickFalse);
}
length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+
cache_info->metacontent_extent);
if (length != (MagickSizeType) ((size_t) length))
cache_info->type=DiskCache;
else
{
status=AcquireMagickResource(MapResource,cache_info->length);
if ((status == MagickFalse) && (cache_info->type != MapCache) &&
(cache_info->type != MemoryCache))
cache_info->type=DiskCache;
else
{
cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode,
cache_info->offset,(size_t) cache_info->length);
if (cache_info->pixels == (Quantum *) NULL)
{
cache_info->type=DiskCache;
cache_info->pixels=source_info.pixels;
}
else
{
/*
Create file-backed memory-mapped pixel cache.
*/
status=MagickTrue;
(void) ClosePixelCacheOnDisk(cache_info);
cache_info->type=MapCache;
cache_info->mapped=MagickTrue;
cache_info->metacontent=(void *) NULL;
if (cache_info->metacontent_extent != 0)
cache_info->metacontent=(void *) (cache_info->pixels+
number_pixels*cache_info->number_channels);
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickTrue,"B",
MagickPathExtent,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MagickPathExtent,
"open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",
cache_info->filename,cache_info->cache_filename,
cache_info->file,type,(double) cache_info->columns,(double)
cache_info->rows,(double) cache_info->number_channels,
format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
if (status == MagickFalse)
cache_info->type=UndefinedCache;
return(status);
}
}
RelinquishMagickResource(MapResource,cache_info->length);
}
status=MagickTrue;
if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickFalse,"B",
MagickPathExtent,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MagickPathExtent,
"open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",cache_info->filename,
cache_info->cache_filename,cache_info->file,type,(double)
cache_info->columns,(double) cache_info->rows,(double)
cache_info->number_channels,format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
if (status == MagickFalse)
cache_info->type=UndefinedCache;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P e r s i s t P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PersistPixelCache() attaches to or initializes a persistent pixel cache. A
% persistent pixel cache is one that resides on disk and is not destroyed
% when the program exits.
%
% The format of the PersistPixelCache() method is:
%
% MagickBooleanType PersistPixelCache(Image *image,const char *filename,
% const MagickBooleanType attach,MagickOffsetType *offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o filename: the persistent pixel cache filename.
%
% o attach: A value other than zero initializes the persistent pixel cache.
%
% o initialize: A value other than zero initializes the persistent pixel
% cache.
%
% o offset: the offset in the persistent cache to store pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType PersistPixelCache(Image *image,
const char *filename,const MagickBooleanType attach,MagickOffsetType *offset,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info,
*magick_restrict clone_info;
Image
clone_image;
MagickBooleanType
status;
ssize_t
page_size;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(image->cache != (void *) NULL);
assert(filename != (const char *) NULL);
assert(offset != (MagickOffsetType *) NULL);
page_size=GetMagickPageSize();
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (attach != MagickFalse)
{
/*
Attach existing persistent pixel cache.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"attach persistent cache");
(void) CopyMagickString(cache_info->cache_filename,filename,
MagickPathExtent);
cache_info->type=DiskCache;
cache_info->offset=(*offset);
if (OpenPixelCache(image,ReadMode,exception) == MagickFalse)
return(MagickFalse);
*offset+=cache_info->length+page_size-(cache_info->length % page_size);
return(MagickTrue);
}
if ((cache_info->mode != ReadMode) &&
((cache_info->type == DiskCache) || (cache_info->type == MapCache)) &&
(cache_info->reference_count == 1))
{
LockSemaphoreInfo(cache_info->semaphore);
if ((cache_info->mode != ReadMode) &&
((cache_info->type == DiskCache) || (cache_info->type == MapCache)) &&
(cache_info->reference_count == 1))
{
/*
Usurp existing persistent pixel cache.
*/
if (rename_utf8(cache_info->cache_filename, filename) == 0)
{
(void) CopyMagickString(cache_info->cache_filename,filename,
MagickPathExtent);
*offset+=cache_info->length+page_size-(cache_info->length %
page_size);
UnlockSemaphoreInfo(cache_info->semaphore);
cache_info=(CacheInfo *) ReferencePixelCache(cache_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"Usurp resident persistent cache");
return(MagickTrue);
}
}
UnlockSemaphoreInfo(cache_info->semaphore);
}
/*
Clone persistent pixel cache.
*/
clone_image=(*image);
clone_info=(CacheInfo *) clone_image.cache;
image->cache=ClonePixelCache(cache_info);
cache_info=(CacheInfo *) ReferencePixelCache(image->cache);
(void) CopyMagickString(cache_info->cache_filename,filename,MagickPathExtent);
cache_info->type=DiskCache;
cache_info->offset=(*offset);
cache_info=(CacheInfo *) image->cache;
status=OpenPixelCache(image,IOMode,exception);
if (status != MagickFalse)
status=ClonePixelCacheRepository(cache_info,clone_info,exception);
*offset+=cache_info->length+page_size-(cache_info->length % page_size);
clone_info=(CacheInfo *) DestroyPixelCache(clone_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as
% defined by the region rectangle and returns a pointer to the region. This
% region is subsequently transferred from the pixel cache with
% SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the
% pixels are transferred, otherwise a NULL is returned.
%
% The format of the QueueAuthenticPixelCacheNexus() method is:
%
% Quantum *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% const MagickBooleanType clone,NexusInfo *nexus_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o nexus_info: the cache nexus to set.
%
% o clone: clone the pixel cache.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickPrivate Quantum *QueueAuthenticPixelCacheNexus(Image *image,
const ssize_t x,const ssize_t y,const size_t columns,const size_t rows,
const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
MagickOffsetType
offset;
MagickSizeType
number_pixels;
Quantum
*magick_restrict pixels;
RectangleInfo
region;
/*
Validate pixel cache geometry.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception);
if (cache_info == (Cache) NULL)
return((Quantum *) NULL);
assert(cache_info->signature == MagickCoreSignature);
if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) ||
(y < 0) || (x >= (ssize_t) cache_info->columns) ||
(y >= (ssize_t) cache_info->rows))
{
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"PixelsAreNotAuthentic","`%s'",image->filename);
return((Quantum *) NULL);
}
offset=(MagickOffsetType) y*cache_info->columns+x;
if (offset < 0)
return((Quantum *) NULL);
number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows;
offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1;
if ((MagickSizeType) offset >= number_pixels)
return((Quantum *) NULL);
/*
Return pixel cache.
*/
region.x=x;
region.y=y;
region.width=columns;
region.height=rows;
pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,®ion,nexus_info,
exception);
return(pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ Q u e u e A u t h e n t i c P i x e l s C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QueueAuthenticPixelsCache() allocates an region to store image pixels as
% defined by the region rectangle and returns a pointer to the region. This
% region is subsequently transferred from the pixel cache with
% SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the
% pixels are transferred, otherwise a NULL is returned.
%
% The format of the QueueAuthenticPixelsCache() method is:
%
% Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
Quantum
*magick_restrict pixels;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse,
cache_info->nexus_info[id],exception);
return(pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Q u e u e A u t h e n t i c P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QueueAuthenticPixels() queues a mutable pixel region. If the region is
% successfully initialized a pointer to a Quantum array representing the
% region is returned, otherwise NULL is returned. The returned pointer may
% point to a temporary working buffer for the pixels or it may point to the
% final location of the pixels in memory.
%
% Write-only access means that any existing pixel values corresponding to
% the region are ignored. This is useful if the initial image is being
% created from scratch, or if the existing pixel values are to be
% completely replaced without need to refer to their pre-existing values.
% The application is free to read and write the pixel buffer returned by
% QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not
% initialize the pixel array values. Initializing pixel array values is the
% application's responsibility.
%
% Performance is maximized if the selected region is part of one row, or
% one or more full rows, since then there is opportunity to access the
% pixels in-place (without a copy) if the image is in memory, or in a
% memory-mapped file. The returned pointer must *never* be deallocated
% by the user.
%
% Pixels accessed via the returned pointer represent a simple array of type
% Quantum. If the image type is CMYK or the storage class is PseudoClass,
% call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to
% obtain the meta-content (of type void) corresponding to the region.
% Once the Quantum (and/or Quantum) array has been updated, the
% changes must be saved back to the underlying image using
% SyncAuthenticPixels() or they may be lost.
%
% The format of the QueueAuthenticPixels() method is:
%
% Quantum *QueueAuthenticPixels(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Quantum *QueueAuthenticPixels(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
Quantum
*magick_restrict pixels;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.queue_authentic_pixels_handler !=
(QueueAuthenticPixelsHandler) NULL)
{
pixels=cache_info->methods.queue_authentic_pixels_handler(image,x,y,
columns,rows,exception);
return(pixels);
}
assert(id < (int) cache_info->number_threads);
pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse,
cache_info->nexus_info[id],exception);
return(pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e a d P i x e l C a c h e M e t a c o n t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPixelCacheMetacontent() reads metacontent from the specified region of
% the pixel cache.
%
% The format of the ReadPixelCacheMetacontent() method is:
%
% MagickBooleanType ReadPixelCacheMetacontent(CacheInfo *cache_info,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o nexus_info: the cache nexus to read the metacontent.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline MagickOffsetType ReadPixelCacheRegion(
const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset,
const MagickSizeType length,unsigned char *magick_restrict buffer)
{
register MagickOffsetType
i;
ssize_t
count;
#if !defined(MAGICKCORE_HAVE_PREAD)
if (lseek(cache_info->file,offset,SEEK_SET) < 0)
return((MagickOffsetType) -1);
#endif
count=0;
for (i=0; i < (MagickOffsetType) length; i+=count)
{
#if !defined(MAGICKCORE_HAVE_PREAD)
count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t)
SSIZE_MAX));
#else
count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t)
SSIZE_MAX),(off_t) (offset+i));
#endif
if (count <= 0)
{
count=0;
if (errno != EINTR)
break;
}
}
return(i);
}
static MagickBooleanType ReadPixelCacheMetacontent(
CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info,
ExceptionInfo *exception)
{
MagickOffsetType
count,
offset;
MagickSizeType
extent,
length;
register ssize_t
y;
register unsigned char
*magick_restrict q;
size_t
rows;
if (cache_info->metacontent_extent == 0)
return(MagickFalse);
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(MagickTrue);
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+
nexus_info->region.x;
length=(MagickSizeType) nexus_info->region.width*
cache_info->metacontent_extent;
extent=length*nexus_info->region.height;
rows=nexus_info->region.height;
y=0;
q=(unsigned char *) nexus_info->metacontent;
switch (cache_info->type)
{
case MemoryCache:
case MapCache:
{
register unsigned char
*magick_restrict p;
/*
Read meta-content from memory.
*/
if ((cache_info->columns == nexus_info->region.width) &&
(extent == (MagickSizeType) ((size_t) extent)))
{
length=extent;
rows=1UL;
}
p=(unsigned char *) cache_info->metacontent+offset*
cache_info->metacontent_extent;
for (y=0; y < (ssize_t) rows; y++)
{
(void) memcpy(q,p,(size_t) length);
p+=cache_info->metacontent_extent*cache_info->columns;
q+=cache_info->metacontent_extent*nexus_info->region.width;
}
break;
}
case DiskCache:
{
/*
Read meta content from disk.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
cache_info->cache_filename);
UnlockSemaphoreInfo(cache_info->file_semaphore);
return(MagickFalse);
}
if ((cache_info->columns == nexus_info->region.width) &&
(extent <= MagickMaxBufferExtent))
{
length=extent;
rows=1UL;
}
extent=(MagickSizeType) cache_info->columns*cache_info->rows;
for (y=0; y < (ssize_t) rows; y++)
{
count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent*
cache_info->number_channels*sizeof(Quantum)+offset*
cache_info->metacontent_extent,length,(unsigned char *) q);
if (count != (MagickOffsetType) length)
break;
offset+=cache_info->columns;
q+=cache_info->metacontent_extent*nexus_info->region.width;
}
if (IsFileDescriptorLimitExceeded() != MagickFalse)
(void) ClosePixelCacheOnDisk(cache_info);
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
case DistributedCache:
{
RectangleInfo
region;
/*
Read metacontent from distributed cache.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
region=nexus_info->region;
if ((cache_info->columns != nexus_info->region.width) ||
(extent > MagickMaxBufferExtent))
region.height=1UL;
else
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=ReadDistributePixelCacheMetacontent((DistributeCacheInfo *)
cache_info->server_info,®ion,length,(unsigned char *) q);
if (count != (MagickOffsetType) length)
break;
q+=cache_info->metacontent_extent*nexus_info->region.width;
region.y++;
}
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
default:
break;
}
if (y < (ssize_t) rows)
{
ThrowFileException(exception,CacheError,"UnableToReadPixelCache",
cache_info->cache_filename);
return(MagickFalse);
}
if ((cache_info->debug != MagickFalse) &&
(CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse))
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double)
nexus_info->region.width,(double) nexus_info->region.height,(double)
nexus_info->region.x,(double) nexus_info->region.y);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e a d P i x e l C a c h e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPixelCachePixels() reads pixels from the specified region of the pixel
% cache.
%
% The format of the ReadPixelCachePixels() method is:
%
% MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o nexus_info: the cache nexus to read the pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType ReadPixelCachePixels(
CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info,
ExceptionInfo *exception)
{
MagickOffsetType
count,
offset;
MagickSizeType
extent,
length;
register Quantum
*magick_restrict q;
register ssize_t
y;
size_t
number_channels,
rows;
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(MagickTrue);
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns;
if ((ssize_t) (offset/cache_info->columns) != nexus_info->region.y)
return(MagickFalse);
offset+=nexus_info->region.x;
number_channels=cache_info->number_channels;
length=(MagickSizeType) number_channels*nexus_info->region.width*
sizeof(Quantum);
if ((length/number_channels/sizeof(Quantum)) != nexus_info->region.width)
return(MagickFalse);
rows=nexus_info->region.height;
extent=length*rows;
if ((extent == 0) || ((extent/length) != rows))
return(MagickFalse);
y=0;
q=nexus_info->pixels;
switch (cache_info->type)
{
case MemoryCache:
case MapCache:
{
register Quantum
*magick_restrict p;
/*
Read pixels from memory.
*/
if ((cache_info->columns == nexus_info->region.width) &&
(extent == (MagickSizeType) ((size_t) extent)))
{
length=extent;
rows=1UL;
}
p=cache_info->pixels+offset*cache_info->number_channels;
for (y=0; y < (ssize_t) rows; y++)
{
(void) memcpy(q,p,(size_t) length);
p+=cache_info->number_channels*cache_info->columns;
q+=cache_info->number_channels*nexus_info->region.width;
}
break;
}
case DiskCache:
{
/*
Read pixels from disk.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
cache_info->cache_filename);
UnlockSemaphoreInfo(cache_info->file_semaphore);
return(MagickFalse);
}
if ((cache_info->columns == nexus_info->region.width) &&
(extent <= MagickMaxBufferExtent))
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset*
cache_info->number_channels*sizeof(*q),length,(unsigned char *) q);
if (count != (MagickOffsetType) length)
break;
offset+=cache_info->columns;
q+=cache_info->number_channels*nexus_info->region.width;
}
if (IsFileDescriptorLimitExceeded() != MagickFalse)
(void) ClosePixelCacheOnDisk(cache_info);
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
case DistributedCache:
{
RectangleInfo
region;
/*
Read pixels from distributed cache.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
region=nexus_info->region;
if ((cache_info->columns != nexus_info->region.width) ||
(extent > MagickMaxBufferExtent))
region.height=1UL;
else
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=ReadDistributePixelCachePixels((DistributeCacheInfo *)
cache_info->server_info,®ion,length,(unsigned char *) q);
if (count != (MagickOffsetType) length)
break;
q+=cache_info->number_channels*nexus_info->region.width;
region.y++;
}
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
default:
break;
}
if (y < (ssize_t) rows)
{
ThrowFileException(exception,CacheError,"UnableToReadPixelCache",
cache_info->cache_filename);
return(MagickFalse);
}
if ((cache_info->debug != MagickFalse) &&
(CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse))
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double)
nexus_info->region.width,(double) nexus_info->region.height,(double)
nexus_info->region.x,(double) nexus_info->region.y);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e f e r e n c e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReferencePixelCache() increments the reference count associated with the
% pixel cache returning a pointer to the cache.
%
% The format of the ReferencePixelCache method is:
%
% Cache ReferencePixelCache(Cache cache_info)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
*/
MagickPrivate Cache ReferencePixelCache(Cache cache)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache *) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
LockSemaphoreInfo(cache_info->semaphore);
cache_info->reference_count++;
UnlockSemaphoreInfo(cache_info->semaphore);
return(cache_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e s e t P i x e l C a c h e E p o c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetPixelCacheEpoch() resets the pixel cache epoch.
%
% The format of the ResetPixelCacheEpoch method is:
%
% void ResetPixelCacheEpoch(void)
%
*/
MagickPrivate void ResetPixelCacheEpoch(void)
{
cache_epoch=0;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S e t P i x e l C a c h e M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetPixelCacheMethods() sets the image pixel methods to the specified ones.
%
% The format of the SetPixelCacheMethods() method is:
%
% SetPixelCacheMethods(Cache *,CacheMethods *cache_methods)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
% o cache_methods: Specifies a pointer to a CacheMethods structure.
%
*/
MagickPrivate void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods)
{
CacheInfo
*magick_restrict cache_info;
GetOneAuthenticPixelFromHandler
get_one_authentic_pixel_from_handler;
GetOneVirtualPixelFromHandler
get_one_virtual_pixel_from_handler;
/*
Set cache pixel methods.
*/
assert(cache != (Cache) NULL);
assert(cache_methods != (CacheMethods *) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL)
cache_info->methods.get_virtual_pixel_handler=
cache_methods->get_virtual_pixel_handler;
if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL)
cache_info->methods.destroy_pixel_handler=
cache_methods->destroy_pixel_handler;
if (cache_methods->get_virtual_metacontent_from_handler !=
(GetVirtualMetacontentFromHandler) NULL)
cache_info->methods.get_virtual_metacontent_from_handler=
cache_methods->get_virtual_metacontent_from_handler;
if (cache_methods->get_authentic_pixels_handler !=
(GetAuthenticPixelsHandler) NULL)
cache_info->methods.get_authentic_pixels_handler=
cache_methods->get_authentic_pixels_handler;
if (cache_methods->queue_authentic_pixels_handler !=
(QueueAuthenticPixelsHandler) NULL)
cache_info->methods.queue_authentic_pixels_handler=
cache_methods->queue_authentic_pixels_handler;
if (cache_methods->sync_authentic_pixels_handler !=
(SyncAuthenticPixelsHandler) NULL)
cache_info->methods.sync_authentic_pixels_handler=
cache_methods->sync_authentic_pixels_handler;
if (cache_methods->get_authentic_pixels_from_handler !=
(GetAuthenticPixelsFromHandler) NULL)
cache_info->methods.get_authentic_pixels_from_handler=
cache_methods->get_authentic_pixels_from_handler;
if (cache_methods->get_authentic_metacontent_from_handler !=
(GetAuthenticMetacontentFromHandler) NULL)
cache_info->methods.get_authentic_metacontent_from_handler=
cache_methods->get_authentic_metacontent_from_handler;
get_one_virtual_pixel_from_handler=
cache_info->methods.get_one_virtual_pixel_from_handler;
if (get_one_virtual_pixel_from_handler !=
(GetOneVirtualPixelFromHandler) NULL)
cache_info->methods.get_one_virtual_pixel_from_handler=
cache_methods->get_one_virtual_pixel_from_handler;
get_one_authentic_pixel_from_handler=
cache_methods->get_one_authentic_pixel_from_handler;
if (get_one_authentic_pixel_from_handler !=
(GetOneAuthenticPixelFromHandler) NULL)
cache_info->methods.get_one_authentic_pixel_from_handler=
cache_methods->get_one_authentic_pixel_from_handler;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S e t P i x e l C a c h e N e x u s P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetPixelCacheNexusPixels() defines the region of the cache for the
% specified cache nexus.
%
% The format of the SetPixelCacheNexusPixels() method is:
%
% Quantum SetPixelCacheNexusPixels(const CacheInfo *cache_info,
% const MapMode mode,const RectangleInfo *region,NexusInfo *nexus_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o mode: ReadMode, WriteMode, or IOMode.
%
% o region: A pointer to the RectangleInfo structure that defines the
% region of this particular cache nexus.
%
% o nexus_info: the cache nexus to set.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline MagickBooleanType AcquireCacheNexusPixels(
const CacheInfo *magick_restrict cache_info,NexusInfo *nexus_info,
ExceptionInfo *exception)
{
if (nexus_info->length != (MagickSizeType) ((size_t) nexus_info->length))
return(MagickFalse);
nexus_info->mapped=MagickFalse;
nexus_info->cache=(Quantum *) MagickAssumeAligned(AcquireAlignedMemory(1,
(size_t) nexus_info->length));
if (nexus_info->cache == (Quantum *) NULL)
{
nexus_info->mapped=MagickTrue;
nexus_info->cache=(Quantum *) MapBlob(-1,IOMode,0,(size_t)
nexus_info->length);
}
if (nexus_info->cache == (Quantum *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
cache_info->filename);
return(MagickFalse);
}
return(MagickTrue);
}
static inline MagickBooleanType IsPixelCacheAuthentic(
const CacheInfo *magick_restrict cache_info,
const NexusInfo *magick_restrict nexus_info)
{
MagickBooleanType
status;
MagickOffsetType
offset;
/*
Does nexus pixels point directly to in-core cache pixels or is it buffered?
*/
if (cache_info->type == PingCache)
return(MagickTrue);
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+
nexus_info->region.x;
status=nexus_info->pixels == (cache_info->pixels+offset*
cache_info->number_channels) ? MagickTrue : MagickFalse;
return(status);
}
static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info,
const MapMode mode)
{
if (mode == ReadMode)
{
MagickCachePrefetch((unsigned char *) nexus_info->pixels,0,1);
return;
}
MagickCachePrefetch((unsigned char *) nexus_info->pixels,1,1);
}
static Quantum *SetPixelCacheNexusPixels(const CacheInfo *cache_info,
const MapMode mode,const RectangleInfo *region,NexusInfo *nexus_info,
ExceptionInfo *exception)
{
MagickBooleanType
status;
MagickSizeType
length,
number_pixels;
assert(cache_info != (const CacheInfo *) NULL);
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->type == UndefinedCache)
return((Quantum *) NULL);
nexus_info->region=(*region);
if ((cache_info->type == MemoryCache) || (cache_info->type == MapCache))
{
ssize_t
x,
y;
x=nexus_info->region.x+(ssize_t) nexus_info->region.width-1;
y=nexus_info->region.y+(ssize_t) nexus_info->region.height-1;
if (((nexus_info->region.x >= 0) && (x < (ssize_t) cache_info->columns) &&
(nexus_info->region.y >= 0) && (y < (ssize_t) cache_info->rows)) &&
((nexus_info->region.height == 1UL) || ((nexus_info->region.x == 0) &&
((nexus_info->region.width == cache_info->columns) ||
((nexus_info->region.width % cache_info->columns) == 0)))))
{
MagickOffsetType
offset;
/*
Pixels are accessed directly from memory.
*/
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+
nexus_info->region.x;
nexus_info->pixels=cache_info->pixels+cache_info->number_channels*
offset;
nexus_info->metacontent=(void *) NULL;
if (cache_info->metacontent_extent != 0)
nexus_info->metacontent=(unsigned char *) cache_info->metacontent+
offset*cache_info->metacontent_extent;
PrefetchPixelCacheNexusPixels(nexus_info,mode);
nexus_info->authentic_pixel_cache=IsPixelCacheAuthentic(cache_info,
nexus_info);
return(nexus_info->pixels);
}
}
/*
Pixels are stored in a staging region until they are synced to the cache.
*/
number_pixels=(MagickSizeType) nexus_info->region.width*
nexus_info->region.height;
length=number_pixels*cache_info->number_channels*sizeof(Quantum);
if (cache_info->metacontent_extent != 0)
length+=number_pixels*cache_info->metacontent_extent;
if (nexus_info->cache == (Quantum *) NULL)
{
nexus_info->length=length;
status=AcquireCacheNexusPixels(cache_info,nexus_info,exception);
if (status == MagickFalse)
{
nexus_info->length=0;
return((Quantum *) NULL);
}
}
else
if (nexus_info->length < length)
{
RelinquishCacheNexusPixels(nexus_info);
nexus_info->length=length;
status=AcquireCacheNexusPixels(cache_info,nexus_info,exception);
if (status == MagickFalse)
{
nexus_info->length=0;
return((Quantum *) NULL);
}
}
nexus_info->pixels=nexus_info->cache;
nexus_info->metacontent=(void *) NULL;
if (cache_info->metacontent_extent != 0)
nexus_info->metacontent=(void *) (nexus_info->pixels+number_pixels*
cache_info->number_channels);
PrefetchPixelCacheNexusPixels(nexus_info,mode);
nexus_info->authentic_pixel_cache=IsPixelCacheAuthentic(cache_info,
nexus_info);
return(nexus_info->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t P i x e l C a c h e V i r t u a l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the
% pixel cache and returns the previous setting. A virtual pixel is any pixel
% access that is outside the boundaries of the image cache.
%
% The format of the SetPixelCacheVirtualMethod() method is:
%
% VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image,
% const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: choose the type of virtual pixel.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType SetCacheAlphaChannel(Image *image,const Quantum alpha,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
CacheView
*magick_restrict image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
image->alpha_trait=BlendPixelTrait;
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception); /* must be virtual */
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelAlpha(image,alpha,q);
q+=GetPixelChannels(image);
}
status=SyncCacheViewAuthenticPixels(image_view,exception);
}
image_view=DestroyCacheView(image_view);
return(status);
}
MagickPrivate VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image,
const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
VirtualPixelMethod
method;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
method=cache_info->virtual_pixel_method;
cache_info->virtual_pixel_method=virtual_pixel_method;
if ((image->columns != 0) && (image->rows != 0))
switch (virtual_pixel_method)
{
case BackgroundVirtualPixelMethod:
{
if ((image->background_color.alpha_trait != UndefinedPixelTrait) &&
(image->alpha_trait == UndefinedPixelTrait))
(void) SetCacheAlphaChannel(image,OpaqueAlpha,exception);
if ((IsPixelInfoGray(&image->background_color) == MagickFalse) &&
(IsGrayColorspace(image->colorspace) != MagickFalse))
(void) SetImageColorspace(image,sRGBColorspace,exception);
break;
}
case TransparentVirtualPixelMethod:
{
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetCacheAlphaChannel(image,OpaqueAlpha,exception);
break;
}
default:
break;
}
return(method);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S y n c A u t h e n t i c P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the
% in-memory or disk cache. The method returns MagickTrue if the pixel region
% is synced, otherwise MagickFalse.
%
% The format of the SyncAuthenticPixelCacheNexus() method is:
%
% MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o nexus_info: the cache nexus to sync.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickPrivate MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image,
NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
MagickBooleanType
status;
/*
Transfer pixels to the cache.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->cache == (Cache) NULL)
ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->type == UndefinedCache)
return(MagickFalse);
if (nexus_info->authentic_pixel_cache != MagickFalse)
{
image->taint=MagickTrue;
return(MagickTrue);
}
assert(cache_info->signature == MagickCoreSignature);
status=WritePixelCachePixels(cache_info,nexus_info,exception);
if ((cache_info->metacontent_extent != 0) &&
(WritePixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse))
return(MagickFalse);
if (status != MagickFalse)
image->taint=MagickTrue;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S y n c A u t h e n t i c P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory
% or disk cache. The method returns MagickTrue if the pixel region is synced,
% otherwise MagickFalse.
%
% The format of the SyncAuthenticPixelsCache() method is:
%
% MagickBooleanType SyncAuthenticPixelsCache(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType SyncAuthenticPixelsCache(Image *image,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id],
exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S y n c A u t h e n t i c P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache.
% The method returns MagickTrue if the pixel region is flushed, otherwise
% MagickFalse.
%
% The format of the SyncAuthenticPixels() method is:
%
% MagickBooleanType SyncAuthenticPixels(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SyncAuthenticPixels(Image *image,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.sync_authentic_pixels_handler !=
(SyncAuthenticPixelsHandler) NULL)
{
status=cache_info->methods.sync_authentic_pixels_handler(image,
exception);
return(status);
}
assert(id < (int) cache_info->number_threads);
status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id],
exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S y n c I m a g e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImagePixelCache() saves the image pixels to the in-memory or disk cache.
% The method returns MagickTrue if the pixel region is flushed, otherwise
% MagickFalse.
%
% The format of the SyncImagePixelCache() method is:
%
% MagickBooleanType SyncImagePixelCache(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (Image *) NULL);
assert(exception != (ExceptionInfo *) NULL);
cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception);
return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ W r i t e P i x e l C a c h e M e t a c o n t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePixelCacheMetacontent() writes the meta-content to the specified region
% of the pixel cache.
%
% The format of the WritePixelCacheMetacontent() method is:
%
% MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o nexus_info: the cache nexus to write the meta-content.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info,
NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception)
{
MagickOffsetType
count,
offset;
MagickSizeType
extent,
length;
register const unsigned char
*magick_restrict p;
register ssize_t
y;
size_t
rows;
if (cache_info->metacontent_extent == 0)
return(MagickFalse);
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(MagickTrue);
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+
nexus_info->region.x;
length=(MagickSizeType) nexus_info->region.width*
cache_info->metacontent_extent;
extent=(MagickSizeType) length*nexus_info->region.height;
rows=nexus_info->region.height;
y=0;
p=(unsigned char *) nexus_info->metacontent;
switch (cache_info->type)
{
case MemoryCache:
case MapCache:
{
register unsigned char
*magick_restrict q;
/*
Write associated pixels to memory.
*/
if ((cache_info->columns == nexus_info->region.width) &&
(extent == (MagickSizeType) ((size_t) extent)))
{
length=extent;
rows=1UL;
}
q=(unsigned char *) cache_info->metacontent+offset*
cache_info->metacontent_extent;
for (y=0; y < (ssize_t) rows; y++)
{
(void) memcpy(q,p,(size_t) length);
p+=nexus_info->region.width*cache_info->metacontent_extent;
q+=cache_info->columns*cache_info->metacontent_extent;
}
break;
}
case DiskCache:
{
/*
Write associated pixels to disk.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
cache_info->cache_filename);
UnlockSemaphoreInfo(cache_info->file_semaphore);
return(MagickFalse);
}
if ((cache_info->columns == nexus_info->region.width) &&
(extent <= MagickMaxBufferExtent))
{
length=extent;
rows=1UL;
}
extent=(MagickSizeType) cache_info->columns*cache_info->rows;
for (y=0; y < (ssize_t) rows; y++)
{
count=WritePixelCacheRegion(cache_info,cache_info->offset+extent*
cache_info->number_channels*sizeof(Quantum)+offset*
cache_info->metacontent_extent,length,(const unsigned char *) p);
if (count != (MagickOffsetType) length)
break;
p+=cache_info->metacontent_extent*nexus_info->region.width;
offset+=cache_info->columns;
}
if (IsFileDescriptorLimitExceeded() != MagickFalse)
(void) ClosePixelCacheOnDisk(cache_info);
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
case DistributedCache:
{
RectangleInfo
region;
/*
Write metacontent to distributed cache.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
region=nexus_info->region;
if ((cache_info->columns != nexus_info->region.width) ||
(extent > MagickMaxBufferExtent))
region.height=1UL;
else
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=WriteDistributePixelCacheMetacontent((DistributeCacheInfo *)
cache_info->server_info,®ion,length,(const unsigned char *) p);
if (count != (MagickOffsetType) length)
break;
p+=cache_info->metacontent_extent*nexus_info->region.width;
region.y++;
}
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
default:
break;
}
if (y < (ssize_t) rows)
{
ThrowFileException(exception,CacheError,"UnableToWritePixelCache",
cache_info->cache_filename);
return(MagickFalse);
}
if ((cache_info->debug != MagickFalse) &&
(CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse))
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double)
nexus_info->region.width,(double) nexus_info->region.height,(double)
nexus_info->region.x,(double) nexus_info->region.y);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ W r i t e C a c h e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePixelCachePixels() writes image pixels to the specified region of the
% pixel cache.
%
% The format of the WritePixelCachePixels() method is:
%
% MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o nexus_info: the cache nexus to write the pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WritePixelCachePixels(
CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info,
ExceptionInfo *exception)
{
MagickOffsetType
count,
offset;
MagickSizeType
extent,
length;
register const Quantum
*magick_restrict p;
register ssize_t
y;
size_t
rows;
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(MagickTrue);
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+
nexus_info->region.x;
length=(MagickSizeType) cache_info->number_channels*nexus_info->region.width*
sizeof(Quantum);
extent=length*nexus_info->region.height;
rows=nexus_info->region.height;
y=0;
p=nexus_info->pixels;
switch (cache_info->type)
{
case MemoryCache:
case MapCache:
{
register Quantum
*magick_restrict q;
/*
Write pixels to memory.
*/
if ((cache_info->columns == nexus_info->region.width) &&
(extent == (MagickSizeType) ((size_t) extent)))
{
length=extent;
rows=1UL;
}
q=cache_info->pixels+offset*cache_info->number_channels;
for (y=0; y < (ssize_t) rows; y++)
{
(void) memcpy(q,p,(size_t) length);
p+=cache_info->number_channels*nexus_info->region.width;
q+=cache_info->columns*cache_info->number_channels;
}
break;
}
case DiskCache:
{
/*
Write pixels to disk.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
cache_info->cache_filename);
UnlockSemaphoreInfo(cache_info->file_semaphore);
return(MagickFalse);
}
if ((cache_info->columns == nexus_info->region.width) &&
(extent <= MagickMaxBufferExtent))
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=WritePixelCacheRegion(cache_info,cache_info->offset+offset*
cache_info->number_channels*sizeof(*p),length,(const unsigned char *)
p);
if (count != (MagickOffsetType) length)
break;
p+=cache_info->number_channels*nexus_info->region.width;
offset+=cache_info->columns;
}
if (IsFileDescriptorLimitExceeded() != MagickFalse)
(void) ClosePixelCacheOnDisk(cache_info);
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
case DistributedCache:
{
RectangleInfo
region;
/*
Write pixels to distributed cache.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
region=nexus_info->region;
if ((cache_info->columns != nexus_info->region.width) ||
(extent > MagickMaxBufferExtent))
region.height=1UL;
else
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=WriteDistributePixelCachePixels((DistributeCacheInfo *)
cache_info->server_info,®ion,length,(const unsigned char *) p);
if (count != (MagickOffsetType) length)
break;
p+=cache_info->number_channels*nexus_info->region.width;
region.y++;
}
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
default:
break;
}
if (y < (ssize_t) rows)
{
ThrowFileException(exception,CacheError,"UnableToWritePixelCache",
cache_info->cache_filename);
return(MagickFalse);
}
if ((cache_info->debug != MagickFalse) &&
(CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse))
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double)
nexus_info->region.width,(double) nexus_info->region.height,(double)
nexus_info->region.x,(double) nexus_info->region.y);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5127_0 |
crossvul-cpp_data_bad_3687_0 | /*
* super.c
*
* PURPOSE
* Super block routines for the OSTA-UDF(tm) filesystem.
*
* DESCRIPTION
* OSTA-UDF(tm) = Optical Storage Technology Association
* Universal Disk Format.
*
* This code is based on version 2.00 of the UDF specification,
* and revision 3 of the ECMA 167 standard [equivalent to ISO 13346].
* http://www.osta.org/
* http://www.ecma.ch/
* http://www.iso.org/
*
* COPYRIGHT
* This file is distributed under the terms of the GNU General Public
* License (GPL). Copies of the GPL can be obtained from:
* ftp://prep.ai.mit.edu/pub/gnu/GPL
* Each contributing author retains all rights to their own work.
*
* (C) 1998 Dave Boynton
* (C) 1998-2004 Ben Fennema
* (C) 2000 Stelias Computing Inc
*
* HISTORY
*
* 09/24/98 dgb changed to allow compiling outside of kernel, and
* added some debugging.
* 10/01/98 dgb updated to allow (some) possibility of compiling w/2.0.34
* 10/16/98 attempting some multi-session support
* 10/17/98 added freespace count for "df"
* 11/11/98 gr added novrs option
* 11/26/98 dgb added fileset,anchor mount options
* 12/06/98 blf really hosed things royally. vat/sparing support. sequenced
* vol descs. rewrote option handling based on isofs
* 12/20/98 find the free space bitmap (if it exists)
*/
#include "udfdecl.h"
#include <linux/blkdev.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/parser.h>
#include <linux/stat.h>
#include <linux/cdrom.h>
#include <linux/nls.h>
#include <linux/buffer_head.h>
#include <linux/vfs.h>
#include <linux/vmalloc.h>
#include <linux/errno.h>
#include <linux/mount.h>
#include <linux/seq_file.h>
#include <linux/bitmap.h>
#include <linux/crc-itu-t.h>
#include <asm/byteorder.h>
#include "udf_sb.h"
#include "udf_i.h"
#include <linux/init.h>
#include <asm/uaccess.h>
#define VDS_POS_PRIMARY_VOL_DESC 0
#define VDS_POS_UNALLOC_SPACE_DESC 1
#define VDS_POS_LOGICAL_VOL_DESC 2
#define VDS_POS_PARTITION_DESC 3
#define VDS_POS_IMP_USE_VOL_DESC 4
#define VDS_POS_VOL_DESC_PTR 5
#define VDS_POS_TERMINATING_DESC 6
#define VDS_POS_LENGTH 7
#define UDF_DEFAULT_BLOCKSIZE 2048
enum { UDF_MAX_LINKS = 0xffff };
/* These are the "meat" - everything else is stuffing */
static int udf_fill_super(struct super_block *, void *, int);
static void udf_put_super(struct super_block *);
static int udf_sync_fs(struct super_block *, int);
static int udf_remount_fs(struct super_block *, int *, char *);
static void udf_load_logicalvolint(struct super_block *, struct kernel_extent_ad);
static int udf_find_fileset(struct super_block *, struct kernel_lb_addr *,
struct kernel_lb_addr *);
static void udf_load_fileset(struct super_block *, struct buffer_head *,
struct kernel_lb_addr *);
static void udf_open_lvid(struct super_block *);
static void udf_close_lvid(struct super_block *);
static unsigned int udf_count_free(struct super_block *);
static int udf_statfs(struct dentry *, struct kstatfs *);
static int udf_show_options(struct seq_file *, struct dentry *);
struct logicalVolIntegrityDescImpUse *udf_sb_lvidiu(struct udf_sb_info *sbi)
{
struct logicalVolIntegrityDesc *lvid =
(struct logicalVolIntegrityDesc *)sbi->s_lvid_bh->b_data;
__u32 number_of_partitions = le32_to_cpu(lvid->numOfPartitions);
__u32 offset = number_of_partitions * 2 *
sizeof(uint32_t)/sizeof(uint8_t);
return (struct logicalVolIntegrityDescImpUse *)&(lvid->impUse[offset]);
}
/* UDF filesystem type */
static struct dentry *udf_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_bdev(fs_type, flags, dev_name, data, udf_fill_super);
}
static struct file_system_type udf_fstype = {
.owner = THIS_MODULE,
.name = "udf",
.mount = udf_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
static struct kmem_cache *udf_inode_cachep;
static struct inode *udf_alloc_inode(struct super_block *sb)
{
struct udf_inode_info *ei;
ei = kmem_cache_alloc(udf_inode_cachep, GFP_KERNEL);
if (!ei)
return NULL;
ei->i_unique = 0;
ei->i_lenExtents = 0;
ei->i_next_alloc_block = 0;
ei->i_next_alloc_goal = 0;
ei->i_strat4096 = 0;
init_rwsem(&ei->i_data_sem);
return &ei->vfs_inode;
}
static void udf_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(udf_inode_cachep, UDF_I(inode));
}
static void udf_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, udf_i_callback);
}
static void init_once(void *foo)
{
struct udf_inode_info *ei = (struct udf_inode_info *)foo;
ei->i_ext.i_data = NULL;
inode_init_once(&ei->vfs_inode);
}
static int init_inodecache(void)
{
udf_inode_cachep = kmem_cache_create("udf_inode_cache",
sizeof(struct udf_inode_info),
0, (SLAB_RECLAIM_ACCOUNT |
SLAB_MEM_SPREAD),
init_once);
if (!udf_inode_cachep)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
kmem_cache_destroy(udf_inode_cachep);
}
/* Superblock operations */
static const struct super_operations udf_sb_ops = {
.alloc_inode = udf_alloc_inode,
.destroy_inode = udf_destroy_inode,
.write_inode = udf_write_inode,
.evict_inode = udf_evict_inode,
.put_super = udf_put_super,
.sync_fs = udf_sync_fs,
.statfs = udf_statfs,
.remount_fs = udf_remount_fs,
.show_options = udf_show_options,
};
struct udf_options {
unsigned char novrs;
unsigned int blocksize;
unsigned int session;
unsigned int lastblock;
unsigned int anchor;
unsigned int volume;
unsigned short partition;
unsigned int fileset;
unsigned int rootdir;
unsigned int flags;
umode_t umask;
gid_t gid;
uid_t uid;
umode_t fmode;
umode_t dmode;
struct nls_table *nls_map;
};
static int __init init_udf_fs(void)
{
int err;
err = init_inodecache();
if (err)
goto out1;
err = register_filesystem(&udf_fstype);
if (err)
goto out;
return 0;
out:
destroy_inodecache();
out1:
return err;
}
static void __exit exit_udf_fs(void)
{
unregister_filesystem(&udf_fstype);
destroy_inodecache();
}
module_init(init_udf_fs)
module_exit(exit_udf_fs)
static int udf_sb_alloc_partition_maps(struct super_block *sb, u32 count)
{
struct udf_sb_info *sbi = UDF_SB(sb);
sbi->s_partmaps = kcalloc(count, sizeof(struct udf_part_map),
GFP_KERNEL);
if (!sbi->s_partmaps) {
udf_err(sb, "Unable to allocate space for %d partition maps\n",
count);
sbi->s_partitions = 0;
return -ENOMEM;
}
sbi->s_partitions = count;
return 0;
}
static int udf_show_options(struct seq_file *seq, struct dentry *root)
{
struct super_block *sb = root->d_sb;
struct udf_sb_info *sbi = UDF_SB(sb);
if (!UDF_QUERY_FLAG(sb, UDF_FLAG_STRICT))
seq_puts(seq, ",nostrict");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_BLOCKSIZE_SET))
seq_printf(seq, ",bs=%lu", sb->s_blocksize);
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UNHIDE))
seq_puts(seq, ",unhide");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UNDELETE))
seq_puts(seq, ",undelete");
if (!UDF_QUERY_FLAG(sb, UDF_FLAG_USE_AD_IN_ICB))
seq_puts(seq, ",noadinicb");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_USE_SHORT_AD))
seq_puts(seq, ",shortad");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UID_FORGET))
seq_puts(seq, ",uid=forget");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UID_IGNORE))
seq_puts(seq, ",uid=ignore");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_GID_FORGET))
seq_puts(seq, ",gid=forget");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_GID_IGNORE))
seq_puts(seq, ",gid=ignore");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UID_SET))
seq_printf(seq, ",uid=%u", sbi->s_uid);
if (UDF_QUERY_FLAG(sb, UDF_FLAG_GID_SET))
seq_printf(seq, ",gid=%u", sbi->s_gid);
if (sbi->s_umask != 0)
seq_printf(seq, ",umask=%ho", sbi->s_umask);
if (sbi->s_fmode != UDF_INVALID_MODE)
seq_printf(seq, ",mode=%ho", sbi->s_fmode);
if (sbi->s_dmode != UDF_INVALID_MODE)
seq_printf(seq, ",dmode=%ho", sbi->s_dmode);
if (UDF_QUERY_FLAG(sb, UDF_FLAG_SESSION_SET))
seq_printf(seq, ",session=%u", sbi->s_session);
if (UDF_QUERY_FLAG(sb, UDF_FLAG_LASTBLOCK_SET))
seq_printf(seq, ",lastblock=%u", sbi->s_last_block);
if (sbi->s_anchor != 0)
seq_printf(seq, ",anchor=%u", sbi->s_anchor);
/*
* volume, partition, fileset and rootdir seem to be ignored
* currently
*/
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UTF8))
seq_puts(seq, ",utf8");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP) && sbi->s_nls_map)
seq_printf(seq, ",iocharset=%s", sbi->s_nls_map->charset);
return 0;
}
/*
* udf_parse_options
*
* PURPOSE
* Parse mount options.
*
* DESCRIPTION
* The following mount options are supported:
*
* gid= Set the default group.
* umask= Set the default umask.
* mode= Set the default file permissions.
* dmode= Set the default directory permissions.
* uid= Set the default user.
* bs= Set the block size.
* unhide Show otherwise hidden files.
* undelete Show deleted files in lists.
* adinicb Embed data in the inode (default)
* noadinicb Don't embed data in the inode
* shortad Use short ad's
* longad Use long ad's (default)
* nostrict Unset strict conformance
* iocharset= Set the NLS character set
*
* The remaining are for debugging and disaster recovery:
*
* novrs Skip volume sequence recognition
*
* The following expect a offset from 0.
*
* session= Set the CDROM session (default= last session)
* anchor= Override standard anchor location. (default= 256)
* volume= Override the VolumeDesc location. (unused)
* partition= Override the PartitionDesc location. (unused)
* lastblock= Set the last block of the filesystem/
*
* The following expect a offset from the partition root.
*
* fileset= Override the fileset block location. (unused)
* rootdir= Override the root directory location. (unused)
* WARNING: overriding the rootdir to a non-directory may
* yield highly unpredictable results.
*
* PRE-CONDITIONS
* options Pointer to mount options string.
* uopts Pointer to mount options variable.
*
* POST-CONDITIONS
* <return> 1 Mount options parsed okay.
* <return> 0 Error parsing mount options.
*
* HISTORY
* July 1, 1997 - Andrew E. Mileski
* Written, tested, and released.
*/
enum {
Opt_novrs, Opt_nostrict, Opt_bs, Opt_unhide, Opt_undelete,
Opt_noadinicb, Opt_adinicb, Opt_shortad, Opt_longad,
Opt_gid, Opt_uid, Opt_umask, Opt_session, Opt_lastblock,
Opt_anchor, Opt_volume, Opt_partition, Opt_fileset,
Opt_rootdir, Opt_utf8, Opt_iocharset,
Opt_err, Opt_uforget, Opt_uignore, Opt_gforget, Opt_gignore,
Opt_fmode, Opt_dmode
};
static const match_table_t tokens = {
{Opt_novrs, "novrs"},
{Opt_nostrict, "nostrict"},
{Opt_bs, "bs=%u"},
{Opt_unhide, "unhide"},
{Opt_undelete, "undelete"},
{Opt_noadinicb, "noadinicb"},
{Opt_adinicb, "adinicb"},
{Opt_shortad, "shortad"},
{Opt_longad, "longad"},
{Opt_uforget, "uid=forget"},
{Opt_uignore, "uid=ignore"},
{Opt_gforget, "gid=forget"},
{Opt_gignore, "gid=ignore"},
{Opt_gid, "gid=%u"},
{Opt_uid, "uid=%u"},
{Opt_umask, "umask=%o"},
{Opt_session, "session=%u"},
{Opt_lastblock, "lastblock=%u"},
{Opt_anchor, "anchor=%u"},
{Opt_volume, "volume=%u"},
{Opt_partition, "partition=%u"},
{Opt_fileset, "fileset=%u"},
{Opt_rootdir, "rootdir=%u"},
{Opt_utf8, "utf8"},
{Opt_iocharset, "iocharset=%s"},
{Opt_fmode, "mode=%o"},
{Opt_dmode, "dmode=%o"},
{Opt_err, NULL}
};
static int udf_parse_options(char *options, struct udf_options *uopt,
bool remount)
{
char *p;
int option;
uopt->novrs = 0;
uopt->partition = 0xFFFF;
uopt->session = 0xFFFFFFFF;
uopt->lastblock = 0;
uopt->anchor = 0;
uopt->volume = 0xFFFFFFFF;
uopt->rootdir = 0xFFFFFFFF;
uopt->fileset = 0xFFFFFFFF;
uopt->nls_map = NULL;
if (!options)
return 1;
while ((p = strsep(&options, ",")) != NULL) {
substring_t args[MAX_OPT_ARGS];
int token;
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_novrs:
uopt->novrs = 1;
break;
case Opt_bs:
if (match_int(&args[0], &option))
return 0;
uopt->blocksize = option;
uopt->flags |= (1 << UDF_FLAG_BLOCKSIZE_SET);
break;
case Opt_unhide:
uopt->flags |= (1 << UDF_FLAG_UNHIDE);
break;
case Opt_undelete:
uopt->flags |= (1 << UDF_FLAG_UNDELETE);
break;
case Opt_noadinicb:
uopt->flags &= ~(1 << UDF_FLAG_USE_AD_IN_ICB);
break;
case Opt_adinicb:
uopt->flags |= (1 << UDF_FLAG_USE_AD_IN_ICB);
break;
case Opt_shortad:
uopt->flags |= (1 << UDF_FLAG_USE_SHORT_AD);
break;
case Opt_longad:
uopt->flags &= ~(1 << UDF_FLAG_USE_SHORT_AD);
break;
case Opt_gid:
if (match_int(args, &option))
return 0;
uopt->gid = option;
uopt->flags |= (1 << UDF_FLAG_GID_SET);
break;
case Opt_uid:
if (match_int(args, &option))
return 0;
uopt->uid = option;
uopt->flags |= (1 << UDF_FLAG_UID_SET);
break;
case Opt_umask:
if (match_octal(args, &option))
return 0;
uopt->umask = option;
break;
case Opt_nostrict:
uopt->flags &= ~(1 << UDF_FLAG_STRICT);
break;
case Opt_session:
if (match_int(args, &option))
return 0;
uopt->session = option;
if (!remount)
uopt->flags |= (1 << UDF_FLAG_SESSION_SET);
break;
case Opt_lastblock:
if (match_int(args, &option))
return 0;
uopt->lastblock = option;
if (!remount)
uopt->flags |= (1 << UDF_FLAG_LASTBLOCK_SET);
break;
case Opt_anchor:
if (match_int(args, &option))
return 0;
uopt->anchor = option;
break;
case Opt_volume:
if (match_int(args, &option))
return 0;
uopt->volume = option;
break;
case Opt_partition:
if (match_int(args, &option))
return 0;
uopt->partition = option;
break;
case Opt_fileset:
if (match_int(args, &option))
return 0;
uopt->fileset = option;
break;
case Opt_rootdir:
if (match_int(args, &option))
return 0;
uopt->rootdir = option;
break;
case Opt_utf8:
uopt->flags |= (1 << UDF_FLAG_UTF8);
break;
#ifdef CONFIG_UDF_NLS
case Opt_iocharset:
uopt->nls_map = load_nls(args[0].from);
uopt->flags |= (1 << UDF_FLAG_NLS_MAP);
break;
#endif
case Opt_uignore:
uopt->flags |= (1 << UDF_FLAG_UID_IGNORE);
break;
case Opt_uforget:
uopt->flags |= (1 << UDF_FLAG_UID_FORGET);
break;
case Opt_gignore:
uopt->flags |= (1 << UDF_FLAG_GID_IGNORE);
break;
case Opt_gforget:
uopt->flags |= (1 << UDF_FLAG_GID_FORGET);
break;
case Opt_fmode:
if (match_octal(args, &option))
return 0;
uopt->fmode = option & 0777;
break;
case Opt_dmode:
if (match_octal(args, &option))
return 0;
uopt->dmode = option & 0777;
break;
default:
pr_err("bad mount option \"%s\" or missing value\n", p);
return 0;
}
}
return 1;
}
static int udf_remount_fs(struct super_block *sb, int *flags, char *options)
{
struct udf_options uopt;
struct udf_sb_info *sbi = UDF_SB(sb);
int error = 0;
uopt.flags = sbi->s_flags;
uopt.uid = sbi->s_uid;
uopt.gid = sbi->s_gid;
uopt.umask = sbi->s_umask;
uopt.fmode = sbi->s_fmode;
uopt.dmode = sbi->s_dmode;
if (!udf_parse_options(options, &uopt, true))
return -EINVAL;
write_lock(&sbi->s_cred_lock);
sbi->s_flags = uopt.flags;
sbi->s_uid = uopt.uid;
sbi->s_gid = uopt.gid;
sbi->s_umask = uopt.umask;
sbi->s_fmode = uopt.fmode;
sbi->s_dmode = uopt.dmode;
write_unlock(&sbi->s_cred_lock);
if (sbi->s_lvid_bh) {
int write_rev = le16_to_cpu(udf_sb_lvidiu(sbi)->minUDFWriteRev);
if (write_rev > UDF_MAX_WRITE_VERSION)
*flags |= MS_RDONLY;
}
if ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY))
goto out_unlock;
if (*flags & MS_RDONLY)
udf_close_lvid(sb);
else
udf_open_lvid(sb);
out_unlock:
return error;
}
/* Check Volume Structure Descriptors (ECMA 167 2/9.1) */
/* We also check any "CD-ROM Volume Descriptor Set" (ECMA 167 2/8.3.1) */
static loff_t udf_check_vsd(struct super_block *sb)
{
struct volStructDesc *vsd = NULL;
loff_t sector = 32768;
int sectorsize;
struct buffer_head *bh = NULL;
int nsr02 = 0;
int nsr03 = 0;
struct udf_sb_info *sbi;
sbi = UDF_SB(sb);
if (sb->s_blocksize < sizeof(struct volStructDesc))
sectorsize = sizeof(struct volStructDesc);
else
sectorsize = sb->s_blocksize;
sector += (sbi->s_session << sb->s_blocksize_bits);
udf_debug("Starting at sector %u (%ld byte sectors)\n",
(unsigned int)(sector >> sb->s_blocksize_bits),
sb->s_blocksize);
/* Process the sequence (if applicable) */
for (; !nsr02 && !nsr03; sector += sectorsize) {
/* Read a block */
bh = udf_tread(sb, sector >> sb->s_blocksize_bits);
if (!bh)
break;
/* Look for ISO descriptors */
vsd = (struct volStructDesc *)(bh->b_data +
(sector & (sb->s_blocksize - 1)));
if (vsd->stdIdent[0] == 0) {
brelse(bh);
break;
} else if (!strncmp(vsd->stdIdent, VSD_STD_ID_CD001,
VSD_STD_ID_LEN)) {
switch (vsd->structType) {
case 0:
udf_debug("ISO9660 Boot Record found\n");
break;
case 1:
udf_debug("ISO9660 Primary Volume Descriptor found\n");
break;
case 2:
udf_debug("ISO9660 Supplementary Volume Descriptor found\n");
break;
case 3:
udf_debug("ISO9660 Volume Partition Descriptor found\n");
break;
case 255:
udf_debug("ISO9660 Volume Descriptor Set Terminator found\n");
break;
default:
udf_debug("ISO9660 VRS (%u) found\n",
vsd->structType);
break;
}
} else if (!strncmp(vsd->stdIdent, VSD_STD_ID_BEA01,
VSD_STD_ID_LEN))
; /* nothing */
else if (!strncmp(vsd->stdIdent, VSD_STD_ID_TEA01,
VSD_STD_ID_LEN)) {
brelse(bh);
break;
} else if (!strncmp(vsd->stdIdent, VSD_STD_ID_NSR02,
VSD_STD_ID_LEN))
nsr02 = sector;
else if (!strncmp(vsd->stdIdent, VSD_STD_ID_NSR03,
VSD_STD_ID_LEN))
nsr03 = sector;
brelse(bh);
}
if (nsr03)
return nsr03;
else if (nsr02)
return nsr02;
else if (sector - (sbi->s_session << sb->s_blocksize_bits) == 32768)
return -1;
else
return 0;
}
static int udf_find_fileset(struct super_block *sb,
struct kernel_lb_addr *fileset,
struct kernel_lb_addr *root)
{
struct buffer_head *bh = NULL;
long lastblock;
uint16_t ident;
struct udf_sb_info *sbi;
if (fileset->logicalBlockNum != 0xFFFFFFFF ||
fileset->partitionReferenceNum != 0xFFFF) {
bh = udf_read_ptagged(sb, fileset, 0, &ident);
if (!bh) {
return 1;
} else if (ident != TAG_IDENT_FSD) {
brelse(bh);
return 1;
}
}
sbi = UDF_SB(sb);
if (!bh) {
/* Search backwards through the partitions */
struct kernel_lb_addr newfileset;
/* --> cvg: FIXME - is it reasonable? */
return 1;
for (newfileset.partitionReferenceNum = sbi->s_partitions - 1;
(newfileset.partitionReferenceNum != 0xFFFF &&
fileset->logicalBlockNum == 0xFFFFFFFF &&
fileset->partitionReferenceNum == 0xFFFF);
newfileset.partitionReferenceNum--) {
lastblock = sbi->s_partmaps
[newfileset.partitionReferenceNum]
.s_partition_len;
newfileset.logicalBlockNum = 0;
do {
bh = udf_read_ptagged(sb, &newfileset, 0,
&ident);
if (!bh) {
newfileset.logicalBlockNum++;
continue;
}
switch (ident) {
case TAG_IDENT_SBD:
{
struct spaceBitmapDesc *sp;
sp = (struct spaceBitmapDesc *)
bh->b_data;
newfileset.logicalBlockNum += 1 +
((le32_to_cpu(sp->numOfBytes) +
sizeof(struct spaceBitmapDesc)
- 1) >> sb->s_blocksize_bits);
brelse(bh);
break;
}
case TAG_IDENT_FSD:
*fileset = newfileset;
break;
default:
newfileset.logicalBlockNum++;
brelse(bh);
bh = NULL;
break;
}
} while (newfileset.logicalBlockNum < lastblock &&
fileset->logicalBlockNum == 0xFFFFFFFF &&
fileset->partitionReferenceNum == 0xFFFF);
}
}
if ((fileset->logicalBlockNum != 0xFFFFFFFF ||
fileset->partitionReferenceNum != 0xFFFF) && bh) {
udf_debug("Fileset at block=%d, partition=%d\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
sbi->s_partition = fileset->partitionReferenceNum;
udf_load_fileset(sb, bh, root);
brelse(bh);
return 0;
}
return 1;
}
static int udf_load_pvoldesc(struct super_block *sb, sector_t block)
{
struct primaryVolDesc *pvoldesc;
struct ustr *instr, *outstr;
struct buffer_head *bh;
uint16_t ident;
int ret = 1;
instr = kmalloc(sizeof(struct ustr), GFP_NOFS);
if (!instr)
return 1;
outstr = kmalloc(sizeof(struct ustr), GFP_NOFS);
if (!outstr)
goto out1;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
goto out2;
BUG_ON(ident != TAG_IDENT_PVD);
pvoldesc = (struct primaryVolDesc *)bh->b_data;
if (udf_disk_stamp_to_time(&UDF_SB(sb)->s_record_time,
pvoldesc->recordingDateAndTime)) {
#ifdef UDFFS_DEBUG
struct timestamp *ts = &pvoldesc->recordingDateAndTime;
udf_debug("recording time %04u/%02u/%02u %02u:%02u (%x)\n",
le16_to_cpu(ts->year), ts->month, ts->day, ts->hour,
ts->minute, le16_to_cpu(ts->typeAndTimezone));
#endif
}
if (!udf_build_ustr(instr, pvoldesc->volIdent, 32))
if (udf_CS0toUTF8(outstr, instr)) {
strncpy(UDF_SB(sb)->s_volume_ident, outstr->u_name,
outstr->u_len > 31 ? 31 : outstr->u_len);
udf_debug("volIdent[] = '%s'\n",
UDF_SB(sb)->s_volume_ident);
}
if (!udf_build_ustr(instr, pvoldesc->volSetIdent, 128))
if (udf_CS0toUTF8(outstr, instr))
udf_debug("volSetIdent[] = '%s'\n", outstr->u_name);
brelse(bh);
ret = 0;
out2:
kfree(outstr);
out1:
kfree(instr);
return ret;
}
struct inode *udf_find_metadata_inode_efe(struct super_block *sb,
u32 meta_file_loc, u32 partition_num)
{
struct kernel_lb_addr addr;
struct inode *metadata_fe;
addr.logicalBlockNum = meta_file_loc;
addr.partitionReferenceNum = partition_num;
metadata_fe = udf_iget(sb, &addr);
if (metadata_fe == NULL)
udf_warn(sb, "metadata inode efe not found\n");
else if (UDF_I(metadata_fe)->i_alloc_type != ICBTAG_FLAG_AD_SHORT) {
udf_warn(sb, "metadata inode efe does not have short allocation descriptors!\n");
iput(metadata_fe);
metadata_fe = NULL;
}
return metadata_fe;
}
static int udf_load_metadata_files(struct super_block *sb, int partition)
{
struct udf_sb_info *sbi = UDF_SB(sb);
struct udf_part_map *map;
struct udf_meta_data *mdata;
struct kernel_lb_addr addr;
map = &sbi->s_partmaps[partition];
mdata = &map->s_type_specific.s_metadata;
/* metadata address */
udf_debug("Metadata file location: block = %d part = %d\n",
mdata->s_meta_file_loc, map->s_partition_num);
mdata->s_metadata_fe = udf_find_metadata_inode_efe(sb,
mdata->s_meta_file_loc, map->s_partition_num);
if (mdata->s_metadata_fe == NULL) {
/* mirror file entry */
udf_debug("Mirror metadata file location: block = %d part = %d\n",
mdata->s_mirror_file_loc, map->s_partition_num);
mdata->s_mirror_fe = udf_find_metadata_inode_efe(sb,
mdata->s_mirror_file_loc, map->s_partition_num);
if (mdata->s_mirror_fe == NULL) {
udf_err(sb, "Both metadata and mirror metadata inode efe can not found\n");
goto error_exit;
}
}
/*
* bitmap file entry
* Note:
* Load only if bitmap file location differs from 0xFFFFFFFF (DCN-5102)
*/
if (mdata->s_bitmap_file_loc != 0xFFFFFFFF) {
addr.logicalBlockNum = mdata->s_bitmap_file_loc;
addr.partitionReferenceNum = map->s_partition_num;
udf_debug("Bitmap file location: block = %d part = %d\n",
addr.logicalBlockNum, addr.partitionReferenceNum);
mdata->s_bitmap_fe = udf_iget(sb, &addr);
if (mdata->s_bitmap_fe == NULL) {
if (sb->s_flags & MS_RDONLY)
udf_warn(sb, "bitmap inode efe not found but it's ok since the disc is mounted read-only\n");
else {
udf_err(sb, "bitmap inode efe not found and attempted read-write mount\n");
goto error_exit;
}
}
}
udf_debug("udf_load_metadata_files Ok\n");
return 0;
error_exit:
return 1;
}
static void udf_load_fileset(struct super_block *sb, struct buffer_head *bh,
struct kernel_lb_addr *root)
{
struct fileSetDesc *fset;
fset = (struct fileSetDesc *)bh->b_data;
*root = lelb_to_cpu(fset->rootDirectoryICB.extLocation);
UDF_SB(sb)->s_serial_number = le16_to_cpu(fset->descTag.tagSerialNum);
udf_debug("Rootdir at block=%d, partition=%d\n",
root->logicalBlockNum, root->partitionReferenceNum);
}
int udf_compute_nr_groups(struct super_block *sb, u32 partition)
{
struct udf_part_map *map = &UDF_SB(sb)->s_partmaps[partition];
return DIV_ROUND_UP(map->s_partition_len +
(sizeof(struct spaceBitmapDesc) << 3),
sb->s_blocksize * 8);
}
static struct udf_bitmap *udf_sb_alloc_bitmap(struct super_block *sb, u32 index)
{
struct udf_bitmap *bitmap;
int nr_groups;
int size;
nr_groups = udf_compute_nr_groups(sb, index);
size = sizeof(struct udf_bitmap) +
(sizeof(struct buffer_head *) * nr_groups);
if (size <= PAGE_SIZE)
bitmap = kzalloc(size, GFP_KERNEL);
else
bitmap = vzalloc(size); /* TODO: get rid of vzalloc */
if (bitmap == NULL)
return NULL;
bitmap->s_block_bitmap = (struct buffer_head **)(bitmap + 1);
bitmap->s_nr_groups = nr_groups;
return bitmap;
}
static int udf_fill_partdesc_info(struct super_block *sb,
struct partitionDesc *p, int p_index)
{
struct udf_part_map *map;
struct udf_sb_info *sbi = UDF_SB(sb);
struct partitionHeaderDesc *phd;
map = &sbi->s_partmaps[p_index];
map->s_partition_len = le32_to_cpu(p->partitionLength); /* blocks */
map->s_partition_root = le32_to_cpu(p->partitionStartingLocation);
if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_READ_ONLY))
map->s_partition_flags |= UDF_PART_FLAG_READ_ONLY;
if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_WRITE_ONCE))
map->s_partition_flags |= UDF_PART_FLAG_WRITE_ONCE;
if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_REWRITABLE))
map->s_partition_flags |= UDF_PART_FLAG_REWRITABLE;
if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_OVERWRITABLE))
map->s_partition_flags |= UDF_PART_FLAG_OVERWRITABLE;
udf_debug("Partition (%d type %x) starts at physical %d, block length %d\n",
p_index, map->s_partition_type,
map->s_partition_root, map->s_partition_len);
if (strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR02) &&
strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR03))
return 0;
phd = (struct partitionHeaderDesc *)p->partitionContentsUse;
if (phd->unallocSpaceTable.extLength) {
struct kernel_lb_addr loc = {
.logicalBlockNum = le32_to_cpu(
phd->unallocSpaceTable.extPosition),
.partitionReferenceNum = p_index,
};
map->s_uspace.s_table = udf_iget(sb, &loc);
if (!map->s_uspace.s_table) {
udf_debug("cannot load unallocSpaceTable (part %d)\n",
p_index);
return 1;
}
map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_TABLE;
udf_debug("unallocSpaceTable (part %d) @ %ld\n",
p_index, map->s_uspace.s_table->i_ino);
}
if (phd->unallocSpaceBitmap.extLength) {
struct udf_bitmap *bitmap = udf_sb_alloc_bitmap(sb, p_index);
if (!bitmap)
return 1;
map->s_uspace.s_bitmap = bitmap;
bitmap->s_extLength = le32_to_cpu(
phd->unallocSpaceBitmap.extLength);
bitmap->s_extPosition = le32_to_cpu(
phd->unallocSpaceBitmap.extPosition);
map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_BITMAP;
udf_debug("unallocSpaceBitmap (part %d) @ %d\n",
p_index, bitmap->s_extPosition);
}
if (phd->partitionIntegrityTable.extLength)
udf_debug("partitionIntegrityTable (part %d)\n", p_index);
if (phd->freedSpaceTable.extLength) {
struct kernel_lb_addr loc = {
.logicalBlockNum = le32_to_cpu(
phd->freedSpaceTable.extPosition),
.partitionReferenceNum = p_index,
};
map->s_fspace.s_table = udf_iget(sb, &loc);
if (!map->s_fspace.s_table) {
udf_debug("cannot load freedSpaceTable (part %d)\n",
p_index);
return 1;
}
map->s_partition_flags |= UDF_PART_FLAG_FREED_TABLE;
udf_debug("freedSpaceTable (part %d) @ %ld\n",
p_index, map->s_fspace.s_table->i_ino);
}
if (phd->freedSpaceBitmap.extLength) {
struct udf_bitmap *bitmap = udf_sb_alloc_bitmap(sb, p_index);
if (!bitmap)
return 1;
map->s_fspace.s_bitmap = bitmap;
bitmap->s_extLength = le32_to_cpu(
phd->freedSpaceBitmap.extLength);
bitmap->s_extPosition = le32_to_cpu(
phd->freedSpaceBitmap.extPosition);
map->s_partition_flags |= UDF_PART_FLAG_FREED_BITMAP;
udf_debug("freedSpaceBitmap (part %d) @ %d\n",
p_index, bitmap->s_extPosition);
}
return 0;
}
static void udf_find_vat_block(struct super_block *sb, int p_index,
int type1_index, sector_t start_block)
{
struct udf_sb_info *sbi = UDF_SB(sb);
struct udf_part_map *map = &sbi->s_partmaps[p_index];
sector_t vat_block;
struct kernel_lb_addr ino;
/*
* VAT file entry is in the last recorded block. Some broken disks have
* it a few blocks before so try a bit harder...
*/
ino.partitionReferenceNum = type1_index;
for (vat_block = start_block;
vat_block >= map->s_partition_root &&
vat_block >= start_block - 3 &&
!sbi->s_vat_inode; vat_block--) {
ino.logicalBlockNum = vat_block - map->s_partition_root;
sbi->s_vat_inode = udf_iget(sb, &ino);
}
}
static int udf_load_vat(struct super_block *sb, int p_index, int type1_index)
{
struct udf_sb_info *sbi = UDF_SB(sb);
struct udf_part_map *map = &sbi->s_partmaps[p_index];
struct buffer_head *bh = NULL;
struct udf_inode_info *vati;
uint32_t pos;
struct virtualAllocationTable20 *vat20;
sector_t blocks = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
udf_find_vat_block(sb, p_index, type1_index, sbi->s_last_block);
if (!sbi->s_vat_inode &&
sbi->s_last_block != blocks - 1) {
pr_notice("Failed to read VAT inode from the last recorded block (%lu), retrying with the last block of the device (%lu).\n",
(unsigned long)sbi->s_last_block,
(unsigned long)blocks - 1);
udf_find_vat_block(sb, p_index, type1_index, blocks - 1);
}
if (!sbi->s_vat_inode)
return 1;
if (map->s_partition_type == UDF_VIRTUAL_MAP15) {
map->s_type_specific.s_virtual.s_start_offset = 0;
map->s_type_specific.s_virtual.s_num_entries =
(sbi->s_vat_inode->i_size - 36) >> 2;
} else if (map->s_partition_type == UDF_VIRTUAL_MAP20) {
vati = UDF_I(sbi->s_vat_inode);
if (vati->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) {
pos = udf_block_map(sbi->s_vat_inode, 0);
bh = sb_bread(sb, pos);
if (!bh)
return 1;
vat20 = (struct virtualAllocationTable20 *)bh->b_data;
} else {
vat20 = (struct virtualAllocationTable20 *)
vati->i_ext.i_data;
}
map->s_type_specific.s_virtual.s_start_offset =
le16_to_cpu(vat20->lengthHeader);
map->s_type_specific.s_virtual.s_num_entries =
(sbi->s_vat_inode->i_size -
map->s_type_specific.s_virtual.
s_start_offset) >> 2;
brelse(bh);
}
return 0;
}
static int udf_load_partdesc(struct super_block *sb, sector_t block)
{
struct buffer_head *bh;
struct partitionDesc *p;
struct udf_part_map *map;
struct udf_sb_info *sbi = UDF_SB(sb);
int i, type1_idx;
uint16_t partitionNumber;
uint16_t ident;
int ret = 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 1;
if (ident != TAG_IDENT_PD)
goto out_bh;
p = (struct partitionDesc *)bh->b_data;
partitionNumber = le16_to_cpu(p->partitionNumber);
/* First scan for TYPE1, SPARABLE and METADATA partitions */
for (i = 0; i < sbi->s_partitions; i++) {
map = &sbi->s_partmaps[i];
udf_debug("Searching map: (%d == %d)\n",
map->s_partition_num, partitionNumber);
if (map->s_partition_num == partitionNumber &&
(map->s_partition_type == UDF_TYPE1_MAP15 ||
map->s_partition_type == UDF_SPARABLE_MAP15))
break;
}
if (i >= sbi->s_partitions) {
udf_debug("Partition (%d) not found in partition map\n",
partitionNumber);
goto out_bh;
}
ret = udf_fill_partdesc_info(sb, p, i);
/*
* Now rescan for VIRTUAL or METADATA partitions when SPARABLE and
* PHYSICAL partitions are already set up
*/
type1_idx = i;
for (i = 0; i < sbi->s_partitions; i++) {
map = &sbi->s_partmaps[i];
if (map->s_partition_num == partitionNumber &&
(map->s_partition_type == UDF_VIRTUAL_MAP15 ||
map->s_partition_type == UDF_VIRTUAL_MAP20 ||
map->s_partition_type == UDF_METADATA_MAP25))
break;
}
if (i >= sbi->s_partitions)
goto out_bh;
ret = udf_fill_partdesc_info(sb, p, i);
if (ret)
goto out_bh;
if (map->s_partition_type == UDF_METADATA_MAP25) {
ret = udf_load_metadata_files(sb, i);
if (ret) {
udf_err(sb, "error loading MetaData partition map %d\n",
i);
goto out_bh;
}
} else {
ret = udf_load_vat(sb, i, type1_idx);
if (ret)
goto out_bh;
/*
* Mark filesystem read-only if we have a partition with
* virtual map since we don't handle writing to it (we
* overwrite blocks instead of relocating them).
*/
sb->s_flags |= MS_RDONLY;
pr_notice("Filesystem marked read-only because writing to pseudooverwrite partition is not implemented\n");
}
out_bh:
/* In case loading failed, we handle cleanup in udf_fill_super */
brelse(bh);
return ret;
}
static int udf_load_logicalvol(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct logicalVolDesc *lvd;
int i, j, offset;
uint8_t type;
struct udf_sb_info *sbi = UDF_SB(sb);
struct genericPartitionMap *gpm;
uint16_t ident;
struct buffer_head *bh;
int ret = 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 1;
BUG_ON(ident != TAG_IDENT_LVD);
lvd = (struct logicalVolDesc *)bh->b_data;
ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
if (ret)
goto out_bh;
for (i = 0, offset = 0;
i < sbi->s_partitions && offset < le32_to_cpu(lvd->mapTableLength);
i++, offset += gpm->partitionMapLength) {
struct udf_part_map *map = &sbi->s_partmaps[i];
gpm = (struct genericPartitionMap *)
&(lvd->partitionMaps[offset]);
type = gpm->partitionMapType;
if (type == 1) {
struct genericPartitionMap1 *gpm1 =
(struct genericPartitionMap1 *)gpm;
map->s_partition_type = UDF_TYPE1_MAP15;
map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
map->s_partition_func = NULL;
} else if (type == 2) {
struct udfPartitionMap2 *upm2 =
(struct udfPartitionMap2 *)gpm;
if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
strlen(UDF_ID_VIRTUAL))) {
u16 suf =
le16_to_cpu(((__le16 *)upm2->partIdent.
identSuffix)[0]);
if (suf < 0x0200) {
map->s_partition_type =
UDF_VIRTUAL_MAP15;
map->s_partition_func =
udf_get_pblock_virt15;
} else {
map->s_partition_type =
UDF_VIRTUAL_MAP20;
map->s_partition_func =
udf_get_pblock_virt20;
}
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_SPARABLE,
strlen(UDF_ID_SPARABLE))) {
uint32_t loc;
struct sparingTable *st;
struct sparablePartitionMap *spm =
(struct sparablePartitionMap *)gpm;
map->s_partition_type = UDF_SPARABLE_MAP15;
map->s_type_specific.s_sparing.s_packet_len =
le16_to_cpu(spm->packetLength);
for (j = 0; j < spm->numSparingTables; j++) {
struct buffer_head *bh2;
loc = le32_to_cpu(
spm->locSparingTable[j]);
bh2 = udf_read_tagged(sb, loc, loc,
&ident);
map->s_type_specific.s_sparing.
s_spar_map[j] = bh2;
if (bh2 == NULL)
continue;
st = (struct sparingTable *)bh2->b_data;
if (ident != 0 || strncmp(
st->sparingIdent.ident,
UDF_ID_SPARING,
strlen(UDF_ID_SPARING))) {
brelse(bh2);
map->s_type_specific.s_sparing.
s_spar_map[j] = NULL;
}
}
map->s_partition_func = udf_get_pblock_spar15;
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_METADATA,
strlen(UDF_ID_METADATA))) {
struct udf_meta_data *mdata =
&map->s_type_specific.s_metadata;
struct metadataPartitionMap *mdm =
(struct metadataPartitionMap *)
&(lvd->partitionMaps[offset]);
udf_debug("Parsing Logical vol part %d type %d id=%s\n",
i, type, UDF_ID_METADATA);
map->s_partition_type = UDF_METADATA_MAP25;
map->s_partition_func = udf_get_pblock_meta25;
mdata->s_meta_file_loc =
le32_to_cpu(mdm->metadataFileLoc);
mdata->s_mirror_file_loc =
le32_to_cpu(mdm->metadataMirrorFileLoc);
mdata->s_bitmap_file_loc =
le32_to_cpu(mdm->metadataBitmapFileLoc);
mdata->s_alloc_unit_size =
le32_to_cpu(mdm->allocUnitSize);
mdata->s_align_unit_size =
le16_to_cpu(mdm->alignUnitSize);
if (mdm->flags & 0x01)
mdata->s_flags |= MF_DUPLICATE_MD;
udf_debug("Metadata Ident suffix=0x%x\n",
le16_to_cpu(*(__le16 *)
mdm->partIdent.identSuffix));
udf_debug("Metadata part num=%d\n",
le16_to_cpu(mdm->partitionNum));
udf_debug("Metadata part alloc unit size=%d\n",
le32_to_cpu(mdm->allocUnitSize));
udf_debug("Metadata file loc=%d\n",
le32_to_cpu(mdm->metadataFileLoc));
udf_debug("Mirror file loc=%d\n",
le32_to_cpu(mdm->metadataMirrorFileLoc));
udf_debug("Bitmap file loc=%d\n",
le32_to_cpu(mdm->metadataBitmapFileLoc));
udf_debug("Flags: %d %d\n",
mdata->s_flags, mdm->flags);
} else {
udf_debug("Unknown ident: %s\n",
upm2->partIdent.ident);
continue;
}
map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
map->s_partition_num = le16_to_cpu(upm2->partitionNum);
}
udf_debug("Partition (%d:%d) type %d on volume %d\n",
i, map->s_partition_num, type, map->s_volumeseqnum);
}
if (fileset) {
struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
*fileset = lelb_to_cpu(la->extLocation);
udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
}
if (lvd->integritySeqExt.extLength)
udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
out_bh:
brelse(bh);
return ret;
}
/*
* udf_load_logicalvolint
*
*/
static void udf_load_logicalvolint(struct super_block *sb, struct kernel_extent_ad loc)
{
struct buffer_head *bh = NULL;
uint16_t ident;
struct udf_sb_info *sbi = UDF_SB(sb);
struct logicalVolIntegrityDesc *lvid;
while (loc.extLength > 0 &&
(bh = udf_read_tagged(sb, loc.extLocation,
loc.extLocation, &ident)) &&
ident == TAG_IDENT_LVID) {
sbi->s_lvid_bh = bh;
lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
if (lvid->nextIntegrityExt.extLength)
udf_load_logicalvolint(sb,
leea_to_cpu(lvid->nextIntegrityExt));
if (sbi->s_lvid_bh != bh)
brelse(bh);
loc.extLength -= sb->s_blocksize;
loc.extLocation++;
}
if (sbi->s_lvid_bh != bh)
brelse(bh);
}
/*
* udf_process_sequence
*
* PURPOSE
* Process a main/reserve volume descriptor sequence.
*
* PRE-CONDITIONS
* sb Pointer to _locked_ superblock.
* block First block of first extent of the sequence.
* lastblock Lastblock of first extent of the sequence.
*
* HISTORY
* July 1, 1997 - Andrew E. Mileski
* Written, tested, and released.
*/
static noinline int udf_process_sequence(struct super_block *sb, long block,
long lastblock, struct kernel_lb_addr *fileset)
{
struct buffer_head *bh = NULL;
struct udf_vds_record vds[VDS_POS_LENGTH];
struct udf_vds_record *curr;
struct generic_desc *gd;
struct volDescPtr *vdp;
int done = 0;
uint32_t vdsn;
uint16_t ident;
long next_s = 0, next_e = 0;
memset(vds, 0, sizeof(struct udf_vds_record) * VDS_POS_LENGTH);
/*
* Read the main descriptor sequence and find which descriptors
* are in it.
*/
for (; (!done && block <= lastblock); block++) {
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh) {
udf_err(sb,
"Block %llu of volume descriptor sequence is corrupted or we could not read it\n",
(unsigned long long)block);
return 1;
}
/* Process each descriptor (ISO 13346 3/8.3-8.4) */
gd = (struct generic_desc *)bh->b_data;
vdsn = le32_to_cpu(gd->volDescSeqNum);
switch (ident) {
case TAG_IDENT_PVD: /* ISO 13346 3/10.1 */
curr = &vds[VDS_POS_PRIMARY_VOL_DESC];
if (vdsn >= curr->volDescSeqNum) {
curr->volDescSeqNum = vdsn;
curr->block = block;
}
break;
case TAG_IDENT_VDP: /* ISO 13346 3/10.3 */
curr = &vds[VDS_POS_VOL_DESC_PTR];
if (vdsn >= curr->volDescSeqNum) {
curr->volDescSeqNum = vdsn;
curr->block = block;
vdp = (struct volDescPtr *)bh->b_data;
next_s = le32_to_cpu(
vdp->nextVolDescSeqExt.extLocation);
next_e = le32_to_cpu(
vdp->nextVolDescSeqExt.extLength);
next_e = next_e >> sb->s_blocksize_bits;
next_e += next_s;
}
break;
case TAG_IDENT_IUVD: /* ISO 13346 3/10.4 */
curr = &vds[VDS_POS_IMP_USE_VOL_DESC];
if (vdsn >= curr->volDescSeqNum) {
curr->volDescSeqNum = vdsn;
curr->block = block;
}
break;
case TAG_IDENT_PD: /* ISO 13346 3/10.5 */
curr = &vds[VDS_POS_PARTITION_DESC];
if (!curr->block)
curr->block = block;
break;
case TAG_IDENT_LVD: /* ISO 13346 3/10.6 */
curr = &vds[VDS_POS_LOGICAL_VOL_DESC];
if (vdsn >= curr->volDescSeqNum) {
curr->volDescSeqNum = vdsn;
curr->block = block;
}
break;
case TAG_IDENT_USD: /* ISO 13346 3/10.8 */
curr = &vds[VDS_POS_UNALLOC_SPACE_DESC];
if (vdsn >= curr->volDescSeqNum) {
curr->volDescSeqNum = vdsn;
curr->block = block;
}
break;
case TAG_IDENT_TD: /* ISO 13346 3/10.9 */
vds[VDS_POS_TERMINATING_DESC].block = block;
if (next_e) {
block = next_s;
lastblock = next_e;
next_s = next_e = 0;
} else
done = 1;
break;
}
brelse(bh);
}
/*
* Now read interesting descriptors again and process them
* in a suitable order
*/
if (!vds[VDS_POS_PRIMARY_VOL_DESC].block) {
udf_err(sb, "Primary Volume Descriptor not found!\n");
return 1;
}
if (udf_load_pvoldesc(sb, vds[VDS_POS_PRIMARY_VOL_DESC].block))
return 1;
if (vds[VDS_POS_LOGICAL_VOL_DESC].block && udf_load_logicalvol(sb,
vds[VDS_POS_LOGICAL_VOL_DESC].block, fileset))
return 1;
if (vds[VDS_POS_PARTITION_DESC].block) {
/*
* We rescan the whole descriptor sequence to find
* partition descriptor blocks and process them.
*/
for (block = vds[VDS_POS_PARTITION_DESC].block;
block < vds[VDS_POS_TERMINATING_DESC].block;
block++)
if (udf_load_partdesc(sb, block))
return 1;
}
return 0;
}
static int udf_load_sequence(struct super_block *sb, struct buffer_head *bh,
struct kernel_lb_addr *fileset)
{
struct anchorVolDescPtr *anchor;
long main_s, main_e, reserve_s, reserve_e;
anchor = (struct anchorVolDescPtr *)bh->b_data;
/* Locate the main sequence */
main_s = le32_to_cpu(anchor->mainVolDescSeqExt.extLocation);
main_e = le32_to_cpu(anchor->mainVolDescSeqExt.extLength);
main_e = main_e >> sb->s_blocksize_bits;
main_e += main_s;
/* Locate the reserve sequence */
reserve_s = le32_to_cpu(anchor->reserveVolDescSeqExt.extLocation);
reserve_e = le32_to_cpu(anchor->reserveVolDescSeqExt.extLength);
reserve_e = reserve_e >> sb->s_blocksize_bits;
reserve_e += reserve_s;
/* Process the main & reserve sequences */
/* responsible for finding the PartitionDesc(s) */
if (!udf_process_sequence(sb, main_s, main_e, fileset))
return 1;
return !udf_process_sequence(sb, reserve_s, reserve_e, fileset);
}
/*
* Check whether there is an anchor block in the given block and
* load Volume Descriptor Sequence if so.
*/
static int udf_check_anchor_block(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct buffer_head *bh;
uint16_t ident;
int ret;
if (UDF_QUERY_FLAG(sb, UDF_FLAG_VARCONV) &&
udf_fixed_to_variable(block) >=
sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits)
return 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 0;
if (ident != TAG_IDENT_AVDP) {
brelse(bh);
return 0;
}
ret = udf_load_sequence(sb, bh, fileset);
brelse(bh);
return ret;
}
/* Search for an anchor volume descriptor pointer */
static sector_t udf_scan_anchors(struct super_block *sb, sector_t lastblock,
struct kernel_lb_addr *fileset)
{
sector_t last[6];
int i;
struct udf_sb_info *sbi = UDF_SB(sb);
int last_count = 0;
/* First try user provided anchor */
if (sbi->s_anchor) {
if (udf_check_anchor_block(sb, sbi->s_anchor, fileset))
return lastblock;
}
/*
* according to spec, anchor is in either:
* block 256
* lastblock-256
* lastblock
* however, if the disc isn't closed, it could be 512.
*/
if (udf_check_anchor_block(sb, sbi->s_session + 256, fileset))
return lastblock;
/*
* The trouble is which block is the last one. Drives often misreport
* this so we try various possibilities.
*/
last[last_count++] = lastblock;
if (lastblock >= 1)
last[last_count++] = lastblock - 1;
last[last_count++] = lastblock + 1;
if (lastblock >= 2)
last[last_count++] = lastblock - 2;
if (lastblock >= 150)
last[last_count++] = lastblock - 150;
if (lastblock >= 152)
last[last_count++] = lastblock - 152;
for (i = 0; i < last_count; i++) {
if (last[i] >= sb->s_bdev->bd_inode->i_size >>
sb->s_blocksize_bits)
continue;
if (udf_check_anchor_block(sb, last[i], fileset))
return last[i];
if (last[i] < 256)
continue;
if (udf_check_anchor_block(sb, last[i] - 256, fileset))
return last[i];
}
/* Finally try block 512 in case media is open */
if (udf_check_anchor_block(sb, sbi->s_session + 512, fileset))
return last[0];
return 0;
}
/*
* Find an anchor volume descriptor and load Volume Descriptor Sequence from
* area specified by it. The function expects sbi->s_lastblock to be the last
* block on the media.
*
* Return 1 if ok, 0 if not found.
*
*/
static int udf_find_anchor(struct super_block *sb,
struct kernel_lb_addr *fileset)
{
sector_t lastblock;
struct udf_sb_info *sbi = UDF_SB(sb);
lastblock = udf_scan_anchors(sb, sbi->s_last_block, fileset);
if (lastblock)
goto out;
/* No anchor found? Try VARCONV conversion of block numbers */
UDF_SET_FLAG(sb, UDF_FLAG_VARCONV);
/* Firstly, we try to not convert number of the last block */
lastblock = udf_scan_anchors(sb,
udf_variable_to_fixed(sbi->s_last_block),
fileset);
if (lastblock)
goto out;
/* Secondly, we try with converted number of the last block */
lastblock = udf_scan_anchors(sb, sbi->s_last_block, fileset);
if (!lastblock) {
/* VARCONV didn't help. Clear it. */
UDF_CLEAR_FLAG(sb, UDF_FLAG_VARCONV);
return 0;
}
out:
sbi->s_last_block = lastblock;
return 1;
}
/*
* Check Volume Structure Descriptor, find Anchor block and load Volume
* Descriptor Sequence
*/
static int udf_load_vrs(struct super_block *sb, struct udf_options *uopt,
int silent, struct kernel_lb_addr *fileset)
{
struct udf_sb_info *sbi = UDF_SB(sb);
loff_t nsr_off;
if (!sb_set_blocksize(sb, uopt->blocksize)) {
if (!silent)
udf_warn(sb, "Bad block size\n");
return 0;
}
sbi->s_last_block = uopt->lastblock;
if (!uopt->novrs) {
/* Check that it is NSR02 compliant */
nsr_off = udf_check_vsd(sb);
if (!nsr_off) {
if (!silent)
udf_warn(sb, "No VRS found\n");
return 0;
}
if (nsr_off == -1)
udf_debug("Failed to read byte 32768. Assuming open disc. Skipping validity check\n");
if (!sbi->s_last_block)
sbi->s_last_block = udf_get_last_block(sb);
} else {
udf_debug("Validity check skipped because of novrs option\n");
}
/* Look for anchor block and load Volume Descriptor Sequence */
sbi->s_anchor = uopt->anchor;
if (!udf_find_anchor(sb, fileset)) {
if (!silent)
udf_warn(sb, "No anchor found\n");
return 0;
}
return 1;
}
static void udf_open_lvid(struct super_block *sb)
{
struct udf_sb_info *sbi = UDF_SB(sb);
struct buffer_head *bh = sbi->s_lvid_bh;
struct logicalVolIntegrityDesc *lvid;
struct logicalVolIntegrityDescImpUse *lvidiu;
if (!bh)
return;
mutex_lock(&sbi->s_alloc_mutex);
lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
lvidiu = udf_sb_lvidiu(sbi);
lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
udf_time_to_disk_stamp(&lvid->recordingDateAndTime,
CURRENT_TIME);
lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_OPEN);
lvid->descTag.descCRC = cpu_to_le16(
crc_itu_t(0, (char *)lvid + sizeof(struct tag),
le16_to_cpu(lvid->descTag.descCRCLength)));
lvid->descTag.tagChecksum = udf_tag_checksum(&lvid->descTag);
mark_buffer_dirty(bh);
sbi->s_lvid_dirty = 0;
mutex_unlock(&sbi->s_alloc_mutex);
}
static void udf_close_lvid(struct super_block *sb)
{
struct udf_sb_info *sbi = UDF_SB(sb);
struct buffer_head *bh = sbi->s_lvid_bh;
struct logicalVolIntegrityDesc *lvid;
struct logicalVolIntegrityDescImpUse *lvidiu;
if (!bh)
return;
mutex_lock(&sbi->s_alloc_mutex);
lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
lvidiu = udf_sb_lvidiu(sbi);
lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
udf_time_to_disk_stamp(&lvid->recordingDateAndTime, CURRENT_TIME);
if (UDF_MAX_WRITE_VERSION > le16_to_cpu(lvidiu->maxUDFWriteRev))
lvidiu->maxUDFWriteRev = cpu_to_le16(UDF_MAX_WRITE_VERSION);
if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFReadRev))
lvidiu->minUDFReadRev = cpu_to_le16(sbi->s_udfrev);
if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFWriteRev))
lvidiu->minUDFWriteRev = cpu_to_le16(sbi->s_udfrev);
lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_CLOSE);
lvid->descTag.descCRC = cpu_to_le16(
crc_itu_t(0, (char *)lvid + sizeof(struct tag),
le16_to_cpu(lvid->descTag.descCRCLength)));
lvid->descTag.tagChecksum = udf_tag_checksum(&lvid->descTag);
/*
* We set buffer uptodate unconditionally here to avoid spurious
* warnings from mark_buffer_dirty() when previous EIO has marked
* the buffer as !uptodate
*/
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
sbi->s_lvid_dirty = 0;
mutex_unlock(&sbi->s_alloc_mutex);
}
u64 lvid_get_unique_id(struct super_block *sb)
{
struct buffer_head *bh;
struct udf_sb_info *sbi = UDF_SB(sb);
struct logicalVolIntegrityDesc *lvid;
struct logicalVolHeaderDesc *lvhd;
u64 uniqueID;
u64 ret;
bh = sbi->s_lvid_bh;
if (!bh)
return 0;
lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
lvhd = (struct logicalVolHeaderDesc *)lvid->logicalVolContentsUse;
mutex_lock(&sbi->s_alloc_mutex);
ret = uniqueID = le64_to_cpu(lvhd->uniqueID);
if (!(++uniqueID & 0xFFFFFFFF))
uniqueID += 16;
lvhd->uniqueID = cpu_to_le64(uniqueID);
mutex_unlock(&sbi->s_alloc_mutex);
mark_buffer_dirty(bh);
return ret;
}
static void udf_sb_free_bitmap(struct udf_bitmap *bitmap)
{
int i;
int nr_groups = bitmap->s_nr_groups;
int size = sizeof(struct udf_bitmap) + (sizeof(struct buffer_head *) *
nr_groups);
for (i = 0; i < nr_groups; i++)
if (bitmap->s_block_bitmap[i])
brelse(bitmap->s_block_bitmap[i]);
if (size <= PAGE_SIZE)
kfree(bitmap);
else
vfree(bitmap);
}
static void udf_free_partition(struct udf_part_map *map)
{
int i;
struct udf_meta_data *mdata;
if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE)
iput(map->s_uspace.s_table);
if (map->s_partition_flags & UDF_PART_FLAG_FREED_TABLE)
iput(map->s_fspace.s_table);
if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP)
udf_sb_free_bitmap(map->s_uspace.s_bitmap);
if (map->s_partition_flags & UDF_PART_FLAG_FREED_BITMAP)
udf_sb_free_bitmap(map->s_fspace.s_bitmap);
if (map->s_partition_type == UDF_SPARABLE_MAP15)
for (i = 0; i < 4; i++)
brelse(map->s_type_specific.s_sparing.s_spar_map[i]);
else if (map->s_partition_type == UDF_METADATA_MAP25) {
mdata = &map->s_type_specific.s_metadata;
iput(mdata->s_metadata_fe);
mdata->s_metadata_fe = NULL;
iput(mdata->s_mirror_fe);
mdata->s_mirror_fe = NULL;
iput(mdata->s_bitmap_fe);
mdata->s_bitmap_fe = NULL;
}
}
static int udf_fill_super(struct super_block *sb, void *options, int silent)
{
int i;
int ret;
struct inode *inode = NULL;
struct udf_options uopt;
struct kernel_lb_addr rootdir, fileset;
struct udf_sb_info *sbi;
uopt.flags = (1 << UDF_FLAG_USE_AD_IN_ICB) | (1 << UDF_FLAG_STRICT);
uopt.uid = -1;
uopt.gid = -1;
uopt.umask = 0;
uopt.fmode = UDF_INVALID_MODE;
uopt.dmode = UDF_INVALID_MODE;
sbi = kzalloc(sizeof(struct udf_sb_info), GFP_KERNEL);
if (!sbi)
return -ENOMEM;
sb->s_fs_info = sbi;
mutex_init(&sbi->s_alloc_mutex);
if (!udf_parse_options((char *)options, &uopt, false))
goto error_out;
if (uopt.flags & (1 << UDF_FLAG_UTF8) &&
uopt.flags & (1 << UDF_FLAG_NLS_MAP)) {
udf_err(sb, "utf8 cannot be combined with iocharset\n");
goto error_out;
}
#ifdef CONFIG_UDF_NLS
if ((uopt.flags & (1 << UDF_FLAG_NLS_MAP)) && !uopt.nls_map) {
uopt.nls_map = load_nls_default();
if (!uopt.nls_map)
uopt.flags &= ~(1 << UDF_FLAG_NLS_MAP);
else
udf_debug("Using default NLS map\n");
}
#endif
if (!(uopt.flags & (1 << UDF_FLAG_NLS_MAP)))
uopt.flags |= (1 << UDF_FLAG_UTF8);
fileset.logicalBlockNum = 0xFFFFFFFF;
fileset.partitionReferenceNum = 0xFFFF;
sbi->s_flags = uopt.flags;
sbi->s_uid = uopt.uid;
sbi->s_gid = uopt.gid;
sbi->s_umask = uopt.umask;
sbi->s_fmode = uopt.fmode;
sbi->s_dmode = uopt.dmode;
sbi->s_nls_map = uopt.nls_map;
rwlock_init(&sbi->s_cred_lock);
if (uopt.session == 0xFFFFFFFF)
sbi->s_session = udf_get_last_session(sb);
else
sbi->s_session = uopt.session;
udf_debug("Multi-session=%d\n", sbi->s_session);
/* Fill in the rest of the superblock */
sb->s_op = &udf_sb_ops;
sb->s_export_op = &udf_export_ops;
sb->s_dirt = 0;
sb->s_magic = UDF_SUPER_MAGIC;
sb->s_time_gran = 1000;
if (uopt.flags & (1 << UDF_FLAG_BLOCKSIZE_SET)) {
ret = udf_load_vrs(sb, &uopt, silent, &fileset);
} else {
uopt.blocksize = bdev_logical_block_size(sb->s_bdev);
ret = udf_load_vrs(sb, &uopt, silent, &fileset);
if (!ret && uopt.blocksize != UDF_DEFAULT_BLOCKSIZE) {
if (!silent)
pr_notice("Rescanning with blocksize %d\n",
UDF_DEFAULT_BLOCKSIZE);
uopt.blocksize = UDF_DEFAULT_BLOCKSIZE;
ret = udf_load_vrs(sb, &uopt, silent, &fileset);
}
}
if (!ret) {
udf_warn(sb, "No partition found (1)\n");
goto error_out;
}
udf_debug("Lastblock=%d\n", sbi->s_last_block);
if (sbi->s_lvid_bh) {
struct logicalVolIntegrityDescImpUse *lvidiu =
udf_sb_lvidiu(sbi);
uint16_t minUDFReadRev = le16_to_cpu(lvidiu->minUDFReadRev);
uint16_t minUDFWriteRev = le16_to_cpu(lvidiu->minUDFWriteRev);
/* uint16_t maxUDFWriteRev =
le16_to_cpu(lvidiu->maxUDFWriteRev); */
if (minUDFReadRev > UDF_MAX_READ_VERSION) {
udf_err(sb, "minUDFReadRev=%x (max is %x)\n",
le16_to_cpu(lvidiu->minUDFReadRev),
UDF_MAX_READ_VERSION);
goto error_out;
} else if (minUDFWriteRev > UDF_MAX_WRITE_VERSION)
sb->s_flags |= MS_RDONLY;
sbi->s_udfrev = minUDFWriteRev;
if (minUDFReadRev >= UDF_VERS_USE_EXTENDED_FE)
UDF_SET_FLAG(sb, UDF_FLAG_USE_EXTENDED_FE);
if (minUDFReadRev >= UDF_VERS_USE_STREAMS)
UDF_SET_FLAG(sb, UDF_FLAG_USE_STREAMS);
}
if (!sbi->s_partitions) {
udf_warn(sb, "No partition found (2)\n");
goto error_out;
}
if (sbi->s_partmaps[sbi->s_partition].s_partition_flags &
UDF_PART_FLAG_READ_ONLY) {
pr_notice("Partition marked readonly; forcing readonly mount\n");
sb->s_flags |= MS_RDONLY;
}
if (udf_find_fileset(sb, &fileset, &rootdir)) {
udf_warn(sb, "No fileset found\n");
goto error_out;
}
if (!silent) {
struct timestamp ts;
udf_time_to_disk_stamp(&ts, sbi->s_record_time);
udf_info("Mounting volume '%s', timestamp %04u/%02u/%02u %02u:%02u (%x)\n",
sbi->s_volume_ident,
le16_to_cpu(ts.year), ts.month, ts.day,
ts.hour, ts.minute, le16_to_cpu(ts.typeAndTimezone));
}
if (!(sb->s_flags & MS_RDONLY))
udf_open_lvid(sb);
/* Assign the root inode */
/* assign inodes by physical block number */
/* perhaps it's not extensible enough, but for now ... */
inode = udf_iget(sb, &rootdir);
if (!inode) {
udf_err(sb, "Error in udf_iget, block=%d, partition=%d\n",
rootdir.logicalBlockNum, rootdir.partitionReferenceNum);
goto error_out;
}
/* Allocate a dentry for the root inode */
sb->s_root = d_make_root(inode);
if (!sb->s_root) {
udf_err(sb, "Couldn't allocate root dentry\n");
goto error_out;
}
sb->s_maxbytes = MAX_LFS_FILESIZE;
sb->s_max_links = UDF_MAX_LINKS;
return 0;
error_out:
if (sbi->s_vat_inode)
iput(sbi->s_vat_inode);
if (sbi->s_partitions)
for (i = 0; i < sbi->s_partitions; i++)
udf_free_partition(&sbi->s_partmaps[i]);
#ifdef CONFIG_UDF_NLS
if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP))
unload_nls(sbi->s_nls_map);
#endif
if (!(sb->s_flags & MS_RDONLY))
udf_close_lvid(sb);
brelse(sbi->s_lvid_bh);
kfree(sbi->s_partmaps);
kfree(sbi);
sb->s_fs_info = NULL;
return -EINVAL;
}
void _udf_err(struct super_block *sb, const char *function,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
/* mark sb error */
if (!(sb->s_flags & MS_RDONLY))
sb->s_dirt = 1;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
pr_err("error (device %s): %s: %pV", sb->s_id, function, &vaf);
va_end(args);
}
void _udf_warn(struct super_block *sb, const char *function,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
pr_warn("warning (device %s): %s: %pV", sb->s_id, function, &vaf);
va_end(args);
}
static void udf_put_super(struct super_block *sb)
{
int i;
struct udf_sb_info *sbi;
sbi = UDF_SB(sb);
if (sbi->s_vat_inode)
iput(sbi->s_vat_inode);
if (sbi->s_partitions)
for (i = 0; i < sbi->s_partitions; i++)
udf_free_partition(&sbi->s_partmaps[i]);
#ifdef CONFIG_UDF_NLS
if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP))
unload_nls(sbi->s_nls_map);
#endif
if (!(sb->s_flags & MS_RDONLY))
udf_close_lvid(sb);
brelse(sbi->s_lvid_bh);
kfree(sbi->s_partmaps);
kfree(sb->s_fs_info);
sb->s_fs_info = NULL;
}
static int udf_sync_fs(struct super_block *sb, int wait)
{
struct udf_sb_info *sbi = UDF_SB(sb);
mutex_lock(&sbi->s_alloc_mutex);
if (sbi->s_lvid_dirty) {
/*
* Blockdevice will be synced later so we don't have to submit
* the buffer for IO
*/
mark_buffer_dirty(sbi->s_lvid_bh);
sb->s_dirt = 0;
sbi->s_lvid_dirty = 0;
}
mutex_unlock(&sbi->s_alloc_mutex);
return 0;
}
static int udf_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct udf_sb_info *sbi = UDF_SB(sb);
struct logicalVolIntegrityDescImpUse *lvidiu;
u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
if (sbi->s_lvid_bh != NULL)
lvidiu = udf_sb_lvidiu(sbi);
else
lvidiu = NULL;
buf->f_type = UDF_SUPER_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_blocks = sbi->s_partmaps[sbi->s_partition].s_partition_len;
buf->f_bfree = udf_count_free(sb);
buf->f_bavail = buf->f_bfree;
buf->f_files = (lvidiu != NULL ? (le32_to_cpu(lvidiu->numFiles) +
le32_to_cpu(lvidiu->numDirs)) : 0)
+ buf->f_bfree;
buf->f_ffree = buf->f_bfree;
buf->f_namelen = UDF_NAME_LEN - 2;
buf->f_fsid.val[0] = (u32)id;
buf->f_fsid.val[1] = (u32)(id >> 32);
return 0;
}
static unsigned int udf_count_free_bitmap(struct super_block *sb,
struct udf_bitmap *bitmap)
{
struct buffer_head *bh = NULL;
unsigned int accum = 0;
int index;
int block = 0, newblock;
struct kernel_lb_addr loc;
uint32_t bytes;
uint8_t *ptr;
uint16_t ident;
struct spaceBitmapDesc *bm;
loc.logicalBlockNum = bitmap->s_extPosition;
loc.partitionReferenceNum = UDF_SB(sb)->s_partition;
bh = udf_read_ptagged(sb, &loc, 0, &ident);
if (!bh) {
udf_err(sb, "udf_count_free failed\n");
goto out;
} else if (ident != TAG_IDENT_SBD) {
brelse(bh);
udf_err(sb, "udf_count_free failed\n");
goto out;
}
bm = (struct spaceBitmapDesc *)bh->b_data;
bytes = le32_to_cpu(bm->numOfBytes);
index = sizeof(struct spaceBitmapDesc); /* offset in first block only */
ptr = (uint8_t *)bh->b_data;
while (bytes > 0) {
u32 cur_bytes = min_t(u32, bytes, sb->s_blocksize - index);
accum += bitmap_weight((const unsigned long *)(ptr + index),
cur_bytes * 8);
bytes -= cur_bytes;
if (bytes) {
brelse(bh);
newblock = udf_get_lb_pblock(sb, &loc, ++block);
bh = udf_tread(sb, newblock);
if (!bh) {
udf_debug("read failed\n");
goto out;
}
index = 0;
ptr = (uint8_t *)bh->b_data;
}
}
brelse(bh);
out:
return accum;
}
static unsigned int udf_count_free_table(struct super_block *sb,
struct inode *table)
{
unsigned int accum = 0;
uint32_t elen;
struct kernel_lb_addr eloc;
int8_t etype;
struct extent_position epos;
mutex_lock(&UDF_SB(sb)->s_alloc_mutex);
epos.block = UDF_I(table)->i_location;
epos.offset = sizeof(struct unallocSpaceEntry);
epos.bh = NULL;
while ((etype = udf_next_aext(table, &epos, &eloc, &elen, 1)) != -1)
accum += (elen >> table->i_sb->s_blocksize_bits);
brelse(epos.bh);
mutex_unlock(&UDF_SB(sb)->s_alloc_mutex);
return accum;
}
static unsigned int udf_count_free(struct super_block *sb)
{
unsigned int accum = 0;
struct udf_sb_info *sbi;
struct udf_part_map *map;
sbi = UDF_SB(sb);
if (sbi->s_lvid_bh) {
struct logicalVolIntegrityDesc *lvid =
(struct logicalVolIntegrityDesc *)
sbi->s_lvid_bh->b_data;
if (le32_to_cpu(lvid->numOfPartitions) > sbi->s_partition) {
accum = le32_to_cpu(
lvid->freeSpaceTable[sbi->s_partition]);
if (accum == 0xFFFFFFFF)
accum = 0;
}
}
if (accum)
return accum;
map = &sbi->s_partmaps[sbi->s_partition];
if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP) {
accum += udf_count_free_bitmap(sb,
map->s_uspace.s_bitmap);
}
if (map->s_partition_flags & UDF_PART_FLAG_FREED_BITMAP) {
accum += udf_count_free_bitmap(sb,
map->s_fspace.s_bitmap);
}
if (accum)
return accum;
if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE) {
accum += udf_count_free_table(sb,
map->s_uspace.s_table);
}
if (map->s_partition_flags & UDF_PART_FLAG_FREED_TABLE) {
accum += udf_count_free_table(sb,
map->s_fspace.s_table);
}
return accum;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3687_0 |
crossvul-cpp_data_good_4787_10 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD CCCC M M %
% D D C MM MM %
% D D C M M M %
% D D C M M %
% DDDD CCCC M M %
% %
% %
% Read DICOM Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/constitute.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
/*
Dicom medical image declarations.
*/
typedef struct _DicomInfo
{
unsigned short
group,
element;
const char
*vr,
*description;
} DicomInfo;
static const DicomInfo
dicom_info[] =
{
{ 0x0000, 0x0000, "UL", "Group Length" },
{ 0x0000, 0x0001, "UL", "Command Length to End" },
{ 0x0000, 0x0002, "UI", "Affected SOP Class UID" },
{ 0x0000, 0x0003, "UI", "Requested SOP Class UID" },
{ 0x0000, 0x0010, "LO", "Command Recognition Code" },
{ 0x0000, 0x0100, "US", "Command Field" },
{ 0x0000, 0x0110, "US", "Message ID" },
{ 0x0000, 0x0120, "US", "Message ID Being Responded To" },
{ 0x0000, 0x0200, "AE", "Initiator" },
{ 0x0000, 0x0300, "AE", "Receiver" },
{ 0x0000, 0x0400, "AE", "Find Location" },
{ 0x0000, 0x0600, "AE", "Move Destination" },
{ 0x0000, 0x0700, "US", "Priority" },
{ 0x0000, 0x0800, "US", "Data Set Type" },
{ 0x0000, 0x0850, "US", "Number of Matches" },
{ 0x0000, 0x0860, "US", "Response Sequence Number" },
{ 0x0000, 0x0900, "US", "Status" },
{ 0x0000, 0x0901, "AT", "Offending Element" },
{ 0x0000, 0x0902, "LO", "Exception Comment" },
{ 0x0000, 0x0903, "US", "Exception ID" },
{ 0x0000, 0x1000, "UI", "Affected SOP Instance UID" },
{ 0x0000, 0x1001, "UI", "Requested SOP Instance UID" },
{ 0x0000, 0x1002, "US", "Event Type ID" },
{ 0x0000, 0x1005, "AT", "Attribute Identifier List" },
{ 0x0000, 0x1008, "US", "Action Type ID" },
{ 0x0000, 0x1020, "US", "Number of Remaining Suboperations" },
{ 0x0000, 0x1021, "US", "Number of Completed Suboperations" },
{ 0x0000, 0x1022, "US", "Number of Failed Suboperations" },
{ 0x0000, 0x1023, "US", "Number of Warning Suboperations" },
{ 0x0000, 0x1030, "AE", "Move Originator Application Entity Title" },
{ 0x0000, 0x1031, "US", "Move Originator Message ID" },
{ 0x0000, 0x4000, "LO", "Dialog Receiver" },
{ 0x0000, 0x4010, "LO", "Terminal Type" },
{ 0x0000, 0x5010, "SH", "Message Set ID" },
{ 0x0000, 0x5020, "SH", "End Message Set" },
{ 0x0000, 0x5110, "LO", "Display Format" },
{ 0x0000, 0x5120, "LO", "Page Position ID" },
{ 0x0000, 0x5130, "LO", "Text Format ID" },
{ 0x0000, 0x5140, "LO", "Normal Reverse" },
{ 0x0000, 0x5150, "LO", "Add Gray Scale" },
{ 0x0000, 0x5160, "LO", "Borders" },
{ 0x0000, 0x5170, "IS", "Copies" },
{ 0x0000, 0x5180, "LO", "OldMagnificationType" },
{ 0x0000, 0x5190, "LO", "Erase" },
{ 0x0000, 0x51a0, "LO", "Print" },
{ 0x0000, 0x51b0, "US", "Overlays" },
{ 0x0002, 0x0000, "UL", "Meta Element Group Length" },
{ 0x0002, 0x0001, "OB", "File Meta Information Version" },
{ 0x0002, 0x0002, "UI", "Media Storage SOP Class UID" },
{ 0x0002, 0x0003, "UI", "Media Storage SOP Instance UID" },
{ 0x0002, 0x0010, "UI", "Transfer Syntax UID" },
{ 0x0002, 0x0012, "UI", "Implementation Class UID" },
{ 0x0002, 0x0013, "SH", "Implementation Version Name" },
{ 0x0002, 0x0016, "AE", "Source Application Entity Title" },
{ 0x0002, 0x0100, "UI", "Private Information Creator UID" },
{ 0x0002, 0x0102, "OB", "Private Information" },
{ 0x0003, 0x0000, "US", "?" },
{ 0x0003, 0x0008, "US", "ISI Command Field" },
{ 0x0003, 0x0011, "US", "Attach ID Application Code" },
{ 0x0003, 0x0012, "UL", "Attach ID Message Count" },
{ 0x0003, 0x0013, "DA", "Attach ID Date" },
{ 0x0003, 0x0014, "TM", "Attach ID Time" },
{ 0x0003, 0x0020, "US", "Message Type" },
{ 0x0003, 0x0030, "DA", "Max Waiting Date" },
{ 0x0003, 0x0031, "TM", "Max Waiting Time" },
{ 0x0004, 0x0000, "UL", "File Set Group Length" },
{ 0x0004, 0x1130, "CS", "File Set ID" },
{ 0x0004, 0x1141, "CS", "File Set Descriptor File ID" },
{ 0x0004, 0x1142, "CS", "File Set Descriptor File Specific Character Set" },
{ 0x0004, 0x1200, "UL", "Root Directory Entity First Directory Record Offset" },
{ 0x0004, 0x1202, "UL", "Root Directory Entity Last Directory Record Offset" },
{ 0x0004, 0x1212, "US", "File Set Consistency Flag" },
{ 0x0004, 0x1220, "SQ", "Directory Record Sequence" },
{ 0x0004, 0x1400, "UL", "Next Directory Record Offset" },
{ 0x0004, 0x1410, "US", "Record In Use Flag" },
{ 0x0004, 0x1420, "UL", "Referenced Lower Level Directory Entity Offset" },
{ 0x0004, 0x1430, "CS", "Directory Record Type" },
{ 0x0004, 0x1432, "UI", "Private Record UID" },
{ 0x0004, 0x1500, "CS", "Referenced File ID" },
{ 0x0004, 0x1504, "UL", "MRDR Directory Record Offset" },
{ 0x0004, 0x1510, "UI", "Referenced SOP Class UID In File" },
{ 0x0004, 0x1511, "UI", "Referenced SOP Instance UID In File" },
{ 0x0004, 0x1512, "UI", "Referenced Transfer Syntax UID In File" },
{ 0x0004, 0x1600, "UL", "Number of References" },
{ 0x0005, 0x0000, "US", "?" },
{ 0x0006, 0x0000, "US", "?" },
{ 0x0008, 0x0000, "UL", "Identifying Group Length" },
{ 0x0008, 0x0001, "UL", "Length to End" },
{ 0x0008, 0x0005, "CS", "Specific Character Set" },
{ 0x0008, 0x0008, "CS", "Image Type" },
{ 0x0008, 0x0010, "LO", "Recognition Code" },
{ 0x0008, 0x0012, "DA", "Instance Creation Date" },
{ 0x0008, 0x0013, "TM", "Instance Creation Time" },
{ 0x0008, 0x0014, "UI", "Instance Creator UID" },
{ 0x0008, 0x0016, "UI", "SOP Class UID" },
{ 0x0008, 0x0018, "UI", "SOP Instance UID" },
{ 0x0008, 0x0020, "DA", "Study Date" },
{ 0x0008, 0x0021, "DA", "Series Date" },
{ 0x0008, 0x0022, "DA", "Acquisition Date" },
{ 0x0008, 0x0023, "DA", "Image Date" },
{ 0x0008, 0x0024, "DA", "Overlay Date" },
{ 0x0008, 0x0025, "DA", "Curve Date" },
{ 0x0008, 0x0030, "TM", "Study Time" },
{ 0x0008, 0x0031, "TM", "Series Time" },
{ 0x0008, 0x0032, "TM", "Acquisition Time" },
{ 0x0008, 0x0033, "TM", "Image Time" },
{ 0x0008, 0x0034, "TM", "Overlay Time" },
{ 0x0008, 0x0035, "TM", "Curve Time" },
{ 0x0008, 0x0040, "xs", "Old Data Set Type" },
{ 0x0008, 0x0041, "xs", "Old Data Set Subtype" },
{ 0x0008, 0x0042, "CS", "Nuclear Medicine Series Type" },
{ 0x0008, 0x0050, "SH", "Accession Number" },
{ 0x0008, 0x0052, "CS", "Query/Retrieve Level" },
{ 0x0008, 0x0054, "AE", "Retrieve AE Title" },
{ 0x0008, 0x0058, "UI", "Failed SOP Instance UID List" },
{ 0x0008, 0x0060, "CS", "Modality" },
{ 0x0008, 0x0062, "SQ", "Modality Subtype" },
{ 0x0008, 0x0064, "CS", "Conversion Type" },
{ 0x0008, 0x0068, "CS", "Presentation Intent Type" },
{ 0x0008, 0x0070, "LO", "Manufacturer" },
{ 0x0008, 0x0080, "LO", "Institution Name" },
{ 0x0008, 0x0081, "ST", "Institution Address" },
{ 0x0008, 0x0082, "SQ", "Institution Code Sequence" },
{ 0x0008, 0x0090, "PN", "Referring Physician's Name" },
{ 0x0008, 0x0092, "ST", "Referring Physician's Address" },
{ 0x0008, 0x0094, "SH", "Referring Physician's Telephone Numbers" },
{ 0x0008, 0x0100, "SH", "Code Value" },
{ 0x0008, 0x0102, "SH", "Coding Scheme Designator" },
{ 0x0008, 0x0103, "SH", "Coding Scheme Version" },
{ 0x0008, 0x0104, "LO", "Code Meaning" },
{ 0x0008, 0x0105, "CS", "Mapping Resource" },
{ 0x0008, 0x0106, "DT", "Context Group Version" },
{ 0x0008, 0x010b, "CS", "Code Set Extension Flag" },
{ 0x0008, 0x010c, "UI", "Private Coding Scheme Creator UID" },
{ 0x0008, 0x010d, "UI", "Code Set Extension Creator UID" },
{ 0x0008, 0x010f, "CS", "Context Identifier" },
{ 0x0008, 0x1000, "LT", "Network ID" },
{ 0x0008, 0x1010, "SH", "Station Name" },
{ 0x0008, 0x1030, "LO", "Study Description" },
{ 0x0008, 0x1032, "SQ", "Procedure Code Sequence" },
{ 0x0008, 0x103e, "LO", "Series Description" },
{ 0x0008, 0x1040, "LO", "Institutional Department Name" },
{ 0x0008, 0x1048, "PN", "Physician of Record" },
{ 0x0008, 0x1050, "PN", "Performing Physician's Name" },
{ 0x0008, 0x1060, "PN", "Name of Physician(s) Reading Study" },
{ 0x0008, 0x1070, "PN", "Operator's Name" },
{ 0x0008, 0x1080, "LO", "Admitting Diagnosis Description" },
{ 0x0008, 0x1084, "SQ", "Admitting Diagnosis Code Sequence" },
{ 0x0008, 0x1090, "LO", "Manufacturer's Model Name" },
{ 0x0008, 0x1100, "SQ", "Referenced Results Sequence" },
{ 0x0008, 0x1110, "SQ", "Referenced Study Sequence" },
{ 0x0008, 0x1111, "SQ", "Referenced Study Component Sequence" },
{ 0x0008, 0x1115, "SQ", "Referenced Series Sequence" },
{ 0x0008, 0x1120, "SQ", "Referenced Patient Sequence" },
{ 0x0008, 0x1125, "SQ", "Referenced Visit Sequence" },
{ 0x0008, 0x1130, "SQ", "Referenced Overlay Sequence" },
{ 0x0008, 0x1140, "SQ", "Referenced Image Sequence" },
{ 0x0008, 0x1145, "SQ", "Referenced Curve Sequence" },
{ 0x0008, 0x1148, "SQ", "Referenced Previous Waveform" },
{ 0x0008, 0x114a, "SQ", "Referenced Simultaneous Waveforms" },
{ 0x0008, 0x114c, "SQ", "Referenced Subsequent Waveform" },
{ 0x0008, 0x1150, "UI", "Referenced SOP Class UID" },
{ 0x0008, 0x1155, "UI", "Referenced SOP Instance UID" },
{ 0x0008, 0x1160, "IS", "Referenced Frame Number" },
{ 0x0008, 0x1195, "UI", "Transaction UID" },
{ 0x0008, 0x1197, "US", "Failure Reason" },
{ 0x0008, 0x1198, "SQ", "Failed SOP Sequence" },
{ 0x0008, 0x1199, "SQ", "Referenced SOP Sequence" },
{ 0x0008, 0x2110, "CS", "Old Lossy Image Compression" },
{ 0x0008, 0x2111, "ST", "Derivation Description" },
{ 0x0008, 0x2112, "SQ", "Source Image Sequence" },
{ 0x0008, 0x2120, "SH", "Stage Name" },
{ 0x0008, 0x2122, "IS", "Stage Number" },
{ 0x0008, 0x2124, "IS", "Number of Stages" },
{ 0x0008, 0x2128, "IS", "View Number" },
{ 0x0008, 0x2129, "IS", "Number of Event Timers" },
{ 0x0008, 0x212a, "IS", "Number of Views in Stage" },
{ 0x0008, 0x2130, "DS", "Event Elapsed Time(s)" },
{ 0x0008, 0x2132, "LO", "Event Timer Name(s)" },
{ 0x0008, 0x2142, "IS", "Start Trim" },
{ 0x0008, 0x2143, "IS", "Stop Trim" },
{ 0x0008, 0x2144, "IS", "Recommended Display Frame Rate" },
{ 0x0008, 0x2200, "CS", "Transducer Position" },
{ 0x0008, 0x2204, "CS", "Transducer Orientation" },
{ 0x0008, 0x2208, "CS", "Anatomic Structure" },
{ 0x0008, 0x2218, "SQ", "Anatomic Region Sequence" },
{ 0x0008, 0x2220, "SQ", "Anatomic Region Modifier Sequence" },
{ 0x0008, 0x2228, "SQ", "Primary Anatomic Structure Sequence" },
{ 0x0008, 0x2230, "SQ", "Primary Anatomic Structure Modifier Sequence" },
{ 0x0008, 0x2240, "SQ", "Transducer Position Sequence" },
{ 0x0008, 0x2242, "SQ", "Transducer Position Modifier Sequence" },
{ 0x0008, 0x2244, "SQ", "Transducer Orientation Sequence" },
{ 0x0008, 0x2246, "SQ", "Transducer Orientation Modifier Sequence" },
{ 0x0008, 0x2251, "SQ", "Anatomic Structure Space Or Region Code Sequence" },
{ 0x0008, 0x2253, "SQ", "Anatomic Portal Of Entrance Code Sequence" },
{ 0x0008, 0x2255, "SQ", "Anatomic Approach Direction Code Sequence" },
{ 0x0008, 0x2256, "ST", "Anatomic Perspective Description" },
{ 0x0008, 0x2257, "SQ", "Anatomic Perspective Code Sequence" },
{ 0x0008, 0x2258, "ST", "Anatomic Location Of Examining Instrument Description" },
{ 0x0008, 0x2259, "SQ", "Anatomic Location Of Examining Instrument Code Sequence" },
{ 0x0008, 0x225a, "SQ", "Anatomic Structure Space Or Region Modifier Code Sequence" },
{ 0x0008, 0x225c, "SQ", "OnAxis Background Anatomic Structure Code Sequence" },
{ 0x0008, 0x4000, "LT", "Identifying Comments" },
{ 0x0009, 0x0000, "xs", "?" },
{ 0x0009, 0x0001, "xs", "?" },
{ 0x0009, 0x0002, "xs", "?" },
{ 0x0009, 0x0003, "xs", "?" },
{ 0x0009, 0x0004, "xs", "?" },
{ 0x0009, 0x0005, "UN", "?" },
{ 0x0009, 0x0006, "UN", "?" },
{ 0x0009, 0x0007, "UN", "?" },
{ 0x0009, 0x0008, "xs", "?" },
{ 0x0009, 0x0009, "LT", "?" },
{ 0x0009, 0x000a, "IS", "?" },
{ 0x0009, 0x000b, "IS", "?" },
{ 0x0009, 0x000c, "IS", "?" },
{ 0x0009, 0x000d, "IS", "?" },
{ 0x0009, 0x000e, "IS", "?" },
{ 0x0009, 0x000f, "UN", "?" },
{ 0x0009, 0x0010, "xs", "?" },
{ 0x0009, 0x0011, "xs", "?" },
{ 0x0009, 0x0012, "xs", "?" },
{ 0x0009, 0x0013, "xs", "?" },
{ 0x0009, 0x0014, "xs", "?" },
{ 0x0009, 0x0015, "xs", "?" },
{ 0x0009, 0x0016, "xs", "?" },
{ 0x0009, 0x0017, "LT", "?" },
{ 0x0009, 0x0018, "LT", "Data Set Identifier" },
{ 0x0009, 0x001a, "US", "?" },
{ 0x0009, 0x001e, "UI", "?" },
{ 0x0009, 0x0020, "xs", "?" },
{ 0x0009, 0x0021, "xs", "?" },
{ 0x0009, 0x0022, "SH", "User Orientation" },
{ 0x0009, 0x0023, "SL", "Initiation Type" },
{ 0x0009, 0x0024, "xs", "?" },
{ 0x0009, 0x0025, "xs", "?" },
{ 0x0009, 0x0026, "xs", "?" },
{ 0x0009, 0x0027, "xs", "?" },
{ 0x0009, 0x0029, "xs", "?" },
{ 0x0009, 0x002a, "SL", "?" },
{ 0x0009, 0x002c, "LO", "Series Comments" },
{ 0x0009, 0x002d, "SL", "Track Beat Average" },
{ 0x0009, 0x002e, "FD", "Distance Prescribed" },
{ 0x0009, 0x002f, "LT", "?" },
{ 0x0009, 0x0030, "xs", "?" },
{ 0x0009, 0x0031, "xs", "?" },
{ 0x0009, 0x0032, "LT", "?" },
{ 0x0009, 0x0034, "xs", "?" },
{ 0x0009, 0x0035, "SL", "Gantry Locus Type" },
{ 0x0009, 0x0037, "SL", "Starting Heart Rate" },
{ 0x0009, 0x0038, "xs", "?" },
{ 0x0009, 0x0039, "SL", "RR Window Offset" },
{ 0x0009, 0x003a, "SL", "Percent Cycle Imaged" },
{ 0x0009, 0x003e, "US", "?" },
{ 0x0009, 0x003f, "US", "?" },
{ 0x0009, 0x0040, "xs", "?" },
{ 0x0009, 0x0041, "xs", "?" },
{ 0x0009, 0x0042, "xs", "?" },
{ 0x0009, 0x0043, "xs", "?" },
{ 0x0009, 0x0050, "LT", "?" },
{ 0x0009, 0x0051, "xs", "?" },
{ 0x0009, 0x0060, "LT", "?" },
{ 0x0009, 0x0061, "LT", "Series Unique Identifier" },
{ 0x0009, 0x0070, "LT", "?" },
{ 0x0009, 0x0080, "LT", "?" },
{ 0x0009, 0x0091, "LT", "?" },
{ 0x0009, 0x00e2, "LT", "?" },
{ 0x0009, 0x00e3, "UI", "Equipment UID" },
{ 0x0009, 0x00e6, "SH", "Genesis Version Now" },
{ 0x0009, 0x00e7, "UL", "Exam Record Checksum" },
{ 0x0009, 0x00e8, "UL", "?" },
{ 0x0009, 0x00e9, "SL", "Actual Series Data Time Stamp" },
{ 0x0009, 0x00f2, "UN", "?" },
{ 0x0009, 0x00f3, "UN", "?" },
{ 0x0009, 0x00f4, "LT", "?" },
{ 0x0009, 0x00f5, "xs", "?" },
{ 0x0009, 0x00f6, "LT", "PDM Data Object Type Extension" },
{ 0x0009, 0x00f8, "US", "?" },
{ 0x0009, 0x00fb, "IS", "?" },
{ 0x0009, 0x1002, "OB", "?" },
{ 0x0009, 0x1003, "OB", "?" },
{ 0x0009, 0x1010, "UN", "?" },
{ 0x0010, 0x0000, "UL", "Patient Group Length" },
{ 0x0010, 0x0010, "PN", "Patient's Name" },
{ 0x0010, 0x0020, "LO", "Patient's ID" },
{ 0x0010, 0x0021, "LO", "Issuer of Patient's ID" },
{ 0x0010, 0x0030, "DA", "Patient's Birth Date" },
{ 0x0010, 0x0032, "TM", "Patient's Birth Time" },
{ 0x0010, 0x0040, "CS", "Patient's Sex" },
{ 0x0010, 0x0050, "SQ", "Patient's Insurance Plan Code Sequence" },
{ 0x0010, 0x1000, "LO", "Other Patient's ID's" },
{ 0x0010, 0x1001, "PN", "Other Patient's Names" },
{ 0x0010, 0x1005, "PN", "Patient's Birth Name" },
{ 0x0010, 0x1010, "AS", "Patient's Age" },
{ 0x0010, 0x1020, "DS", "Patient's Size" },
{ 0x0010, 0x1030, "DS", "Patient's Weight" },
{ 0x0010, 0x1040, "LO", "Patient's Address" },
{ 0x0010, 0x1050, "LT", "Insurance Plan Identification" },
{ 0x0010, 0x1060, "PN", "Patient's Mother's Birth Name" },
{ 0x0010, 0x1080, "LO", "Military Rank" },
{ 0x0010, 0x1081, "LO", "Branch of Service" },
{ 0x0010, 0x1090, "LO", "Medical Record Locator" },
{ 0x0010, 0x2000, "LO", "Medical Alerts" },
{ 0x0010, 0x2110, "LO", "Contrast Allergies" },
{ 0x0010, 0x2150, "LO", "Country of Residence" },
{ 0x0010, 0x2152, "LO", "Region of Residence" },
{ 0x0010, 0x2154, "SH", "Patients Telephone Numbers" },
{ 0x0010, 0x2160, "SH", "Ethnic Group" },
{ 0x0010, 0x2180, "SH", "Occupation" },
{ 0x0010, 0x21a0, "CS", "Smoking Status" },
{ 0x0010, 0x21b0, "LT", "Additional Patient History" },
{ 0x0010, 0x21c0, "US", "Pregnancy Status" },
{ 0x0010, 0x21d0, "DA", "Last Menstrual Date" },
{ 0x0010, 0x21f0, "LO", "Patients Religious Preference" },
{ 0x0010, 0x4000, "LT", "Patient Comments" },
{ 0x0011, 0x0001, "xs", "?" },
{ 0x0011, 0x0002, "US", "?" },
{ 0x0011, 0x0003, "LT", "Patient UID" },
{ 0x0011, 0x0004, "LT", "Patient ID" },
{ 0x0011, 0x000a, "xs", "?" },
{ 0x0011, 0x000b, "SL", "Effective Series Duration" },
{ 0x0011, 0x000c, "SL", "Num Beats" },
{ 0x0011, 0x000d, "LO", "Radio Nuclide Name" },
{ 0x0011, 0x0010, "xs", "?" },
{ 0x0011, 0x0011, "xs", "?" },
{ 0x0011, 0x0012, "LO", "Dataset Name" },
{ 0x0011, 0x0013, "LO", "Dataset Type" },
{ 0x0011, 0x0015, "xs", "?" },
{ 0x0011, 0x0016, "SL", "Energy Number" },
{ 0x0011, 0x0017, "SL", "RR Interval Window Number" },
{ 0x0011, 0x0018, "SL", "MG Bin Number" },
{ 0x0011, 0x0019, "FD", "Radius Of Rotation" },
{ 0x0011, 0x001a, "SL", "Detector Count Zone" },
{ 0x0011, 0x001b, "SL", "Num Energy Windows" },
{ 0x0011, 0x001c, "SL", "Energy Offset" },
{ 0x0011, 0x001d, "SL", "Energy Range" },
{ 0x0011, 0x001f, "SL", "Image Orientation" },
{ 0x0011, 0x0020, "xs", "?" },
{ 0x0011, 0x0021, "xs", "?" },
{ 0x0011, 0x0022, "xs", "?" },
{ 0x0011, 0x0023, "xs", "?" },
{ 0x0011, 0x0024, "SL", "FOV Mask Y Cutoff Angle" },
{ 0x0011, 0x0025, "xs", "?" },
{ 0x0011, 0x0026, "SL", "Table Orientation" },
{ 0x0011, 0x0027, "SL", "ROI Top Left" },
{ 0x0011, 0x0028, "SL", "ROI Bottom Right" },
{ 0x0011, 0x0030, "xs", "?" },
{ 0x0011, 0x0031, "xs", "?" },
{ 0x0011, 0x0032, "UN", "?" },
{ 0x0011, 0x0033, "LO", "Energy Correct Name" },
{ 0x0011, 0x0034, "LO", "Spatial Correct Name" },
{ 0x0011, 0x0035, "xs", "?" },
{ 0x0011, 0x0036, "LO", "Uniformity Correct Name" },
{ 0x0011, 0x0037, "LO", "Acquisition Specific Correct Name" },
{ 0x0011, 0x0038, "SL", "Byte Order" },
{ 0x0011, 0x003a, "SL", "Picture Format" },
{ 0x0011, 0x003b, "FD", "Pixel Scale" },
{ 0x0011, 0x003c, "FD", "Pixel Offset" },
{ 0x0011, 0x003e, "SL", "FOV Shape" },
{ 0x0011, 0x003f, "SL", "Dataset Flags" },
{ 0x0011, 0x0040, "xs", "?" },
{ 0x0011, 0x0041, "LT", "Medical Alerts" },
{ 0x0011, 0x0042, "LT", "Contrast Allergies" },
{ 0x0011, 0x0044, "FD", "Threshold Center" },
{ 0x0011, 0x0045, "FD", "Threshold Width" },
{ 0x0011, 0x0046, "SL", "Interpolation Type" },
{ 0x0011, 0x0055, "FD", "Period" },
{ 0x0011, 0x0056, "FD", "ElapsedTime" },
{ 0x0011, 0x00a1, "DA", "Patient Registration Date" },
{ 0x0011, 0x00a2, "TM", "Patient Registration Time" },
{ 0x0011, 0x00b0, "LT", "Patient Last Name" },
{ 0x0011, 0x00b2, "LT", "Patient First Name" },
{ 0x0011, 0x00b4, "LT", "Patient Hospital Status" },
{ 0x0011, 0x00bc, "TM", "Current Location Time" },
{ 0x0011, 0x00c0, "LT", "Patient Insurance Status" },
{ 0x0011, 0x00d0, "LT", "Patient Billing Type" },
{ 0x0011, 0x00d2, "LT", "Patient Billing Address" },
{ 0x0013, 0x0000, "LT", "Modifying Physician" },
{ 0x0013, 0x0010, "xs", "?" },
{ 0x0013, 0x0011, "SL", "?" },
{ 0x0013, 0x0012, "xs", "?" },
{ 0x0013, 0x0016, "SL", "AutoTrack Peak" },
{ 0x0013, 0x0017, "SL", "AutoTrack Width" },
{ 0x0013, 0x0018, "FD", "Transmission Scan Time" },
{ 0x0013, 0x0019, "FD", "Transmission Mask Width" },
{ 0x0013, 0x001a, "FD", "Copper Attenuator Thickness" },
{ 0x0013, 0x001c, "FD", "?" },
{ 0x0013, 0x001d, "FD", "?" },
{ 0x0013, 0x001e, "FD", "Tomo View Offset" },
{ 0x0013, 0x0020, "LT", "Patient Name" },
{ 0x0013, 0x0022, "LT", "Patient Id" },
{ 0x0013, 0x0026, "LT", "Study Comments" },
{ 0x0013, 0x0030, "DA", "Patient Birthdate" },
{ 0x0013, 0x0031, "DS", "Patient Weight" },
{ 0x0013, 0x0032, "LT", "Patients Maiden Name" },
{ 0x0013, 0x0033, "LT", "Referring Physician" },
{ 0x0013, 0x0034, "LT", "Admitting Diagnosis" },
{ 0x0013, 0x0035, "LT", "Patient Sex" },
{ 0x0013, 0x0040, "LT", "Procedure Description" },
{ 0x0013, 0x0042, "LT", "Patient Rest Direction" },
{ 0x0013, 0x0044, "LT", "Patient Position" },
{ 0x0013, 0x0046, "LT", "View Direction" },
{ 0x0015, 0x0001, "DS", "Stenosis Calibration Ratio" },
{ 0x0015, 0x0002, "DS", "Stenosis Magnification" },
{ 0x0015, 0x0003, "DS", "Cardiac Calibration Ratio" },
{ 0x0018, 0x0000, "UL", "Acquisition Group Length" },
{ 0x0018, 0x0010, "LO", "Contrast/Bolus Agent" },
{ 0x0018, 0x0012, "SQ", "Contrast/Bolus Agent Sequence" },
{ 0x0018, 0x0014, "SQ", "Contrast/Bolus Administration Route Sequence" },
{ 0x0018, 0x0015, "CS", "Body Part Examined" },
{ 0x0018, 0x0020, "CS", "Scanning Sequence" },
{ 0x0018, 0x0021, "CS", "Sequence Variant" },
{ 0x0018, 0x0022, "CS", "Scan Options" },
{ 0x0018, 0x0023, "CS", "MR Acquisition Type" },
{ 0x0018, 0x0024, "SH", "Sequence Name" },
{ 0x0018, 0x0025, "CS", "Angio Flag" },
{ 0x0018, 0x0026, "SQ", "Intervention Drug Information Sequence" },
{ 0x0018, 0x0027, "TM", "Intervention Drug Stop Time" },
{ 0x0018, 0x0028, "DS", "Intervention Drug Dose" },
{ 0x0018, 0x0029, "SQ", "Intervention Drug Code Sequence" },
{ 0x0018, 0x002a, "SQ", "Additional Drug Sequence" },
{ 0x0018, 0x0030, "LO", "Radionuclide" },
{ 0x0018, 0x0031, "LO", "Radiopharmaceutical" },
{ 0x0018, 0x0032, "DS", "Energy Window Centerline" },
{ 0x0018, 0x0033, "DS", "Energy Window Total Width" },
{ 0x0018, 0x0034, "LO", "Intervention Drug Name" },
{ 0x0018, 0x0035, "TM", "Intervention Drug Start Time" },
{ 0x0018, 0x0036, "SQ", "Intervention Therapy Sequence" },
{ 0x0018, 0x0037, "CS", "Therapy Type" },
{ 0x0018, 0x0038, "CS", "Intervention Status" },
{ 0x0018, 0x0039, "CS", "Therapy Description" },
{ 0x0018, 0x0040, "IS", "Cine Rate" },
{ 0x0018, 0x0050, "DS", "Slice Thickness" },
{ 0x0018, 0x0060, "DS", "KVP" },
{ 0x0018, 0x0070, "IS", "Counts Accumulated" },
{ 0x0018, 0x0071, "CS", "Acquisition Termination Condition" },
{ 0x0018, 0x0072, "DS", "Effective Series Duration" },
{ 0x0018, 0x0073, "CS", "Acquisition Start Condition" },
{ 0x0018, 0x0074, "IS", "Acquisition Start Condition Data" },
{ 0x0018, 0x0075, "IS", "Acquisition Termination Condition Data" },
{ 0x0018, 0x0080, "DS", "Repetition Time" },
{ 0x0018, 0x0081, "DS", "Echo Time" },
{ 0x0018, 0x0082, "DS", "Inversion Time" },
{ 0x0018, 0x0083, "DS", "Number of Averages" },
{ 0x0018, 0x0084, "DS", "Imaging Frequency" },
{ 0x0018, 0x0085, "SH", "Imaged Nucleus" },
{ 0x0018, 0x0086, "IS", "Echo Number(s)" },
{ 0x0018, 0x0087, "DS", "Magnetic Field Strength" },
{ 0x0018, 0x0088, "DS", "Spacing Between Slices" },
{ 0x0018, 0x0089, "IS", "Number of Phase Encoding Steps" },
{ 0x0018, 0x0090, "DS", "Data Collection Diameter" },
{ 0x0018, 0x0091, "IS", "Echo Train Length" },
{ 0x0018, 0x0093, "DS", "Percent Sampling" },
{ 0x0018, 0x0094, "DS", "Percent Phase Field of View" },
{ 0x0018, 0x0095, "DS", "Pixel Bandwidth" },
{ 0x0018, 0x1000, "LO", "Device Serial Number" },
{ 0x0018, 0x1004, "LO", "Plate ID" },
{ 0x0018, 0x1010, "LO", "Secondary Capture Device ID" },
{ 0x0018, 0x1012, "DA", "Date of Secondary Capture" },
{ 0x0018, 0x1014, "TM", "Time of Secondary Capture" },
{ 0x0018, 0x1016, "LO", "Secondary Capture Device Manufacturer" },
{ 0x0018, 0x1018, "LO", "Secondary Capture Device Manufacturer Model Name" },
{ 0x0018, 0x1019, "LO", "Secondary Capture Device Software Version(s)" },
{ 0x0018, 0x1020, "LO", "Software Version(s)" },
{ 0x0018, 0x1022, "SH", "Video Image Format Acquired" },
{ 0x0018, 0x1023, "LO", "Digital Image Format Acquired" },
{ 0x0018, 0x1030, "LO", "Protocol Name" },
{ 0x0018, 0x1040, "LO", "Contrast/Bolus Route" },
{ 0x0018, 0x1041, "DS", "Contrast/Bolus Volume" },
{ 0x0018, 0x1042, "TM", "Contrast/Bolus Start Time" },
{ 0x0018, 0x1043, "TM", "Contrast/Bolus Stop Time" },
{ 0x0018, 0x1044, "DS", "Contrast/Bolus Total Dose" },
{ 0x0018, 0x1045, "IS", "Syringe Counts" },
{ 0x0018, 0x1046, "DS", "Contrast Flow Rate" },
{ 0x0018, 0x1047, "DS", "Contrast Flow Duration" },
{ 0x0018, 0x1048, "CS", "Contrast/Bolus Ingredient" },
{ 0x0018, 0x1049, "DS", "Contrast/Bolus Ingredient Concentration" },
{ 0x0018, 0x1050, "DS", "Spatial Resolution" },
{ 0x0018, 0x1060, "DS", "Trigger Time" },
{ 0x0018, 0x1061, "LO", "Trigger Source or Type" },
{ 0x0018, 0x1062, "IS", "Nominal Interval" },
{ 0x0018, 0x1063, "DS", "Frame Time" },
{ 0x0018, 0x1064, "LO", "Framing Type" },
{ 0x0018, 0x1065, "DS", "Frame Time Vector" },
{ 0x0018, 0x1066, "DS", "Frame Delay" },
{ 0x0018, 0x1067, "DS", "Image Trigger Delay" },
{ 0x0018, 0x1068, "DS", "Group Time Offset" },
{ 0x0018, 0x1069, "DS", "Trigger Time Offset" },
{ 0x0018, 0x106a, "CS", "Synchronization Trigger" },
{ 0x0018, 0x106b, "UI", "Synchronization Frame of Reference" },
{ 0x0018, 0x106e, "UL", "Trigger Sample Position" },
{ 0x0018, 0x1070, "LO", "Radiopharmaceutical Route" },
{ 0x0018, 0x1071, "DS", "Radiopharmaceutical Volume" },
{ 0x0018, 0x1072, "TM", "Radiopharmaceutical Start Time" },
{ 0x0018, 0x1073, "TM", "Radiopharmaceutical Stop Time" },
{ 0x0018, 0x1074, "DS", "Radionuclide Total Dose" },
{ 0x0018, 0x1075, "DS", "Radionuclide Half Life" },
{ 0x0018, 0x1076, "DS", "Radionuclide Positron Fraction" },
{ 0x0018, 0x1077, "DS", "Radiopharmaceutical Specific Activity" },
{ 0x0018, 0x1080, "CS", "Beat Rejection Flag" },
{ 0x0018, 0x1081, "IS", "Low R-R Value" },
{ 0x0018, 0x1082, "IS", "High R-R Value" },
{ 0x0018, 0x1083, "IS", "Intervals Acquired" },
{ 0x0018, 0x1084, "IS", "Intervals Rejected" },
{ 0x0018, 0x1085, "LO", "PVC Rejection" },
{ 0x0018, 0x1086, "IS", "Skip Beats" },
{ 0x0018, 0x1088, "IS", "Heart Rate" },
{ 0x0018, 0x1090, "IS", "Cardiac Number of Images" },
{ 0x0018, 0x1094, "IS", "Trigger Window" },
{ 0x0018, 0x1100, "DS", "Reconstruction Diameter" },
{ 0x0018, 0x1110, "DS", "Distance Source to Detector" },
{ 0x0018, 0x1111, "DS", "Distance Source to Patient" },
{ 0x0018, 0x1114, "DS", "Estimated Radiographic Magnification Factor" },
{ 0x0018, 0x1120, "DS", "Gantry/Detector Tilt" },
{ 0x0018, 0x1121, "DS", "Gantry/Detector Slew" },
{ 0x0018, 0x1130, "DS", "Table Height" },
{ 0x0018, 0x1131, "DS", "Table Traverse" },
{ 0x0018, 0x1134, "CS", "Table Motion" },
{ 0x0018, 0x1135, "DS", "Table Vertical Increment" },
{ 0x0018, 0x1136, "DS", "Table Lateral Increment" },
{ 0x0018, 0x1137, "DS", "Table Longitudinal Increment" },
{ 0x0018, 0x1138, "DS", "Table Angle" },
{ 0x0018, 0x113a, "CS", "Table Type" },
{ 0x0018, 0x1140, "CS", "Rotation Direction" },
{ 0x0018, 0x1141, "DS", "Angular Position" },
{ 0x0018, 0x1142, "DS", "Radial Position" },
{ 0x0018, 0x1143, "DS", "Scan Arc" },
{ 0x0018, 0x1144, "DS", "Angular Step" },
{ 0x0018, 0x1145, "DS", "Center of Rotation Offset" },
{ 0x0018, 0x1146, "DS", "Rotation Offset" },
{ 0x0018, 0x1147, "CS", "Field of View Shape" },
{ 0x0018, 0x1149, "IS", "Field of View Dimension(s)" },
{ 0x0018, 0x1150, "IS", "Exposure Time" },
{ 0x0018, 0x1151, "IS", "X-ray Tube Current" },
{ 0x0018, 0x1152, "IS", "Exposure" },
{ 0x0018, 0x1153, "IS", "Exposure in uAs" },
{ 0x0018, 0x1154, "DS", "AveragePulseWidth" },
{ 0x0018, 0x1155, "CS", "RadiationSetting" },
{ 0x0018, 0x1156, "CS", "Rectification Type" },
{ 0x0018, 0x115a, "CS", "RadiationMode" },
{ 0x0018, 0x115e, "DS", "ImageAreaDoseProduct" },
{ 0x0018, 0x1160, "SH", "Filter Type" },
{ 0x0018, 0x1161, "LO", "TypeOfFilters" },
{ 0x0018, 0x1162, "DS", "IntensifierSize" },
{ 0x0018, 0x1164, "DS", "ImagerPixelSpacing" },
{ 0x0018, 0x1166, "CS", "Grid" },
{ 0x0018, 0x1170, "IS", "Generator Power" },
{ 0x0018, 0x1180, "SH", "Collimator/Grid Name" },
{ 0x0018, 0x1181, "CS", "Collimator Type" },
{ 0x0018, 0x1182, "IS", "Focal Distance" },
{ 0x0018, 0x1183, "DS", "X Focus Center" },
{ 0x0018, 0x1184, "DS", "Y Focus Center" },
{ 0x0018, 0x1190, "DS", "Focal Spot(s)" },
{ 0x0018, 0x1191, "CS", "Anode Target Material" },
{ 0x0018, 0x11a0, "DS", "Body Part Thickness" },
{ 0x0018, 0x11a2, "DS", "Compression Force" },
{ 0x0018, 0x1200, "DA", "Date of Last Calibration" },
{ 0x0018, 0x1201, "TM", "Time of Last Calibration" },
{ 0x0018, 0x1210, "SH", "Convolution Kernel" },
{ 0x0018, 0x1240, "IS", "Upper/Lower Pixel Values" },
{ 0x0018, 0x1242, "IS", "Actual Frame Duration" },
{ 0x0018, 0x1243, "IS", "Count Rate" },
{ 0x0018, 0x1244, "US", "Preferred Playback Sequencing" },
{ 0x0018, 0x1250, "SH", "Receiving Coil" },
{ 0x0018, 0x1251, "SH", "Transmitting Coil" },
{ 0x0018, 0x1260, "SH", "Plate Type" },
{ 0x0018, 0x1261, "LO", "Phosphor Type" },
{ 0x0018, 0x1300, "DS", "Scan Velocity" },
{ 0x0018, 0x1301, "CS", "Whole Body Technique" },
{ 0x0018, 0x1302, "IS", "Scan Length" },
{ 0x0018, 0x1310, "US", "Acquisition Matrix" },
{ 0x0018, 0x1312, "CS", "Phase Encoding Direction" },
{ 0x0018, 0x1314, "DS", "Flip Angle" },
{ 0x0018, 0x1315, "CS", "Variable Flip Angle Flag" },
{ 0x0018, 0x1316, "DS", "SAR" },
{ 0x0018, 0x1318, "DS", "dB/dt" },
{ 0x0018, 0x1400, "LO", "Acquisition Device Processing Description" },
{ 0x0018, 0x1401, "LO", "Acquisition Device Processing Code" },
{ 0x0018, 0x1402, "CS", "Cassette Orientation" },
{ 0x0018, 0x1403, "CS", "Cassette Size" },
{ 0x0018, 0x1404, "US", "Exposures on Plate" },
{ 0x0018, 0x1405, "IS", "Relative X-ray Exposure" },
{ 0x0018, 0x1450, "DS", "Column Angulation" },
{ 0x0018, 0x1460, "DS", "Tomo Layer Height" },
{ 0x0018, 0x1470, "DS", "Tomo Angle" },
{ 0x0018, 0x1480, "DS", "Tomo Time" },
{ 0x0018, 0x1490, "CS", "Tomo Type" },
{ 0x0018, 0x1491, "CS", "Tomo Class" },
{ 0x0018, 0x1495, "IS", "Number of Tomosynthesis Source Images" },
{ 0x0018, 0x1500, "CS", "PositionerMotion" },
{ 0x0018, 0x1508, "CS", "Positioner Type" },
{ 0x0018, 0x1510, "DS", "PositionerPrimaryAngle" },
{ 0x0018, 0x1511, "DS", "PositionerSecondaryAngle" },
{ 0x0018, 0x1520, "DS", "PositionerPrimaryAngleIncrement" },
{ 0x0018, 0x1521, "DS", "PositionerSecondaryAngleIncrement" },
{ 0x0018, 0x1530, "DS", "DetectorPrimaryAngle" },
{ 0x0018, 0x1531, "DS", "DetectorSecondaryAngle" },
{ 0x0018, 0x1600, "CS", "Shutter Shape" },
{ 0x0018, 0x1602, "IS", "Shutter Left Vertical Edge" },
{ 0x0018, 0x1604, "IS", "Shutter Right Vertical Edge" },
{ 0x0018, 0x1606, "IS", "Shutter Upper Horizontal Edge" },
{ 0x0018, 0x1608, "IS", "Shutter Lower Horizonta lEdge" },
{ 0x0018, 0x1610, "IS", "Center of Circular Shutter" },
{ 0x0018, 0x1612, "IS", "Radius of Circular Shutter" },
{ 0x0018, 0x1620, "IS", "Vertices of Polygonal Shutter" },
{ 0x0018, 0x1622, "US", "Shutter Presentation Value" },
{ 0x0018, 0x1623, "US", "Shutter Overlay Group" },
{ 0x0018, 0x1700, "CS", "Collimator Shape" },
{ 0x0018, 0x1702, "IS", "Collimator Left Vertical Edge" },
{ 0x0018, 0x1704, "IS", "Collimator Right Vertical Edge" },
{ 0x0018, 0x1706, "IS", "Collimator Upper Horizontal Edge" },
{ 0x0018, 0x1708, "IS", "Collimator Lower Horizontal Edge" },
{ 0x0018, 0x1710, "IS", "Center of Circular Collimator" },
{ 0x0018, 0x1712, "IS", "Radius of Circular Collimator" },
{ 0x0018, 0x1720, "IS", "Vertices of Polygonal Collimator" },
{ 0x0018, 0x1800, "CS", "Acquisition Time Synchronized" },
{ 0x0018, 0x1801, "SH", "Time Source" },
{ 0x0018, 0x1802, "CS", "Time Distribution Protocol" },
{ 0x0018, 0x4000, "LT", "Acquisition Comments" },
{ 0x0018, 0x5000, "SH", "Output Power" },
{ 0x0018, 0x5010, "LO", "Transducer Data" },
{ 0x0018, 0x5012, "DS", "Focus Depth" },
{ 0x0018, 0x5020, "LO", "Processing Function" },
{ 0x0018, 0x5021, "LO", "Postprocessing Function" },
{ 0x0018, 0x5022, "DS", "Mechanical Index" },
{ 0x0018, 0x5024, "DS", "Thermal Index" },
{ 0x0018, 0x5026, "DS", "Cranial Thermal Index" },
{ 0x0018, 0x5027, "DS", "Soft Tissue Thermal Index" },
{ 0x0018, 0x5028, "DS", "Soft Tissue-Focus Thermal Index" },
{ 0x0018, 0x5029, "DS", "Soft Tissue-Surface Thermal Index" },
{ 0x0018, 0x5030, "DS", "Dynamic Range" },
{ 0x0018, 0x5040, "DS", "Total Gain" },
{ 0x0018, 0x5050, "IS", "Depth of Scan Field" },
{ 0x0018, 0x5100, "CS", "Patient Position" },
{ 0x0018, 0x5101, "CS", "View Position" },
{ 0x0018, 0x5104, "SQ", "Projection Eponymous Name Code Sequence" },
{ 0x0018, 0x5210, "DS", "Image Transformation Matrix" },
{ 0x0018, 0x5212, "DS", "Image Translation Vector" },
{ 0x0018, 0x6000, "DS", "Sensitivity" },
{ 0x0018, 0x6011, "IS", "Sequence of Ultrasound Regions" },
{ 0x0018, 0x6012, "US", "Region Spatial Format" },
{ 0x0018, 0x6014, "US", "Region Data Type" },
{ 0x0018, 0x6016, "UL", "Region Flags" },
{ 0x0018, 0x6018, "UL", "Region Location Min X0" },
{ 0x0018, 0x601a, "UL", "Region Location Min Y0" },
{ 0x0018, 0x601c, "UL", "Region Location Max X1" },
{ 0x0018, 0x601e, "UL", "Region Location Max Y1" },
{ 0x0018, 0x6020, "SL", "Reference Pixel X0" },
{ 0x0018, 0x6022, "SL", "Reference Pixel Y0" },
{ 0x0018, 0x6024, "US", "Physical Units X Direction" },
{ 0x0018, 0x6026, "US", "Physical Units Y Direction" },
{ 0x0018, 0x6028, "FD", "Reference Pixel Physical Value X" },
{ 0x0018, 0x602a, "US", "Reference Pixel Physical Value Y" },
{ 0x0018, 0x602c, "US", "Physical Delta X" },
{ 0x0018, 0x602e, "US", "Physical Delta Y" },
{ 0x0018, 0x6030, "UL", "Transducer Frequency" },
{ 0x0018, 0x6031, "CS", "Transducer Type" },
{ 0x0018, 0x6032, "UL", "Pulse Repetition Frequency" },
{ 0x0018, 0x6034, "FD", "Doppler Correction Angle" },
{ 0x0018, 0x6036, "FD", "Steering Angle" },
{ 0x0018, 0x6038, "UL", "Doppler Sample Volume X Position" },
{ 0x0018, 0x603a, "UL", "Doppler Sample Volume Y Position" },
{ 0x0018, 0x603c, "UL", "TM-Line Position X0" },
{ 0x0018, 0x603e, "UL", "TM-Line Position Y0" },
{ 0x0018, 0x6040, "UL", "TM-Line Position X1" },
{ 0x0018, 0x6042, "UL", "TM-Line Position Y1" },
{ 0x0018, 0x6044, "US", "Pixel Component Organization" },
{ 0x0018, 0x6046, "UL", "Pixel Component Mask" },
{ 0x0018, 0x6048, "UL", "Pixel Component Range Start" },
{ 0x0018, 0x604a, "UL", "Pixel Component Range Stop" },
{ 0x0018, 0x604c, "US", "Pixel Component Physical Units" },
{ 0x0018, 0x604e, "US", "Pixel Component Data Type" },
{ 0x0018, 0x6050, "UL", "Number of Table Break Points" },
{ 0x0018, 0x6052, "UL", "Table of X Break Points" },
{ 0x0018, 0x6054, "FD", "Table of Y Break Points" },
{ 0x0018, 0x6056, "UL", "Number of Table Entries" },
{ 0x0018, 0x6058, "UL", "Table of Pixel Values" },
{ 0x0018, 0x605a, "FL", "Table of Parameter Values" },
{ 0x0018, 0x7000, "CS", "Detector Conditions Nominal Flag" },
{ 0x0018, 0x7001, "DS", "Detector Temperature" },
{ 0x0018, 0x7004, "CS", "Detector Type" },
{ 0x0018, 0x7005, "CS", "Detector Configuration" },
{ 0x0018, 0x7006, "LT", "Detector Description" },
{ 0x0018, 0x7008, "LT", "Detector Mode" },
{ 0x0018, 0x700a, "SH", "Detector ID" },
{ 0x0018, 0x700c, "DA", "Date of Last Detector Calibration " },
{ 0x0018, 0x700e, "TM", "Time of Last Detector Calibration" },
{ 0x0018, 0x7010, "IS", "Exposures on Detector Since Last Calibration" },
{ 0x0018, 0x7011, "IS", "Exposures on Detector Since Manufactured" },
{ 0x0018, 0x7012, "DS", "Detector Time Since Last Exposure" },
{ 0x0018, 0x7014, "DS", "Detector Active Time" },
{ 0x0018, 0x7016, "DS", "Detector Activation Offset From Exposure" },
{ 0x0018, 0x701a, "DS", "Detector Binning" },
{ 0x0018, 0x7020, "DS", "Detector Element Physical Size" },
{ 0x0018, 0x7022, "DS", "Detector Element Spacing" },
{ 0x0018, 0x7024, "CS", "Detector Active Shape" },
{ 0x0018, 0x7026, "DS", "Detector Active Dimensions" },
{ 0x0018, 0x7028, "DS", "Detector Active Origin" },
{ 0x0018, 0x7030, "DS", "Field of View Origin" },
{ 0x0018, 0x7032, "DS", "Field of View Rotation" },
{ 0x0018, 0x7034, "CS", "Field of View Horizontal Flip" },
{ 0x0018, 0x7040, "LT", "Grid Absorbing Material" },
{ 0x0018, 0x7041, "LT", "Grid Spacing Material" },
{ 0x0018, 0x7042, "DS", "Grid Thickness" },
{ 0x0018, 0x7044, "DS", "Grid Pitch" },
{ 0x0018, 0x7046, "IS", "Grid Aspect Ratio" },
{ 0x0018, 0x7048, "DS", "Grid Period" },
{ 0x0018, 0x704c, "DS", "Grid Focal Distance" },
{ 0x0018, 0x7050, "LT", "Filter Material" },
{ 0x0018, 0x7052, "DS", "Filter Thickness Minimum" },
{ 0x0018, 0x7054, "DS", "Filter Thickness Maximum" },
{ 0x0018, 0x7060, "CS", "Exposure Control Mode" },
{ 0x0018, 0x7062, "LT", "Exposure Control Mode Description" },
{ 0x0018, 0x7064, "CS", "Exposure Status" },
{ 0x0018, 0x7065, "DS", "Phototimer Setting" },
{ 0x0019, 0x0000, "xs", "?" },
{ 0x0019, 0x0001, "xs", "?" },
{ 0x0019, 0x0002, "xs", "?" },
{ 0x0019, 0x0003, "xs", "?" },
{ 0x0019, 0x0004, "xs", "?" },
{ 0x0019, 0x0005, "xs", "?" },
{ 0x0019, 0x0006, "xs", "?" },
{ 0x0019, 0x0007, "xs", "?" },
{ 0x0019, 0x0008, "xs", "?" },
{ 0x0019, 0x0009, "xs", "?" },
{ 0x0019, 0x000a, "xs", "?" },
{ 0x0019, 0x000b, "DS", "?" },
{ 0x0019, 0x000c, "US", "?" },
{ 0x0019, 0x000d, "TM", "Time" },
{ 0x0019, 0x000e, "xs", "?" },
{ 0x0019, 0x000f, "DS", "Horizontal Frame Of Reference" },
{ 0x0019, 0x0010, "xs", "?" },
{ 0x0019, 0x0011, "xs", "?" },
{ 0x0019, 0x0012, "xs", "?" },
{ 0x0019, 0x0013, "xs", "?" },
{ 0x0019, 0x0014, "xs", "?" },
{ 0x0019, 0x0015, "xs", "?" },
{ 0x0019, 0x0016, "xs", "?" },
{ 0x0019, 0x0017, "xs", "?" },
{ 0x0019, 0x0018, "xs", "?" },
{ 0x0019, 0x0019, "xs", "?" },
{ 0x0019, 0x001a, "xs", "?" },
{ 0x0019, 0x001b, "xs", "?" },
{ 0x0019, 0x001c, "CS", "Dose" },
{ 0x0019, 0x001d, "IS", "Side Mark" },
{ 0x0019, 0x001e, "xs", "?" },
{ 0x0019, 0x001f, "DS", "Exposure Duration" },
{ 0x0019, 0x0020, "xs", "?" },
{ 0x0019, 0x0021, "xs", "?" },
{ 0x0019, 0x0022, "xs", "?" },
{ 0x0019, 0x0023, "xs", "?" },
{ 0x0019, 0x0024, "xs", "?" },
{ 0x0019, 0x0025, "xs", "?" },
{ 0x0019, 0x0026, "xs", "?" },
{ 0x0019, 0x0027, "xs", "?" },
{ 0x0019, 0x0028, "xs", "?" },
{ 0x0019, 0x0029, "IS", "?" },
{ 0x0019, 0x002a, "xs", "?" },
{ 0x0019, 0x002b, "DS", "Xray Off Position" },
{ 0x0019, 0x002c, "xs", "?" },
{ 0x0019, 0x002d, "US", "?" },
{ 0x0019, 0x002e, "xs", "?" },
{ 0x0019, 0x002f, "DS", "Trigger Frequency" },
{ 0x0019, 0x0030, "xs", "?" },
{ 0x0019, 0x0031, "xs", "?" },
{ 0x0019, 0x0032, "xs", "?" },
{ 0x0019, 0x0033, "UN", "ECG 2 Offset 2" },
{ 0x0019, 0x0034, "US", "?" },
{ 0x0019, 0x0036, "US", "?" },
{ 0x0019, 0x0038, "US", "?" },
{ 0x0019, 0x0039, "xs", "?" },
{ 0x0019, 0x003a, "xs", "?" },
{ 0x0019, 0x003b, "LT", "?" },
{ 0x0019, 0x003c, "xs", "?" },
{ 0x0019, 0x003e, "xs", "?" },
{ 0x0019, 0x003f, "UN", "?" },
{ 0x0019, 0x0040, "xs", "?" },
{ 0x0019, 0x0041, "xs", "?" },
{ 0x0019, 0x0042, "xs", "?" },
{ 0x0019, 0x0043, "xs", "?" },
{ 0x0019, 0x0044, "xs", "?" },
{ 0x0019, 0x0045, "xs", "?" },
{ 0x0019, 0x0046, "xs", "?" },
{ 0x0019, 0x0047, "xs", "?" },
{ 0x0019, 0x0048, "xs", "?" },
{ 0x0019, 0x0049, "US", "?" },
{ 0x0019, 0x004a, "xs", "?" },
{ 0x0019, 0x004b, "SL", "Data Size For Scan Data" },
{ 0x0019, 0x004c, "US", "?" },
{ 0x0019, 0x004e, "US", "?" },
{ 0x0019, 0x0050, "xs", "?" },
{ 0x0019, 0x0051, "xs", "?" },
{ 0x0019, 0x0052, "xs", "?" },
{ 0x0019, 0x0053, "LT", "Barcode" },
{ 0x0019, 0x0054, "xs", "?" },
{ 0x0019, 0x0055, "DS", "Receiver Reference Gain" },
{ 0x0019, 0x0056, "xs", "?" },
{ 0x0019, 0x0057, "SS", "CT Water Number" },
{ 0x0019, 0x0058, "xs", "?" },
{ 0x0019, 0x005a, "xs", "?" },
{ 0x0019, 0x005c, "xs", "?" },
{ 0x0019, 0x005d, "US", "?" },
{ 0x0019, 0x005e, "xs", "?" },
{ 0x0019, 0x005f, "SL", "Increment Between Channels" },
{ 0x0019, 0x0060, "xs", "?" },
{ 0x0019, 0x0061, "xs", "?" },
{ 0x0019, 0x0062, "xs", "?" },
{ 0x0019, 0x0063, "xs", "?" },
{ 0x0019, 0x0064, "xs", "?" },
{ 0x0019, 0x0065, "xs", "?" },
{ 0x0019, 0x0066, "xs", "?" },
{ 0x0019, 0x0067, "xs", "?" },
{ 0x0019, 0x0068, "xs", "?" },
{ 0x0019, 0x0069, "UL", "Convolution Mode" },
{ 0x0019, 0x006a, "xs", "?" },
{ 0x0019, 0x006b, "SS", "Field Of View In Detector Cells" },
{ 0x0019, 0x006c, "US", "?" },
{ 0x0019, 0x006e, "US", "?" },
{ 0x0019, 0x0070, "xs", "?" },
{ 0x0019, 0x0071, "xs", "?" },
{ 0x0019, 0x0072, "xs", "?" },
{ 0x0019, 0x0073, "xs", "?" },
{ 0x0019, 0x0074, "xs", "?" },
{ 0x0019, 0x0075, "xs", "?" },
{ 0x0019, 0x0076, "xs", "?" },
{ 0x0019, 0x0077, "US", "?" },
{ 0x0019, 0x0078, "US", "?" },
{ 0x0019, 0x007a, "US", "?" },
{ 0x0019, 0x007c, "US", "?" },
{ 0x0019, 0x007d, "DS", "Second Echo" },
{ 0x0019, 0x007e, "xs", "?" },
{ 0x0019, 0x007f, "DS", "Table Delta" },
{ 0x0019, 0x0080, "xs", "?" },
{ 0x0019, 0x0081, "xs", "?" },
{ 0x0019, 0x0082, "xs", "?" },
{ 0x0019, 0x0083, "xs", "?" },
{ 0x0019, 0x0084, "xs", "?" },
{ 0x0019, 0x0085, "xs", "?" },
{ 0x0019, 0x0086, "xs", "?" },
{ 0x0019, 0x0087, "xs", "?" },
{ 0x0019, 0x0088, "xs", "?" },
{ 0x0019, 0x008a, "xs", "?" },
{ 0x0019, 0x008b, "SS", "Actual Receive Gain Digital" },
{ 0x0019, 0x008c, "US", "?" },
{ 0x0019, 0x008d, "DS", "Delay After Trigger" },
{ 0x0019, 0x008e, "US", "?" },
{ 0x0019, 0x008f, "SS", "Swap Phase Frequency" },
{ 0x0019, 0x0090, "xs", "?" },
{ 0x0019, 0x0091, "xs", "?" },
{ 0x0019, 0x0092, "xs", "?" },
{ 0x0019, 0x0093, "xs", "?" },
{ 0x0019, 0x0094, "xs", "?" },
{ 0x0019, 0x0095, "SS", "Analog Receiver Gain" },
{ 0x0019, 0x0096, "xs", "?" },
{ 0x0019, 0x0097, "xs", "?" },
{ 0x0019, 0x0098, "xs", "?" },
{ 0x0019, 0x0099, "US", "?" },
{ 0x0019, 0x009a, "US", "?" },
{ 0x0019, 0x009b, "SS", "Pulse Sequence Mode" },
{ 0x0019, 0x009c, "xs", "?" },
{ 0x0019, 0x009d, "DT", "Pulse Sequence Date" },
{ 0x0019, 0x009e, "xs", "?" },
{ 0x0019, 0x009f, "xs", "?" },
{ 0x0019, 0x00a0, "xs", "?" },
{ 0x0019, 0x00a1, "xs", "?" },
{ 0x0019, 0x00a2, "xs", "?" },
{ 0x0019, 0x00a3, "xs", "?" },
{ 0x0019, 0x00a4, "xs", "?" },
{ 0x0019, 0x00a5, "xs", "?" },
{ 0x0019, 0x00a6, "xs", "?" },
{ 0x0019, 0x00a7, "xs", "?" },
{ 0x0019, 0x00a8, "xs", "?" },
{ 0x0019, 0x00a9, "xs", "?" },
{ 0x0019, 0x00aa, "xs", "?" },
{ 0x0019, 0x00ab, "xs", "?" },
{ 0x0019, 0x00ac, "xs", "?" },
{ 0x0019, 0x00ad, "xs", "?" },
{ 0x0019, 0x00ae, "xs", "?" },
{ 0x0019, 0x00af, "xs", "?" },
{ 0x0019, 0x00b0, "xs", "?" },
{ 0x0019, 0x00b1, "xs", "?" },
{ 0x0019, 0x00b2, "xs", "?" },
{ 0x0019, 0x00b3, "xs", "?" },
{ 0x0019, 0x00b4, "xs", "?" },
{ 0x0019, 0x00b5, "xs", "?" },
{ 0x0019, 0x00b6, "DS", "User Data" },
{ 0x0019, 0x00b7, "DS", "User Data" },
{ 0x0019, 0x00b8, "DS", "User Data" },
{ 0x0019, 0x00b9, "DS", "User Data" },
{ 0x0019, 0x00ba, "DS", "User Data" },
{ 0x0019, 0x00bb, "DS", "User Data" },
{ 0x0019, 0x00bc, "DS", "User Data" },
{ 0x0019, 0x00bd, "DS", "User Data" },
{ 0x0019, 0x00be, "DS", "Projection Angle" },
{ 0x0019, 0x00c0, "xs", "?" },
{ 0x0019, 0x00c1, "xs", "?" },
{ 0x0019, 0x00c2, "xs", "?" },
{ 0x0019, 0x00c3, "xs", "?" },
{ 0x0019, 0x00c4, "xs", "?" },
{ 0x0019, 0x00c5, "xs", "?" },
{ 0x0019, 0x00c6, "SS", "SAT Location H" },
{ 0x0019, 0x00c7, "SS", "SAT Location F" },
{ 0x0019, 0x00c8, "SS", "SAT Thickness R L" },
{ 0x0019, 0x00c9, "SS", "SAT Thickness A P" },
{ 0x0019, 0x00ca, "SS", "SAT Thickness H F" },
{ 0x0019, 0x00cb, "xs", "?" },
{ 0x0019, 0x00cc, "xs", "?" },
{ 0x0019, 0x00cd, "SS", "Thickness Disclaimer" },
{ 0x0019, 0x00ce, "SS", "Prescan Type" },
{ 0x0019, 0x00cf, "SS", "Prescan Status" },
{ 0x0019, 0x00d0, "SH", "Raw Data Type" },
{ 0x0019, 0x00d1, "DS", "Flow Sensitivity" },
{ 0x0019, 0x00d2, "xs", "?" },
{ 0x0019, 0x00d3, "xs", "?" },
{ 0x0019, 0x00d4, "xs", "?" },
{ 0x0019, 0x00d5, "xs", "?" },
{ 0x0019, 0x00d6, "xs", "?" },
{ 0x0019, 0x00d7, "xs", "?" },
{ 0x0019, 0x00d8, "xs", "?" },
{ 0x0019, 0x00d9, "xs", "?" },
{ 0x0019, 0x00da, "xs", "?" },
{ 0x0019, 0x00db, "DS", "Back Projector Coefficient" },
{ 0x0019, 0x00dc, "SS", "Primary Speed Correction Used" },
{ 0x0019, 0x00dd, "SS", "Overrange Correction Used" },
{ 0x0019, 0x00de, "DS", "Dynamic Z Alpha Value" },
{ 0x0019, 0x00df, "DS", "User Data" },
{ 0x0019, 0x00e0, "DS", "User Data" },
{ 0x0019, 0x00e1, "xs", "?" },
{ 0x0019, 0x00e2, "xs", "?" },
{ 0x0019, 0x00e3, "xs", "?" },
{ 0x0019, 0x00e4, "LT", "?" },
{ 0x0019, 0x00e5, "IS", "?" },
{ 0x0019, 0x00e6, "US", "?" },
{ 0x0019, 0x00e8, "DS", "?" },
{ 0x0019, 0x00e9, "DS", "?" },
{ 0x0019, 0x00eb, "DS", "?" },
{ 0x0019, 0x00ec, "US", "?" },
{ 0x0019, 0x00f0, "xs", "?" },
{ 0x0019, 0x00f1, "xs", "?" },
{ 0x0019, 0x00f2, "xs", "?" },
{ 0x0019, 0x00f3, "xs", "?" },
{ 0x0019, 0x00f4, "LT", "?" },
{ 0x0019, 0x00f9, "DS", "Transmission Gain" },
{ 0x0019, 0x1015, "UN", "?" },
{ 0x0020, 0x0000, "UL", "Relationship Group Length" },
{ 0x0020, 0x000d, "UI", "Study Instance UID" },
{ 0x0020, 0x000e, "UI", "Series Instance UID" },
{ 0x0020, 0x0010, "SH", "Study ID" },
{ 0x0020, 0x0011, "IS", "Series Number" },
{ 0x0020, 0x0012, "IS", "Acquisition Number" },
{ 0x0020, 0x0013, "IS", "Instance (formerly Image) Number" },
{ 0x0020, 0x0014, "IS", "Isotope Number" },
{ 0x0020, 0x0015, "IS", "Phase Number" },
{ 0x0020, 0x0016, "IS", "Interval Number" },
{ 0x0020, 0x0017, "IS", "Time Slot Number" },
{ 0x0020, 0x0018, "IS", "Angle Number" },
{ 0x0020, 0x0020, "CS", "Patient Orientation" },
{ 0x0020, 0x0022, "IS", "Overlay Number" },
{ 0x0020, 0x0024, "IS", "Curve Number" },
{ 0x0020, 0x0026, "IS", "LUT Number" },
{ 0x0020, 0x0030, "DS", "Image Position" },
{ 0x0020, 0x0032, "DS", "Image Position (Patient)" },
{ 0x0020, 0x0035, "DS", "Image Orientation" },
{ 0x0020, 0x0037, "DS", "Image Orientation (Patient)" },
{ 0x0020, 0x0050, "DS", "Location" },
{ 0x0020, 0x0052, "UI", "Frame of Reference UID" },
{ 0x0020, 0x0060, "CS", "Laterality" },
{ 0x0020, 0x0062, "CS", "Image Laterality" },
{ 0x0020, 0x0070, "LT", "Image Geometry Type" },
{ 0x0020, 0x0080, "LO", "Masking Image" },
{ 0x0020, 0x0100, "IS", "Temporal Position Identifier" },
{ 0x0020, 0x0105, "IS", "Number of Temporal Positions" },
{ 0x0020, 0x0110, "DS", "Temporal Resolution" },
{ 0x0020, 0x1000, "IS", "Series in Study" },
{ 0x0020, 0x1001, "DS", "Acquisitions in Series" },
{ 0x0020, 0x1002, "IS", "Images in Acquisition" },
{ 0x0020, 0x1003, "IS", "Images in Series" },
{ 0x0020, 0x1004, "IS", "Acquisitions in Study" },
{ 0x0020, 0x1005, "IS", "Images in Study" },
{ 0x0020, 0x1020, "LO", "Reference" },
{ 0x0020, 0x1040, "LO", "Position Reference Indicator" },
{ 0x0020, 0x1041, "DS", "Slice Location" },
{ 0x0020, 0x1070, "IS", "Other Study Numbers" },
{ 0x0020, 0x1200, "IS", "Number of Patient Related Studies" },
{ 0x0020, 0x1202, "IS", "Number of Patient Related Series" },
{ 0x0020, 0x1204, "IS", "Number of Patient Related Images" },
{ 0x0020, 0x1206, "IS", "Number of Study Related Series" },
{ 0x0020, 0x1208, "IS", "Number of Study Related Series" },
{ 0x0020, 0x3100, "LO", "Source Image IDs" },
{ 0x0020, 0x3401, "LO", "Modifying Device ID" },
{ 0x0020, 0x3402, "LO", "Modified Image ID" },
{ 0x0020, 0x3403, "xs", "Modified Image Date" },
{ 0x0020, 0x3404, "LO", "Modifying Device Manufacturer" },
{ 0x0020, 0x3405, "xs", "Modified Image Time" },
{ 0x0020, 0x3406, "xs", "Modified Image Description" },
{ 0x0020, 0x4000, "LT", "Image Comments" },
{ 0x0020, 0x5000, "AT", "Original Image Identification" },
{ 0x0020, 0x5002, "LO", "Original Image Identification Nomenclature" },
{ 0x0021, 0x0000, "xs", "?" },
{ 0x0021, 0x0001, "xs", "?" },
{ 0x0021, 0x0002, "xs", "?" },
{ 0x0021, 0x0003, "xs", "?" },
{ 0x0021, 0x0004, "DS", "VOI Position" },
{ 0x0021, 0x0005, "xs", "?" },
{ 0x0021, 0x0006, "IS", "CSI Matrix Size Original" },
{ 0x0021, 0x0007, "xs", "?" },
{ 0x0021, 0x0008, "DS", "Spatial Grid Shift" },
{ 0x0021, 0x0009, "DS", "Signal Limits Minimum" },
{ 0x0021, 0x0010, "xs", "?" },
{ 0x0021, 0x0011, "xs", "?" },
{ 0x0021, 0x0012, "xs", "?" },
{ 0x0021, 0x0013, "xs", "?" },
{ 0x0021, 0x0014, "xs", "?" },
{ 0x0021, 0x0015, "xs", "?" },
{ 0x0021, 0x0016, "xs", "?" },
{ 0x0021, 0x0017, "DS", "EPI Operation Mode Flag" },
{ 0x0021, 0x0018, "xs", "?" },
{ 0x0021, 0x0019, "xs", "?" },
{ 0x0021, 0x0020, "xs", "?" },
{ 0x0021, 0x0021, "xs", "?" },
{ 0x0021, 0x0022, "xs", "?" },
{ 0x0021, 0x0024, "xs", "?" },
{ 0x0021, 0x0025, "US", "?" },
{ 0x0021, 0x0026, "IS", "Image Pixel Offset" },
{ 0x0021, 0x0030, "xs", "?" },
{ 0x0021, 0x0031, "xs", "?" },
{ 0x0021, 0x0032, "xs", "?" },
{ 0x0021, 0x0034, "xs", "?" },
{ 0x0021, 0x0035, "SS", "Series From Which Prescribed" },
{ 0x0021, 0x0036, "xs", "?" },
{ 0x0021, 0x0037, "SS", "Screen Format" },
{ 0x0021, 0x0039, "DS", "Slab Thickness" },
{ 0x0021, 0x0040, "xs", "?" },
{ 0x0021, 0x0041, "xs", "?" },
{ 0x0021, 0x0042, "xs", "?" },
{ 0x0021, 0x0043, "xs", "?" },
{ 0x0021, 0x0044, "xs", "?" },
{ 0x0021, 0x0045, "xs", "?" },
{ 0x0021, 0x0046, "xs", "?" },
{ 0x0021, 0x0047, "xs", "?" },
{ 0x0021, 0x0048, "xs", "?" },
{ 0x0021, 0x0049, "xs", "?" },
{ 0x0021, 0x004a, "xs", "?" },
{ 0x0021, 0x004e, "US", "?" },
{ 0x0021, 0x004f, "xs", "?" },
{ 0x0021, 0x0050, "xs", "?" },
{ 0x0021, 0x0051, "xs", "?" },
{ 0x0021, 0x0052, "xs", "?" },
{ 0x0021, 0x0053, "xs", "?" },
{ 0x0021, 0x0054, "xs", "?" },
{ 0x0021, 0x0055, "xs", "?" },
{ 0x0021, 0x0056, "xs", "?" },
{ 0x0021, 0x0057, "xs", "?" },
{ 0x0021, 0x0058, "xs", "?" },
{ 0x0021, 0x0059, "xs", "?" },
{ 0x0021, 0x005a, "SL", "Integer Slop" },
{ 0x0021, 0x005b, "DS", "Float Slop" },
{ 0x0021, 0x005c, "DS", "Float Slop" },
{ 0x0021, 0x005d, "DS", "Float Slop" },
{ 0x0021, 0x005e, "DS", "Float Slop" },
{ 0x0021, 0x005f, "DS", "Float Slop" },
{ 0x0021, 0x0060, "xs", "?" },
{ 0x0021, 0x0061, "DS", "Image Normal" },
{ 0x0021, 0x0062, "IS", "Reference Type Code" },
{ 0x0021, 0x0063, "DS", "Image Distance" },
{ 0x0021, 0x0065, "US", "Image Positioning History Mask" },
{ 0x0021, 0x006a, "DS", "Image Row" },
{ 0x0021, 0x006b, "DS", "Image Column" },
{ 0x0021, 0x0070, "xs", "?" },
{ 0x0021, 0x0071, "xs", "?" },
{ 0x0021, 0x0072, "xs", "?" },
{ 0x0021, 0x0073, "DS", "Second Repetition Time" },
{ 0x0021, 0x0075, "DS", "Light Brightness" },
{ 0x0021, 0x0076, "DS", "Light Contrast" },
{ 0x0021, 0x007a, "IS", "Overlay Threshold" },
{ 0x0021, 0x007b, "IS", "Surface Threshold" },
{ 0x0021, 0x007c, "IS", "Grey Scale Threshold" },
{ 0x0021, 0x0080, "xs", "?" },
{ 0x0021, 0x0081, "DS", "Auto Window Level Alpha" },
{ 0x0021, 0x0082, "xs", "?" },
{ 0x0021, 0x0083, "DS", "Auto Window Level Window" },
{ 0x0021, 0x0084, "DS", "Auto Window Level Level" },
{ 0x0021, 0x0090, "xs", "?" },
{ 0x0021, 0x0091, "xs", "?" },
{ 0x0021, 0x0092, "xs", "?" },
{ 0x0021, 0x0093, "xs", "?" },
{ 0x0021, 0x0094, "DS", "EPI Change Value of X Component" },
{ 0x0021, 0x0095, "DS", "EPI Change Value of Y Component" },
{ 0x0021, 0x0096, "DS", "EPI Change Value of Z Component" },
{ 0x0021, 0x00a0, "xs", "?" },
{ 0x0021, 0x00a1, "DS", "?" },
{ 0x0021, 0x00a2, "xs", "?" },
{ 0x0021, 0x00a3, "LT", "?" },
{ 0x0021, 0x00a4, "LT", "?" },
{ 0x0021, 0x00a7, "LT", "?" },
{ 0x0021, 0x00b0, "IS", "?" },
{ 0x0021, 0x00c0, "IS", "?" },
{ 0x0023, 0x0000, "xs", "?" },
{ 0x0023, 0x0001, "SL", "Number Of Series In Study" },
{ 0x0023, 0x0002, "SL", "Number Of Unarchived Series" },
{ 0x0023, 0x0010, "xs", "?" },
{ 0x0023, 0x0020, "xs", "?" },
{ 0x0023, 0x0030, "xs", "?" },
{ 0x0023, 0x0040, "xs", "?" },
{ 0x0023, 0x0050, "xs", "?" },
{ 0x0023, 0x0060, "xs", "?" },
{ 0x0023, 0x0070, "xs", "?" },
{ 0x0023, 0x0074, "SL", "Number Of Updates To Info" },
{ 0x0023, 0x007d, "SS", "Indicates If Study Has Complete Info" },
{ 0x0023, 0x0080, "xs", "?" },
{ 0x0023, 0x0090, "xs", "?" },
{ 0x0023, 0x00ff, "US", "?" },
{ 0x0025, 0x0000, "UL", "Group Length" },
{ 0x0025, 0x0006, "SS", "Last Pulse Sequence Used" },
{ 0x0025, 0x0007, "SL", "Images In Series" },
{ 0x0025, 0x0010, "SS", "Landmark Counter" },
{ 0x0025, 0x0011, "SS", "Number Of Acquisitions" },
{ 0x0025, 0x0014, "SL", "Indicates Number Of Updates To Info" },
{ 0x0025, 0x0017, "SL", "Series Complete Flag" },
{ 0x0025, 0x0018, "SL", "Number Of Images Archived" },
{ 0x0025, 0x0019, "SL", "Last Image Number Used" },
{ 0x0025, 0x001a, "SH", "Primary Receiver Suite And Host" },
{ 0x0027, 0x0000, "US", "?" },
{ 0x0027, 0x0006, "SL", "Image Archive Flag" },
{ 0x0027, 0x0010, "SS", "Scout Type" },
{ 0x0027, 0x0011, "UN", "?" },
{ 0x0027, 0x0012, "IS", "?" },
{ 0x0027, 0x0013, "IS", "?" },
{ 0x0027, 0x0014, "IS", "?" },
{ 0x0027, 0x0015, "IS", "?" },
{ 0x0027, 0x0016, "LT", "?" },
{ 0x0027, 0x001c, "SL", "Vma Mamp" },
{ 0x0027, 0x001d, "SS", "Vma Phase" },
{ 0x0027, 0x001e, "SL", "Vma Mod" },
{ 0x0027, 0x001f, "SL", "Vma Clip" },
{ 0x0027, 0x0020, "SS", "Smart Scan On Off Flag" },
{ 0x0027, 0x0030, "SH", "Foreign Image Revision" },
{ 0x0027, 0x0031, "SS", "Imaging Mode" },
{ 0x0027, 0x0032, "SS", "Pulse Sequence" },
{ 0x0027, 0x0033, "SL", "Imaging Options" },
{ 0x0027, 0x0035, "SS", "Plane Type" },
{ 0x0027, 0x0036, "SL", "Oblique Plane" },
{ 0x0027, 0x0040, "SH", "RAS Letter Of Image Location" },
{ 0x0027, 0x0041, "FL", "Image Location" },
{ 0x0027, 0x0042, "FL", "Center R Coord Of Plane Image" },
{ 0x0027, 0x0043, "FL", "Center A Coord Of Plane Image" },
{ 0x0027, 0x0044, "FL", "Center S Coord Of Plane Image" },
{ 0x0027, 0x0045, "FL", "Normal R Coord" },
{ 0x0027, 0x0046, "FL", "Normal A Coord" },
{ 0x0027, 0x0047, "FL", "Normal S Coord" },
{ 0x0027, 0x0048, "FL", "R Coord Of Top Right Corner" },
{ 0x0027, 0x0049, "FL", "A Coord Of Top Right Corner" },
{ 0x0027, 0x004a, "FL", "S Coord Of Top Right Corner" },
{ 0x0027, 0x004b, "FL", "R Coord Of Bottom Right Corner" },
{ 0x0027, 0x004c, "FL", "A Coord Of Bottom Right Corner" },
{ 0x0027, 0x004d, "FL", "S Coord Of Bottom Right Corner" },
{ 0x0027, 0x0050, "FL", "Table Start Location" },
{ 0x0027, 0x0051, "FL", "Table End Location" },
{ 0x0027, 0x0052, "SH", "RAS Letter For Side Of Image" },
{ 0x0027, 0x0053, "SH", "RAS Letter For Anterior Posterior" },
{ 0x0027, 0x0054, "SH", "RAS Letter For Scout Start Loc" },
{ 0x0027, 0x0055, "SH", "RAS Letter For Scout End Loc" },
{ 0x0027, 0x0060, "FL", "Image Dimension X" },
{ 0x0027, 0x0061, "FL", "Image Dimension Y" },
{ 0x0027, 0x0062, "FL", "Number Of Excitations" },
{ 0x0028, 0x0000, "UL", "Image Presentation Group Length" },
{ 0x0028, 0x0002, "US", "Samples per Pixel" },
{ 0x0028, 0x0004, "CS", "Photometric Interpretation" },
{ 0x0028, 0x0005, "US", "Image Dimensions" },
{ 0x0028, 0x0006, "US", "Planar Configuration" },
{ 0x0028, 0x0008, "IS", "Number of Frames" },
{ 0x0028, 0x0009, "AT", "Frame Increment Pointer" },
{ 0x0028, 0x0010, "US", "Rows" },
{ 0x0028, 0x0011, "US", "Columns" },
{ 0x0028, 0x0012, "US", "Planes" },
{ 0x0028, 0x0014, "US", "Ultrasound Color Data Present" },
{ 0x0028, 0x0030, "DS", "Pixel Spacing" },
{ 0x0028, 0x0031, "DS", "Zoom Factor" },
{ 0x0028, 0x0032, "DS", "Zoom Center" },
{ 0x0028, 0x0034, "IS", "Pixel Aspect Ratio" },
{ 0x0028, 0x0040, "LO", "Image Format" },
{ 0x0028, 0x0050, "LT", "Manipulated Image" },
{ 0x0028, 0x0051, "CS", "Corrected Image" },
{ 0x0028, 0x005f, "LO", "Compression Recognition Code" },
{ 0x0028, 0x0060, "LO", "Compression Code" },
{ 0x0028, 0x0061, "SH", "Compression Originator" },
{ 0x0028, 0x0062, "SH", "Compression Label" },
{ 0x0028, 0x0063, "SH", "Compression Description" },
{ 0x0028, 0x0065, "LO", "Compression Sequence" },
{ 0x0028, 0x0066, "AT", "Compression Step Pointers" },
{ 0x0028, 0x0068, "US", "Repeat Interval" },
{ 0x0028, 0x0069, "US", "Bits Grouped" },
{ 0x0028, 0x0070, "US", "Perimeter Table" },
{ 0x0028, 0x0071, "xs", "Perimeter Value" },
{ 0x0028, 0x0080, "US", "Predictor Rows" },
{ 0x0028, 0x0081, "US", "Predictor Columns" },
{ 0x0028, 0x0082, "US", "Predictor Constants" },
{ 0x0028, 0x0090, "LO", "Blocked Pixels" },
{ 0x0028, 0x0091, "US", "Block Rows" },
{ 0x0028, 0x0092, "US", "Block Columns" },
{ 0x0028, 0x0093, "US", "Row Overlap" },
{ 0x0028, 0x0094, "US", "Column Overlap" },
{ 0x0028, 0x0100, "US", "Bits Allocated" },
{ 0x0028, 0x0101, "US", "Bits Stored" },
{ 0x0028, 0x0102, "US", "High Bit" },
{ 0x0028, 0x0103, "US", "Pixel Representation" },
{ 0x0028, 0x0104, "xs", "Smallest Valid Pixel Value" },
{ 0x0028, 0x0105, "xs", "Largest Valid Pixel Value" },
{ 0x0028, 0x0106, "xs", "Smallest Image Pixel Value" },
{ 0x0028, 0x0107, "xs", "Largest Image Pixel Value" },
{ 0x0028, 0x0108, "xs", "Smallest Pixel Value in Series" },
{ 0x0028, 0x0109, "xs", "Largest Pixel Value in Series" },
{ 0x0028, 0x0110, "xs", "Smallest Pixel Value in Plane" },
{ 0x0028, 0x0111, "xs", "Largest Pixel Value in Plane" },
{ 0x0028, 0x0120, "xs", "Pixel Padding Value" },
{ 0x0028, 0x0200, "xs", "Image Location" },
{ 0x0028, 0x0300, "CS", "Quality Control Image" },
{ 0x0028, 0x0301, "CS", "Burned In Annotation" },
{ 0x0028, 0x0400, "xs", "?" },
{ 0x0028, 0x0401, "xs", "?" },
{ 0x0028, 0x0402, "xs", "?" },
{ 0x0028, 0x0403, "xs", "?" },
{ 0x0028, 0x0404, "AT", "Details of Coefficients" },
{ 0x0028, 0x0700, "LO", "DCT Label" },
{ 0x0028, 0x0701, "LO", "Data Block Description" },
{ 0x0028, 0x0702, "AT", "Data Block" },
{ 0x0028, 0x0710, "US", "Normalization Factor Format" },
{ 0x0028, 0x0720, "US", "Zonal Map Number Format" },
{ 0x0028, 0x0721, "AT", "Zonal Map Location" },
{ 0x0028, 0x0722, "US", "Zonal Map Format" },
{ 0x0028, 0x0730, "US", "Adaptive Map Format" },
{ 0x0028, 0x0740, "US", "Code Number Format" },
{ 0x0028, 0x0800, "LO", "Code Label" },
{ 0x0028, 0x0802, "US", "Number of Tables" },
{ 0x0028, 0x0803, "AT", "Code Table Location" },
{ 0x0028, 0x0804, "US", "Bits For Code Word" },
{ 0x0028, 0x0808, "AT", "Image Data Location" },
{ 0x0028, 0x1040, "CS", "Pixel Intensity Relationship" },
{ 0x0028, 0x1041, "SS", "Pixel Intensity Relationship Sign" },
{ 0x0028, 0x1050, "DS", "Window Center" },
{ 0x0028, 0x1051, "DS", "Window Width" },
{ 0x0028, 0x1052, "DS", "Rescale Intercept" },
{ 0x0028, 0x1053, "DS", "Rescale Slope" },
{ 0x0028, 0x1054, "LO", "Rescale Type" },
{ 0x0028, 0x1055, "LO", "Window Center & Width Explanation" },
{ 0x0028, 0x1080, "LO", "Gray Scale" },
{ 0x0028, 0x1090, "CS", "Recommended Viewing Mode" },
{ 0x0028, 0x1100, "xs", "Gray Lookup Table Descriptor" },
{ 0x0028, 0x1101, "xs", "Red Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1102, "xs", "Green Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1103, "xs", "Blue Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1111, "OW", "Large Red Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1112, "OW", "Large Green Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1113, "OW", "Large Blue Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1199, "UI", "Palette Color Lookup Table UID" },
{ 0x0028, 0x1200, "xs", "Gray Lookup Table Data" },
{ 0x0028, 0x1201, "OW", "Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1202, "OW", "Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1203, "OW", "Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1211, "OW", "Large Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1212, "OW", "Large Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1213, "OW", "Large Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1214, "UI", "Large Palette Color Lookup Table UID" },
{ 0x0028, 0x1221, "OW", "Segmented Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1222, "OW", "Segmented Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1223, "OW", "Segmented Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1300, "CS", "Implant Present" },
{ 0x0028, 0x2110, "CS", "Lossy Image Compression" },
{ 0x0028, 0x2112, "DS", "Lossy Image Compression Ratio" },
{ 0x0028, 0x3000, "SQ", "Modality LUT Sequence" },
{ 0x0028, 0x3002, "US", "LUT Descriptor" },
{ 0x0028, 0x3003, "LO", "LUT Explanation" },
{ 0x0028, 0x3004, "LO", "Modality LUT Type" },
{ 0x0028, 0x3006, "US", "LUT Data" },
{ 0x0028, 0x3010, "xs", "VOI LUT Sequence" },
{ 0x0028, 0x4000, "LT", "Image Presentation Comments" },
{ 0x0028, 0x5000, "SQ", "Biplane Acquisition Sequence" },
{ 0x0028, 0x6010, "US", "Representative Frame Number" },
{ 0x0028, 0x6020, "US", "Frame Numbers of Interest" },
{ 0x0028, 0x6022, "LO", "Frame of Interest Description" },
{ 0x0028, 0x6030, "US", "Mask Pointer" },
{ 0x0028, 0x6040, "US", "R Wave Pointer" },
{ 0x0028, 0x6100, "SQ", "Mask Subtraction Sequence" },
{ 0x0028, 0x6101, "CS", "Mask Operation" },
{ 0x0028, 0x6102, "US", "Applicable Frame Range" },
{ 0x0028, 0x6110, "US", "Mask Frame Numbers" },
{ 0x0028, 0x6112, "US", "Contrast Frame Averaging" },
{ 0x0028, 0x6114, "FL", "Mask Sub-Pixel Shift" },
{ 0x0028, 0x6120, "SS", "TID Offset" },
{ 0x0028, 0x6190, "ST", "Mask Operation Explanation" },
{ 0x0029, 0x0000, "xs", "?" },
{ 0x0029, 0x0001, "xs", "?" },
{ 0x0029, 0x0002, "xs", "?" },
{ 0x0029, 0x0003, "xs", "?" },
{ 0x0029, 0x0004, "xs", "?" },
{ 0x0029, 0x0005, "xs", "?" },
{ 0x0029, 0x0006, "xs", "?" },
{ 0x0029, 0x0007, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0008, "SH", "Lower Range Of Pixels" },
{ 0x0029, 0x0009, "SH", "Lower Range Of Pixels" },
{ 0x0029, 0x000a, "SS", "Lower Range Of Pixels" },
{ 0x0029, 0x000c, "xs", "?" },
{ 0x0029, 0x000e, "CS", "Zoom Enable Status" },
{ 0x0029, 0x000f, "CS", "Zoom Select Status" },
{ 0x0029, 0x0010, "xs", "?" },
{ 0x0029, 0x0011, "xs", "?" },
{ 0x0029, 0x0013, "LT", "?" },
{ 0x0029, 0x0015, "xs", "?" },
{ 0x0029, 0x0016, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0017, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0018, "SL", "Upper Range Of Pixels" },
{ 0x0029, 0x001a, "SL", "Length Of Total Info In Bytes" },
{ 0x0029, 0x001e, "xs", "?" },
{ 0x0029, 0x001f, "xs", "?" },
{ 0x0029, 0x0020, "xs", "?" },
{ 0x0029, 0x0022, "IS", "Pixel Quality Value" },
{ 0x0029, 0x0025, "LT", "Processed Pixel Data Quality" },
{ 0x0029, 0x0026, "SS", "Version Of Info Structure" },
{ 0x0029, 0x0030, "xs", "?" },
{ 0x0029, 0x0031, "xs", "?" },
{ 0x0029, 0x0032, "xs", "?" },
{ 0x0029, 0x0033, "xs", "?" },
{ 0x0029, 0x0034, "xs", "?" },
{ 0x0029, 0x0035, "SL", "Advantage Comp Underflow" },
{ 0x0029, 0x0038, "US", "?" },
{ 0x0029, 0x0040, "xs", "?" },
{ 0x0029, 0x0041, "DS", "Magnifying Glass Rectangle" },
{ 0x0029, 0x0043, "DS", "Magnifying Glass Factor" },
{ 0x0029, 0x0044, "US", "Magnifying Glass Function" },
{ 0x0029, 0x004e, "CS", "Magnifying Glass Enable Status" },
{ 0x0029, 0x004f, "CS", "Magnifying Glass Select Status" },
{ 0x0029, 0x0050, "xs", "?" },
{ 0x0029, 0x0051, "LT", "Exposure Code" },
{ 0x0029, 0x0052, "LT", "Sort Code" },
{ 0x0029, 0x0053, "LT", "?" },
{ 0x0029, 0x0060, "xs", "?" },
{ 0x0029, 0x0061, "xs", "?" },
{ 0x0029, 0x0067, "LT", "?" },
{ 0x0029, 0x0070, "xs", "?" },
{ 0x0029, 0x0071, "xs", "?" },
{ 0x0029, 0x0072, "xs", "?" },
{ 0x0029, 0x0077, "CS", "Window Select Status" },
{ 0x0029, 0x0078, "LT", "ECG Display Printing ID" },
{ 0x0029, 0x0079, "CS", "ECG Display Printing" },
{ 0x0029, 0x007e, "CS", "ECG Display Printing Enable Status" },
{ 0x0029, 0x007f, "CS", "ECG Display Printing Select Status" },
{ 0x0029, 0x0080, "xs", "?" },
{ 0x0029, 0x0081, "xs", "?" },
{ 0x0029, 0x0082, "IS", "View Zoom" },
{ 0x0029, 0x0083, "IS", "View Transform" },
{ 0x0029, 0x008e, "CS", "Physiological Display Enable Status" },
{ 0x0029, 0x008f, "CS", "Physiological Display Select Status" },
{ 0x0029, 0x0090, "IS", "?" },
{ 0x0029, 0x0099, "LT", "Shutter Type" },
{ 0x0029, 0x00a0, "US", "Rows of Rectangular Shutter" },
{ 0x0029, 0x00a1, "US", "Columns of Rectangular Shutter" },
{ 0x0029, 0x00a2, "US", "Origin of Rectangular Shutter" },
{ 0x0029, 0x00b0, "US", "Radius of Circular Shutter" },
{ 0x0029, 0x00b2, "US", "Origin of Circular Shutter" },
{ 0x0029, 0x00c0, "LT", "Functional Shutter ID" },
{ 0x0029, 0x00c1, "xs", "?" },
{ 0x0029, 0x00c3, "IS", "Scan Resolution" },
{ 0x0029, 0x00c4, "IS", "Field of View" },
{ 0x0029, 0x00c5, "LT", "Field Of Shutter Rectangle" },
{ 0x0029, 0x00ce, "CS", "Shutter Enable Status" },
{ 0x0029, 0x00cf, "CS", "Shutter Select Status" },
{ 0x0029, 0x00d0, "IS", "?" },
{ 0x0029, 0x00d1, "IS", "?" },
{ 0x0029, 0x00d5, "LT", "Slice Thickness" },
{ 0x0031, 0x0010, "LT", "Request UID" },
{ 0x0031, 0x0012, "LT", "Examination Reason" },
{ 0x0031, 0x0030, "DA", "Requested Date" },
{ 0x0031, 0x0032, "TM", "Worklist Request Start Time" },
{ 0x0031, 0x0033, "TM", "Worklist Request End Time" },
{ 0x0031, 0x0045, "LT", "Requesting Physician" },
{ 0x0031, 0x004a, "TM", "Requested Time" },
{ 0x0031, 0x0050, "LT", "Requested Physician" },
{ 0x0031, 0x0080, "LT", "Requested Location" },
{ 0x0032, 0x0000, "UL", "Study Group Length" },
{ 0x0032, 0x000a, "CS", "Study Status ID" },
{ 0x0032, 0x000c, "CS", "Study Priority ID" },
{ 0x0032, 0x0012, "LO", "Study ID Issuer" },
{ 0x0032, 0x0032, "DA", "Study Verified Date" },
{ 0x0032, 0x0033, "TM", "Study Verified Time" },
{ 0x0032, 0x0034, "DA", "Study Read Date" },
{ 0x0032, 0x0035, "TM", "Study Read Time" },
{ 0x0032, 0x1000, "DA", "Scheduled Study Start Date" },
{ 0x0032, 0x1001, "TM", "Scheduled Study Start Time" },
{ 0x0032, 0x1010, "DA", "Scheduled Study Stop Date" },
{ 0x0032, 0x1011, "TM", "Scheduled Study Stop Time" },
{ 0x0032, 0x1020, "LO", "Scheduled Study Location" },
{ 0x0032, 0x1021, "AE", "Scheduled Study Location AE Title(s)" },
{ 0x0032, 0x1030, "LO", "Reason for Study" },
{ 0x0032, 0x1032, "PN", "Requesting Physician" },
{ 0x0032, 0x1033, "LO", "Requesting Service" },
{ 0x0032, 0x1040, "DA", "Study Arrival Date" },
{ 0x0032, 0x1041, "TM", "Study Arrival Time" },
{ 0x0032, 0x1050, "DA", "Study Completion Date" },
{ 0x0032, 0x1051, "TM", "Study Completion Time" },
{ 0x0032, 0x1055, "CS", "Study Component Status ID" },
{ 0x0032, 0x1060, "LO", "Requested Procedure Description" },
{ 0x0032, 0x1064, "SQ", "Requested Procedure Code Sequence" },
{ 0x0032, 0x1070, "LO", "Requested Contrast Agent" },
{ 0x0032, 0x4000, "LT", "Study Comments" },
{ 0x0033, 0x0001, "UN", "?" },
{ 0x0033, 0x0002, "UN", "?" },
{ 0x0033, 0x0005, "UN", "?" },
{ 0x0033, 0x0006, "UN", "?" },
{ 0x0033, 0x0010, "LT", "Patient Study UID" },
{ 0x0037, 0x0010, "LO", "ReferringDepartment" },
{ 0x0037, 0x0020, "US", "ScreenNumber" },
{ 0x0037, 0x0040, "SH", "LeftOrientation" },
{ 0x0037, 0x0042, "SH", "RightOrientation" },
{ 0x0037, 0x0050, "CS", "Inversion" },
{ 0x0037, 0x0060, "US", "DSA" },
{ 0x0038, 0x0000, "UL", "Visit Group Length" },
{ 0x0038, 0x0004, "SQ", "Referenced Patient Alias Sequence" },
{ 0x0038, 0x0008, "CS", "Visit Status ID" },
{ 0x0038, 0x0010, "LO", "Admission ID" },
{ 0x0038, 0x0011, "LO", "Issuer of Admission ID" },
{ 0x0038, 0x0016, "LO", "Route of Admissions" },
{ 0x0038, 0x001a, "DA", "Scheduled Admission Date" },
{ 0x0038, 0x001b, "TM", "Scheduled Admission Time" },
{ 0x0038, 0x001c, "DA", "Scheduled Discharge Date" },
{ 0x0038, 0x001d, "TM", "Scheduled Discharge Time" },
{ 0x0038, 0x001e, "LO", "Scheduled Patient Institution Residence" },
{ 0x0038, 0x0020, "DA", "Admitting Date" },
{ 0x0038, 0x0021, "TM", "Admitting Time" },
{ 0x0038, 0x0030, "DA", "Discharge Date" },
{ 0x0038, 0x0032, "TM", "Discharge Time" },
{ 0x0038, 0x0040, "LO", "Discharge Diagnosis Description" },
{ 0x0038, 0x0044, "SQ", "Discharge Diagnosis Code Sequence" },
{ 0x0038, 0x0050, "LO", "Special Needs" },
{ 0x0038, 0x0300, "LO", "Current Patient Location" },
{ 0x0038, 0x0400, "LO", "Patient's Institution Residence" },
{ 0x0038, 0x0500, "LO", "Patient State" },
{ 0x0038, 0x4000, "LT", "Visit Comments" },
{ 0x0039, 0x0080, "IS", "Private Entity Number" },
{ 0x0039, 0x0085, "DA", "Private Entity Date" },
{ 0x0039, 0x0090, "TM", "Private Entity Time" },
{ 0x0039, 0x0095, "LO", "Private Entity Launch Command" },
{ 0x0039, 0x00aa, "CS", "Private Entity Type" },
{ 0x003a, 0x0002, "SQ", "Waveform Sequence" },
{ 0x003a, 0x0005, "US", "Waveform Number of Channels" },
{ 0x003a, 0x0010, "UL", "Waveform Number of Samples" },
{ 0x003a, 0x001a, "DS", "Sampling Frequency" },
{ 0x003a, 0x0020, "SH", "Group Label" },
{ 0x003a, 0x0103, "CS", "Waveform Sample Value Representation" },
{ 0x003a, 0x0122, "OB", "Waveform Padding Value" },
{ 0x003a, 0x0200, "SQ", "Channel Definition" },
{ 0x003a, 0x0202, "IS", "Waveform Channel Number" },
{ 0x003a, 0x0203, "SH", "Channel Label" },
{ 0x003a, 0x0205, "CS", "Channel Status" },
{ 0x003a, 0x0208, "SQ", "Channel Source" },
{ 0x003a, 0x0209, "SQ", "Channel Source Modifiers" },
{ 0x003a, 0x020a, "SQ", "Differential Channel Source" },
{ 0x003a, 0x020b, "SQ", "Differential Channel Source Modifiers" },
{ 0x003a, 0x0210, "DS", "Channel Sensitivity" },
{ 0x003a, 0x0211, "SQ", "Channel Sensitivity Units" },
{ 0x003a, 0x0212, "DS", "Channel Sensitivity Correction Factor" },
{ 0x003a, 0x0213, "DS", "Channel Baseline" },
{ 0x003a, 0x0214, "DS", "Channel Time Skew" },
{ 0x003a, 0x0215, "DS", "Channel Sample Skew" },
{ 0x003a, 0x0216, "OB", "Channel Minimum Value" },
{ 0x003a, 0x0217, "OB", "Channel Maximum Value" },
{ 0x003a, 0x0218, "DS", "Channel Offset" },
{ 0x003a, 0x021a, "US", "Bits Per Sample" },
{ 0x003a, 0x0220, "DS", "Filter Low Frequency" },
{ 0x003a, 0x0221, "DS", "Filter High Frequency" },
{ 0x003a, 0x0222, "DS", "Notch Filter Frequency" },
{ 0x003a, 0x0223, "DS", "Notch Filter Bandwidth" },
{ 0x003a, 0x1000, "OB", "Waveform Data" },
{ 0x0040, 0x0001, "AE", "Scheduled Station AE Title" },
{ 0x0040, 0x0002, "DA", "Scheduled Procedure Step Start Date" },
{ 0x0040, 0x0003, "TM", "Scheduled Procedure Step Start Time" },
{ 0x0040, 0x0004, "DA", "Scheduled Procedure Step End Date" },
{ 0x0040, 0x0005, "TM", "Scheduled Procedure Step End Time" },
{ 0x0040, 0x0006, "PN", "Scheduled Performing Physician Name" },
{ 0x0040, 0x0007, "LO", "Scheduled Procedure Step Description" },
{ 0x0040, 0x0008, "SQ", "Scheduled Action Item Code Sequence" },
{ 0x0040, 0x0009, "SH", "Scheduled Procedure Step ID" },
{ 0x0040, 0x0010, "SH", "Scheduled Station Name" },
{ 0x0040, 0x0011, "SH", "Scheduled Procedure Step Location" },
{ 0x0040, 0x0012, "LO", "Pre-Medication" },
{ 0x0040, 0x0020, "CS", "Scheduled Procedure Step Status" },
{ 0x0040, 0x0100, "SQ", "Scheduled Procedure Step Sequence" },
{ 0x0040, 0x0302, "US", "Entrance Dose" },
{ 0x0040, 0x0303, "US", "Exposed Area" },
{ 0x0040, 0x0306, "DS", "Distance Source to Entrance" },
{ 0x0040, 0x0307, "DS", "Distance Source to Support" },
{ 0x0040, 0x0310, "ST", "Comments On Radiation Dose" },
{ 0x0040, 0x0312, "DS", "X-Ray Output" },
{ 0x0040, 0x0314, "DS", "Half Value Layer" },
{ 0x0040, 0x0316, "DS", "Organ Dose" },
{ 0x0040, 0x0318, "CS", "Organ Exposed" },
{ 0x0040, 0x0400, "LT", "Comments On Scheduled Procedure Step" },
{ 0x0040, 0x050a, "LO", "Specimen Accession Number" },
{ 0x0040, 0x0550, "SQ", "Specimen Sequence" },
{ 0x0040, 0x0551, "LO", "Specimen Identifier" },
{ 0x0040, 0x0552, "SQ", "Specimen Description Sequence" },
{ 0x0040, 0x0553, "ST", "Specimen Description" },
{ 0x0040, 0x0555, "SQ", "Acquisition Context Sequence" },
{ 0x0040, 0x0556, "ST", "Acquisition Context Description" },
{ 0x0040, 0x059a, "SQ", "Specimen Type Code Sequence" },
{ 0x0040, 0x06fa, "LO", "Slide Identifier" },
{ 0x0040, 0x071a, "SQ", "Image Center Point Coordinates Sequence" },
{ 0x0040, 0x072a, "DS", "X Offset In Slide Coordinate System" },
{ 0x0040, 0x073a, "DS", "Y Offset In Slide Coordinate System" },
{ 0x0040, 0x074a, "DS", "Z Offset In Slide Coordinate System" },
{ 0x0040, 0x08d8, "SQ", "Pixel Spacing Sequence" },
{ 0x0040, 0x08da, "SQ", "Coordinate System Axis Code Sequence" },
{ 0x0040, 0x08ea, "SQ", "Measurement Units Code Sequence" },
{ 0x0040, 0x09f8, "SQ", "Vital Stain Code Sequence" },
{ 0x0040, 0x1001, "SH", "Requested Procedure ID" },
{ 0x0040, 0x1002, "LO", "Reason For Requested Procedure" },
{ 0x0040, 0x1003, "SH", "Requested Procedure Priority" },
{ 0x0040, 0x1004, "LO", "Patient Transport Arrangements" },
{ 0x0040, 0x1005, "LO", "Requested Procedure Location" },
{ 0x0040, 0x1006, "SH", "Placer Order Number of Procedure" },
{ 0x0040, 0x1007, "SH", "Filler Order Number of Procedure" },
{ 0x0040, 0x1008, "LO", "Confidentiality Code" },
{ 0x0040, 0x1009, "SH", "Reporting Priority" },
{ 0x0040, 0x1010, "PN", "Names of Intended Recipients of Results" },
{ 0x0040, 0x1400, "LT", "Requested Procedure Comments" },
{ 0x0040, 0x2001, "LO", "Reason For Imaging Service Request" },
{ 0x0040, 0x2004, "DA", "Issue Date of Imaging Service Request" },
{ 0x0040, 0x2005, "TM", "Issue Time of Imaging Service Request" },
{ 0x0040, 0x2006, "SH", "Placer Order Number of Imaging Service Request" },
{ 0x0040, 0x2007, "SH", "Filler Order Number of Imaging Service Request" },
{ 0x0040, 0x2008, "PN", "Order Entered By" },
{ 0x0040, 0x2009, "SH", "Order Enterer Location" },
{ 0x0040, 0x2010, "SH", "Order Callback Phone Number" },
{ 0x0040, 0x2400, "LT", "Imaging Service Request Comments" },
{ 0x0040, 0x3001, "LO", "Confidentiality Constraint On Patient Data" },
{ 0x0040, 0xa007, "CS", "Findings Flag" },
{ 0x0040, 0xa020, "SQ", "Findings Sequence" },
{ 0x0040, 0xa021, "UI", "Findings Group UID" },
{ 0x0040, 0xa022, "UI", "Referenced Findings Group UID" },
{ 0x0040, 0xa023, "DA", "Findings Group Recording Date" },
{ 0x0040, 0xa024, "TM", "Findings Group Recording Time" },
{ 0x0040, 0xa026, "SQ", "Findings Source Category Code Sequence" },
{ 0x0040, 0xa027, "LO", "Documenting Organization" },
{ 0x0040, 0xa028, "SQ", "Documenting Organization Identifier Code Sequence" },
{ 0x0040, 0xa032, "LO", "History Reliability Qualifier Description" },
{ 0x0040, 0xa043, "SQ", "Concept Name Code Sequence" },
{ 0x0040, 0xa047, "LO", "Measurement Precision Description" },
{ 0x0040, 0xa057, "CS", "Urgency or Priority Alerts" },
{ 0x0040, 0xa060, "LO", "Sequencing Indicator" },
{ 0x0040, 0xa066, "SQ", "Document Identifier Code Sequence" },
{ 0x0040, 0xa067, "PN", "Document Author" },
{ 0x0040, 0xa068, "SQ", "Document Author Identifier Code Sequence" },
{ 0x0040, 0xa070, "SQ", "Identifier Code Sequence" },
{ 0x0040, 0xa073, "LO", "Object String Identifier" },
{ 0x0040, 0xa074, "OB", "Object Binary Identifier" },
{ 0x0040, 0xa075, "PN", "Documenting Observer" },
{ 0x0040, 0xa076, "SQ", "Documenting Observer Identifier Code Sequence" },
{ 0x0040, 0xa078, "SQ", "Observation Subject Identifier Code Sequence" },
{ 0x0040, 0xa080, "SQ", "Person Identifier Code Sequence" },
{ 0x0040, 0xa085, "SQ", "Procedure Identifier Code Sequence" },
{ 0x0040, 0xa088, "LO", "Object Directory String Identifier" },
{ 0x0040, 0xa089, "OB", "Object Directory Binary Identifier" },
{ 0x0040, 0xa090, "CS", "History Reliability Qualifier" },
{ 0x0040, 0xa0a0, "CS", "Referenced Type of Data" },
{ 0x0040, 0xa0b0, "US", "Referenced Waveform Channels" },
{ 0x0040, 0xa110, "DA", "Date of Document or Verbal Transaction" },
{ 0x0040, 0xa112, "TM", "Time of Document Creation or Verbal Transaction" },
{ 0x0040, 0xa121, "DA", "Date" },
{ 0x0040, 0xa122, "TM", "Time" },
{ 0x0040, 0xa123, "PN", "Person Name" },
{ 0x0040, 0xa124, "SQ", "Referenced Person Sequence" },
{ 0x0040, 0xa125, "CS", "Report Status ID" },
{ 0x0040, 0xa130, "CS", "Temporal Range Type" },
{ 0x0040, 0xa132, "UL", "Referenced Sample Offsets" },
{ 0x0040, 0xa136, "US", "Referenced Frame Numbers" },
{ 0x0040, 0xa138, "DS", "Referenced Time Offsets" },
{ 0x0040, 0xa13a, "DT", "Referenced Datetime" },
{ 0x0040, 0xa160, "UT", "Text Value" },
{ 0x0040, 0xa167, "SQ", "Observation Category Code Sequence" },
{ 0x0040, 0xa168, "SQ", "Concept Code Sequence" },
{ 0x0040, 0xa16a, "ST", "Bibliographic Citation" },
{ 0x0040, 0xa170, "CS", "Observation Class" },
{ 0x0040, 0xa171, "UI", "Observation UID" },
{ 0x0040, 0xa172, "UI", "Referenced Observation UID" },
{ 0x0040, 0xa173, "CS", "Referenced Observation Class" },
{ 0x0040, 0xa174, "CS", "Referenced Object Observation Class" },
{ 0x0040, 0xa180, "US", "Annotation Group Number" },
{ 0x0040, 0xa192, "DA", "Observation Date" },
{ 0x0040, 0xa193, "TM", "Observation Time" },
{ 0x0040, 0xa194, "CS", "Measurement Automation" },
{ 0x0040, 0xa195, "SQ", "Concept Name Code Sequence Modifier" },
{ 0x0040, 0xa224, "ST", "Identification Description" },
{ 0x0040, 0xa290, "CS", "Coordinates Set Geometric Type" },
{ 0x0040, 0xa296, "SQ", "Algorithm Code Sequence" },
{ 0x0040, 0xa297, "ST", "Algorithm Description" },
{ 0x0040, 0xa29a, "SL", "Pixel Coordinates Set" },
{ 0x0040, 0xa300, "SQ", "Measured Value Sequence" },
{ 0x0040, 0xa307, "PN", "Current Observer" },
{ 0x0040, 0xa30a, "DS", "Numeric Value" },
{ 0x0040, 0xa313, "SQ", "Referenced Accession Sequence" },
{ 0x0040, 0xa33a, "ST", "Report Status Comment" },
{ 0x0040, 0xa340, "SQ", "Procedure Context Sequence" },
{ 0x0040, 0xa352, "PN", "Verbal Source" },
{ 0x0040, 0xa353, "ST", "Address" },
{ 0x0040, 0xa354, "LO", "Telephone Number" },
{ 0x0040, 0xa358, "SQ", "Verbal Source Identifier Code Sequence" },
{ 0x0040, 0xa380, "SQ", "Report Detail Sequence" },
{ 0x0040, 0xa402, "UI", "Observation Subject UID" },
{ 0x0040, 0xa403, "CS", "Observation Subject Class" },
{ 0x0040, 0xa404, "SQ", "Observation Subject Type Code Sequence" },
{ 0x0040, 0xa600, "CS", "Observation Subject Context Flag" },
{ 0x0040, 0xa601, "CS", "Observer Context Flag" },
{ 0x0040, 0xa603, "CS", "Procedure Context Flag" },
{ 0x0040, 0xa730, "SQ", "Observations Sequence" },
{ 0x0040, 0xa731, "SQ", "Relationship Sequence" },
{ 0x0040, 0xa732, "SQ", "Relationship Type Code Sequence" },
{ 0x0040, 0xa744, "SQ", "Language Code Sequence" },
{ 0x0040, 0xa992, "ST", "Uniform Resource Locator" },
{ 0x0040, 0xb020, "SQ", "Annotation Sequence" },
{ 0x0040, 0xdb73, "SQ", "Relationship Type Code Sequence Modifier" },
{ 0x0041, 0x0000, "LT", "Papyrus Comments" },
{ 0x0041, 0x0010, "xs", "?" },
{ 0x0041, 0x0011, "xs", "?" },
{ 0x0041, 0x0012, "UL", "Pixel Offset" },
{ 0x0041, 0x0013, "SQ", "Image Identifier Sequence" },
{ 0x0041, 0x0014, "SQ", "External File Reference Sequence" },
{ 0x0041, 0x0015, "US", "Number of Images" },
{ 0x0041, 0x0020, "xs", "?" },
{ 0x0041, 0x0021, "UI", "Referenced SOP Class UID" },
{ 0x0041, 0x0022, "UI", "Referenced SOP Instance UID" },
{ 0x0041, 0x0030, "xs", "?" },
{ 0x0041, 0x0031, "xs", "?" },
{ 0x0041, 0x0032, "xs", "?" },
{ 0x0041, 0x0034, "DA", "Modified Date" },
{ 0x0041, 0x0036, "TM", "Modified Time" },
{ 0x0041, 0x0040, "LT", "Owner Name" },
{ 0x0041, 0x0041, "UI", "Referenced Image SOP Class UID" },
{ 0x0041, 0x0042, "UI", "Referenced Image SOP Instance UID" },
{ 0x0041, 0x0050, "xs", "?" },
{ 0x0041, 0x0060, "UL", "Number of Images" },
{ 0x0041, 0x0062, "UL", "Number of Other" },
{ 0x0041, 0x00a0, "LT", "External Folder Element DSID" },
{ 0x0041, 0x00a1, "US", "External Folder Element Data Set Type" },
{ 0x0041, 0x00a2, "LT", "External Folder Element File Location" },
{ 0x0041, 0x00a3, "UL", "External Folder Element Length" },
{ 0x0041, 0x00b0, "LT", "Internal Folder Element DSID" },
{ 0x0041, 0x00b1, "US", "Internal Folder Element Data Set Type" },
{ 0x0041, 0x00b2, "UL", "Internal Offset To Data Set" },
{ 0x0041, 0x00b3, "UL", "Internal Offset To Image" },
{ 0x0043, 0x0001, "SS", "Bitmap Of Prescan Options" },
{ 0x0043, 0x0002, "SS", "Gradient Offset In X" },
{ 0x0043, 0x0003, "SS", "Gradient Offset In Y" },
{ 0x0043, 0x0004, "SS", "Gradient Offset In Z" },
{ 0x0043, 0x0005, "SS", "Image Is Original Or Unoriginal" },
{ 0x0043, 0x0006, "SS", "Number Of EPI Shots" },
{ 0x0043, 0x0007, "SS", "Views Per Segment" },
{ 0x0043, 0x0008, "SS", "Respiratory Rate In BPM" },
{ 0x0043, 0x0009, "SS", "Respiratory Trigger Point" },
{ 0x0043, 0x000a, "SS", "Type Of Receiver Used" },
{ 0x0043, 0x000b, "DS", "Peak Rate Of Change Of Gradient Field" },
{ 0x0043, 0x000c, "DS", "Limits In Units Of Percent" },
{ 0x0043, 0x000d, "DS", "PSD Estimated Limit" },
{ 0x0043, 0x000e, "DS", "PSD Estimated Limit In Tesla Per Second" },
{ 0x0043, 0x000f, "DS", "SAR Avg Head" },
{ 0x0043, 0x0010, "US", "Window Value" },
{ 0x0043, 0x0011, "US", "Total Input Views" },
{ 0x0043, 0x0012, "SS", "Xray Chain" },
{ 0x0043, 0x0013, "SS", "Recon Kernel Parameters" },
{ 0x0043, 0x0014, "SS", "Calibration Parameters" },
{ 0x0043, 0x0015, "SS", "Total Output Views" },
{ 0x0043, 0x0016, "SS", "Number Of Overranges" },
{ 0x0043, 0x0017, "DS", "IBH Image Scale Factors" },
{ 0x0043, 0x0018, "DS", "BBH Coefficients" },
{ 0x0043, 0x0019, "SS", "Number Of BBH Chains To Blend" },
{ 0x0043, 0x001a, "SL", "Starting Channel Number" },
{ 0x0043, 0x001b, "SS", "PPScan Parameters" },
{ 0x0043, 0x001c, "SS", "GE Image Integrity" },
{ 0x0043, 0x001d, "SS", "Level Value" },
{ 0x0043, 0x001e, "xs", "?" },
{ 0x0043, 0x001f, "SL", "Max Overranges In A View" },
{ 0x0043, 0x0020, "DS", "Avg Overranges All Views" },
{ 0x0043, 0x0021, "SS", "Corrected Afterglow Terms" },
{ 0x0043, 0x0025, "SS", "Reference Channels" },
{ 0x0043, 0x0026, "US", "No Views Ref Channels Blocked" },
{ 0x0043, 0x0027, "xs", "?" },
{ 0x0043, 0x0028, "OB", "Unique Image Identifier" },
{ 0x0043, 0x0029, "OB", "Histogram Tables" },
{ 0x0043, 0x002a, "OB", "User Defined Data" },
{ 0x0043, 0x002b, "SS", "Private Scan Options" },
{ 0x0043, 0x002c, "SS", "Effective Echo Spacing" },
{ 0x0043, 0x002d, "SH", "String Slop Field 1" },
{ 0x0043, 0x002e, "SH", "String Slop Field 2" },
{ 0x0043, 0x002f, "SS", "Raw Data Type" },
{ 0x0043, 0x0030, "SS", "Raw Data Type" },
{ 0x0043, 0x0031, "DS", "RA Coord Of Target Recon Centre" },
{ 0x0043, 0x0032, "SS", "Raw Data Type" },
{ 0x0043, 0x0033, "FL", "Neg Scan Spacing" },
{ 0x0043, 0x0034, "IS", "Offset Frequency" },
{ 0x0043, 0x0035, "UL", "User Usage Tag" },
{ 0x0043, 0x0036, "UL", "User Fill Map MSW" },
{ 0x0043, 0x0037, "UL", "User Fill Map LSW" },
{ 0x0043, 0x0038, "FL", "User 25 To User 48" },
{ 0x0043, 0x0039, "IS", "Slop Integer 6 To Slop Integer 9" },
{ 0x0043, 0x0040, "FL", "Trigger On Position" },
{ 0x0043, 0x0041, "FL", "Degree Of Rotation" },
{ 0x0043, 0x0042, "SL", "DAS Trigger Source" },
{ 0x0043, 0x0043, "SL", "DAS Fpa Gain" },
{ 0x0043, 0x0044, "SL", "DAS Output Source" },
{ 0x0043, 0x0045, "SL", "DAS Ad Input" },
{ 0x0043, 0x0046, "SL", "DAS Cal Mode" },
{ 0x0043, 0x0047, "SL", "DAS Cal Frequency" },
{ 0x0043, 0x0048, "SL", "DAS Reg Xm" },
{ 0x0043, 0x0049, "SL", "DAS Auto Zero" },
{ 0x0043, 0x004a, "SS", "Starting Channel Of View" },
{ 0x0043, 0x004b, "SL", "DAS Xm Pattern" },
{ 0x0043, 0x004c, "SS", "TGGC Trigger Mode" },
{ 0x0043, 0x004d, "FL", "Start Scan To Xray On Delay" },
{ 0x0043, 0x004e, "FL", "Duration Of Xray On" },
{ 0x0044, 0x0000, "UI", "?" },
{ 0x0045, 0x0004, "CS", "AES" },
{ 0x0045, 0x0006, "DS", "Angulation" },
{ 0x0045, 0x0009, "DS", "Real Magnification Factor" },
{ 0x0045, 0x000b, "CS", "Senograph Type" },
{ 0x0045, 0x000c, "DS", "Integration Time" },
{ 0x0045, 0x000d, "DS", "ROI Origin X and Y" },
{ 0x0045, 0x0011, "DS", "Receptor Size cm X and Y" },
{ 0x0045, 0x0012, "IS", "Receptor Size Pixels X and Y" },
{ 0x0045, 0x0013, "ST", "Screen" },
{ 0x0045, 0x0014, "DS", "Pixel Pitch Microns" },
{ 0x0045, 0x0015, "IS", "Pixel Depth Bits" },
{ 0x0045, 0x0016, "IS", "Binning Factor X and Y" },
{ 0x0045, 0x001b, "CS", "Clinical View" },
{ 0x0045, 0x001d, "DS", "Mean Of Raw Gray Levels" },
{ 0x0045, 0x001e, "DS", "Mean Of Offset Gray Levels" },
{ 0x0045, 0x001f, "DS", "Mean Of Corrected Gray Levels" },
{ 0x0045, 0x0020, "DS", "Mean Of Region Gray Levels" },
{ 0x0045, 0x0021, "DS", "Mean Of Log Region Gray Levels" },
{ 0x0045, 0x0022, "DS", "Standard Deviation Of Raw Gray Levels" },
{ 0x0045, 0x0023, "DS", "Standard Deviation Of Corrected Gray Levels" },
{ 0x0045, 0x0024, "DS", "Standard Deviation Of Region Gray Levels" },
{ 0x0045, 0x0025, "DS", "Standard Deviation Of Log Region Gray Levels" },
{ 0x0045, 0x0026, "OB", "MAO Buffer" },
{ 0x0045, 0x0027, "IS", "Set Number" },
{ 0x0045, 0x0028, "CS", "WindowingType (LINEAR or GAMMA)" },
{ 0x0045, 0x0029, "DS", "WindowingParameters" },
{ 0x0045, 0x002a, "IS", "Crosshair Cursor X Coordinates" },
{ 0x0045, 0x002b, "IS", "Crosshair Cursor Y Coordinates" },
{ 0x0045, 0x0039, "US", "Vignette Rows" },
{ 0x0045, 0x003a, "US", "Vignette Columns" },
{ 0x0045, 0x003b, "US", "Vignette Bits Allocated" },
{ 0x0045, 0x003c, "US", "Vignette Bits Stored" },
{ 0x0045, 0x003d, "US", "Vignette High Bit" },
{ 0x0045, 0x003e, "US", "Vignette Pixel Representation" },
{ 0x0045, 0x003f, "OB", "Vignette Pixel Data" },
{ 0x0047, 0x0001, "SQ", "Reconstruction Parameters Sequence" },
{ 0x0047, 0x0050, "UL", "Volume Voxel Count" },
{ 0x0047, 0x0051, "UL", "Volume Segment Count" },
{ 0x0047, 0x0053, "US", "Volume Slice Size" },
{ 0x0047, 0x0054, "US", "Volume Slice Count" },
{ 0x0047, 0x0055, "SL", "Volume Threshold Value" },
{ 0x0047, 0x0057, "DS", "Volume Voxel Ratio" },
{ 0x0047, 0x0058, "DS", "Volume Voxel Size" },
{ 0x0047, 0x0059, "US", "Volume Z Position Size" },
{ 0x0047, 0x0060, "DS", "Volume Base Line" },
{ 0x0047, 0x0061, "DS", "Volume Center Point" },
{ 0x0047, 0x0063, "SL", "Volume Skew Base" },
{ 0x0047, 0x0064, "DS", "Volume Registration Transform Rotation Matrix" },
{ 0x0047, 0x0065, "DS", "Volume Registration Transform Translation Vector" },
{ 0x0047, 0x0070, "DS", "KVP List" },
{ 0x0047, 0x0071, "IS", "XRay Tube Current List" },
{ 0x0047, 0x0072, "IS", "Exposure List" },
{ 0x0047, 0x0080, "LO", "Acquisition DLX Identifier" },
{ 0x0047, 0x0085, "SQ", "Acquisition DLX 2D Series Sequence" },
{ 0x0047, 0x0089, "DS", "Contrast Agent Volume List" },
{ 0x0047, 0x008a, "US", "Number Of Injections" },
{ 0x0047, 0x008b, "US", "Frame Count" },
{ 0x0047, 0x0096, "IS", "Used Frames" },
{ 0x0047, 0x0091, "LO", "XA 3D Reconstruction Algorithm Name" },
{ 0x0047, 0x0092, "CS", "XA 3D Reconstruction Algorithm Version" },
{ 0x0047, 0x0093, "DA", "DLX Calibration Date" },
{ 0x0047, 0x0094, "TM", "DLX Calibration Time" },
{ 0x0047, 0x0095, "CS", "DLX Calibration Status" },
{ 0x0047, 0x0098, "US", "Transform Count" },
{ 0x0047, 0x0099, "SQ", "Transform Sequence" },
{ 0x0047, 0x009a, "DS", "Transform Rotation Matrix" },
{ 0x0047, 0x009b, "DS", "Transform Translation Vector" },
{ 0x0047, 0x009c, "LO", "Transform Label" },
{ 0x0047, 0x00b1, "US", "Wireframe Count" },
{ 0x0047, 0x00b2, "US", "Location System" },
{ 0x0047, 0x00b0, "SQ", "Wireframe List" },
{ 0x0047, 0x00b5, "LO", "Wireframe Name" },
{ 0x0047, 0x00b6, "LO", "Wireframe Group Name" },
{ 0x0047, 0x00b7, "LO", "Wireframe Color" },
{ 0x0047, 0x00b8, "SL", "Wireframe Attributes" },
{ 0x0047, 0x00b9, "SL", "Wireframe Point Count" },
{ 0x0047, 0x00ba, "SL", "Wireframe Timestamp" },
{ 0x0047, 0x00bb, "SQ", "Wireframe Point List" },
{ 0x0047, 0x00bc, "DS", "Wireframe Points Coordinates" },
{ 0x0047, 0x00c0, "DS", "Volume Upper Left High Corner RAS" },
{ 0x0047, 0x00c1, "DS", "Volume Slice To RAS Rotation Matrix" },
{ 0x0047, 0x00c2, "DS", "Volume Upper Left High Corner TLOC" },
{ 0x0047, 0x00d1, "OB", "Volume Segment List" },
{ 0x0047, 0x00d2, "OB", "Volume Gradient List" },
{ 0x0047, 0x00d3, "OB", "Volume Density List" },
{ 0x0047, 0x00d4, "OB", "Volume Z Position List" },
{ 0x0047, 0x00d5, "OB", "Volume Original Index List" },
{ 0x0050, 0x0000, "UL", "Calibration Group Length" },
{ 0x0050, 0x0004, "CS", "Calibration Object" },
{ 0x0050, 0x0010, "SQ", "DeviceSequence" },
{ 0x0050, 0x0014, "DS", "DeviceLength" },
{ 0x0050, 0x0016, "DS", "DeviceDiameter" },
{ 0x0050, 0x0017, "CS", "DeviceDiameterUnits" },
{ 0x0050, 0x0018, "DS", "DeviceVolume" },
{ 0x0050, 0x0019, "DS", "InterMarkerDistance" },
{ 0x0050, 0x0020, "LO", "DeviceDescription" },
{ 0x0050, 0x0030, "SQ", "CodedInterventionDeviceSequence" },
{ 0x0051, 0x0010, "xs", "Image Text" },
{ 0x0054, 0x0000, "UL", "Nuclear Acquisition Group Length" },
{ 0x0054, 0x0010, "US", "Energy Window Vector" },
{ 0x0054, 0x0011, "US", "Number of Energy Windows" },
{ 0x0054, 0x0012, "SQ", "Energy Window Information Sequence" },
{ 0x0054, 0x0013, "SQ", "Energy Window Range Sequence" },
{ 0x0054, 0x0014, "DS", "Energy Window Lower Limit" },
{ 0x0054, 0x0015, "DS", "Energy Window Upper Limit" },
{ 0x0054, 0x0016, "SQ", "Radiopharmaceutical Information Sequence" },
{ 0x0054, 0x0017, "IS", "Residual Syringe Counts" },
{ 0x0054, 0x0018, "SH", "Energy Window Name" },
{ 0x0054, 0x0020, "US", "Detector Vector" },
{ 0x0054, 0x0021, "US", "Number of Detectors" },
{ 0x0054, 0x0022, "SQ", "Detector Information Sequence" },
{ 0x0054, 0x0030, "US", "Phase Vector" },
{ 0x0054, 0x0031, "US", "Number of Phases" },
{ 0x0054, 0x0032, "SQ", "Phase Information Sequence" },
{ 0x0054, 0x0033, "US", "Number of Frames In Phase" },
{ 0x0054, 0x0036, "IS", "Phase Delay" },
{ 0x0054, 0x0038, "IS", "Pause Between Frames" },
{ 0x0054, 0x0050, "US", "Rotation Vector" },
{ 0x0054, 0x0051, "US", "Number of Rotations" },
{ 0x0054, 0x0052, "SQ", "Rotation Information Sequence" },
{ 0x0054, 0x0053, "US", "Number of Frames In Rotation" },
{ 0x0054, 0x0060, "US", "R-R Interval Vector" },
{ 0x0054, 0x0061, "US", "Number of R-R Intervals" },
{ 0x0054, 0x0062, "SQ", "Gated Information Sequence" },
{ 0x0054, 0x0063, "SQ", "Data Information Sequence" },
{ 0x0054, 0x0070, "US", "Time Slot Vector" },
{ 0x0054, 0x0071, "US", "Number of Time Slots" },
{ 0x0054, 0x0072, "SQ", "Time Slot Information Sequence" },
{ 0x0054, 0x0073, "DS", "Time Slot Time" },
{ 0x0054, 0x0080, "US", "Slice Vector" },
{ 0x0054, 0x0081, "US", "Number of Slices" },
{ 0x0054, 0x0090, "US", "Angular View Vector" },
{ 0x0054, 0x0100, "US", "Time Slice Vector" },
{ 0x0054, 0x0101, "US", "Number Of Time Slices" },
{ 0x0054, 0x0200, "DS", "Start Angle" },
{ 0x0054, 0x0202, "CS", "Type of Detector Motion" },
{ 0x0054, 0x0210, "IS", "Trigger Vector" },
{ 0x0054, 0x0211, "US", "Number of Triggers in Phase" },
{ 0x0054, 0x0220, "SQ", "View Code Sequence" },
{ 0x0054, 0x0222, "SQ", "View Modifier Code Sequence" },
{ 0x0054, 0x0300, "SQ", "Radionuclide Code Sequence" },
{ 0x0054, 0x0302, "SQ", "Radiopharmaceutical Route Code Sequence" },
{ 0x0054, 0x0304, "SQ", "Radiopharmaceutical Code Sequence" },
{ 0x0054, 0x0306, "SQ", "Calibration Data Sequence" },
{ 0x0054, 0x0308, "US", "Energy Window Number" },
{ 0x0054, 0x0400, "SH", "Image ID" },
{ 0x0054, 0x0410, "SQ", "Patient Orientation Code Sequence" },
{ 0x0054, 0x0412, "SQ", "Patient Orientation Modifier Code Sequence" },
{ 0x0054, 0x0414, "SQ", "Patient Gantry Relationship Code Sequence" },
{ 0x0054, 0x1000, "CS", "Positron Emission Tomography Series Type" },
{ 0x0054, 0x1001, "CS", "Positron Emission Tomography Units" },
{ 0x0054, 0x1002, "CS", "Counts Source" },
{ 0x0054, 0x1004, "CS", "Reprojection Method" },
{ 0x0054, 0x1100, "CS", "Randoms Correction Method" },
{ 0x0054, 0x1101, "LO", "Attenuation Correction Method" },
{ 0x0054, 0x1102, "CS", "Decay Correction" },
{ 0x0054, 0x1103, "LO", "Reconstruction Method" },
{ 0x0054, 0x1104, "LO", "Detector Lines of Response Used" },
{ 0x0054, 0x1105, "LO", "Scatter Correction Method" },
{ 0x0054, 0x1200, "DS", "Axial Acceptance" },
{ 0x0054, 0x1201, "IS", "Axial Mash" },
{ 0x0054, 0x1202, "IS", "Transverse Mash" },
{ 0x0054, 0x1203, "DS", "Detector Element Size" },
{ 0x0054, 0x1210, "DS", "Coincidence Window Width" },
{ 0x0054, 0x1220, "CS", "Secondary Counts Type" },
{ 0x0054, 0x1300, "DS", "Frame Reference Time" },
{ 0x0054, 0x1310, "IS", "Primary Prompts Counts Accumulated" },
{ 0x0054, 0x1311, "IS", "Secondary Counts Accumulated" },
{ 0x0054, 0x1320, "DS", "Slice Sensitivity Factor" },
{ 0x0054, 0x1321, "DS", "Decay Factor" },
{ 0x0054, 0x1322, "DS", "Dose Calibration Factor" },
{ 0x0054, 0x1323, "DS", "Scatter Fraction Factor" },
{ 0x0054, 0x1324, "DS", "Dead Time Factor" },
{ 0x0054, 0x1330, "US", "Image Index" },
{ 0x0054, 0x1400, "CS", "Counts Included" },
{ 0x0054, 0x1401, "CS", "Dead Time Correction Flag" },
{ 0x0055, 0x0046, "LT", "Current Ward" },
{ 0x0058, 0x0000, "SQ", "?" },
{ 0x0060, 0x3000, "SQ", "Histogram Sequence" },
{ 0x0060, 0x3002, "US", "Histogram Number of Bins" },
{ 0x0060, 0x3004, "xs", "Histogram First Bin Value" },
{ 0x0060, 0x3006, "xs", "Histogram Last Bin Value" },
{ 0x0060, 0x3008, "US", "Histogram Bin Width" },
{ 0x0060, 0x3010, "LO", "Histogram Explanation" },
{ 0x0060, 0x3020, "UL", "Histogram Data" },
{ 0x0070, 0x0001, "SQ", "Graphic Annotation Sequence" },
{ 0x0070, 0x0002, "CS", "Graphic Layer" },
{ 0x0070, 0x0003, "CS", "Bounding Box Annotation Units" },
{ 0x0070, 0x0004, "CS", "Anchor Point Annotation Units" },
{ 0x0070, 0x0005, "CS", "Graphic Annotation Units" },
{ 0x0070, 0x0006, "ST", "Unformatted Text Value" },
{ 0x0070, 0x0008, "SQ", "Text Object Sequence" },
{ 0x0070, 0x0009, "SQ", "Graphic Object Sequence" },
{ 0x0070, 0x0010, "FL", "Bounding Box TLHC" },
{ 0x0070, 0x0011, "FL", "Bounding Box BRHC" },
{ 0x0070, 0x0014, "FL", "Anchor Point" },
{ 0x0070, 0x0015, "CS", "Anchor Point Visibility" },
{ 0x0070, 0x0020, "US", "Graphic Dimensions" },
{ 0x0070, 0x0021, "US", "Number Of Graphic Points" },
{ 0x0070, 0x0022, "FL", "Graphic Data" },
{ 0x0070, 0x0023, "CS", "Graphic Type" },
{ 0x0070, 0x0024, "CS", "Graphic Filled" },
{ 0x0070, 0x0040, "IS", "Image Rotation" },
{ 0x0070, 0x0041, "CS", "Image Horizontal Flip" },
{ 0x0070, 0x0050, "US", "Displayed Area TLHC" },
{ 0x0070, 0x0051, "US", "Displayed Area BRHC" },
{ 0x0070, 0x0060, "SQ", "Graphic Layer Sequence" },
{ 0x0070, 0x0062, "IS", "Graphic Layer Order" },
{ 0x0070, 0x0066, "US", "Graphic Layer Recommended Display Value" },
{ 0x0070, 0x0068, "LO", "Graphic Layer Description" },
{ 0x0070, 0x0080, "CS", "Presentation Label" },
{ 0x0070, 0x0081, "LO", "Presentation Description" },
{ 0x0070, 0x0082, "DA", "Presentation Creation Date" },
{ 0x0070, 0x0083, "TM", "Presentation Creation Time" },
{ 0x0070, 0x0084, "PN", "Presentation Creator's Name" },
{ 0x0087, 0x0010, "CS", "Media Type" },
{ 0x0087, 0x0020, "CS", "Media Location" },
{ 0x0087, 0x0050, "IS", "Estimated Retrieve Time" },
{ 0x0088, 0x0000, "UL", "Storage Group Length" },
{ 0x0088, 0x0130, "SH", "Storage Media FileSet ID" },
{ 0x0088, 0x0140, "UI", "Storage Media FileSet UID" },
{ 0x0088, 0x0200, "SQ", "Icon Image Sequence" },
{ 0x0088, 0x0904, "LO", "Topic Title" },
{ 0x0088, 0x0906, "ST", "Topic Subject" },
{ 0x0088, 0x0910, "LO", "Topic Author" },
{ 0x0088, 0x0912, "LO", "Topic Key Words" },
{ 0x0095, 0x0001, "LT", "Examination Folder ID" },
{ 0x0095, 0x0004, "UL", "Folder Reported Status" },
{ 0x0095, 0x0005, "LT", "Folder Reporting Radiologist" },
{ 0x0095, 0x0007, "LT", "SIENET ISA PLA" },
{ 0x0099, 0x0002, "UL", "Data Object Attributes" },
{ 0x00e1, 0x0001, "US", "Data Dictionary Version" },
{ 0x00e1, 0x0014, "LT", "?" },
{ 0x00e1, 0x0022, "DS", "?" },
{ 0x00e1, 0x0023, "DS", "?" },
{ 0x00e1, 0x0024, "LT", "?" },
{ 0x00e1, 0x0025, "LT", "?" },
{ 0x00e1, 0x0040, "SH", "Offset From CT MR Images" },
{ 0x0193, 0x0002, "DS", "RIS Key" },
{ 0x0307, 0x0001, "UN", "RIS Worklist IMGEF" },
{ 0x0309, 0x0001, "UN", "RIS Report IMGEF" },
{ 0x0601, 0x0000, "SH", "Implementation Version" },
{ 0x0601, 0x0020, "DS", "Relative Table Position" },
{ 0x0601, 0x0021, "DS", "Relative Table Height" },
{ 0x0601, 0x0030, "SH", "Surview Direction" },
{ 0x0601, 0x0031, "DS", "Surview Length" },
{ 0x0601, 0x0050, "SH", "Image View Type" },
{ 0x0601, 0x0070, "DS", "Batch Number" },
{ 0x0601, 0x0071, "DS", "Batch Size" },
{ 0x0601, 0x0072, "DS", "Batch Slice Number" },
{ 0x1000, 0x0000, "xs", "?" },
{ 0x1000, 0x0001, "US", "Run Length Triplet" },
{ 0x1000, 0x0002, "US", "Huffman Table Size" },
{ 0x1000, 0x0003, "US", "Huffman Table Triplet" },
{ 0x1000, 0x0004, "US", "Shift Table Size" },
{ 0x1000, 0x0005, "US", "Shift Table Triplet" },
{ 0x1010, 0x0000, "xs", "?" },
{ 0x1369, 0x0000, "US", "?" },
{ 0x2000, 0x0000, "UL", "Film Session Group Length" },
{ 0x2000, 0x0010, "IS", "Number of Copies" },
{ 0x2000, 0x0020, "CS", "Print Priority" },
{ 0x2000, 0x0030, "CS", "Medium Type" },
{ 0x2000, 0x0040, "CS", "Film Destination" },
{ 0x2000, 0x0050, "LO", "Film Session Label" },
{ 0x2000, 0x0060, "IS", "Memory Allocation" },
{ 0x2000, 0x0500, "SQ", "Referenced Film Box Sequence" },
{ 0x2010, 0x0000, "UL", "Film Box Group Length" },
{ 0x2010, 0x0010, "ST", "Image Display Format" },
{ 0x2010, 0x0030, "CS", "Annotation Display Format ID" },
{ 0x2010, 0x0040, "CS", "Film Orientation" },
{ 0x2010, 0x0050, "CS", "Film Size ID" },
{ 0x2010, 0x0060, "CS", "Magnification Type" },
{ 0x2010, 0x0080, "CS", "Smoothing Type" },
{ 0x2010, 0x0100, "CS", "Border Density" },
{ 0x2010, 0x0110, "CS", "Empty Image Density" },
{ 0x2010, 0x0120, "US", "Min Density" },
{ 0x2010, 0x0130, "US", "Max Density" },
{ 0x2010, 0x0140, "CS", "Trim" },
{ 0x2010, 0x0150, "ST", "Configuration Information" },
{ 0x2010, 0x0500, "SQ", "Referenced Film Session Sequence" },
{ 0x2010, 0x0510, "SQ", "Referenced Image Box Sequence" },
{ 0x2010, 0x0520, "SQ", "Referenced Basic Annotation Box Sequence" },
{ 0x2020, 0x0000, "UL", "Image Box Group Length" },
{ 0x2020, 0x0010, "US", "Image Box Position" },
{ 0x2020, 0x0020, "CS", "Polarity" },
{ 0x2020, 0x0030, "DS", "Requested Image Size" },
{ 0x2020, 0x0110, "SQ", "Preformatted Grayscale Image Sequence" },
{ 0x2020, 0x0111, "SQ", "Preformatted Color Image Sequence" },
{ 0x2020, 0x0130, "SQ", "Referenced Image Overlay Box Sequence" },
{ 0x2020, 0x0140, "SQ", "Referenced VOI LUT Box Sequence" },
{ 0x2030, 0x0000, "UL", "Annotation Group Length" },
{ 0x2030, 0x0010, "US", "Annotation Position" },
{ 0x2030, 0x0020, "LO", "Text String" },
{ 0x2040, 0x0000, "UL", "Overlay Box Group Length" },
{ 0x2040, 0x0010, "SQ", "Referenced Overlay Plane Sequence" },
{ 0x2040, 0x0011, "US", "Referenced Overlay Plane Groups" },
{ 0x2040, 0x0060, "CS", "Overlay Magnification Type" },
{ 0x2040, 0x0070, "CS", "Overlay Smoothing Type" },
{ 0x2040, 0x0080, "CS", "Overlay Foreground Density" },
{ 0x2040, 0x0090, "CS", "Overlay Mode" },
{ 0x2040, 0x0100, "CS", "Threshold Density" },
{ 0x2040, 0x0500, "SQ", "Referenced Overlay Image Box Sequence" },
{ 0x2050, 0x0010, "SQ", "Presentation LUT Sequence" },
{ 0x2050, 0x0020, "CS", "Presentation LUT Shape" },
{ 0x2100, 0x0000, "UL", "Print Job Group Length" },
{ 0x2100, 0x0020, "CS", "Execution Status" },
{ 0x2100, 0x0030, "CS", "Execution Status Info" },
{ 0x2100, 0x0040, "DA", "Creation Date" },
{ 0x2100, 0x0050, "TM", "Creation Time" },
{ 0x2100, 0x0070, "AE", "Originator" },
{ 0x2100, 0x0500, "SQ", "Referenced Print Job Sequence" },
{ 0x2110, 0x0000, "UL", "Printer Group Length" },
{ 0x2110, 0x0010, "CS", "Printer Status" },
{ 0x2110, 0x0020, "CS", "Printer Status Info" },
{ 0x2110, 0x0030, "LO", "Printer Name" },
{ 0x2110, 0x0099, "SH", "Print Queue ID" },
{ 0x3002, 0x0002, "SH", "RT Image Label" },
{ 0x3002, 0x0003, "LO", "RT Image Name" },
{ 0x3002, 0x0004, "ST", "RT Image Description" },
{ 0x3002, 0x000a, "CS", "Reported Values Origin" },
{ 0x3002, 0x000c, "CS", "RT Image Plane" },
{ 0x3002, 0x000e, "DS", "X-Ray Image Receptor Angle" },
{ 0x3002, 0x0010, "DS", "RTImageOrientation" },
{ 0x3002, 0x0011, "DS", "Image Plane Pixel Spacing" },
{ 0x3002, 0x0012, "DS", "RT Image Position" },
{ 0x3002, 0x0020, "SH", "Radiation Machine Name" },
{ 0x3002, 0x0022, "DS", "Radiation Machine SAD" },
{ 0x3002, 0x0024, "DS", "Radiation Machine SSD" },
{ 0x3002, 0x0026, "DS", "RT Image SID" },
{ 0x3002, 0x0028, "DS", "Source to Reference Object Distance" },
{ 0x3002, 0x0029, "IS", "Fraction Number" },
{ 0x3002, 0x0030, "SQ", "Exposure Sequence" },
{ 0x3002, 0x0032, "DS", "Meterset Exposure" },
{ 0x3004, 0x0001, "CS", "DVH Type" },
{ 0x3004, 0x0002, "CS", "Dose Units" },
{ 0x3004, 0x0004, "CS", "Dose Type" },
{ 0x3004, 0x0006, "LO", "Dose Comment" },
{ 0x3004, 0x0008, "DS", "Normalization Point" },
{ 0x3004, 0x000a, "CS", "Dose Summation Type" },
{ 0x3004, 0x000c, "DS", "GridFrame Offset Vector" },
{ 0x3004, 0x000e, "DS", "Dose Grid Scaling" },
{ 0x3004, 0x0010, "SQ", "RT Dose ROI Sequence" },
{ 0x3004, 0x0012, "DS", "Dose Value" },
{ 0x3004, 0x0040, "DS", "DVH Normalization Point" },
{ 0x3004, 0x0042, "DS", "DVH Normalization Dose Value" },
{ 0x3004, 0x0050, "SQ", "DVH Sequence" },
{ 0x3004, 0x0052, "DS", "DVH Dose Scaling" },
{ 0x3004, 0x0054, "CS", "DVH Volume Units" },
{ 0x3004, 0x0056, "IS", "DVH Number of Bins" },
{ 0x3004, 0x0058, "DS", "DVH Data" },
{ 0x3004, 0x0060, "SQ", "DVH Referenced ROI Sequence" },
{ 0x3004, 0x0062, "CS", "DVH ROI Contribution Type" },
{ 0x3004, 0x0070, "DS", "DVH Minimum Dose" },
{ 0x3004, 0x0072, "DS", "DVH Maximum Dose" },
{ 0x3004, 0x0074, "DS", "DVH Mean Dose" },
{ 0x3006, 0x0002, "SH", "Structure Set Label" },
{ 0x3006, 0x0004, "LO", "Structure Set Name" },
{ 0x3006, 0x0006, "ST", "Structure Set Description" },
{ 0x3006, 0x0008, "DA", "Structure Set Date" },
{ 0x3006, 0x0009, "TM", "Structure Set Time" },
{ 0x3006, 0x0010, "SQ", "Referenced Frame of Reference Sequence" },
{ 0x3006, 0x0012, "SQ", "RT Referenced Study Sequence" },
{ 0x3006, 0x0014, "SQ", "RT Referenced Series Sequence" },
{ 0x3006, 0x0016, "SQ", "Contour Image Sequence" },
{ 0x3006, 0x0020, "SQ", "Structure Set ROI Sequence" },
{ 0x3006, 0x0022, "IS", "ROI Number" },
{ 0x3006, 0x0024, "UI", "Referenced Frame of Reference UID" },
{ 0x3006, 0x0026, "LO", "ROI Name" },
{ 0x3006, 0x0028, "ST", "ROI Description" },
{ 0x3006, 0x002a, "IS", "ROI Display Color" },
{ 0x3006, 0x002c, "DS", "ROI Volume" },
{ 0x3006, 0x0030, "SQ", "RT Related ROI Sequence" },
{ 0x3006, 0x0033, "CS", "RT ROI Relationship" },
{ 0x3006, 0x0036, "CS", "ROI Generation Algorithm" },
{ 0x3006, 0x0038, "LO", "ROI Generation Description" },
{ 0x3006, 0x0039, "SQ", "ROI Contour Sequence" },
{ 0x3006, 0x0040, "SQ", "Contour Sequence" },
{ 0x3006, 0x0042, "CS", "Contour Geometric Type" },
{ 0x3006, 0x0044, "DS", "Contour SlabT hickness" },
{ 0x3006, 0x0045, "DS", "Contour Offset Vector" },
{ 0x3006, 0x0046, "IS", "Number of Contour Points" },
{ 0x3006, 0x0050, "DS", "Contour Data" },
{ 0x3006, 0x0080, "SQ", "RT ROI Observations Sequence" },
{ 0x3006, 0x0082, "IS", "Observation Number" },
{ 0x3006, 0x0084, "IS", "Referenced ROI Number" },
{ 0x3006, 0x0085, "SH", "ROI Observation Label" },
{ 0x3006, 0x0086, "SQ", "RT ROI Identification Code Sequence" },
{ 0x3006, 0x0088, "ST", "ROI Observation Description" },
{ 0x3006, 0x00a0, "SQ", "Related RT ROI Observations Sequence" },
{ 0x3006, 0x00a4, "CS", "RT ROI Interpreted Type" },
{ 0x3006, 0x00a6, "PN", "ROI Interpreter" },
{ 0x3006, 0x00b0, "SQ", "ROI Physical Properties Sequence" },
{ 0x3006, 0x00b2, "CS", "ROI Physical Property" },
{ 0x3006, 0x00b4, "DS", "ROI Physical Property Value" },
{ 0x3006, 0x00c0, "SQ", "Frame of Reference Relationship Sequence" },
{ 0x3006, 0x00c2, "UI", "Related Frame of Reference UID" },
{ 0x3006, 0x00c4, "CS", "Frame of Reference Transformation Type" },
{ 0x3006, 0x00c6, "DS", "Frame of Reference Transformation Matrix" },
{ 0x3006, 0x00c8, "LO", "Frame of Reference Transformation Comment" },
{ 0x300a, 0x0002, "SH", "RT Plan Label" },
{ 0x300a, 0x0003, "LO", "RT Plan Name" },
{ 0x300a, 0x0004, "ST", "RT Plan Description" },
{ 0x300a, 0x0006, "DA", "RT Plan Date" },
{ 0x300a, 0x0007, "TM", "RT Plan Time" },
{ 0x300a, 0x0009, "LO", "Treatment Protocols" },
{ 0x300a, 0x000a, "CS", "Treatment Intent" },
{ 0x300a, 0x000b, "LO", "Treatment Sites" },
{ 0x300a, 0x000c, "CS", "RT Plan Geometry" },
{ 0x300a, 0x000e, "ST", "Prescription Description" },
{ 0x300a, 0x0010, "SQ", "Dose ReferenceSequence" },
{ 0x300a, 0x0012, "IS", "Dose ReferenceNumber" },
{ 0x300a, 0x0014, "CS", "Dose Reference Structure Type" },
{ 0x300a, 0x0016, "LO", "Dose ReferenceDescription" },
{ 0x300a, 0x0018, "DS", "Dose Reference Point Coordinates" },
{ 0x300a, 0x001a, "DS", "Nominal Prior Dose" },
{ 0x300a, 0x0020, "CS", "Dose Reference Type" },
{ 0x300a, 0x0021, "DS", "Constraint Weight" },
{ 0x300a, 0x0022, "DS", "Delivery Warning Dose" },
{ 0x300a, 0x0023, "DS", "Delivery Maximum Dose" },
{ 0x300a, 0x0025, "DS", "Target Minimum Dose" },
{ 0x300a, 0x0026, "DS", "Target Prescription Dose" },
{ 0x300a, 0x0027, "DS", "Target Maximum Dose" },
{ 0x300a, 0x0028, "DS", "Target Underdose Volume Fraction" },
{ 0x300a, 0x002a, "DS", "Organ at Risk Full-volume Dose" },
{ 0x300a, 0x002b, "DS", "Organ at Risk Limit Dose" },
{ 0x300a, 0x002c, "DS", "Organ at Risk Maximum Dose" },
{ 0x300a, 0x002d, "DS", "Organ at Risk Overdose Volume Fraction" },
{ 0x300a, 0x0040, "SQ", "Tolerance Table Sequence" },
{ 0x300a, 0x0042, "IS", "Tolerance Table Number" },
{ 0x300a, 0x0043, "SH", "Tolerance Table Label" },
{ 0x300a, 0x0044, "DS", "Gantry Angle Tolerance" },
{ 0x300a, 0x0046, "DS", "Beam Limiting Device Angle Tolerance" },
{ 0x300a, 0x0048, "SQ", "Beam Limiting Device Tolerance Sequence" },
{ 0x300a, 0x004a, "DS", "Beam Limiting Device Position Tolerance" },
{ 0x300a, 0x004c, "DS", "Patient Support Angle Tolerance" },
{ 0x300a, 0x004e, "DS", "Table Top Eccentric Angle Tolerance" },
{ 0x300a, 0x0051, "DS", "Table Top Vertical Position Tolerance" },
{ 0x300a, 0x0052, "DS", "Table Top Longitudinal Position Tolerance" },
{ 0x300a, 0x0053, "DS", "Table Top Lateral Position Tolerance" },
{ 0x300a, 0x0055, "CS", "RT Plan Relationship" },
{ 0x300a, 0x0070, "SQ", "Fraction Group Sequence" },
{ 0x300a, 0x0071, "IS", "Fraction Group Number" },
{ 0x300a, 0x0078, "IS", "Number of Fractions Planned" },
{ 0x300a, 0x0079, "IS", "Number of Fractions Per Day" },
{ 0x300a, 0x007a, "IS", "Repeat Fraction Cycle Length" },
{ 0x300a, 0x007b, "LT", "Fraction Pattern" },
{ 0x300a, 0x0080, "IS", "Number of Beams" },
{ 0x300a, 0x0082, "DS", "Beam Dose Specification Point" },
{ 0x300a, 0x0084, "DS", "Beam Dose" },
{ 0x300a, 0x0086, "DS", "Beam Meterset" },
{ 0x300a, 0x00a0, "IS", "Number of Brachy Application Setups" },
{ 0x300a, 0x00a2, "DS", "Brachy Application Setup Dose Specification Point" },
{ 0x300a, 0x00a4, "DS", "Brachy Application Setup Dose" },
{ 0x300a, 0x00b0, "SQ", "Beam Sequence" },
{ 0x300a, 0x00b2, "SH", "Treatment Machine Name " },
{ 0x300a, 0x00b3, "CS", "Primary Dosimeter Unit" },
{ 0x300a, 0x00b4, "DS", "Source-Axis Distance" },
{ 0x300a, 0x00b6, "SQ", "Beam Limiting Device Sequence" },
{ 0x300a, 0x00b8, "CS", "RT Beam Limiting Device Type" },
{ 0x300a, 0x00ba, "DS", "Source to Beam Limiting Device Distance" },
{ 0x300a, 0x00bc, "IS", "Number of Leaf/Jaw Pairs" },
{ 0x300a, 0x00be, "DS", "Leaf Position Boundaries" },
{ 0x300a, 0x00c0, "IS", "Beam Number" },
{ 0x300a, 0x00c2, "LO", "Beam Name" },
{ 0x300a, 0x00c3, "ST", "Beam Description" },
{ 0x300a, 0x00c4, "CS", "Beam Type" },
{ 0x300a, 0x00c6, "CS", "Radiation Type" },
{ 0x300a, 0x00c8, "IS", "Reference Image Number" },
{ 0x300a, 0x00ca, "SQ", "Planned Verification Image Sequence" },
{ 0x300a, 0x00cc, "LO", "Imaging Device Specific Acquisition Parameters" },
{ 0x300a, 0x00ce, "CS", "Treatment Delivery Type" },
{ 0x300a, 0x00d0, "IS", "Number of Wedges" },
{ 0x300a, 0x00d1, "SQ", "Wedge Sequence" },
{ 0x300a, 0x00d2, "IS", "Wedge Number" },
{ 0x300a, 0x00d3, "CS", "Wedge Type" },
{ 0x300a, 0x00d4, "SH", "Wedge ID" },
{ 0x300a, 0x00d5, "IS", "Wedge Angle" },
{ 0x300a, 0x00d6, "DS", "Wedge Factor" },
{ 0x300a, 0x00d8, "DS", "Wedge Orientation" },
{ 0x300a, 0x00da, "DS", "Source to Wedge Tray Distance" },
{ 0x300a, 0x00e0, "IS", "Number of Compensators" },
{ 0x300a, 0x00e1, "SH", "Material ID" },
{ 0x300a, 0x00e2, "DS", "Total Compensator Tray Factor" },
{ 0x300a, 0x00e3, "SQ", "Compensator Sequence" },
{ 0x300a, 0x00e4, "IS", "Compensator Number" },
{ 0x300a, 0x00e5, "SH", "Compensator ID" },
{ 0x300a, 0x00e6, "DS", "Source to Compensator Tray Distance" },
{ 0x300a, 0x00e7, "IS", "Compensator Rows" },
{ 0x300a, 0x00e8, "IS", "Compensator Columns" },
{ 0x300a, 0x00e9, "DS", "Compensator Pixel Spacing" },
{ 0x300a, 0x00ea, "DS", "Compensator Position" },
{ 0x300a, 0x00eb, "DS", "Compensator Transmission Data" },
{ 0x300a, 0x00ec, "DS", "Compensator Thickness Data" },
{ 0x300a, 0x00ed, "IS", "Number of Boli" },
{ 0x300a, 0x00f0, "IS", "Number of Blocks" },
{ 0x300a, 0x00f2, "DS", "Total Block Tray Factor" },
{ 0x300a, 0x00f4, "SQ", "Block Sequence" },
{ 0x300a, 0x00f5, "SH", "Block Tray ID" },
{ 0x300a, 0x00f6, "DS", "Source to Block Tray Distance" },
{ 0x300a, 0x00f8, "CS", "Block Type" },
{ 0x300a, 0x00fa, "CS", "Block Divergence" },
{ 0x300a, 0x00fc, "IS", "Block Number" },
{ 0x300a, 0x00fe, "LO", "Block Name" },
{ 0x300a, 0x0100, "DS", "Block Thickness" },
{ 0x300a, 0x0102, "DS", "Block Transmission" },
{ 0x300a, 0x0104, "IS", "Block Number of Points" },
{ 0x300a, 0x0106, "DS", "Block Data" },
{ 0x300a, 0x0107, "SQ", "Applicator Sequence" },
{ 0x300a, 0x0108, "SH", "Applicator ID" },
{ 0x300a, 0x0109, "CS", "Applicator Type" },
{ 0x300a, 0x010a, "LO", "Applicator Description" },
{ 0x300a, 0x010c, "DS", "Cumulative Dose Reference Coefficient" },
{ 0x300a, 0x010e, "DS", "Final Cumulative Meterset Weight" },
{ 0x300a, 0x0110, "IS", "Number of Control Points" },
{ 0x300a, 0x0111, "SQ", "Control Point Sequence" },
{ 0x300a, 0x0112, "IS", "Control Point Index" },
{ 0x300a, 0x0114, "DS", "Nominal Beam Energy" },
{ 0x300a, 0x0115, "DS", "Dose Rate Set" },
{ 0x300a, 0x0116, "SQ", "Wedge Position Sequence" },
{ 0x300a, 0x0118, "CS", "Wedge Position" },
{ 0x300a, 0x011a, "SQ", "Beam Limiting Device Position Sequence" },
{ 0x300a, 0x011c, "DS", "Leaf Jaw Positions" },
{ 0x300a, 0x011e, "DS", "Gantry Angle" },
{ 0x300a, 0x011f, "CS", "Gantry Rotation Direction" },
{ 0x300a, 0x0120, "DS", "Beam Limiting Device Angle" },
{ 0x300a, 0x0121, "CS", "Beam Limiting Device Rotation Direction" },
{ 0x300a, 0x0122, "DS", "Patient Support Angle" },
{ 0x300a, 0x0123, "CS", "Patient Support Rotation Direction" },
{ 0x300a, 0x0124, "DS", "Table Top Eccentric Axis Distance" },
{ 0x300a, 0x0125, "DS", "Table Top Eccentric Angle" },
{ 0x300a, 0x0126, "CS", "Table Top Eccentric Rotation Direction" },
{ 0x300a, 0x0128, "DS", "Table Top Vertical Position" },
{ 0x300a, 0x0129, "DS", "Table Top Longitudinal Position" },
{ 0x300a, 0x012a, "DS", "Table Top Lateral Position" },
{ 0x300a, 0x012c, "DS", "Isocenter Position" },
{ 0x300a, 0x012e, "DS", "Surface Entry Point" },
{ 0x300a, 0x0130, "DS", "Source to Surface Distance" },
{ 0x300a, 0x0134, "DS", "Cumulative Meterset Weight" },
{ 0x300a, 0x0180, "SQ", "Patient Setup Sequence" },
{ 0x300a, 0x0182, "IS", "Patient Setup Number" },
{ 0x300a, 0x0184, "LO", "Patient Additional Position" },
{ 0x300a, 0x0190, "SQ", "Fixation Device Sequence" },
{ 0x300a, 0x0192, "CS", "Fixation Device Type" },
{ 0x300a, 0x0194, "SH", "Fixation Device Label" },
{ 0x300a, 0x0196, "ST", "Fixation Device Description" },
{ 0x300a, 0x0198, "SH", "Fixation Device Position" },
{ 0x300a, 0x01a0, "SQ", "Shielding Device Sequence" },
{ 0x300a, 0x01a2, "CS", "Shielding Device Type" },
{ 0x300a, 0x01a4, "SH", "Shielding Device Label" },
{ 0x300a, 0x01a6, "ST", "Shielding Device Description" },
{ 0x300a, 0x01a8, "SH", "Shielding Device Position" },
{ 0x300a, 0x01b0, "CS", "Setup Technique" },
{ 0x300a, 0x01b2, "ST", "Setup TechniqueDescription" },
{ 0x300a, 0x01b4, "SQ", "Setup Device Sequence" },
{ 0x300a, 0x01b6, "CS", "Setup Device Type" },
{ 0x300a, 0x01b8, "SH", "Setup Device Label" },
{ 0x300a, 0x01ba, "ST", "Setup Device Description" },
{ 0x300a, 0x01bc, "DS", "Setup Device Parameter" },
{ 0x300a, 0x01d0, "ST", "Setup ReferenceDescription" },
{ 0x300a, 0x01d2, "DS", "Table Top Vertical Setup Displacement" },
{ 0x300a, 0x01d4, "DS", "Table Top Longitudinal Setup Displacement" },
{ 0x300a, 0x01d6, "DS", "Table Top Lateral Setup Displacement" },
{ 0x300a, 0x0200, "CS", "Brachy Treatment Technique" },
{ 0x300a, 0x0202, "CS", "Brachy Treatment Type" },
{ 0x300a, 0x0206, "SQ", "Treatment Machine Sequence" },
{ 0x300a, 0x0210, "SQ", "Source Sequence" },
{ 0x300a, 0x0212, "IS", "Source Number" },
{ 0x300a, 0x0214, "CS", "Source Type" },
{ 0x300a, 0x0216, "LO", "Source Manufacturer" },
{ 0x300a, 0x0218, "DS", "Active Source Diameter" },
{ 0x300a, 0x021a, "DS", "Active Source Length" },
{ 0x300a, 0x0222, "DS", "Source Encapsulation Nominal Thickness" },
{ 0x300a, 0x0224, "DS", "Source Encapsulation Nominal Transmission" },
{ 0x300a, 0x0226, "LO", "Source IsotopeName" },
{ 0x300a, 0x0228, "DS", "Source Isotope Half Life" },
{ 0x300a, 0x022a, "DS", "Reference Air Kerma Rate" },
{ 0x300a, 0x022c, "DA", "Air Kerma Rate Reference Date" },
{ 0x300a, 0x022e, "TM", "Air Kerma Rate Reference Time" },
{ 0x300a, 0x0230, "SQ", "Application Setup Sequence" },
{ 0x300a, 0x0232, "CS", "Application Setup Type" },
{ 0x300a, 0x0234, "IS", "Application Setup Number" },
{ 0x300a, 0x0236, "LO", "Application Setup Name" },
{ 0x300a, 0x0238, "LO", "Application Setup Manufacturer" },
{ 0x300a, 0x0240, "IS", "Template Number" },
{ 0x300a, 0x0242, "SH", "Template Type" },
{ 0x300a, 0x0244, "LO", "Template Name" },
{ 0x300a, 0x0250, "DS", "Total Reference Air Kerma" },
{ 0x300a, 0x0260, "SQ", "Brachy Accessory Device Sequence" },
{ 0x300a, 0x0262, "IS", "Brachy Accessory Device Number" },
{ 0x300a, 0x0263, "SH", "Brachy Accessory Device ID" },
{ 0x300a, 0x0264, "CS", "Brachy Accessory Device Type" },
{ 0x300a, 0x0266, "LO", "Brachy Accessory Device Name" },
{ 0x300a, 0x026a, "DS", "Brachy Accessory Device Nominal Thickness" },
{ 0x300a, 0x026c, "DS", "Brachy Accessory Device Nominal Transmission" },
{ 0x300a, 0x0280, "SQ", "Channel Sequence" },
{ 0x300a, 0x0282, "IS", "Channel Number" },
{ 0x300a, 0x0284, "DS", "Channel Length" },
{ 0x300a, 0x0286, "DS", "Channel Total Time" },
{ 0x300a, 0x0288, "CS", "Source Movement Type" },
{ 0x300a, 0x028a, "IS", "Number of Pulses" },
{ 0x300a, 0x028c, "DS", "Pulse Repetition Interval" },
{ 0x300a, 0x0290, "IS", "Source Applicator Number" },
{ 0x300a, 0x0291, "SH", "Source Applicator ID" },
{ 0x300a, 0x0292, "CS", "Source Applicator Type" },
{ 0x300a, 0x0294, "LO", "Source Applicator Name" },
{ 0x300a, 0x0296, "DS", "Source Applicator Length" },
{ 0x300a, 0x0298, "LO", "Source Applicator Manufacturer" },
{ 0x300a, 0x029c, "DS", "Source Applicator Wall Nominal Thickness" },
{ 0x300a, 0x029e, "DS", "Source Applicator Wall Nominal Transmission" },
{ 0x300a, 0x02a0, "DS", "Source Applicator Step Size" },
{ 0x300a, 0x02a2, "IS", "Transfer Tube Number" },
{ 0x300a, 0x02a4, "DS", "Transfer Tube Length" },
{ 0x300a, 0x02b0, "SQ", "Channel Shield Sequence" },
{ 0x300a, 0x02b2, "IS", "Channel Shield Number" },
{ 0x300a, 0x02b3, "SH", "Channel Shield ID" },
{ 0x300a, 0x02b4, "LO", "Channel Shield Name" },
{ 0x300a, 0x02b8, "DS", "Channel Shield Nominal Thickness" },
{ 0x300a, 0x02ba, "DS", "Channel Shield Nominal Transmission" },
{ 0x300a, 0x02c8, "DS", "Final Cumulative Time Weight" },
{ 0x300a, 0x02d0, "SQ", "Brachy Control Point Sequence" },
{ 0x300a, 0x02d2, "DS", "Control Point Relative Position" },
{ 0x300a, 0x02d4, "DS", "Control Point 3D Position" },
{ 0x300a, 0x02d6, "DS", "Cumulative Time Weight" },
{ 0x300c, 0x0002, "SQ", "Referenced RT Plan Sequence" },
{ 0x300c, 0x0004, "SQ", "Referenced Beam Sequence" },
{ 0x300c, 0x0006, "IS", "Referenced Beam Number" },
{ 0x300c, 0x0007, "IS", "Referenced Reference Image Number" },
{ 0x300c, 0x0008, "DS", "Start Cumulative Meterset Weight" },
{ 0x300c, 0x0009, "DS", "End Cumulative Meterset Weight" },
{ 0x300c, 0x000a, "SQ", "Referenced Brachy Application Setup Sequence" },
{ 0x300c, 0x000c, "IS", "Referenced Brachy Application Setup Number" },
{ 0x300c, 0x000e, "IS", "Referenced Source Number" },
{ 0x300c, 0x0020, "SQ", "Referenced Fraction Group Sequence" },
{ 0x300c, 0x0022, "IS", "Referenced Fraction Group Number" },
{ 0x300c, 0x0040, "SQ", "Referenced Verification Image Sequence" },
{ 0x300c, 0x0042, "SQ", "Referenced Reference Image Sequence" },
{ 0x300c, 0x0050, "SQ", "Referenced Dose Reference Sequence" },
{ 0x300c, 0x0051, "IS", "Referenced Dose Reference Number" },
{ 0x300c, 0x0055, "SQ", "Brachy Referenced Dose Reference Sequence" },
{ 0x300c, 0x0060, "SQ", "Referenced Structure Set Sequence" },
{ 0x300c, 0x006a, "IS", "Referenced Patient Setup Number" },
{ 0x300c, 0x0080, "SQ", "Referenced Dose Sequence" },
{ 0x300c, 0x00a0, "IS", "Referenced Tolerance Table Number" },
{ 0x300c, 0x00b0, "SQ", "Referenced Bolus Sequence" },
{ 0x300c, 0x00c0, "IS", "Referenced Wedge Number" },
{ 0x300c, 0x00d0, "IS", "Referenced Compensato rNumber" },
{ 0x300c, 0x00e0, "IS", "Referenced Block Number" },
{ 0x300c, 0x00f0, "IS", "Referenced Control Point" },
{ 0x300e, 0x0002, "CS", "Approval Status" },
{ 0x300e, 0x0004, "DA", "Review Date" },
{ 0x300e, 0x0005, "TM", "Review Time" },
{ 0x300e, 0x0008, "PN", "Reviewer Name" },
{ 0x4000, 0x0000, "UL", "Text Group Length" },
{ 0x4000, 0x0010, "LT", "Text Arbitrary" },
{ 0x4000, 0x4000, "LT", "Text Comments" },
{ 0x4008, 0x0000, "UL", "Results Group Length" },
{ 0x4008, 0x0040, "SH", "Results ID" },
{ 0x4008, 0x0042, "LO", "Results ID Issuer" },
{ 0x4008, 0x0050, "SQ", "Referenced Interpretation Sequence" },
{ 0x4008, 0x00ff, "CS", "Report Production Status" },
{ 0x4008, 0x0100, "DA", "Interpretation Recorded Date" },
{ 0x4008, 0x0101, "TM", "Interpretation Recorded Time" },
{ 0x4008, 0x0102, "PN", "Interpretation Recorder" },
{ 0x4008, 0x0103, "LO", "Reference to Recorded Sound" },
{ 0x4008, 0x0108, "DA", "Interpretation Transcription Date" },
{ 0x4008, 0x0109, "TM", "Interpretation Transcription Time" },
{ 0x4008, 0x010a, "PN", "Interpretation Transcriber" },
{ 0x4008, 0x010b, "ST", "Interpretation Text" },
{ 0x4008, 0x010c, "PN", "Interpretation Author" },
{ 0x4008, 0x0111, "SQ", "Interpretation Approver Sequence" },
{ 0x4008, 0x0112, "DA", "Interpretation Approval Date" },
{ 0x4008, 0x0113, "TM", "Interpretation Approval Time" },
{ 0x4008, 0x0114, "PN", "Physician Approving Interpretation" },
{ 0x4008, 0x0115, "LT", "Interpretation Diagnosis Description" },
{ 0x4008, 0x0117, "SQ", "InterpretationDiagnosis Code Sequence" },
{ 0x4008, 0x0118, "SQ", "Results Distribution List Sequence" },
{ 0x4008, 0x0119, "PN", "Distribution Name" },
{ 0x4008, 0x011a, "LO", "Distribution Address" },
{ 0x4008, 0x0200, "SH", "Interpretation ID" },
{ 0x4008, 0x0202, "LO", "Interpretation ID Issuer" },
{ 0x4008, 0x0210, "CS", "Interpretation Type ID" },
{ 0x4008, 0x0212, "CS", "Interpretation Status ID" },
{ 0x4008, 0x0300, "ST", "Impressions" },
{ 0x4008, 0x4000, "ST", "Results Comments" },
{ 0x4009, 0x0001, "LT", "Report ID" },
{ 0x4009, 0x0020, "LT", "Report Status" },
{ 0x4009, 0x0030, "DA", "Report Creation Date" },
{ 0x4009, 0x0070, "LT", "Report Approving Physician" },
{ 0x4009, 0x00e0, "LT", "Report Text" },
{ 0x4009, 0x00e1, "LT", "Report Author" },
{ 0x4009, 0x00e3, "LT", "Reporting Radiologist" },
{ 0x5000, 0x0000, "UL", "Curve Group Length" },
{ 0x5000, 0x0005, "US", "Curve Dimensions" },
{ 0x5000, 0x0010, "US", "Number of Points" },
{ 0x5000, 0x0020, "CS", "Type of Data" },
{ 0x5000, 0x0022, "LO", "Curve Description" },
{ 0x5000, 0x0030, "SH", "Axis Units" },
{ 0x5000, 0x0040, "SH", "Axis Labels" },
{ 0x5000, 0x0103, "US", "Data Value Representation" },
{ 0x5000, 0x0104, "US", "Minimum Coordinate Value" },
{ 0x5000, 0x0105, "US", "Maximum Coordinate Value" },
{ 0x5000, 0x0106, "SH", "Curve Range" },
{ 0x5000, 0x0110, "US", "Curve Data Descriptor" },
{ 0x5000, 0x0112, "US", "Coordinate Start Value" },
{ 0x5000, 0x0114, "US", "Coordinate Step Value" },
{ 0x5000, 0x1001, "CS", "Curve Activation Layer" },
{ 0x5000, 0x2000, "US", "Audio Type" },
{ 0x5000, 0x2002, "US", "Audio Sample Format" },
{ 0x5000, 0x2004, "US", "Number of Channels" },
{ 0x5000, 0x2006, "UL", "Number of Samples" },
{ 0x5000, 0x2008, "UL", "Sample Rate" },
{ 0x5000, 0x200a, "UL", "Total Time" },
{ 0x5000, 0x200c, "xs", "Audio Sample Data" },
{ 0x5000, 0x200e, "LT", "Audio Comments" },
{ 0x5000, 0x2500, "LO", "Curve Label" },
{ 0x5000, 0x2600, "SQ", "CurveReferenced Overlay Sequence" },
{ 0x5000, 0x2610, "US", "CurveReferenced Overlay Group" },
{ 0x5000, 0x3000, "OW", "Curve Data" },
{ 0x6000, 0x0000, "UL", "Overlay Group Length" },
{ 0x6000, 0x0001, "US", "Gray Palette Color Lookup Table Descriptor" },
{ 0x6000, 0x0002, "US", "Gray Palette Color Lookup Table Data" },
{ 0x6000, 0x0010, "US", "Overlay Rows" },
{ 0x6000, 0x0011, "US", "Overlay Columns" },
{ 0x6000, 0x0012, "US", "Overlay Planes" },
{ 0x6000, 0x0015, "IS", "Number of Frames in Overlay" },
{ 0x6000, 0x0022, "LO", "Overlay Description" },
{ 0x6000, 0x0040, "CS", "Overlay Type" },
{ 0x6000, 0x0045, "CS", "Overlay Subtype" },
{ 0x6000, 0x0050, "SS", "Overlay Origin" },
{ 0x6000, 0x0051, "US", "Image Frame Origin" },
{ 0x6000, 0x0052, "US", "Plane Origin" },
{ 0x6000, 0x0060, "LO", "Overlay Compression Code" },
{ 0x6000, 0x0061, "SH", "Overlay Compression Originator" },
{ 0x6000, 0x0062, "SH", "Overlay Compression Label" },
{ 0x6000, 0x0063, "SH", "Overlay Compression Description" },
{ 0x6000, 0x0066, "AT", "Overlay Compression Step Pointers" },
{ 0x6000, 0x0068, "US", "Overlay Repeat Interval" },
{ 0x6000, 0x0069, "US", "Overlay Bits Grouped" },
{ 0x6000, 0x0100, "US", "Overlay Bits Allocated" },
{ 0x6000, 0x0102, "US", "Overlay Bit Position" },
{ 0x6000, 0x0110, "LO", "Overlay Format" },
{ 0x6000, 0x0200, "xs", "Overlay Location" },
{ 0x6000, 0x0800, "LO", "Overlay Code Label" },
{ 0x6000, 0x0802, "US", "Overlay Number of Tables" },
{ 0x6000, 0x0803, "AT", "Overlay Code Table Location" },
{ 0x6000, 0x0804, "US", "Overlay Bits For Code Word" },
{ 0x6000, 0x1001, "CS", "Overlay Activation Layer" },
{ 0x6000, 0x1100, "US", "Overlay Descriptor - Gray" },
{ 0x6000, 0x1101, "US", "Overlay Descriptor - Red" },
{ 0x6000, 0x1102, "US", "Overlay Descriptor - Green" },
{ 0x6000, 0x1103, "US", "Overlay Descriptor - Blue" },
{ 0x6000, 0x1200, "US", "Overlays - Gray" },
{ 0x6000, 0x1201, "US", "Overlays - Red" },
{ 0x6000, 0x1202, "US", "Overlays - Green" },
{ 0x6000, 0x1203, "US", "Overlays - Blue" },
{ 0x6000, 0x1301, "IS", "ROI Area" },
{ 0x6000, 0x1302, "DS", "ROI Mean" },
{ 0x6000, 0x1303, "DS", "ROI Standard Deviation" },
{ 0x6000, 0x1500, "LO", "Overlay Label" },
{ 0x6000, 0x3000, "OW", "Overlay Data" },
{ 0x6000, 0x4000, "LT", "Overlay Comments" },
{ 0x6001, 0x0000, "UN", "?" },
{ 0x6001, 0x0010, "LO", "?" },
{ 0x6001, 0x1010, "xs", "?" },
{ 0x6001, 0x1030, "xs", "?" },
{ 0x6021, 0x0000, "xs", "?" },
{ 0x6021, 0x0010, "xs", "?" },
{ 0x7001, 0x0010, "LT", "Dummy" },
{ 0x7003, 0x0010, "LT", "Info" },
{ 0x7005, 0x0010, "LT", "Dummy" },
{ 0x7000, 0x0004, "ST", "TextAnnotation" },
{ 0x7000, 0x0005, "IS", "Box" },
{ 0x7000, 0x0007, "IS", "ArrowEnd" },
{ 0x7fe0, 0x0000, "UL", "Pixel Data Group Length" },
{ 0x7fe0, 0x0010, "xs", "Pixel Data" },
{ 0x7fe0, 0x0020, "OW", "Coefficients SDVN" },
{ 0x7fe0, 0x0030, "OW", "Coefficients SDHN" },
{ 0x7fe0, 0x0040, "OW", "Coefficients SDDN" },
{ 0x7fe1, 0x0010, "xs", "Pixel Data" },
{ 0x7f00, 0x0000, "UL", "Variable Pixel Data Group Length" },
{ 0x7f00, 0x0010, "xs", "Variable Pixel Data" },
{ 0x7f00, 0x0011, "US", "Variable Next Data Group" },
{ 0x7f00, 0x0020, "OW", "Variable Coefficients SDVN" },
{ 0x7f00, 0x0030, "OW", "Variable Coefficients SDHN" },
{ 0x7f00, 0x0040, "OW", "Variable Coefficients SDDN" },
{ 0x7fe1, 0x0000, "OB", "Binary Data" },
{ 0x7fe3, 0x0000, "LT", "Image Graphics Format Code" },
{ 0x7fe3, 0x0010, "OB", "Image Graphics" },
{ 0x7fe3, 0x0020, "OB", "Image Graphics Dummy" },
{ 0x7ff1, 0x0001, "US", "?" },
{ 0x7ff1, 0x0002, "US", "?" },
{ 0x7ff1, 0x0003, "xs", "?" },
{ 0x7ff1, 0x0004, "IS", "?" },
{ 0x7ff1, 0x0005, "US", "?" },
{ 0x7ff1, 0x0007, "US", "?" },
{ 0x7ff1, 0x0008, "US", "?" },
{ 0x7ff1, 0x0009, "US", "?" },
{ 0x7ff1, 0x000a, "LT", "?" },
{ 0x7ff1, 0x000b, "US", "?" },
{ 0x7ff1, 0x000c, "US", "?" },
{ 0x7ff1, 0x000d, "US", "?" },
{ 0x7ff1, 0x0010, "US", "?" },
{ 0xfffc, 0xfffc, "OB", "Data Set Trailing Padding" },
{ 0xfffe, 0xe000, "!!", "Item" },
{ 0xfffe, 0xe00d, "!!", "Item Delimitation Item" },
{ 0xfffe, 0xe0dd, "!!", "Sequence Delimitation Item" },
{ 0xffff, 0xffff, "xs", (char *) NULL }
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D C M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDCM() returns MagickTrue if the image format type, identified by the
% magick string, is DCM.
%
% The format of the ReadDCMImage method is:
%
% MagickBooleanType IsDCM(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsDCM(const unsigned char *magick,const size_t length)
{
if (length < 132)
return(MagickFalse);
if (LocaleNCompare((char *) (magick+128),"DICM",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadDCMImage() reads a Digital Imaging and Communications in Medicine
% (DICOM) file and returns it. It allocates the memory necessary for the
% new Image structure and returns a pointer to the new image.
%
% The format of the ReadDCMImage method is:
%
% Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline size_t MagickMax(const size_t x,const size_t y)
{
if (x > y)
return(x);
return(y);
}
static inline size_t MagickMin(const size_t x,const size_t y)
{
if (x < y)
return(x);
return(y);
}
typedef struct _DCMStreamInfo
{
size_t
remaining,
segment_count;
ssize_t
segments[15];
size_t
offset_count;
ssize_t
*offsets;
ssize_t
count;
int
byte;
} DCMStreamInfo;
static int ReadDCMByte(DCMStreamInfo *stream_info,Image *image)
{
if (image->compression != RLECompression)
return(ReadBlobByte(image));
if (stream_info->count == 0)
{
int
byte;
ssize_t
count;
if (stream_info->remaining <= 2)
stream_info->remaining=0;
else
stream_info->remaining-=2;
count=(ssize_t) ReadBlobByte(image);
byte=ReadBlobByte(image);
if (count == 128)
return(0);
else
if (count < 128)
{
/*
Literal bytes.
*/
stream_info->count=count;
stream_info->byte=(-1);
return(byte);
}
else
{
/*
Repeated bytes.
*/
stream_info->count=256-count;
stream_info->byte=byte;
return(byte);
}
}
stream_info->count--;
if (stream_info->byte >= 0)
return(stream_info->byte);
if (stream_info->remaining > 0)
stream_info->remaining--;
return(ReadBlobByte(image));
}
static unsigned short ReadDCMShort(DCMStreamInfo *stream_info,Image *image)
{
int
shift;
unsigned short
value;
if (image->compression != RLECompression)
return(ReadBlobLSBShort(image));
shift=image->depth < 16 ? 4 : 8;
value=ReadDCMByte(stream_info,image) | (unsigned short)
(ReadDCMByte(stream_info,image) << shift);
return(value);
}
static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
explicit_vr[MaxTextExtent],
implicit_vr[MaxTextExtent],
magick[MaxTextExtent],
photometric[MaxTextExtent];
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
index,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
polarity,
sequence,
use_explicit;
MagickOffsetType
offset;
Quantum
*scale;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
size_t
bits_allocated,
bytes_per_pixel,
colors,
depth,
height,
length,
mask,
max_value,
number_scenes,
quantum,
samples_per_pixel,
signed_data,
significant_bits,
status,
width,
window_width;
ssize_t
count,
scene,
window_center,
y;
unsigned char
*data;
unsigned short
group,
element;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MaxTextExtent);
bits_allocated=8;
bytes_per_pixel=1;
polarity=MagickFalse;
data=(unsigned char *) NULL;
depth=8;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
max_value=255UL;
mask=0xffff;
number_scenes=1;
samples_per_pixel=1;
scale=(Quantum *) NULL;
sequence=MagickFalse;
signed_data=(~0UL);
significant_bits=0;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
window_center=0;
window_width=0;
for (group=0; (group != 0x7FE0) || (element != 0x0010) ||
(sequence != MagickFalse); )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) && (element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MaxTextExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strcmp(implicit_vr,"xs") == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MaxTextExtent);
if ((use_explicit == MagickFalse) || (strcmp(implicit_vr,"!!") == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strcmp(explicit_vr,"OB") == 0) ||
(strcmp(explicit_vr,"UN") == 0) ||
(strcmp(explicit_vr,"OW") == 0) || (strcmp(explicit_vr,"SQ") == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=(int) ReadBlobLSBLong(image);
else
datum=(int) ReadBlobLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=(int) ReadBlobLSBShort(image);
else
datum=(int) ReadBlobShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strcmp(implicit_vr,"SS") == 0) ||
(strcmp(implicit_vr,"US") == 0))
quantum=2;
else
if ((strcmp(implicit_vr,"UL") == 0) ||
(strcmp(implicit_vr,"SL") == 0) ||
(strcmp(implicit_vr,"FL") == 0))
quantum=4;
else
if (strcmp(implicit_vr,"FD") != 0)
quantum=1;
else
quantum=8;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=(int) ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=(int) ReadBlobLSBShort(image);
else
datum=(int) ReadBlobShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=(int) ReadBlobLSBLong(image);
else
datum=(int) ReadBlobLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
else
if ((unsigned int) datum == 0xFFFFFFFFU)
{
sequence=MagickTrue;
continue;
}
if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
sequence=MagickFalse;
continue;
}
if (sequence != MagickFalse)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MaxTextExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MaxTextExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
subtype,
type;
type=0;
subtype=0;
(void) sscanf(transfer_syntax+17,".%d.%d",&type,&subtype);
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
samples_per_pixel=(size_t) datum;
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
for (i=0; i < (ssize_t) MagickMin(length,MaxTextExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
bits_allocated=(size_t) datum;
bytes_per_pixel=1;
if (datum > 8)
bytes_per_pixel=2;
depth=bits_allocated;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << bits_allocated)-1;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
significant_bits=(size_t) datum;
bytes_per_pixel=1;
if (significant_bits > 8)
bytes_per_pixel=2;
depth=significant_bits;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << significant_bits)-1;
mask=(size_t) GetQuantumRange(significant_bits);
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
window_center=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
window_width=StringToUnsignedLong((char *) data);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/bytes_per_pixel);
datum=(int) colors;
graymap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) colors; i++)
if (bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
redmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
greenmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
bluemap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char*) data,"INVERSE", 7) == 0))
polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((width == 0) || (height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (signed_data == 0xffff)
signed_data=(size_t) (significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
size_t
length;
unsigned int
tag;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MaxTextExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for ( ; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
(void) fputc(c,file);
}
(void) fclose(file);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"j2k:%s",
filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property));
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
image=DestroyImage(image);
return(GetFirstImageInList(images));
}
if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
size_t
length;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(depth)+1);
scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale));
if (scale == (Quantum *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
range=GetQuantumRange(depth);
for (i=0; i < (ssize_t) (GetQuantumRange(depth)+1); i++)
scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
size_t
length;
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
if (image_info->ping != MagickFalse)
break;
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
break;
}
image->colorspace=RGBColorspace;
if ((image->colormap == (PixelPacket *) NULL) && (samples_per_pixel == 1))
{
size_t
one;
one=1;
if (colors == 0)
colors=one << depth;
if (AcquireImageColormap(image,one << depth) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(Quantum) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].green=(Quantum) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].blue=(Quantum) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(Quantum) index;
image->colormap[i].green=(Quantum) index;
image->colormap[i].blue=(Quantum) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
if (stream_info->segment_count > 1)
{
bytes_per_pixel=1;
depth=8;
}
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
stream_info->remaining-=64;
}
if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 1:
{
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 2:
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 3:
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
default:
break;
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
int
byte;
LongPixelPacket
pixel;
/*
Convert DCM Medical image to pixel packets.
*/
byte=0;
i=0;
if ((window_center != 0) && (window_width == 0))
window_width=(size_t) window_center;
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
window_width=0;
}
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ? ((int) max_value-
ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
pixel_value=(int) (polarity != MagickFalse ? (max_value-
ReadDCMShort(stream_info,image)) :
ReadDCMShort(stream_info,image));
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=(int) ReadDCMShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=pixel_value;
if (window_width == 0)
{
if (signed_data == 1)
index=pixel_value-32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t) pixel_value <= window_min)
index=0;
else
if ((ssize_t) pixel_value > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((pixel_value-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index);
SetPixelIndex(indexes+x,index);
pixel.red=1U*image->colormap[index].red;
pixel.green=1U*image->colormap[index].green;
pixel.blue=1U*image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (stream_info->segment_count > 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ? ((int) max_value-
ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
{
pixel_value=(int) (polarity != MagickFalse ? (max_value-
ReadDCMShort(stream_info,image)) :
ReadDCMShort(stream_info,image));
if (signed_data == 1)
pixel_value=((signed short) pixel_value);
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=(int) ReadDCMShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=pixel_value;
if (window_width == 0)
{
if (signed_data == 1)
index=pixel_value-32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t) pixel_value <= window_min)
index=0;
else
if ((ssize_t) pixel_value > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((pixel_value-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index);
SetPixelIndex(indexes+x,(((size_t) GetPixelIndex(indexes+x)) |
(((size_t) index) << 8)));
pixel.red=1U*image->colormap[index].red;
pixel.green=1U*image->colormap[index].green;
pixel.blue=1U*image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(q,(((size_t) GetPixelRed(q)) |
(((size_t) pixel.red) << 8)));
SetPixelGreen(q,(((size_t) GetPixelGreen(q)) |
(((size_t) pixel.green) << 8)));
SetPixelBlue(q,(((size_t) GetPixelBlue(q)) |
(((size_t) pixel.blue) << 8)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (IsGrayImage(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (scale != (Quantum *) NULL)
scale=(Quantum *) RelinquishMagickMemory(scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterDCMImage() adds attributes for the DCM image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterDCMImage method is:
%
% size_t RegisterDCMImage(void)
%
*/
ModuleExport size_t RegisterDCMImage(void)
{
MagickInfo
*entry;
static const char
*DCMNote=
{
"DICOM is used by the medical community for images like X-rays. The\n"
"specification, \"Digital Imaging and Communications in Medicine\n"
"(DICOM)\", is available at http://medical.nema.org/. In particular,\n"
"see part 5 which describes the image encoding (RLE, JPEG, JPEG-LS),\n"
"and supplement 61 which adds JPEG-2000 encoding."
};
entry=SetMagickInfo("DCM");
entry->decoder=(DecodeImageHandler *) ReadDCMImage;
entry->magick=(IsImageFormatHandler *) IsDCM;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString(
"Digital Imaging and Communications in Medicine image");
entry->note=ConstantString(DCMNote);
entry->module=ConstantString("DCM");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterDCMImage() removes format registrations made by the
% DCM module from the list of supported formats.
%
% The format of the UnregisterDCMImage method is:
%
% UnregisterDCMImage(void)
%
*/
ModuleExport void UnregisterDCMImage(void)
{
(void) UnregisterMagickInfo("DCM");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_10 |
crossvul-cpp_data_good_3407_3 | /* radare - LGPL - Copyright 2011-2017 pancake<nopcode.org> */
#include <r_io.h>
#include <r_fs.h>
#include "grubfs.h"
#include <stdio.h>
#include <string.h>
static RIOBind *bio = NULL;
static ut64 delta = 0;
static void* empty (int sz) {
void *p = malloc (sz);
if (p) memset (p, '\0', sz);
return p;
}
static grub_err_t read_foo (struct grub_disk *disk, grub_disk_addr_t sector, grub_size_t size, char *buf) {
if (!disk) {
eprintf ("oops. no disk\n");
return 1;
}
const int blocksize = 512; // TODO unhardcode 512
RIOBind *iob = disk->data;
if (bio) {
iob = bio;
}
//printf ("io %p\n", file->root->iob.io);
if (iob->read_at (iob->io, delta+(blocksize*sector), (ut8*)buf, size*blocksize) == -1) {
return 1;
}
return 0;
}
GrubFS *grubfs_new (struct grub_fs *myfs, void *data) {
struct grub_file *file;
GrubFS *gfs = empty (sizeof (GrubFS));
// hacky mallocs :D
gfs->file = file = empty (sizeof (struct grub_file));
file->device = empty (sizeof (struct grub_device)+1024);
file->device->disk = empty (sizeof (struct grub_disk));
file->device->disk->dev = (grub_disk_dev_t)file->device; // hack!
file->device->disk->dev->read = read_foo; // grub_disk_dev
file->device->disk->data = data;
//file->device->disk->read_hook = read_foo; //read_hook;
file->fs = myfs;
return gfs;
}
grub_disk_t grubfs_disk (void *data) {
struct grub_disk *disk = empty (sizeof (struct grub_disk));
disk->dev = empty (sizeof (struct grub_disk_dev));
disk->dev->read = read_foo; // grub_disk_dev
disk->data = data;
return disk;
}
void grubfs_free (GrubFS *gf) {
if (gf) {
if (gf->file && gf->file->device) {
free (gf->file->device->disk);
}
//free (gf->file->device);
free (gf->file);
free (gf);
}
}
void grubfs_bind_io (RIOBind *iob, ut64 _delta) {
bio = iob;
delta = _delta;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3407_3 |
crossvul-cpp_data_good_4788_2 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% EEEEE X X CCCC EEEEE PPPP TTTTT IIIII OOO N N %
% E X X C E P P T I O O NN N %
% EEE X C EEE PPPP T I O O N N N %
% E X X C E P T I O O N NN %
% EEEEE X X CCCC EEEEE P T IIIII OOO N N %
% %
% %
% MagickCore Exception Methods %
% %
% Software Design %
% Cristy %
% July 1993 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/client.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/hashmap.h"
#include "magick/locale_.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/string_.h"
#include "magick/utility.h"
/*
Global declarations.
*/
#define MaxExceptions 128
/*
Forward declarations.
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static void
DefaultErrorHandler(const ExceptionType,const char *,const char *),
DefaultFatalErrorHandler(const ExceptionType,const char *,const char *),
DefaultWarningHandler(const ExceptionType,const char *,const char *);
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
/*
Global declarations.
*/
static ErrorHandler
error_handler = DefaultErrorHandler;
static FatalErrorHandler
fatal_error_handler = DefaultFatalErrorHandler;
static WarningHandler
warning_handler = DefaultWarningHandler;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e E x c e p t i o n I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireExceptionInfo() allocates the ExceptionInfo structure.
%
% The format of the AcquireExceptionInfo method is:
%
% ExceptionInfo *AcquireExceptionInfo(void)
%
*/
MagickExport ExceptionInfo *AcquireExceptionInfo(void)
{
ExceptionInfo
*exception;
exception=(ExceptionInfo *) AcquireMagickMemory(sizeof(*exception));
if (exception == (ExceptionInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
InitializeExceptionInfo(exception);
exception->relinquish=MagickTrue;
return(exception);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l e a r M a g i c k E x c e p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClearMagickException() clears any exception that may not have been caught
% yet.
%
% The format of the ClearMagickException method is:
%
% ClearMagickException(ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o exception: the exception info.
%
*/
static void *DestroyExceptionElement(void *exception)
{
register ExceptionInfo
*p;
p=(ExceptionInfo *) exception;
if (p->reason != (char *) NULL)
p->reason=DestroyString(p->reason);
if (p->description != (char *) NULL)
p->description=DestroyString(p->description);
p=(ExceptionInfo *) RelinquishMagickMemory(p);
return((void *) NULL);
}
MagickExport void ClearMagickException(ExceptionInfo *exception)
{
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (exception->exceptions == (void *) NULL)
return;
LockSemaphoreInfo(exception->semaphore);
ClearLinkedList((LinkedListInfo *) exception->exceptions,
DestroyExceptionElement);
exception->severity=UndefinedException;
exception->reason=(char *) NULL;
exception->description=(char *) NULL;
UnlockSemaphoreInfo(exception->semaphore);
errno=0;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C a t c h E x c e p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CatchException() returns if no exceptions is found otherwise it reports
% the exception as a warning, error, or fatal depending on the severity.
%
% The format of the CatchException method is:
%
% CatchException(ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o exception: the exception info.
%
*/
MagickExport void CatchException(ExceptionInfo *exception)
{
register const ExceptionInfo
*p;
ssize_t
i;
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (exception->exceptions == (void *) NULL)
return;
LockSemaphoreInfo(exception->semaphore);
ResetLinkedListIterator((LinkedListInfo *) exception->exceptions);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
for (i=0; p != (const ExceptionInfo *) NULL; i++)
{
if (p->severity >= FatalErrorException)
MagickFatalError(p->severity,p->reason,p->description);
if (i < MaxExceptions)
{
if ((p->severity >= ErrorException) &&
(p->severity < FatalErrorException))
MagickError(p->severity,p->reason,p->description);
if ((p->severity >= WarningException) && (p->severity < ErrorException))
MagickWarning(p->severity,p->reason,p->description);
}
else
if (i == MaxExceptions)
MagickError(ResourceLimitError,"too many exceptions",
"exception processing suspended");
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
}
UnlockSemaphoreInfo(exception->semaphore);
ClearMagickException(exception);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e E x c e p t i o n I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneExceptionInfo() clones the ExceptionInfo structure.
%
% The format of the CloneExceptionInfo method is:
%
% ExceptionInfo *CloneException(ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o exception: the exception info.
%
*/
MagickExport ExceptionInfo *CloneExceptionInfo(ExceptionInfo *exception)
{
ExceptionInfo
*clone_exception;
clone_exception=(ExceptionInfo *) AcquireMagickMemory(sizeof(*exception));
if (clone_exception == (ExceptionInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
InitializeExceptionInfo(clone_exception);
InheritException(clone_exception,exception);
clone_exception->relinquish=MagickTrue;
return(clone_exception);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e f a u l t E r r o r H a n d l e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DefaultErrorHandler() displays an error reason.
%
% The format of the DefaultErrorHandler method is:
%
% void MagickError(const ExceptionType severity,const char *reason,
% const char *description)
%
% A description of each parameter follows:
%
% o severity: Specifies the numeric error category.
%
% o reason: Specifies the reason to display before terminating the
% program.
%
% o description: Specifies any description to the reason.
%
*/
static void DefaultErrorHandler(const ExceptionType magick_unused(severity),
const char *reason,const char *description)
{
magick_unreferenced(severity);
if (reason == (char *) NULL)
return;
(void) FormatLocaleFile(stderr,"%s: %s",GetClientName(),reason);
if (description != (char *) NULL)
(void) FormatLocaleFile(stderr," (%s)",description);
(void) FormatLocaleFile(stderr,".\n");
(void) fflush(stderr);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e f a u l t F a t a l E r r o r H a n d l e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DefaultFatalErrorHandler() displays an error reason and then terminates the
% program.
%
% The format of the DefaultFatalErrorHandler method is:
%
% void MagickFatalError(const ExceptionType severity,const char *reason,
% const char *description)
%
% A description of each parameter follows:
%
% o severity: Specifies the numeric error category.
%
% o reason: Specifies the reason to display before terminating the program.
%
% o description: Specifies any description to the reason.
%
*/
static void DefaultFatalErrorHandler(const ExceptionType severity,
const char *reason,const char *description)
{
if (reason == (char *) NULL)
return;
(void) FormatLocaleFile(stderr,"%s: %s",GetClientName(),reason);
if (description != (char *) NULL)
(void) FormatLocaleFile(stderr," (%s)",description);
(void) FormatLocaleFile(stderr,".\n");
(void) fflush(stderr);
MagickCoreTerminus();
exit((int) (severity-FatalErrorException)+1);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e f a u l t W a r n i n g H a n d l e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DefaultWarningHandler() displays a warning reason.
%
% The format of the DefaultWarningHandler method is:
%
% void DefaultWarningHandler(const ExceptionType severity,
% const char *reason,const char *description)
%
% A description of each parameter follows:
%
% o severity: Specifies the numeric warning category.
%
% o reason: Specifies the reason to display before terminating the
% program.
%
% o description: Specifies any description to the reason.
%
*/
static void DefaultWarningHandler(const ExceptionType magick_unused(severity),
const char *reason,const char *description)
{
magick_unreferenced(severity);
if (reason == (char *) NULL)
return;
(void) FormatLocaleFile(stderr,"%s: %s",GetClientName(),reason);
if (description != (char *) NULL)
(void) FormatLocaleFile(stderr," (%s)",description);
(void) FormatLocaleFile(stderr,".\n");
(void) fflush(stderr);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y E x c e p t i o n I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyExceptionInfo() deallocates memory associated with an exception.
%
% The format of the DestroyExceptionInfo method is:
%
% ExceptionInfo *DestroyExceptionInfo(ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o exception: the exception info.
%
*/
MagickPrivate MagickBooleanType ClearExceptionInfo(ExceptionInfo *exception,
MagickBooleanType relinquish)
{
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (exception->semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&exception->semaphore);
LockSemaphoreInfo(exception->semaphore);
if (relinquish == MagickFalse)
relinquish=exception->relinquish;
exception->severity=UndefinedException;
if (relinquish != MagickFalse)
{
exception->signature=(~MagickSignature);
if (exception->exceptions != (void *) NULL)
exception->exceptions=(void *) DestroyLinkedList((LinkedListInfo *)
exception->exceptions,DestroyExceptionElement);
}
else if (exception->exceptions != (void *) NULL)
ClearLinkedList((LinkedListInfo *) exception->exceptions,
DestroyExceptionElement);
UnlockSemaphoreInfo(exception->semaphore);
if (relinquish != MagickFalse)
DestroySemaphoreInfo(&exception->semaphore);
return(relinquish);
}
MagickExport ExceptionInfo *DestroyExceptionInfo(ExceptionInfo *exception)
{
if (ClearExceptionInfo(exception,MagickFalse) != MagickFalse)
exception=(ExceptionInfo *) RelinquishMagickMemory(exception);
return(exception);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t E x c e p t i o n M e s s a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetExceptionMessage() returns the error message defined by the specified
% error code.
%
% The format of the GetExceptionMessage method is:
%
% char *GetExceptionMessage(const int error)
%
% A description of each parameter follows:
%
% o error: the error code.
%
*/
MagickExport char *GetExceptionMessage(const int error)
{
char
exception[MaxTextExtent];
*exception='\0';
#if defined(MAGICKCORE_HAVE_STRERROR_R)
#if !defined(MAGICKCORE_STRERROR_R_CHAR_P)
(void) strerror_r(error,exception,sizeof(exception));
#else
(void) CopyMagickString(exception,strerror_r(error,exception,
sizeof(exception)),sizeof(exception));
#endif
#else
(void) CopyMagickString(exception,strerror(error),sizeof(exception));
#endif
return(ConstantString(exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t L o c a l e E x c e p t i o n M e s s a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleExceptionMessage() converts a enumerated exception severity and tag
% to a message in the current locale.
%
% The format of the GetLocaleExceptionMessage method is:
%
% const char *GetLocaleExceptionMessage(const ExceptionType severity,
% const char *tag)
%
% A description of each parameter follows:
%
% o severity: the severity of the exception.
%
% o tag: the message tag.
%
*/
static const char *ExceptionSeverityToTag(const ExceptionType severity)
{
switch (severity)
{
case ResourceLimitWarning: return("Resource/Limit/Warning/");
case TypeWarning: return("Type/Warning/");
case OptionWarning: return("Option/Warning/");
case DelegateWarning: return("Delegate/Warning/");
case MissingDelegateWarning: return("Missing/Delegate/Warning/");
case CorruptImageWarning: return("Corrupt/Image/Warning/");
case FileOpenWarning: return("File/Open/Warning/");
case BlobWarning: return("Blob/Warning/");
case StreamWarning: return("Stream/Warning/");
case CacheWarning: return("Cache/Warning/");
case CoderWarning: return("Coder/Warning/");
case FilterWarning: return("Filter/Warning/");
case ModuleWarning: return("Module/Warning/");
case DrawWarning: return("Draw/Warning/");
case ImageWarning: return("Image/Warning/");
case WandWarning: return("Wand/Warning/");
case XServerWarning: return("XServer/Warning/");
case MonitorWarning: return("Monitor/Warning/");
case RegistryWarning: return("Registry/Warning/");
case ConfigureWarning: return("Configure/Warning/");
case PolicyWarning: return("Policy/Warning/");
case ResourceLimitError: return("Resource/Limit/Error/");
case TypeError: return("Type/Error/");
case OptionError: return("Option/Error/");
case DelegateError: return("Delegate/Error/");
case MissingDelegateError: return("Missing/Delegate/Error/");
case CorruptImageError: return("Corrupt/Image/Error/");
case FileOpenError: return("File/Open/Error/");
case BlobError: return("Blob/Error/");
case StreamError: return("Stream/Error/");
case CacheError: return("Cache/Error/");
case CoderError: return("Coder/Error/");
case FilterError: return("Filter/Error/");
case ModuleError: return("Module/Error/");
case DrawError: return("Draw/Error/");
case ImageError: return("Image/Error/");
case WandError: return("Wand/Error/");
case XServerError: return("XServer/Error/");
case MonitorError: return("Monitor/Error/");
case RegistryError: return("Registry/Error/");
case ConfigureError: return("Configure/Error/");
case PolicyError: return("Policy/Error/");
case ResourceLimitFatalError: return("Resource/Limit/FatalError/");
case TypeFatalError: return("Type/FatalError/");
case OptionFatalError: return("Option/FatalError/");
case DelegateFatalError: return("Delegate/FatalError/");
case MissingDelegateFatalError: return("Missing/Delegate/FatalError/");
case CorruptImageFatalError: return("Corrupt/Image/FatalError/");
case FileOpenFatalError: return("File/Open/FatalError/");
case BlobFatalError: return("Blob/FatalError/");
case StreamFatalError: return("Stream/FatalError/");
case CacheFatalError: return("Cache/FatalError/");
case CoderFatalError: return("Coder/FatalError/");
case FilterFatalError: return("Filter/FatalError/");
case ModuleFatalError: return("Module/FatalError/");
case DrawFatalError: return("Draw/FatalError/");
case ImageFatalError: return("Image/FatalError/");
case WandFatalError: return("Wand/FatalError/");
case XServerFatalError: return("XServer/FatalError/");
case MonitorFatalError: return("Monitor/FatalError/");
case RegistryFatalError: return("Registry/FatalError/");
case ConfigureFatalError: return("Configure/FatalError/");
case PolicyFatalError: return("Policy/FatalError/");
default: break;
}
return("");
}
MagickExport const char *GetLocaleExceptionMessage(const ExceptionType severity,
const char *tag)
{
char
message[MaxTextExtent];
const char
*locale_message;
assert(tag != (const char *) NULL);
(void) FormatLocaleString(message,MaxTextExtent,"Exception/%s%s",
ExceptionSeverityToTag(severity),tag);
locale_message=GetLocaleMessage(message);
if (locale_message == (const char *) NULL)
return(tag);
if (locale_message == message)
return(tag);
return(locale_message);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n h e r i t E x c e p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InheritException() inherits an exception from a related exception.
%
% The format of the InheritException method is:
%
% InheritException(ExceptionInfo *exception,const ExceptionInfo *relative)
%
% A description of each parameter follows:
%
% o exception: the exception info.
%
% o relative: the related exception info.
%
*/
MagickExport void InheritException(ExceptionInfo *exception,
const ExceptionInfo *relative)
{
register const ExceptionInfo
*p;
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
assert(relative != (ExceptionInfo *) NULL);
assert(relative->signature == MagickSignature);
assert(exception != relative);
if (relative->exceptions == (void *) NULL)
return;
LockSemaphoreInfo(relative->semaphore);
ResetLinkedListIterator((LinkedListInfo *) relative->exceptions);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
relative->exceptions);
while (p != (const ExceptionInfo *) NULL)
{
(void) ThrowException(exception,p->severity,p->reason,p->description);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
relative->exceptions);
}
UnlockSemaphoreInfo(relative->semaphore);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n i t i a l i z e E x c e p t i o n I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InitializeExceptionInfo() initializes an exception to default values.
%
% The format of the InitializeExceptionInfo method is:
%
% InitializeExceptionInfo(ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o exception: the exception info.
%
*/
MagickPrivate void InitializeExceptionInfo(ExceptionInfo *exception)
{
assert(exception != (ExceptionInfo *) NULL);
(void) ResetMagickMemory(exception,0,sizeof(*exception));
exception->severity=UndefinedException;
exception->exceptions=(void *) NewLinkedList(0);
exception->semaphore=AllocateSemaphoreInfo();
exception->signature=MagickSignature;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M a g i c k E r r o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagickError() calls the exception handler methods with an error reason.
%
% The format of the MagickError method is:
%
% void MagickError(const ExceptionType error,const char *reason,
% const char *description)
%
% A description of each parameter follows:
%
% o exception: Specifies the numeric error category.
%
% o reason: Specifies the reason to display before terminating the
% program.
%
% o description: Specifies any description to the reason.
%
*/
MagickExport void MagickError(const ExceptionType error,const char *reason,
const char *description)
{
if (error_handler != (ErrorHandler) NULL)
(*error_handler)(error,reason,description);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M a g i c k F a t al E r r o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagickFatalError() calls the fatal exception handler methods with an error
% reason.
%
% The format of the MagickError method is:
%
% void MagickFatalError(const ExceptionType error,const char *reason,
% const char *description)
%
% A description of each parameter follows:
%
% o exception: Specifies the numeric error category.
%
% o reason: Specifies the reason to display before terminating the
% program.
%
% o description: Specifies any description to the reason.
%
*/
MagickExport void MagickFatalError(const ExceptionType error,const char *reason,
const char *description)
{
if (fatal_error_handler != (ErrorHandler) NULL)
(*fatal_error_handler)(error,reason,description);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M a g i c k W a r n i n g %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagickWarning() calls the warning handler methods with a warning reason.
%
% The format of the MagickWarning method is:
%
% void MagickWarning(const ExceptionType warning,const char *reason,
% const char *description)
%
% A description of each parameter follows:
%
% o warning: the warning severity.
%
% o reason: Define the reason for the warning.
%
% o description: Describe the warning.
%
*/
MagickExport void MagickWarning(const ExceptionType warning,const char *reason,
const char *description)
{
if (warning_handler != (WarningHandler) NULL)
(*warning_handler)(warning,reason,description);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t E r r o r H a n d l e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetErrorHandler() sets the exception handler to the specified method
% and returns the previous exception handler.
%
% The format of the SetErrorHandler method is:
%
% ErrorHandler SetErrorHandler(ErrorHandler handler)
%
% A description of each parameter follows:
%
% o handler: the method to handle errors.
%
*/
MagickExport ErrorHandler SetErrorHandler(ErrorHandler handler)
{
ErrorHandler
previous_handler;
previous_handler=error_handler;
error_handler=handler;
return(previous_handler);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t F a t a l E r r o r H a n d l e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetFatalErrorHandler() sets the fatal exception handler to the specified
% method and returns the previous fatal exception handler.
%
% The format of the SetErrorHandler method is:
%
% ErrorHandler SetErrorHandler(ErrorHandler handler)
%
% A description of each parameter follows:
%
% o handler: the method to handle errors.
%
*/
MagickExport FatalErrorHandler SetFatalErrorHandler(FatalErrorHandler handler)
{
FatalErrorHandler
previous_handler;
previous_handler=fatal_error_handler;
fatal_error_handler=handler;
return(previous_handler);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t W a r n i n g H a n d l e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetWarningHandler() sets the warning handler to the specified method
% and returns the previous warning handler.
%
% The format of the SetWarningHandler method is:
%
% ErrorHandler SetWarningHandler(ErrorHandler handler)
%
% A description of each parameter follows:
%
% o handler: the method to handle warnings.
%
*/
MagickExport WarningHandler SetWarningHandler(WarningHandler handler)
{
WarningHandler
previous_handler;
previous_handler=warning_handler;
warning_handler=handler;
return(previous_handler);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T h r o w E x c e p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ThrowException() throws an exception with the specified severity code,
% reason, and optional description.
%
% The format of the ThrowException method is:
%
% MagickBooleanType ThrowException(ExceptionInfo *exception,
% const ExceptionType severity,const char *reason,
% const char *description)
%
% A description of each parameter follows:
%
% o exception: the exception info.
%
% o severity: the severity of the exception.
%
% o reason: the reason for the exception.
%
% o description: the exception description.
%
*/
MagickExport MagickBooleanType ThrowException(ExceptionInfo *exception,
const ExceptionType severity,const char *reason,const char *description)
{
register ExceptionInfo
*p;
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
LockSemaphoreInfo(exception->semaphore);
p=(ExceptionInfo *) GetLastValueInLinkedList((LinkedListInfo *)
exception->exceptions);
if ((p != (ExceptionInfo *) NULL) && (p->severity == severity) &&
(LocaleCompare(exception->reason,reason) == 0) &&
(LocaleCompare(exception->description,description) == 0))
{
UnlockSemaphoreInfo(exception->semaphore);
return(MagickTrue);
}
p=(ExceptionInfo *) AcquireMagickMemory(sizeof(*p));
if (p == (ExceptionInfo *) NULL)
{
UnlockSemaphoreInfo(exception->semaphore);
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
}
(void) ResetMagickMemory(p,0,sizeof(*p));
p->severity=severity;
if (reason != (const char *) NULL)
p->reason=ConstantString(reason);
if (description != (const char *) NULL)
p->description=ConstantString(description);
p->signature=MagickSignature;
(void) AppendValueToLinkedList((LinkedListInfo *) exception->exceptions,p);
if (p->severity >= exception->severity)
{
exception->severity=p->severity;
exception->reason=p->reason;
exception->description=p->description;
}
UnlockSemaphoreInfo(exception->semaphore);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T h r o w M a g i c k E x c e p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ThrowMagickException logs an exception as determined by the log configuration
% file. If an error occurs, MagickFalse is returned otherwise MagickTrue.
%
% The format of the ThrowMagickException method is:
%
% MagickBooleanType ThrowFileException(ExceptionInfo *exception,
% const char *module,const char *function,const size_t line,
% const ExceptionType severity,const char *tag,const char *format,...)
%
% A description of each parameter follows:
%
% o exception: the exception info.
%
% o filename: the source module filename.
%
% o function: the function name.
%
% o line: the line number of the source module.
%
% o severity: Specifies the numeric error category.
%
% o tag: the locale tag.
%
% o format: the output format.
%
*/
MagickExport MagickBooleanType ThrowMagickExceptionList(
ExceptionInfo *exception,const char *module,const char *function,
const size_t line,const ExceptionType severity,const char *tag,
const char *format,va_list operands)
{
char
message[MaxTextExtent],
path[MaxTextExtent],
reason[MaxTextExtent];
const char
*locale,
*type;
int
n;
MagickBooleanType
status;
size_t
length;
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
locale=GetLocaleExceptionMessage(severity,tag);
(void) CopyMagickString(reason,locale,MaxTextExtent);
(void) ConcatenateMagickString(reason," ",MaxTextExtent);
length=strlen(reason);
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
n=vsnprintf(reason+length,MaxTextExtent-length,format,operands);
#else
n=vsprintf(reason+length,format,operands);
#endif
if (n < 0)
reason[MaxTextExtent-1]='\0';
status=LogMagickEvent(ExceptionEvent,module,function,line,"%s",reason);
GetPathComponent(module,TailPath,path);
type="undefined";
if ((severity >= WarningException) && (severity < ErrorException))
type="warning";
if ((severity >= ErrorException) && (severity < FatalErrorException))
type="error";
if (severity >= FatalErrorException)
type="fatal";
(void) FormatLocaleString(message,MaxTextExtent,"%s @ %s/%s/%s/%.20g",reason,
type,path,function,(double) line);
(void) ThrowException(exception,severity,message,(char *) NULL);
return(status);
}
MagickExport MagickBooleanType ThrowMagickException(ExceptionInfo *exception,
const char *module,const char *function,const size_t line,
const ExceptionType severity,const char *tag,const char *format,...)
{
MagickBooleanType
status;
va_list
operands;
va_start(operands,format);
status=ThrowMagickExceptionList(exception,module,function,line,severity,tag,
format,operands);
va_end(operands);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4788_2 |
crossvul-cpp_data_bad_5252_0 | /*
Mac-Telnet - Connect to RouterOS or mactelnetd devices via MAC address
Copyright (C) 2010, Håkon Nessjøen <haakon.nessjoen@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#define _BSD_SOURCE
#include <libintl.h>
#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#if defined(__APPLE__)
# include <libkern/OSByteOrder.h>
# define htole16 OSSwapHostToLittleInt16
#elif defined(__FreeBSD__)
#include <sys/endian.h>
#else
#include <endian.h>
#endif
#if defined(__FreeBSD__) || defined(__APPLE__)
#include <sys/types.h>
#include <net/ethernet.h>
#else
#include <netinet/ether.h>
#endif
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#ifdef __linux__
#include <linux/if_ether.h>
#include <sys/mman.h>
#endif
#include "md5.h"
#include "protocol.h"
#include "console.h"
#include "interfaces.h"
#include "config.h"
#include "mactelnet.h"
#include "mndp.h"
#include "autologin.h"
#include "utlist.h"
#define PROGRAM_NAME "MAC-Telnet"
#define _(String) gettext (String)
static int sockfd = 0;
static int insockfd;
static unsigned int outcounter = 0;
static long incounter = -1;
static int sessionkey = 0;
static int running = 1;
static unsigned char use_raw_socket = 0;
static unsigned char terminal_mode = 0;
static unsigned char srcmac[ETH_ALEN];
static unsigned char dstmac[ETH_ALEN];
static struct in_addr sourceip;
static struct in_addr destip;
static int sourceport;
static int connect_timeout = CONNECT_TIMEOUT;
static char run_mndp = 0;
static int mndp_timeout = 0;
static int is_a_tty = 1;
static int quiet_mode = 0;
static int batch_mode = 0;
static int no_autologin = 0;
static char autologin_path[255];
static int keepalive_counter = 0;
static unsigned char pass_salt[17];
static char username[MT_MNDP_MAX_STRING_SIZE];
static char password[MT_MNDP_MAX_STRING_SIZE];
static char nonpriv_username[MT_MNDP_MAX_STRING_SIZE];
struct net_interface *interfaces=NULL;
struct net_interface *active_interface;
/* Protocol data direction */
unsigned char mt_direction_fromserver = 0;
static unsigned int send_socket;
static int handle_packet(unsigned char *data, int data_len);
static void print_version() {
fprintf(stderr, PROGRAM_NAME " " PROGRAM_VERSION "\n");
}
void drop_privileges(char *username) {
struct passwd *user = (struct passwd *) getpwnam(username);
if (user == NULL) {
fprintf(stderr, _("Failed dropping privileges. The user %s is not a valid username on local system.\n"), username);
exit(1);
}
if (getuid() == 0) {
/* process is running as root, drop privileges */
if (setgid(user->pw_gid) != 0) {
fprintf(stderr, _("setgid: Error dropping group privileges\n"));
exit(1);
}
if (setuid(user->pw_uid) != 0) {
fprintf(stderr, _("setuid: Error dropping user privileges\n"));
exit(1);
}
/* Verify if the privileges were developed. */
if (setuid(0) != -1) {
fprintf(stderr, _("Failed to drop privileges\n"));
exit(1);
}
}
}
static int send_udp(struct mt_packet *packet, int retransmit) {
int sent_bytes;
/* Clear keepalive counter */
keepalive_counter = 0;
if (!use_raw_socket) {
/* Init SendTo struct */
struct sockaddr_in socket_address;
socket_address.sin_family = AF_INET;
socket_address.sin_port = htons(MT_MACTELNET_PORT);
socket_address.sin_addr.s_addr = htonl(INADDR_BROADCAST);
sent_bytes = sendto(send_socket, packet->data, packet->size, 0, (struct sockaddr*)&socket_address, sizeof(socket_address));
} else {
sent_bytes = net_send_udp(sockfd, active_interface, srcmac, dstmac, &sourceip, sourceport, &destip, MT_MACTELNET_PORT, packet->data, packet->size);
}
/*
* Retransmit packet if no data is received within
* retransmit_intervals milliseconds.
*/
if (retransmit) {
int i;
for (i = 0; i < MAX_RETRANSMIT_INTERVALS; ++i) {
fd_set read_fds;
int reads;
struct timeval timeout;
int interval = retransmit_intervals[i] * 1000;
/* Init select */
FD_ZERO(&read_fds);
FD_SET(insockfd, &read_fds);
timeout.tv_sec = 0;
timeout.tv_usec = interval;
/* Wait for data or timeout */
reads = select(insockfd + 1, &read_fds, NULL, NULL, &timeout);
if (reads && FD_ISSET(insockfd, &read_fds)) {
unsigned char buff[MT_PACKET_LEN];
int result;
bzero(buff, sizeof(buff));
result = recvfrom(insockfd, buff, sizeof(buff), 0, 0, 0);
/* Handle incoming packets, waiting for an ack */
if (result > 0 && handle_packet(buff, result) == MT_PTYPE_ACK) {
return sent_bytes;
}
}
/* Retransmit */
send_udp(packet, 0);
}
if (is_a_tty && terminal_mode) {
reset_term();
}
fprintf(stderr, _("\nConnection timed out\n"));
exit(1);
}
return sent_bytes;
}
static void send_auth(char *username, char *password) {
struct mt_packet data;
unsigned short width = 0;
unsigned short height = 0;
char *terminal = getenv("TERM");
char md5data[100];
unsigned char md5sum[17];
int plen;
md5_state_t state;
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(md5data, sizeof(md5data));
mlock(md5sum, sizeof(md5data));
#endif
/* Concat string of 0 + password + pass_salt */
md5data[0] = 0;
strncpy(md5data + 1, password, 82);
md5data[83] = '\0';
memcpy(md5data + 1 + strlen(password), pass_salt, 16);
/* Generate md5 sum of md5data with a leading 0 */
md5_init(&state);
md5_append(&state, (const md5_byte_t *)md5data, strlen(password) + 17);
md5_finish(&state, (md5_byte_t *)md5sum + 1);
md5sum[0] = 0;
/* Send combined packet to server */
init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
plen = add_control_packet(&data, MT_CPTYPE_PASSWORD, md5sum, 17);
plen += add_control_packet(&data, MT_CPTYPE_USERNAME, username, strlen(username));
plen += add_control_packet(&data, MT_CPTYPE_TERM_TYPE, terminal, strlen(terminal));
if (is_a_tty && get_terminal_size(&width, &height) != -1) {
width = htole16(width);
height = htole16(height);
plen += add_control_packet(&data, MT_CPTYPE_TERM_WIDTH, &width, 2);
plen += add_control_packet(&data, MT_CPTYPE_TERM_HEIGHT, &height, 2);
}
outcounter += plen;
/* TODO: handle result */
send_udp(&data, 1);
}
static void sig_winch(int sig) {
unsigned short width,height;
struct mt_packet data;
int plen;
/* terminal height/width has changed, inform server */
if (get_terminal_size(&width, &height) != -1) {
init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
width = htole16(width);
height = htole16(height);
plen = add_control_packet(&data, MT_CPTYPE_TERM_WIDTH, &width, 2);
plen += add_control_packet(&data, MT_CPTYPE_TERM_HEIGHT, &height, 2);
outcounter += plen;
send_udp(&data, 1);
}
/* reinstate signal handler */
signal(SIGWINCH, sig_winch);
}
static int handle_packet(unsigned char *data, int data_len) {
struct mt_mactelnet_hdr pkthdr;
/* Minimal size checks (pings are not supported here) */
if (data_len < MT_HEADER_LEN){
return -1;
}
parse_packet(data, &pkthdr);
/* We only care about packets with correct sessionkey */
if (pkthdr.seskey != sessionkey) {
return -1;
}
/* Handle data packets */
if (pkthdr.ptype == MT_PTYPE_DATA) {
struct mt_packet odata;
struct mt_mactelnet_control_hdr cpkt;
int success = 0;
/* Always transmit ACKNOWLEDGE packets in response to DATA packets */
init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, pkthdr.counter + (data_len - MT_HEADER_LEN));
send_udp(&odata, 0);
/* Accept first packet, and all packets greater than incounter, and if counter has
wrapped around. */
if (pkthdr.counter > incounter || (incounter - pkthdr.counter) > 65535) {
incounter = pkthdr.counter;
} else {
/* Ignore double or old packets */
return -1;
}
/* Parse controlpacket data */
success = parse_control_packet(data + MT_HEADER_LEN, data_len - MT_HEADER_LEN, &cpkt);
while (success) {
/* If we receive pass_salt, transmit auth data back */
if (cpkt.cptype == MT_CPTYPE_PASSSALT) {
memcpy(pass_salt, cpkt.data, cpkt.length);
send_auth(username, password);
}
/* If the (remaining) data did not have a control-packet magic byte sequence,
the data is raw terminal data to be outputted to the terminal. */
else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) {
fwrite((const void *)cpkt.data, 1, cpkt.length, stdout);
}
/* END_AUTH means that the user/password negotiation is done, and after this point
terminal data may arrive, so we set up the terminal to raw mode. */
else if (cpkt.cptype == MT_CPTYPE_END_AUTH) {
/* we have entered "terminal mode" */
terminal_mode = 1;
if (is_a_tty) {
/* stop input buffering at all levels. Give full control of terminal to RouterOS */
raw_term();
setvbuf(stdin, (char*)NULL, _IONBF, 0);
/* Add resize signal handler */
signal(SIGWINCH, sig_winch);
}
}
/* Parse next controlpacket */
success = parse_control_packet(NULL, 0, &cpkt);
}
}
else if (pkthdr.ptype == MT_PTYPE_ACK) {
/* Handled elsewhere */
}
/* The server wants to terminate the connection, we have to oblige */
else if (pkthdr.ptype == MT_PTYPE_END) {
struct mt_packet odata;
/* Acknowledge the disconnection by sending a END packet in return */
init_packet(&odata, MT_PTYPE_END, srcmac, dstmac, pkthdr.seskey, 0);
send_udp(&odata, 0);
if (!quiet_mode) {
fprintf(stderr, _("Connection closed.\n"));
}
/* exit */
running = 0;
} else {
fprintf(stderr, _("Unhandeled packet type: %d received from server %s\n"), pkthdr.ptype, ether_ntoa((struct ether_addr *)dstmac));
return -1;
}
return pkthdr.ptype;
}
static int find_interface() {
fd_set read_fds;
struct mt_packet data;
struct sockaddr_in myip;
unsigned char emptymac[ETH_ALEN];
int testsocket;
struct timeval timeout;
int optval = 1;
struct net_interface *interface;
/* TODO: reread interfaces on HUP */
//bzero(&interfaces, sizeof(struct net_interface) * MAX_INTERFACES);
bzero(emptymac, ETH_ALEN);
if (net_get_interfaces(&interfaces) <= 0) {
fprintf(stderr, _("Error: No suitable devices found\n"));
exit(1);
}
DL_FOREACH(interfaces, interface) {
/* Skip loopback interfaces */
if (memcmp("lo", interface->name, 2) == 0) {
continue;
}
/* Initialize receiving socket on the device chosen */
myip.sin_family = AF_INET;
memcpy((void *)&myip.sin_addr, interface->ipv4_addr, IPV4_ALEN);
myip.sin_port = htons(sourceport);
/* Initialize socket and bind to udp port */
if ((testsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
continue;
}
setsockopt(testsocket, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval));
setsockopt(testsocket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
if (bind(testsocket, (struct sockaddr *)&myip, sizeof(struct sockaddr_in)) == -1) {
close(testsocket);
continue;
}
/* Ensure that we have mac-address for this interface */
if (!interface->has_mac) {
close(testsocket);
continue;
}
/* Set the global socket handle and source mac address for send_udp() */
send_socket = testsocket;
memcpy(srcmac, interface->mac_addr, ETH_ALEN);
active_interface = interface;
/* Send a SESSIONSTART message with the current device */
init_packet(&data, MT_PTYPE_SESSIONSTART, srcmac, dstmac, sessionkey, 0);
send_udp(&data, 0);
timeout.tv_sec = connect_timeout;
timeout.tv_usec = 0;
FD_ZERO(&read_fds);
FD_SET(insockfd, &read_fds);
select(insockfd + 1, &read_fds, NULL, NULL, &timeout);
if (FD_ISSET(insockfd, &read_fds)) {
/* We got a response, this is the correct device to use */
return 1;
}
close(testsocket);
}
return 0;
}
/*
* TODO: Rewrite main() when all sub-functionality is tested
*/
int main (int argc, char **argv) {
int result;
struct mt_packet data;
struct sockaddr_in si_me;
struct autologin_profile *login_profile;
struct net_interface *interface, *tmp;
unsigned char buff[MT_PACKET_LEN];
unsigned char print_help = 0, have_username = 0, have_password = 0;
unsigned char drop_priv = 0;
int c;
int optval = 1;
strncpy(autologin_path, AUTOLOGIN_PATH, sizeof(autologin_path));
setlocale(LC_ALL, "");
bindtextdomain("mactelnet","/usr/share/locale");
textdomain("mactelnet");
while (1) {
c = getopt(argc, argv, "lnqt:u:p:U:vh?BAa:");
if (c == -1) {
break;
}
switch (c) {
case 'n':
use_raw_socket = 1;
break;
case 'u':
/* Save username */
strncpy(username, optarg, sizeof(username) - 1);
username[sizeof(username) - 1] = '\0';
have_username = 1;
break;
case 'p':
/* Save password */
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(password, sizeof(password));
#endif
strncpy(password, optarg, sizeof(password) - 1);
password[sizeof(password) - 1] = '\0';
have_password = 1;
break;
case 'U':
/* Save nonpriv_username */
strncpy(nonpriv_username, optarg, sizeof(nonpriv_username) - 1);
nonpriv_username[sizeof(nonpriv_username) - 1] = '\0';
drop_priv = 1;
break;
case 't':
connect_timeout = atoi(optarg);
mndp_timeout = connect_timeout;
break;
case 'v':
print_version();
exit(0);
break;
case 'q':
quiet_mode = 1;
break;
case 'l':
run_mndp = 1;
break;
case 'B':
batch_mode = 1;
break;
case 'A':
no_autologin = 1;
break;
case 'a':
strncpy(autologin_path, optarg, sizeof(autologin_path) - 1);
autologin_path[sizeof(autologin_path) - 1] = '\0';
break;
case 'h':
case '?':
print_help = 1;
break;
}
}
if (run_mndp) {
return mndp(mndp_timeout, batch_mode);
}
if (argc - optind < 1 || print_help) {
print_version();
fprintf(stderr, _("Usage: %s <MAC|identity> [-h] [-n] [-a <path>] [-A] [-t <timeout>] [-u <user>] [-p <password>] [-U <user>] | -l [-B] [-t <timeout>]\n"), argv[0]);
if (print_help) {
fprintf(stderr, _("\nParameters:\n"
" MAC MAC-Address of the RouterOS/mactelnetd device. Use mndp to\n"
" discover it.\n"
" identity The identity/name of your destination device. Uses\n"
" MNDP protocol to find it.\n"
" -l List/Search for routers nearby (MNDP). You may use -t to set timeout.\n"
" -B Batch mode. Use computer readable output (CSV), for use with -l.\n"
" -n Do not use broadcast packets. Less insecure but requires\n"
" root privileges.\n"
" -a <path> Use specified path instead of the default: " AUTOLOGIN_PATH " for autologin config file.\n"
" -A Disable autologin feature.\n"
" -t <timeout> Amount of seconds to wait for a response on each interface.\n"
" -u <user> Specify username on command line.\n"
" -p <password> Specify password on command line.\n"
" -U <user> Drop privileges to this user. Used in conjunction with -n\n"
" for security.\n"
" -q Quiet mode.\n"
" -h This help.\n"
"\n"));
}
return 1;
}
is_a_tty = isatty(fileno(stdout)) && isatty(fileno(stdin));
if (!is_a_tty) {
quiet_mode = 1;
}
if (!no_autologin) {
autologin_readfile(autologin_path);
login_profile = autologin_find_profile(argv[optind]);
if (!quiet_mode && login_profile != NULL && (login_profile->hasUsername || login_profile->hasPassword)) {
fprintf(stderr, _("Using autologin credentials from %s\n"), autologin_path);
}
if (!have_username) {
if (login_profile != NULL && login_profile->hasUsername) {
have_username = 1;
strncpy(username, login_profile->username, sizeof(username) - 1);
username[sizeof(username) - 1] = '\0';
}
}
if (!have_password) {
if (login_profile != NULL && login_profile->hasPassword) {
have_password = 1;
strncpy(password, login_profile->password, sizeof(password) - 1);
password[sizeof(password) - 1] = '\0';
}
}
}
/* Seed randomizer */
srand(time(NULL));
if (use_raw_socket) {
if (geteuid() != 0) {
fprintf(stderr, _("You need to have root privileges to use the -n parameter.\n"));
return 1;
}
sockfd = net_init_raw_socket();
if (drop_priv) {
drop_privileges(nonpriv_username);
}
} else if (drop_priv) {
fprintf(stderr, _("The -U option must be used in conjunction with the -n parameter.\n"));
return 1;
}
/* Receive regular udp packets with this socket */
insockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (insockfd < 0) {
perror("insockfd");
return 1;
}
if (!use_raw_socket) {
if (setsockopt(insockfd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof (optval))==-1) {
perror("SO_BROADCAST");
return 1;
}
}
/* Need to use, to be able to autodetect which interface to use */
setsockopt(insockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (optval));
/* Get mac-address from string, or check for hostname via mndp */
if (!query_mndp_or_mac(argv[optind], dstmac, !quiet_mode)) {
/* No valid mac address found, abort */
return 1;
}
if (!have_username) {
if (!quiet_mode) {
printf(_("Login: "));
fflush(stdout);
}
scanf("%127s", username);
}
if (!have_password) {
char *tmp;
tmp = getpass(quiet_mode ? "" : _("Password: "));
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(password, sizeof(password));
#endif
strncpy(password, tmp, sizeof(password) - 1);
password[sizeof(password) - 1] = '\0';
/* security */
memset(tmp, 0, strlen(tmp));
#ifdef __linux__
free(tmp);
#endif
}
/* Set random source port */
sourceport = 1024 + (rand() % 1024);
/* Set up global info about the connection */
inet_pton(AF_INET, (char *)"255.255.255.255", &destip);
memcpy(&sourceip, &(si_me.sin_addr), IPV4_ALEN);
/* Session key */
sessionkey = rand() % 65535;
/* stop output buffering */
setvbuf(stdout, (char*)NULL, _IONBF, 0);
if (!quiet_mode) {
printf(_("Connecting to %s..."), ether_ntoa((struct ether_addr *)dstmac));
}
/* Initialize receiving socket on the device chosen */
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(sourceport);
/* Bind to udp port */
if (bind(insockfd, (struct sockaddr *)&si_me, sizeof(si_me)) == -1) {
fprintf(stderr, _("Error binding to %s:%d, %s\n"), inet_ntoa(si_me.sin_addr), sourceport, strerror(errno));
return 1;
}
if (!find_interface() || (result = recvfrom(insockfd, buff, sizeof(buff), 0, 0, 0)) < 1) {
fprintf(stderr, _("Connection failed.\n"));
return 1;
}
if (!quiet_mode) {
printf(_("done\n"));
}
/* Handle first received packet */
handle_packet(buff, result);
init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, 0);
outcounter += add_control_packet(&data, MT_CPTYPE_BEGINAUTH, NULL, 0);
/* TODO: handle result of send_udp */
result = send_udp(&data, 1);
while (running) {
fd_set read_fds;
int reads;
static int terminal_gone = 0;
struct timeval timeout;
/* Init select */
FD_ZERO(&read_fds);
if (!terminal_gone) {
FD_SET(0, &read_fds);
}
FD_SET(insockfd, &read_fds);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
/* Wait for data or timeout */
reads = select(insockfd+1, &read_fds, NULL, NULL, &timeout);
if (reads > 0) {
/* Handle data from server */
if (FD_ISSET(insockfd, &read_fds)) {
bzero(buff, sizeof(buff));
result = recvfrom(insockfd, buff, sizeof(buff), 0, 0, 0);
handle_packet(buff, result);
}
/* Handle data from keyboard/local terminal */
if (FD_ISSET(0, &read_fds) && terminal_mode) {
unsigned char keydata[512];
int datalen;
datalen = read(STDIN_FILENO, &keydata, sizeof(keydata));
if (datalen > 0) {
/* Data received, transmit to server */
init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
add_control_packet(&data, MT_CPTYPE_PLAINDATA, &keydata, datalen);
outcounter += datalen;
send_udp(&data, 1);
} else {
terminal_gone = 1;
}
}
/* Handle select() timeout */
} else {
/* handle keepalive counter, transmit keepalive packet every 10 seconds
of inactivity */
if (keepalive_counter++ == 10) {
struct mt_packet odata;
init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, outcounter);
send_udp(&odata, 0);
}
}
}
if (is_a_tty && terminal_mode) {
/* Reset terminal back to old settings */
reset_term();
}
close(sockfd);
close(insockfd);
DL_FOREACH_SAFE(interfaces, interface, tmp) {
DL_DELETE(interfaces, interface);
free(interface);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5252_0 |
crossvul-cpp_data_bad_651_2 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre, Romain Bouqueau, Cyril Concolato
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / Media Tools sub-project
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/internal/media_dev.h>
#include <gpac/constants.h>
#include <gpac/mpeg4_odf.h>
#include <gpac/maths.h>
#ifndef GPAC_DISABLE_OGG
#include <gpac/internal/ogg.h>
#endif
static const struct {
u32 w, h;
} std_par[ ] =
{
{ 4, 3}, {3, 2}, {16, 9}, {5, 3}, {5, 4}, {8, 5}, {2, 1},
{0, 0},
};
GF_EXPORT
void gf_media_reduce_aspect_ratio(u32 *width, u32 *height)
{
u32 i=0;
u32 w = *width;
u32 h = *height;
while (std_par[i].w) {
if (std_par[i].w * h == std_par[i].h * w) {
*width = std_par[i].w;
*height = std_par[i].h;
return;
}
i++;
}
}
GF_EXPORT
void gf_media_get_reduced_frame_rate(u32 *timescale, u32 *sample_dur)
{
u32 res;
if (! *sample_dur) return;
res = *timescale / *sample_dur;
if (res **sample_dur == *timescale) {
*timescale = res;
*sample_dur = 1;
} else if ((double)(*timescale * 1001 - (res+1) * *sample_dur * 1000) / ((res+1) * *sample_dur * 1000) < 0.001) {
*timescale = (res+1) * 1000;
*sample_dur = 1001;
}
}
GF_EXPORT
const char *gf_m4v_get_profile_name(u8 video_pl)
{
switch (video_pl) {
case 0x00:
return "Reserved (0x00) Profile";
case 0x01:
return "Simple Profile @ Level 1";
case 0x02:
return "Simple Profile @ Level 2";
case 0x03:
return "Simple Profile @ Level 3";
case 0x08:
return "Simple Profile @ Level 0";
case 0x10:
return "Simple Scalable Profile @ Level 0";
case 0x11:
return "Simple Scalable Profile @ Level 1";
case 0x12:
return "Simple Scalable Profile @ Level 2";
case 0x21:
return "Core Profile @ Level 1";
case 0x22:
return "Core Profile @ Level 2";
case 0x32:
return "Main Profile @ Level 2";
case 0x33:
return "Main Profile @ Level 3";
case 0x34:
return "Main Profile @ Level 4";
case 0x42:
return "N-bit Profile @ Level 2";
case 0x51:
return "Scalable Texture Profile @ Level 1";
case 0x61:
return "Simple Face Animation Profile @ Level 1";
case 0x62:
return "Simple Face Animation Profile @ Level 2";
case 0x63:
return "Simple FBA Profile @ Level 1";
case 0x64:
return "Simple FBA Profile @ Level 2";
case 0x71:
return "Basic Animated Texture Profile @ Level 1";
case 0x72:
return "Basic Animated Texture Profile @ Level 2";
case 0x7F:
return "AVC/H264 Profile";
case 0x81:
return "Hybrid Profile @ Level 1";
case 0x82:
return "Hybrid Profile @ Level 2";
case 0x91:
return "Advanced Real Time Simple Profile @ Level 1";
case 0x92:
return "Advanced Real Time Simple Profile @ Level 2";
case 0x93:
return "Advanced Real Time Simple Profile @ Level 3";
case 0x94:
return "Advanced Real Time Simple Profile @ Level 4";
case 0xA1:
return "Core Scalable Profile @ Level1";
case 0xA2:
return "Core Scalable Profile @ Level2";
case 0xA3:
return "Core Scalable Profile @ Level3";
case 0xB1:
return "Advanced Coding Efficiency Profile @ Level 1";
case 0xB2:
return "Advanced Coding Efficiency Profile @ Level 2";
case 0xB3:
return "Advanced Coding Efficiency Profile @ Level 3";
case 0xB4:
return "Advanced Coding Efficiency Profile @ Level 4";
case 0xC1:
return "Advanced Core Profile @ Level 1";
case 0xC2:
return "Advanced Core Profile @ Level 2";
case 0xD1:
return "Advanced Scalable Texture @ Level1";
case 0xD2:
return "Advanced Scalable Texture @ Level2";
case 0xE1:
return "Simple Studio Profile @ Level 1";
case 0xE2:
return "Simple Studio Profile @ Level 2";
case 0xE3:
return "Simple Studio Profile @ Level 3";
case 0xE4:
return "Simple Studio Profile @ Level 4";
case 0xE5:
return "Core Studio Profile @ Level 1";
case 0xE6:
return "Core Studio Profile @ Level 2";
case 0xE7:
return "Core Studio Profile @ Level 3";
case 0xE8:
return "Core Studio Profile @ Level 4";
case 0xF0:
return "Advanced Simple Profile @ Level 0";
case 0xF1:
return "Advanced Simple Profile @ Level 1";
case 0xF2:
return "Advanced Simple Profile @ Level 2";
case 0xF3:
return "Advanced Simple Profile @ Level 3";
case 0xF4:
return "Advanced Simple Profile @ Level 4";
case 0xF5:
return "Advanced Simple Profile @ Level 5";
case 0xF7:
return "Advanced Simple Profile @ Level 3b";
case 0xF8:
return "Fine Granularity Scalable Profile @ Level 0";
case 0xF9:
return "Fine Granularity Scalable Profile @ Level 1";
case 0xFA:
return "Fine Granularity Scalable Profile @ Level 2";
case 0xFB:
return "Fine Granularity Scalable Profile @ Level 3";
case 0xFC:
return "Fine Granularity Scalable Profile @ Level 4";
case 0xFD:
return "Fine Granularity Scalable Profile @ Level 5";
case 0xFE:
return "Not part of MPEG-4 Visual profiles";
case 0xFF:
return "No visual capability required";
default:
return "ISO Reserved Profile";
}
}
#ifndef GPAC_DISABLE_AV_PARSERS
#define MPEG12_START_CODE_PREFIX 0x000001
#define MPEG12_PICTURE_START_CODE 0x00000100
#define MPEG12_SLICE_MIN_START 0x00000101
#define MPEG12_SLICE_MAX_START 0x000001af
#define MPEG12_USER_DATA_START_CODE 0x000001b2
#define MPEG12_SEQUENCE_START_CODE 0x000001b3
#define MPEG12_SEQUENCE_ERR_START_CODE 0x000001b4
#define MPEG12_EXT_START_CODE 0x000001b5
#define MPEG12_SEQUENCE_END_START_CODE 0x000001b7
#define MPEG12_GOP_START_CODE 0x000001b8
s32 gf_mv12_next_start_code(unsigned char *pbuffer, u32 buflen, u32 *optr, u32 *scode)
{
u32 value;
u32 offset;
if (buflen < 4) return -1;
for (offset = 0; offset < buflen - 3; offset++, pbuffer++) {
#ifdef GPAC_BIG_ENDIAN
value = *(u32 *)pbuffer >> 8;
#else
value = (pbuffer[0] << 16) | (pbuffer[1] << 8) | (pbuffer[2] << 0);
#endif
if (value == MPEG12_START_CODE_PREFIX) {
*optr = offset;
*scode = (value << 8) | pbuffer[3];
return 0;
}
}
return -1;
}
s32 gf_mv12_next_slice_start(unsigned char *pbuffer, u32 startoffset, u32 buflen, u32 *slice_offset)
{
u32 slicestart, code;
while (gf_mv12_next_start_code(pbuffer + startoffset, buflen - startoffset, &slicestart, &code) >= 0) {
if ((code >= MPEG12_SLICE_MIN_START) && (code <= MPEG12_SLICE_MAX_START)) {
*slice_offset = slicestart + startoffset;
return 0;
}
startoffset += slicestart + 4;
}
return -1;
}
/*
MPEG-4 video (14496-2)
*/
#define M4V_VO_START_CODE 0x00
#define M4V_VOL_START_CODE 0x20
#define M4V_VOP_START_CODE 0xB6
#define M4V_VISOBJ_START_CODE 0xB5
#define M4V_VOS_START_CODE 0xB0
#define M4V_GOV_START_CODE 0xB3
#define M4V_UDTA_START_CODE 0xB2
#define M2V_PIC_START_CODE 0x00
#define M2V_SEQ_START_CODE 0xB3
#define M2V_EXT_START_CODE 0xB5
#define M2V_GOP_START_CODE 0xB8
struct __tag_m4v_parser
{
GF_BitStream *bs;
Bool mpeg12;
u32 current_object_type;
u64 current_object_start;
u32 tc_dec, prev_tc_dec, tc_disp, prev_tc_disp;
};
GF_EXPORT
GF_M4VParser *gf_m4v_parser_new(char *data, u64 data_size, Bool mpeg12video)
{
GF_M4VParser *tmp;
if (!data || !data_size) return NULL;
GF_SAFEALLOC(tmp, GF_M4VParser);
if (!tmp) return NULL;
tmp->bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
tmp->mpeg12 = mpeg12video;
return tmp;
}
GF_M4VParser *gf_m4v_parser_bs_new(GF_BitStream *bs, Bool mpeg12video)
{
GF_M4VParser *tmp;
GF_SAFEALLOC(tmp, GF_M4VParser);
if (!tmp) return NULL;
tmp->bs = bs;
tmp->mpeg12 = mpeg12video;
return tmp;
}
GF_EXPORT
void gf_m4v_parser_del(GF_M4VParser *m4v)
{
gf_bs_del(m4v->bs);
gf_free(m4v);
}
#define M4V_CACHE_SIZE 4096
s32 M4V_LoadObject(GF_M4VParser *m4v)
{
u32 v, bpos, found;
char m4v_cache[M4V_CACHE_SIZE];
u64 end, cache_start, load_size;
if (!m4v) return 0;
bpos = 0;
found = 0;
load_size = 0;
end = 0;
cache_start = 0;
v = 0xffffffff;
while (!end) {
/*refill cache*/
if (bpos == (u32) load_size) {
if (!gf_bs_available(m4v->bs)) break;
load_size = gf_bs_available(m4v->bs);
if (load_size>M4V_CACHE_SIZE) load_size=M4V_CACHE_SIZE;
bpos = 0;
cache_start = gf_bs_get_position(m4v->bs);
gf_bs_read_data(m4v->bs, m4v_cache, (u32) load_size);
}
v = ( (v<<8) & 0xFFFFFF00) | ((u8) m4v_cache[bpos]);
bpos++;
if ((v & 0xFFFFFF00) == 0x00000100) {
end = cache_start+bpos-4;
found = 1;
break;
}
}
if (!found) return -1;
m4v->current_object_start = end;
gf_bs_seek(m4v->bs, end+3);
m4v->current_object_type = gf_bs_read_u8(m4v->bs);
return (s32) m4v->current_object_type;
}
GF_EXPORT
void gf_m4v_rewrite_pl(char **o_data, u32 *o_dataLen, u8 PL)
{
u32 pos = 0;
unsigned char *data = (unsigned char *)*o_data;
u32 dataLen = *o_dataLen;
while (pos+4<dataLen) {
if (!data[pos] && !data[pos+1] && (data[pos+2]==0x01) && (data[pos+3]==M4V_VOS_START_CODE)) {
data[pos+4] = PL;
return;
}
pos ++;
}
/*emulate VOS at beggining*/
(*o_data) = (char *)gf_malloc(sizeof(char)*(dataLen+5));
(*o_data)[0] = 0;
(*o_data)[1] = 0;
(*o_data)[2] = 1;
(*o_data)[3] = (char) M4V_VOS_START_CODE;
(*o_data)[4] = PL;
memcpy( (*o_data + 5), data, sizeof(char)*dataLen);
gf_free(data);
(*o_dataLen) = dataLen + 5;
}
static GF_Err M4V_Reset(GF_M4VParser *m4v, u64 start)
{
gf_bs_seek(m4v->bs, start);
assert(start < 1<<31);
m4v->current_object_start = (u32) start;
m4v->current_object_type = 0;
return GF_OK;
}
static GF_Err gf_m4v_parse_config_mpeg12(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)
{
unsigned char p[4];
u32 ext_type;
s32 o_type;
u8 go, par;
if (!m4v || !dsi) return GF_BAD_PARAM;
memset(dsi, 0, sizeof(GF_M4VDecSpecInfo));
dsi->VideoPL = 0;
go = 1;
while (go) {
o_type = M4V_LoadObject(m4v);
switch (o_type) {
case M2V_SEQ_START_CODE:
dsi->RAP_stream = 1;
gf_bs_read_data(m4v->bs, (char *) p, 4);
dsi->width = (p[0] << 4) | ((p[1] >> 4) & 0xf);
dsi->height = ((p[1] & 0xf) << 8) | p[2];
dsi->VideoPL = GPAC_OTI_VIDEO_MPEG1;
par = (p[3] >> 4) & 0xf;
switch (par) {
case 2:
dsi->par_num = dsi->height/3;
dsi->par_den = dsi->width/4;
break;
case 3:
dsi->par_num = dsi->height/9;
dsi->par_den = dsi->width/16;
break;
case 4:
dsi->par_num = dsi->height/2;
dsi->par_den = dsi->width/21;
break;
default:
dsi->par_den = dsi->par_num = 0;
break;
}
switch (p[3] & 0xf) {
case 0:
break;
case 1:
dsi->fps = 24000.0/1001.0;
break;
case 2:
dsi->fps = 24.0;
break;
case 3:
dsi->fps = 25.0;
break;
case 4:
dsi->fps = 30000.0/1001.0;
break;
case 5:
dsi->fps = 30.0;
break;
case 6:
dsi->fps = 50.0;
break;
case 7:
dsi->fps = ((60.0*1000.0)/1001.0);
break;
case 8:
dsi->fps = 60.0;
break;
case 9:
dsi->fps = 1;
break;
case 10:
dsi->fps = 5;
break;
case 11:
dsi->fps = 10;
break;
case 12:
dsi->fps = 12;
break;
case 13:
dsi->fps = 15;
break;
}
break;
case M2V_EXT_START_CODE:
gf_bs_read_data(m4v->bs, (char *) p, 4);
ext_type = ((p[0] >> 4) & 0xf);
if (ext_type == 1) {
dsi->VideoPL = 0x65;
dsi->height = ((p[1] & 0x1) << 13) | ((p[2] & 0x80) << 5) | (dsi->height & 0x0fff);
dsi->width = (((p[2] >> 5) & 0x3) << 12) | (dsi->width & 0x0fff);
}
break;
case M2V_PIC_START_CODE:
if (dsi->width) go = 0;
break;
default:
break;
/*EOS*/
case -1:
go = 0;
m4v->current_object_start = gf_bs_get_position(m4v->bs);
break;
}
}
M4V_Reset(m4v, 0);
return GF_OK;
}
static const struct {
u32 w, h;
} m4v_sar[6] = { { 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 }, { 40, 33 } };
static u8 m4v_get_sar_idx(u32 w, u32 h)
{
u32 i;
for (i=0; i<6; i++) {
if ((m4v_sar[i].w==w) && (m4v_sar[i].h==h)) return i;
}
return 0xF;
}
static GF_Err gf_m4v_parse_config_mpeg4(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)
{
s32 o_type;
u8 go, verid, par;
s32 clock_rate;
if (!m4v || !dsi) return GF_BAD_PARAM;
memset(dsi, 0, sizeof(GF_M4VDecSpecInfo));
go = 1;
while (go) {
o_type = M4V_LoadObject(m4v);
switch (o_type) {
/*vosh*/
case M4V_VOS_START_CODE:
dsi->VideoPL = (u8) gf_bs_read_u8(m4v->bs);
break;
case M4V_VOL_START_CODE:
verid = 0;
dsi->RAP_stream = gf_bs_read_int(m4v->bs, 1);
dsi->objectType = gf_bs_read_int(m4v->bs, 8);
if (gf_bs_read_int(m4v->bs, 1)) {
verid = gf_bs_read_int(m4v->bs, 4);
gf_bs_read_int(m4v->bs, 3);
}
par = gf_bs_read_int(m4v->bs, 4);
if (par == 0xF) {
dsi->par_num = gf_bs_read_int(m4v->bs, 8);
dsi->par_den = gf_bs_read_int(m4v->bs, 8);
} else if (par<6) {
dsi->par_num = m4v_sar[par].w;
dsi->par_den = m4v_sar[par].h;
}
if (gf_bs_read_int(m4v->bs, 1)) {
gf_bs_read_int(m4v->bs, 3);
if (gf_bs_read_int(m4v->bs, 1)) gf_bs_read_int(m4v->bs, 79);
}
dsi->has_shape = gf_bs_read_int(m4v->bs, 2);
if (dsi->has_shape && (verid!=1) ) gf_bs_read_int(m4v->bs, 4);
gf_bs_read_int(m4v->bs, 1);
/*clock rate*/
dsi->clock_rate = gf_bs_read_int(m4v->bs, 16);
/*marker*/
gf_bs_read_int(m4v->bs, 1);
clock_rate = dsi->clock_rate-1;
if (clock_rate >= 65536) clock_rate = 65535;
if (clock_rate > 0) {
for (dsi->NumBitsTimeIncrement = 1; dsi->NumBitsTimeIncrement < 16; dsi->NumBitsTimeIncrement++) {
if (clock_rate == 1) break;
clock_rate = (clock_rate >> 1);
}
} else {
/*fix from vivien for divX*/
dsi->NumBitsTimeIncrement = 1;
}
/*fixed FPS stream*/
dsi->time_increment = 0;
if (gf_bs_read_int(m4v->bs, 1)) {
dsi->time_increment = gf_bs_read_int(m4v->bs, dsi->NumBitsTimeIncrement);
}
if (!dsi->has_shape) {
gf_bs_read_int(m4v->bs, 1);
dsi->width = gf_bs_read_int(m4v->bs, 13);
gf_bs_read_int(m4v->bs, 1);
dsi->height = gf_bs_read_int(m4v->bs, 13);
} else {
dsi->width = dsi->height = 0;
}
/*shape will be done later*/
gf_bs_align(m4v->bs);
break;
case M4V_VOP_START_CODE:
case M4V_GOV_START_CODE:
go = 0;
break;
/*EOS*/
case -1:
go = 0;
m4v->current_object_start = gf_bs_get_position(m4v->bs);
break;
/*don't interest us*/
case M4V_UDTA_START_CODE:
default:
break;
}
}
return GF_OK;
}
GF_EXPORT
GF_Err gf_m4v_parse_config(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)
{
if (m4v->mpeg12) {
return gf_m4v_parse_config_mpeg12(m4v, dsi);
} else {
return gf_m4v_parse_config_mpeg4(m4v, dsi);
}
}
static GF_Err gf_m4v_parse_frame_mpeg12(GF_M4VParser *m4v, GF_M4VDecSpecInfo dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)
{
u8 go, hasVOP, firstObj, val;
s32 o_type;
if (!m4v || !size || !start || !frame_type) return GF_BAD_PARAM;
*size = 0;
firstObj = 1;
hasVOP = 0;
*is_coded = GF_FALSE;
m4v->current_object_type = (u32) -1;
*frame_type = 0;
M4V_Reset(m4v, m4v->current_object_start);
go = 1;
while (go) {
o_type = M4V_LoadObject(m4v);
switch (o_type) {
case M2V_PIC_START_CODE:
/*done*/
if (hasVOP) {
go = 0;
break;
}
if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
hasVOP = 1;
*is_coded = 1;
/*val = */gf_bs_read_u8(m4v->bs);
val = gf_bs_read_u8(m4v->bs);
*frame_type = ( (val >> 3) & 0x7 ) - 1;
break;
case M2V_GOP_START_CODE:
if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
if (hasVOP) go = 0;
break;
case M2V_SEQ_START_CODE:
if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
if (hasVOP) {
go = 0;
break;
}
/**/
break;
default:
break;
case -1:
*size = gf_bs_get_position(m4v->bs) - *start;
return GF_EOS;
}
}
*size = m4v->current_object_start - *start;
return GF_OK;
}
static GF_Err gf_m4v_parse_frame_mpeg4(GF_M4VParser *m4v, GF_M4VDecSpecInfo dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)
{
u8 go, hasVOP, firstObj, secs;
s32 o_type;
u32 vop_inc = 0;
if (!m4v || !size || !start || !frame_type) return GF_BAD_PARAM;
*size = 0;
firstObj = 1;
hasVOP = 0;
*is_coded = 0;
m4v->current_object_type = (u32) -1;
*frame_type = 0;
M4V_Reset(m4v, m4v->current_object_start);
go = 1;
while (go) {
o_type = M4V_LoadObject(m4v);
switch (o_type) {
case M4V_VOP_START_CODE:
/*done*/
if (hasVOP) {
go = 0;
break;
}
if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
hasVOP = 1;
/*coding type*/
*frame_type = gf_bs_read_int(m4v->bs, 2);
/*modulo time base*/
secs = 0;
while (gf_bs_read_int(m4v->bs, 1) != 0)
secs ++;
/*no support for B frames in parsing*/
secs += (dsi.enh_layer || *frame_type!=2) ? m4v->tc_dec : m4v->tc_disp;
/*marker*/
gf_bs_read_int(m4v->bs, 1);
/*vop_time_inc*/
if (dsi.NumBitsTimeIncrement)
vop_inc = gf_bs_read_int(m4v->bs, dsi.NumBitsTimeIncrement);
m4v->prev_tc_dec = m4v->tc_dec;
m4v->prev_tc_disp = m4v->tc_disp;
if (dsi.enh_layer || *frame_type!=2) {
m4v->tc_disp = m4v->tc_dec;
m4v->tc_dec = secs;
}
*time_inc = secs * dsi.clock_rate + vop_inc;
/*marker*/
gf_bs_read_int(m4v->bs, 1);
/*coded*/
*is_coded = gf_bs_read_int(m4v->bs, 1);
gf_bs_align(m4v->bs);
break;
case M4V_GOV_START_CODE:
if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
if (hasVOP) go = 0;
break;
case M4V_VOS_START_CODE:
case M4V_VOL_START_CODE:
if (hasVOP) {
go = 0;
} else if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
break;
case M4V_VO_START_CODE:
default:
break;
case -1:
*size = gf_bs_get_position(m4v->bs) - *start;
return GF_EOS;
}
}
*size = m4v->current_object_start - *start;
return GF_OK;
}
GF_EXPORT
GF_Err gf_m4v_parse_frame(GF_M4VParser *m4v, GF_M4VDecSpecInfo dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)
{
if (m4v->mpeg12) {
return gf_m4v_parse_frame_mpeg12(m4v, dsi, frame_type, time_inc, size, start, is_coded);
} else {
return gf_m4v_parse_frame_mpeg4(m4v, dsi, frame_type, time_inc, size, start, is_coded);
}
}
GF_Err gf_m4v_rewrite_par(char **o_data, u32 *o_dataLen, s32 par_n, s32 par_d)
{
u64 start, end, size;
GF_BitStream *mod;
GF_M4VParser *m4v;
Bool go = 1;
m4v = gf_m4v_parser_new(*o_data, *o_dataLen, 0);
mod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
start = 0;
while (go) {
u32 type = M4V_LoadObject(m4v);
end = gf_bs_get_position(m4v->bs) - 4;
size = end - start;
/*store previous object*/
if (size) {
assert (size < 1<<31);
if (size) gf_bs_write_data(mod, *o_data + start, (u32) size);
start = end;
}
switch (type) {
case M4V_VOL_START_CODE:
gf_bs_write_int(mod, 0, 8);
gf_bs_write_int(mod, 0, 8);
gf_bs_write_int(mod, 1, 8);
gf_bs_write_int(mod, M4V_VOL_START_CODE, 8);
gf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 1), 1);
gf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 8), 8);
start = gf_bs_read_int(m4v->bs, 1);
gf_bs_write_int(mod, (u32) start, 1);
if (start) {
gf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 7), 7);
}
start = gf_bs_read_int(m4v->bs, 4);
if (start == 0xF) {
gf_bs_read_int(m4v->bs, 8);
gf_bs_read_int(m4v->bs, 8);
}
if ((par_n>=0) && (par_d>=0)) {
u8 par = m4v_get_sar_idx(par_n, par_d);
gf_bs_write_int(mod, par, 4);
if (par==0xF) {
gf_bs_write_int(mod, par_n, 8);
gf_bs_write_int(mod, par_d, 8);
}
} else {
gf_bs_write_int(mod, 0x0, 4);
}
case -1:
go = 0;
break;
default:
break;
}
}
while (gf_bs_bits_available(m4v->bs)) {
u32 b = gf_bs_read_int(m4v->bs, 1);
gf_bs_write_int(mod, b, 1);
}
gf_m4v_parser_del(m4v);
gf_free(*o_data);
gf_bs_get_content(mod, o_data, o_dataLen);
gf_bs_del(mod);
return GF_OK;
}
GF_EXPORT
u64 gf_m4v_get_object_start(GF_M4VParser *m4v)
{
return m4v->current_object_start;
}
GF_EXPORT
Bool gf_m4v_is_valid_object_type(GF_M4VParser *m4v)
{
return ((s32) m4v->current_object_type==-1) ? 0 : 1;
}
GF_EXPORT
GF_Err gf_m4v_get_config(char *rawdsi, u32 rawdsi_size, GF_M4VDecSpecInfo *dsi)
{
GF_Err e;
GF_M4VParser *vparse;
if (!rawdsi || !rawdsi_size) return GF_NON_COMPLIANT_BITSTREAM;
vparse = gf_m4v_parser_new(rawdsi, rawdsi_size, 0);
e = gf_m4v_parse_config(vparse, dsi);
dsi->next_object_start = (u32) vparse->current_object_start;
gf_m4v_parser_del(vparse);
return e;
}
GF_EXPORT
GF_Err gf_mpegv12_get_config(char *rawdsi, u32 rawdsi_size, GF_M4VDecSpecInfo *dsi)
{
GF_Err e;
GF_M4VParser *vparse;
if (!rawdsi || !rawdsi_size) return GF_NON_COMPLIANT_BITSTREAM;
vparse = gf_m4v_parser_new(rawdsi, rawdsi_size, GF_TRUE);
e = gf_m4v_parse_config(vparse, dsi);
dsi->next_object_start = (u32) vparse->current_object_start;
gf_m4v_parser_del(vparse);
return e;
}
#endif
/*
AAC parser
*/
GF_EXPORT
const char *gf_m4a_object_type_name(u32 objectType)
{
switch (objectType) {
case 0:
return "MPEG-4 Audio Reserved";
case 1:
return "MPEG-4 Audio AAC Main";
case 2:
return "MPEG-4 Audio AAC LC";
case 3:
return "MPEG-4 Audio AAC SSR";
case 4:
return "MPEG-4 Audio AAC LTP";
case 5:
return "MPEG-4 Audio SBR";
case 6:
return "MPEG-4 Audio AAC Scalable";
case 7:
return "MPEG-4 Audio TwinVQ";
case 8:
return "MPEG-4 Audio CELP";
case 9:
return "MPEG-4 Audio HVXC";
case 10:
return "MPEG-4 Audio Reserved";
case 11:
return "MPEG-4 Audio Reserved";
case 12:
return "MPEG-4 Audio TTSI";
case 13:
return "MPEG-4 Audio Main synthetic";
case 14:
return "MPEG-4 Audio Wavetable synthesis";
case 15:
return "MPEG-4 Audio General MIDI";
case 16:
return "MPEG-4 Audio Algorithmic Synthesis and Audio FX";
case 17:
return "MPEG-4 Audio ER AAC LC";
case 18:
return "MPEG-4 Audio Reserved";
case 19:
return "MPEG-4 Audio ER AAC LTP";
case 20:
return "MPEG-4 Audio ER AAC scalable";
case 21:
return "MPEG-4 Audio ER TwinVQ";
case 22:
return "MPEG-4 Audio ER BSAC";
case 23:
return "MPEG-4 Audio ER AAC LD";
case 24:
return "MPEG-4 Audio ER CELP";
case 25:
return "MPEG-4 Audio ER HVXC";
case 26:
return "MPEG-4 Audio ER HILN";
case 27:
return "MPEG-4 Audio ER Parametric";
case 28:
return "MPEG-4 Audio SSC";
case 29:
return "MPEG-4 Audio ParametricStereo";
case 30:
return "MPEG-4 Audio Reserved";
case 31:
return "MPEG-4 Audio Reserved";
case 32:
return "MPEG-1 Audio Layer-1";
case 33:
return "MPEG-1 Audio Layer-2";
case 34:
return "MPEG-1 Audio Layer-3";
case 35:
return "MPEG-4 Audio DST";
case 36:
return "MPEG-4 Audio ALS";
default:
return "MPEG-4 Audio Unknown";
}
}
GF_EXPORT
const char *gf_m4a_get_profile_name(u8 audio_pl)
{
switch (audio_pl) {
case 0x00:
return "ISO Reserved (0x00)";
case 0x01:
return "Main Audio Profile @ Level 1";
case 0x02:
return "Main Audio Profile @ Level 2";
case 0x03:
return "Main Audio Profile @ Level 3";
case 0x04:
return "Main Audio Profile @ Level 4";
case 0x05:
return "Scalable Audio Profile @ Level 1";
case 0x06:
return "Scalable Audio Profile @ Level 2";
case 0x07:
return "Scalable Audio Profile @ Level 3";
case 0x08:
return "Scalable Audio Profile @ Level 4";
case 0x09:
return "Speech Audio Profile @ Level 1";
case 0x0A:
return "Speech Audio Profile @ Level 2";
case 0x0B:
return "Synthetic Audio Profile @ Level 1";
case 0x0C:
return "Synthetic Audio Profile @ Level 2";
case 0x0D:
return "Synthetic Audio Profile @ Level 3";
case 0x0E:
return "High Quality Audio Profile @ Level 1";
case 0x0F:
return "High Quality Audio Profile @ Level 2";
case 0x10:
return "High Quality Audio Profile @ Level 3";
case 0x11:
return "High Quality Audio Profile @ Level 4";
case 0x12:
return "High Quality Audio Profile @ Level 5";
case 0x13:
return "High Quality Audio Profile @ Level 6";
case 0x14:
return "High Quality Audio Profile @ Level 7";
case 0x15:
return "High Quality Audio Profile @ Level 8";
case 0x16:
return "Low Delay Audio Profile @ Level 1";
case 0x17:
return "Low Delay Audio Profile @ Level 2";
case 0x18:
return "Low Delay Audio Profile @ Level 3";
case 0x19:
return "Low Delay Audio Profile @ Level 4";
case 0x1A:
return "Low Delay Audio Profile @ Level 5";
case 0x1B:
return "Low Delay Audio Profile @ Level 6";
case 0x1C:
return "Low Delay Audio Profile @ Level 7";
case 0x1D:
return "Low Delay Audio Profile @ Level 8";
case 0x1E:
return "Natural Audio Profile @ Level 1";
case 0x1F:
return "Natural Audio Profile @ Level 2";
case 0x20:
return "Natural Audio Profile @ Level 3";
case 0x21:
return "Natural Audio Profile @ Level 4";
case 0x22:
return "Mobile Audio Internetworking Profile @ Level 1";
case 0x23:
return "Mobile Audio Internetworking Profile @ Level 2";
case 0x24:
return "Mobile Audio Internetworking Profile @ Level 3";
case 0x25:
return "Mobile Audio Internetworking Profile @ Level 4";
case 0x26:
return "Mobile Audio Internetworking Profile @ Level 5";
case 0x27:
return "Mobile Audio Internetworking Profile @ Level 6";
case 0x28:
return "AAC Profile @ Level 1";
case 0x29:
return "AAC Profile @ Level 2";
case 0x2A:
return "AAC Profile @ Level 4";
case 0x2B:
return "AAC Profile @ Level 5";
case 0x2C:
return "High Efficiency AAC Profile @ Level 2";
case 0x2D:
return "High Efficiency AAC Profile @ Level 3";
case 0x2E:
return "High Efficiency AAC Profile @ Level 4";
case 0x2F:
return "High Efficiency AAC Profile @ Level 5";
case 0x30:
return "High Efficiency AAC v2 Profile @ Level 2";
case 0x31:
return "High Efficiency AAC v2 Profile @ Level 3";
case 0x32:
return "High Efficiency AAC v2 Profile @ Level 4";
case 0x33:
return "High Efficiency AAC v2 Profile @ Level 5";
case 0x34:
return "Low Delay AAC Profile";
case 0x35:
return "Baseline MPEG Surround Profile @ Level 1";
case 0x36:
return "Baseline MPEG Surround Profile @ Level 2";
case 0x37:
return "Baseline MPEG Surround Profile @ Level 3";
case 0x38:
return "Baseline MPEG Surround Profile @ Level 4";
case 0x39:
return "Baseline MPEG Surround Profile @ Level 5";
case 0x3A:
return "Baseline MPEG Surround Profile @ Level 6";
case 0x50:
return "AAC Profile @ Level 6";
case 0x51:
return "AAC Profile @ Level 7";
case 0x52:
return "High Efficiency AAC Profile @ Level 6";
case 0x53:
return "High Efficiency AAC Profile @ Level 7";
case 0x54:
return "High Efficiency AAC v2 Profile @ Level 6";
case 0x55:
return "High Efficiency AAC v2 Profile @ Level 7";
case 0x56:
return "Extended High Efficiency AAC Profile @ Level 6";
case 0x57:
return "Extended High Efficiency AAC Profile @ Level 7";
case 0xFE:
return "Not part of MPEG-4 audio profiles";
case 0xFF:
return "No audio capability required";
default:
return "ISO Reserved / User Private";
}
}
#ifndef GPAC_DISABLE_AV_PARSERS
GF_EXPORT
u32 gf_m4a_get_profile(GF_M4ADecSpecInfo *cfg)
{
switch (cfg->base_object_type) {
case 2: /*AAC LC*/
if (cfg->nb_chan<=2)
return (cfg->base_sr<=24000) ? 0x28 : 0x29; /*LC@L1 or LC@L2*/
if (cfg->nb_chan<=5)
return (cfg->base_sr<=48000) ? 0x2A : 0x2B; /*LC@L4 or LC@L5*/
return (cfg->base_sr<=48000) ? 0x50 : 0x51; /*LC@L4 or LC@L5*/
case 5: /*HE-AAC - SBR*/
if (cfg->nb_chan<=2)
return (cfg->base_sr<=24000) ? 0x2C : 0x2D; /*HE@L2 or HE@L3*/
if (cfg->nb_chan<=5)
return (cfg->base_sr<=48000) ? 0x2E : 0x2F; /*HE@L4 or HE@L5*/
return (cfg->base_sr<=48000) ? 0x52 : 0x53; /*HE@L6 or HE@L7*/
case 29: /*HE-AACv2 - SBR+PS*/
if (cfg->nb_chan<=2)
return (cfg->base_sr<=24000) ? 0x30 : 0x31; /*HE-AACv2@L2 or HE-AACv2@L3*/
if (cfg->nb_chan<=5)
return (cfg->base_sr<=48000) ? 0x32 : 0x33; /*HE-AACv2@L4 or HE-AACv2@L5*/
return (cfg->base_sr<=48000) ? 0x54 : 0x55; /*HE-AACv2@L6 or HE-AACv2@L7*/
/*default to HQ*/
default:
if (cfg->nb_chan<=2) return (cfg->base_sr<24000) ? 0x0E : 0x0F; /*HQ@L1 or HQ@L2*/
return 0x10; /*HQ@L3*/
}
}
GF_EXPORT
GF_Err gf_m4a_parse_config(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg, Bool size_known)
{
u32 channel_configuration = 0;
memset(cfg, 0, sizeof(GF_M4ADecSpecInfo));
cfg->base_object_type = gf_bs_read_int(bs, 5);
/*extended object type*/
if (cfg->base_object_type==31) {
cfg->base_object_type = 32 + gf_bs_read_int(bs, 6);
}
cfg->base_sr_index = gf_bs_read_int(bs, 4);
if (cfg->base_sr_index == 0x0F) {
cfg->base_sr = gf_bs_read_int(bs, 24);
} else {
cfg->base_sr = GF_M4ASampleRates[cfg->base_sr_index];
}
channel_configuration = gf_bs_read_int(bs, 4);
if (channel_configuration) {
cfg->nb_chan = GF_M4ANumChannels[channel_configuration-1];
}
if (cfg->base_object_type==5 || cfg->base_object_type==29) {
if (cfg->base_object_type==29) {
cfg->has_ps = 1;
cfg->nb_chan = 1;
}
cfg->has_sbr = GF_TRUE;
cfg->sbr_sr_index = gf_bs_read_int(bs, 4);
if (cfg->sbr_sr_index == 0x0F) {
cfg->sbr_sr = gf_bs_read_int(bs, 24);
} else {
cfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];
}
cfg->sbr_object_type = gf_bs_read_int(bs, 5);
}
/*object cfg*/
switch (cfg->base_object_type) {
case 1:
case 2:
case 3:
case 4:
case 6:
case 7:
case 17:
case 19:
case 20:
case 21:
case 22:
case 23:
{
Bool ext_flag;
/*frame length flag*/
/*fl_flag = */gf_bs_read_int(bs, 1);
/*depends on core coder*/
if (gf_bs_read_int(bs, 1))
/*delay = */gf_bs_read_int(bs, 14);
ext_flag = gf_bs_read_int(bs, 1);
if (! channel_configuration) {
u32 i;
cfg->program_config_element_present = 1;
cfg->element_instance_tag = gf_bs_read_int(bs, 4);
cfg->object_type = gf_bs_read_int(bs, 2);
cfg->sampling_frequency_index = gf_bs_read_int(bs, 4);
cfg->num_front_channel_elements = gf_bs_read_int(bs, 4);
cfg->num_side_channel_elements = gf_bs_read_int(bs, 4);
cfg->num_back_channel_elements = gf_bs_read_int(bs, 4);
cfg->num_lfe_channel_elements = gf_bs_read_int(bs, 2);
cfg->num_assoc_data_elements = gf_bs_read_int(bs, 3);
cfg->num_valid_cc_elements = gf_bs_read_int(bs, 4);
cfg-> mono_mixdown_present = (Bool) gf_bs_read_int(bs, 1);
if (cfg->mono_mixdown_present) {
cfg->mono_mixdown_element_number = gf_bs_read_int(bs, 4);
}
cfg->stereo_mixdown_present = gf_bs_read_int(bs, 1);
if (cfg->stereo_mixdown_present) {
cfg->stereo_mixdown_element_number = gf_bs_read_int(bs, 4);
}
cfg->matrix_mixdown_idx_present = gf_bs_read_int(bs, 1);
if (cfg->matrix_mixdown_idx_present) {
cfg->matrix_mixdown_idx = gf_bs_read_int(bs, 2);
cfg->pseudo_surround_enable = gf_bs_read_int(bs, 1);
}
for (i = 0; i < cfg->num_front_channel_elements; i++) {
cfg->front_element_is_cpe[i] = gf_bs_read_int(bs, 1);
cfg->front_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
for (i = 0; i < cfg->num_side_channel_elements; i++) {
cfg->side_element_is_cpe[i] = gf_bs_read_int(bs, 1);
cfg->side_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
for (i = 0; i < cfg->num_back_channel_elements; i++) {
cfg->back_element_is_cpe[i] = gf_bs_read_int(bs, 1);
cfg->back_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
for (i = 0; i < cfg->num_lfe_channel_elements; i++) {
cfg->lfe_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
for ( i = 0; i < cfg->num_assoc_data_elements; i++) {
cfg->assoc_data_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
for (i = 0; i < cfg->num_valid_cc_elements; i++) {
cfg->cc_element_is_ind_sw[i] = gf_bs_read_int(bs, 1);
cfg->valid_cc_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
gf_bs_align(bs);
cfg->comment_field_bytes = gf_bs_read_int(bs, 8);
gf_bs_read_data(bs, (char *) cfg->comments, cfg->comment_field_bytes);
cfg->nb_chan = cfg->num_front_channel_elements + cfg->num_back_channel_elements + cfg->num_side_channel_elements + cfg->num_lfe_channel_elements;
}
if ((cfg->base_object_type == 6) || (cfg->base_object_type == 20)) {
gf_bs_read_int(bs, 3);
}
if (ext_flag) {
if (cfg->base_object_type == 22) {
gf_bs_read_int(bs, 5);
gf_bs_read_int(bs, 11);
}
if ((cfg->base_object_type == 17)
|| (cfg->base_object_type == 19)
|| (cfg->base_object_type == 20)
|| (cfg->base_object_type == 23)
) {
gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 1);
}
/*ext_flag = */gf_bs_read_int(bs, 1);
}
}
break;
}
/*ER cfg*/
switch (cfg->base_object_type) {
case 17:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
case 26:
case 27:
{
u32 epConfig = gf_bs_read_int(bs, 2);
if ((epConfig == 2) || (epConfig == 3) ) {
}
if (epConfig == 3) {
gf_bs_read_int(bs, 1);
}
}
break;
}
if (size_known && (cfg->base_object_type != 5) && (cfg->base_object_type != 29) ) {
while (gf_bs_available(bs)>=2) {
u32 sync = gf_bs_peek_bits(bs, 11, 0);
if (sync==0x2b7) {
gf_bs_read_int(bs, 11);
cfg->sbr_object_type = gf_bs_read_int(bs, 5);
cfg->has_sbr = gf_bs_read_int(bs, 1);
if (cfg->has_sbr) {
cfg->sbr_sr_index = gf_bs_read_int(bs, 4);
if (cfg->sbr_sr_index == 0x0F) {
cfg->sbr_sr = gf_bs_read_int(bs, 24);
} else {
cfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];
}
}
} else if (sync == 0x548) {
gf_bs_read_int(bs, 11);
cfg->has_ps = gf_bs_read_int(bs, 1);
if (cfg->has_ps)
cfg->nb_chan = 1;
} else {
break;
}
}
}
cfg->audioPL = gf_m4a_get_profile(cfg);
return GF_OK;
}
GF_EXPORT
GF_Err gf_m4a_get_config(char *dsi, u32 dsi_size, GF_M4ADecSpecInfo *cfg)
{
GF_BitStream *bs;
if (!dsi || !dsi_size || (dsi_size<2) ) return GF_NON_COMPLIANT_BITSTREAM;
bs = gf_bs_new(dsi, dsi_size, GF_BITSTREAM_READ);
gf_m4a_parse_config(bs, cfg, 1);
gf_bs_del(bs);
return GF_OK;
}
u32 gf_latm_get_value(GF_BitStream *bs)
{
u32 i, tmp, value = 0;
u32 bytesForValue = gf_bs_read_int(bs, 2);
for (i=0; i <= bytesForValue; i++) {
value <<= 8;
tmp = gf_bs_read_int(bs, 8);
value += tmp;
}
return value;
}
GF_EXPORT
u32 gf_m4a_get_channel_cfg(u32 nb_chan)
{
u32 i, count = sizeof(GF_M4ANumChannels)/sizeof(u32);
for (i=0; i<count; i++) {
if (GF_M4ANumChannels[i] == nb_chan) return i+1;
}
return 0;
}
GF_EXPORT
GF_Err gf_m4a_write_config_bs(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg)
{
if (!cfg->base_sr_index) {
if (!cfg->base_sr) return GF_BAD_PARAM;
while (GF_M4ASampleRates[cfg->base_sr_index]) {
if (GF_M4ASampleRates[cfg->base_sr_index]==cfg->base_sr)
break;
cfg->base_sr_index++;
}
}
if (cfg->sbr_sr && !cfg->sbr_sr_index) {
while (GF_M4ASampleRates[cfg->sbr_sr_index]) {
if (GF_M4ASampleRates[cfg->sbr_sr_index]==cfg->sbr_sr)
break;
cfg->sbr_sr_index++;
}
}
/*extended object type*/
if (cfg->base_object_type>=32) {
gf_bs_write_int(bs, 31, 5);
gf_bs_write_int(bs, cfg->base_object_type-32, 6);
} else {
gf_bs_write_int(bs, cfg->base_object_type, 5);
}
gf_bs_write_int(bs, cfg->base_sr_index, 4);
if (cfg->base_sr_index == 0x0F) {
gf_bs_write_int(bs, cfg->base_sr, 24);
}
if (cfg->program_config_element_present) {
gf_bs_write_int(bs, 0, 4);
} else {
gf_bs_write_int(bs, gf_m4a_get_channel_cfg( cfg->nb_chan) , 4);
}
if (cfg->base_object_type==5 || cfg->base_object_type==29) {
if (cfg->base_object_type == 29) {
cfg->has_ps = 1;
cfg->nb_chan = 1;
}
cfg->has_sbr = 1;
gf_bs_write_int(bs, cfg->sbr_sr_index, 4);
if (cfg->sbr_sr_index == 0x0F) {
gf_bs_write_int(bs, cfg->sbr_sr, 24);
}
gf_bs_write_int(bs, cfg->sbr_object_type, 5);
}
/*object cfg*/
switch (cfg->base_object_type) {
case 1:
case 2:
case 3:
case 4:
case 6:
case 7:
case 17:
case 19:
case 20:
case 21:
case 22:
case 23:
{
/*frame length flag*/
gf_bs_write_int(bs, 0, 1);
/*depends on core coder*/
gf_bs_write_int(bs, 0, 1);
/*ext flag*/
gf_bs_write_int(bs, 0, 1);
if (cfg->program_config_element_present) {
u32 i;
gf_bs_write_int(bs, cfg->element_instance_tag, 4);
gf_bs_write_int(bs, cfg->object_type, 2);
gf_bs_write_int(bs, cfg->sampling_frequency_index, 4);
gf_bs_write_int(bs, cfg->num_front_channel_elements, 4);
gf_bs_write_int(bs, cfg->num_side_channel_elements, 4);
gf_bs_write_int(bs, cfg->num_back_channel_elements, 4);
gf_bs_write_int(bs, cfg->num_lfe_channel_elements, 2);
gf_bs_write_int(bs, cfg->num_assoc_data_elements, 3);
gf_bs_write_int(bs, cfg->num_valid_cc_elements, 4);
gf_bs_write_int(bs, cfg-> mono_mixdown_present, 1);
if (cfg->mono_mixdown_present) {
gf_bs_write_int(bs, cfg->mono_mixdown_element_number, 4);
}
gf_bs_write_int(bs, cfg->stereo_mixdown_present, 1);
if (cfg->stereo_mixdown_present) {
gf_bs_write_int(bs, cfg->stereo_mixdown_element_number, 4);
}
gf_bs_write_int(bs, cfg->matrix_mixdown_idx_present, 1);
if (cfg->matrix_mixdown_idx_present) {
gf_bs_write_int(bs, cfg->matrix_mixdown_idx, 2);
gf_bs_write_int(bs, cfg->pseudo_surround_enable, 1);
}
for (i = 0; i < cfg->num_front_channel_elements; i++) {
gf_bs_write_int(bs, cfg->front_element_is_cpe[i], 1);
gf_bs_write_int(bs, cfg->front_element_tag_select[i], 4);
}
for (i = 0; i < cfg->num_side_channel_elements; i++) {
gf_bs_write_int(bs, cfg->side_element_is_cpe[i], 1);
gf_bs_write_int(bs, cfg->side_element_tag_select[i], 4);
}
for (i = 0; i < cfg->num_back_channel_elements; i++) {
gf_bs_write_int(bs, cfg->back_element_is_cpe[i], 1);
gf_bs_write_int(bs, cfg->back_element_tag_select[i], 4);
}
for (i = 0; i < cfg->num_lfe_channel_elements; i++) {
gf_bs_write_int(bs, cfg->lfe_element_tag_select[i], 4);
}
for ( i = 0; i < cfg->num_assoc_data_elements; i++) {
gf_bs_write_int(bs, cfg->assoc_data_element_tag_select[i], 4);
}
for (i = 0; i < cfg->num_valid_cc_elements; i++) {
gf_bs_write_int(bs, cfg->cc_element_is_ind_sw[i], 1);
gf_bs_write_int(bs, cfg->valid_cc_element_tag_select[i], 4);
}
gf_bs_align(bs);
gf_bs_write_int(bs, cfg->comment_field_bytes, 8);
gf_bs_write_data(bs, (char *) cfg->comments, cfg->comment_field_bytes);
}
if ((cfg->base_object_type == 6) || (cfg->base_object_type == 20)) {
gf_bs_write_int(bs, 0, 3);
}
}
break;
}
/*ER cfg - not supported*/
/*implicit sbr - not used yet*/
if (0 && (cfg->base_object_type != 5) && (cfg->base_object_type != 29) ) {
gf_bs_write_int(bs, 0x2b7, 11);
cfg->sbr_object_type = gf_bs_read_int(bs, 5);
cfg->has_sbr = gf_bs_read_int(bs, 1);
if (cfg->has_sbr) {
cfg->sbr_sr_index = gf_bs_read_int(bs, 4);
if (cfg->sbr_sr_index == 0x0F) {
cfg->sbr_sr = gf_bs_read_int(bs, 24);
} else {
cfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];
}
}
}
return GF_OK;
}
GF_EXPORT
GF_Err gf_m4a_write_config(GF_M4ADecSpecInfo *cfg, char **dsi, u32 *dsi_size)
{
GF_BitStream *bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
gf_m4a_write_config_bs(bs, cfg);
gf_bs_get_content(bs, dsi, dsi_size);
gf_bs_del(bs);
return GF_OK;
}
#endif /*GPAC_DISABLE_AV_PARSERS*/
GF_EXPORT
u8 gf_mp3_version(u32 hdr)
{
return ((hdr >> 19) & 0x3);
}
GF_EXPORT
const char *gf_mp3_version_name(u32 hdr)
{
u32 v = gf_mp3_version(hdr);
switch (v) {
case 0:
return "MPEG-2.5";
case 1:
return "Reserved";
case 2:
return "MPEG-2";
case 3:
return "MPEG-1";
default:
return "Unknown";
}
}
#ifndef GPAC_DISABLE_AV_PARSERS
GF_EXPORT
u8 gf_mp3_layer(u32 hdr)
{
return 4 - (((hdr >> 17) & 0x3));
}
GF_EXPORT
u8 gf_mp3_num_channels(u32 hdr)
{
if (((hdr >> 6) & 0x3) == 3) return 1;
return 2;
}
GF_EXPORT
u16 gf_mp3_sampling_rate(u32 hdr)
{
u16 res;
/* extract the necessary fields from the MP3 header */
u8 version = gf_mp3_version(hdr);
u8 sampleRateIndex = (hdr >> 10) & 0x3;
switch (sampleRateIndex) {
case 0:
res = 44100;
break;
case 1:
res = 48000;
break;
case 2:
res = 32000;
break;
default:
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[MPEG-1/2 Audio] Samplerate index not valid\n"));
return 0;
}
/*reserved or MPEG-1*/
if (version & 1) return res;
/*MPEG-2*/
res /= 2;
/*MPEG-2.5*/
if (version == 0) res /= 2;
return res;
}
GF_EXPORT
u16 gf_mp3_window_size(u32 hdr)
{
u8 version = gf_mp3_version(hdr);
u8 layer = gf_mp3_layer(hdr);
if (layer == 3) {
if (version == 3) return 1152;
return 576;
}
if (layer == 2) return 1152;
return 384;
}
GF_EXPORT
u8 gf_mp3_object_type_indication(u32 hdr)
{
switch (gf_mp3_version(hdr)) {
case 3:
return GPAC_OTI_AUDIO_MPEG1;
case 2:
case 0:
return GPAC_OTI_AUDIO_MPEG2_PART3;
default:
return 0x00;
}
}
/*aligned bitrate parsing with libMAD*/
static
u32 const bitrate_table[5][15] = {
/* MPEG-1 */
{ 0, 32000, 64000, 96000, 128000, 160000, 192000, 224000, /* Layer I */
256000, 288000, 320000, 352000, 384000, 416000, 448000
},
{ 0, 32000, 48000, 56000, 64000, 80000, 96000, 112000, /* Layer II */
128000, 160000, 192000, 224000, 256000, 320000, 384000
},
{ 0, 32000, 40000, 48000, 56000, 64000, 80000, 96000, /* Layer III */
112000, 128000, 160000, 192000, 224000, 256000, 320000
},
/* MPEG-2 LSF */
{ 0, 32000, 48000, 56000, 64000, 80000, 96000, 112000, /* Layer I */
128000, 144000, 160000, 176000, 192000, 224000, 256000
},
{ 0, 8000, 16000, 24000, 32000, 40000, 48000, 56000, /* Layers */
64000, 80000, 96000, 112000, 128000, 144000, 160000
} /* II & III */
};
u32 gf_mp3_bit_rate(u32 hdr)
{
u8 version = gf_mp3_version(hdr);
u8 layer = gf_mp3_layer(hdr);
u8 bitRateIndex = (hdr >> 12) & 0xF;
if (bitRateIndex == 15) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[MPEG-1/2 Audio] Bitrate index not valid\n"));
return 0;
}
/*MPEG-1*/
if (version & 1)
return bitrate_table[layer - 1][bitRateIndex];
/*MPEG-2/2.5*/
else
return bitrate_table[3 + (layer >> 1)][bitRateIndex];
}
GF_EXPORT
u16 gf_mp3_frame_size(u32 hdr)
{
u8 version = gf_mp3_version(hdr);
u8 layer = gf_mp3_layer(hdr);
u32 pad = ( (hdr >> 9) & 0x1) ? 1 : 0;
u32 bitrate = gf_mp3_bit_rate(hdr);
u32 samplerate = gf_mp3_sampling_rate(hdr);
u32 frameSize = 0;
if (!samplerate || !bitrate) return 0;
if (layer==1) {
frameSize = (( 12 * bitrate / samplerate) + pad) * 4;
} else {
u32 slots_per_frame = 144;
if ((layer == 3) && !(version & 1)) slots_per_frame = 72;
frameSize = (slots_per_frame * bitrate / samplerate) + pad;
}
return (u16) frameSize;
}
GF_EXPORT
u32 gf_mp3_get_next_header(FILE* in)
{
u8 b, state = 0;
u32 dropped = 0;
unsigned char bytes[4];
bytes[0] = bytes[1] = bytes[2] = bytes[3] = 0;
while (1) {
if (fread(&b, 1, 1, in) == 0) return 0;
if (state==3) {
bytes[state] = b;
return GF_4CC(bytes[0], bytes[1], bytes[2], bytes[3]);
}
if (state==2) {
if (((b & 0xF0) == 0) || ((b & 0xF0) == 0xF0) || ((b & 0x0C) == 0x0C)) {
if (bytes[1] == 0xFF) state = 1;
else state = 0;
} else {
bytes[state] = b;
state = 3;
}
}
if (state==1) {
if (((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {
bytes[state] = b;
state = 2;
} else {
state = 0;
}
}
if (state==0) {
if (b == 0xFF) {
bytes[state] = b;
state = 1;
} else {
if ((dropped == 0) && ((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {
bytes[0] = (u8) 0xFF;
bytes[1] = b;
state = 2;
} else {
dropped++;
}
}
}
}
return 0;
}
GF_EXPORT
u32 gf_mp3_get_next_header_mem(const char *buffer, u32 size, u32 *pos)
{
u32 cur;
u8 b, state = 0;
u32 dropped = 0;
unsigned char bytes[4];
bytes[0] = bytes[1] = bytes[2] = bytes[3] = 0;
cur = 0;
*pos = 0;
while (cur<size) {
b = (u8) buffer[cur];
cur++;
if (state==3) {
u32 val;
bytes[state] = b;
val = GF_4CC(bytes[0], bytes[1], bytes[2], bytes[3]);
if (gf_mp3_frame_size(val)) {
*pos = dropped;
return val;
}
state = 0;
dropped = cur;
}
if (state==2) {
if (((b & 0xF0) == 0) || ((b & 0xF0) == 0xF0) || ((b & 0x0C) == 0x0C)) {
if (bytes[1] == 0xFF) {
state = 1;
dropped+=1;
} else {
state = 0;
dropped = cur;
}
} else {
bytes[state] = b;
state = 3;
}
}
if (state==1) {
if (((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {
bytes[state] = b;
state = 2;
} else {
state = 0;
dropped = cur;
}
}
if (state==0) {
if (b == 0xFF) {
bytes[state] = b;
state = 1;
} else {
dropped++;
}
}
}
return 0;
}
#endif /*GPAC_DISABLE_AV_PARSERS*/
GF_EXPORT
Bool gf_avc_is_rext_profile(u8 profile_idc)
{
switch (profile_idc) {
case 100:
case 110:
case 122:
case 244:
case 44:
case 83:
case 86:
case 118:
case 128:
case 138:
case 139:
case 134:
case 135:
return GF_TRUE;
default:
return GF_FALSE;
}
}
GF_EXPORT
const char *gf_avc_get_profile_name(u8 video_prof)
{
switch (video_prof) {
case 0x42:
return "Baseline";
case 0x4D:
return "Main";
case 0x53:
return "Scalable Baseline";
case 0x56:
return "Scalable High";
case 0x58:
return "Extended";
case 0x64:
return "High";
case 0x6E:
return "High 10";
case 0x7A:
return "High 4:2:2";
case 0x90:
case 0xF4:
return "High 4:4:4";
default:
return "Unknown";
}
}
GF_EXPORT
const char *gf_hevc_get_profile_name(u8 video_prof)
{
switch (video_prof) {
case 0x01:
return "Main";
case 0x02:
return "Main 10";
case 0x03:
return "Main Still Picture";
default:
return "Unknown";
}
}
GF_EXPORT
const char *gf_avc_hevc_get_chroma_format_name(u8 chroma_format)
{
switch (chroma_format) {
case 1:
return "YUV 4:2:0";
case 2:
return "YUV 4:2:2";
case 3:
return "YUV 4:4:4";
default:
return "Unknown";
}
}
#ifndef GPAC_DISABLE_AV_PARSERS
static u8 avc_golomb_bits[256] = {
8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0
};
static u32 bs_get_ue(GF_BitStream *bs)
{
u8 coded;
u32 bits = 0, read = 0;
while (1) {
read = gf_bs_peek_bits(bs, 8, 0);
if (read) break;
//check whether we still have bits once the peek is done since we may have less than 8 bits available
if (!gf_bs_available(bs)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AVC/HEVC] Not enough bits in bitstream !!\n"));
return 0;
}
gf_bs_read_int(bs, 8);
bits += 8;
}
coded = avc_golomb_bits[read];
gf_bs_read_int(bs, coded);
bits += coded;
return gf_bs_read_int(bs, bits + 1) - 1;
}
static s32 bs_get_se(GF_BitStream *bs)
{
u32 v = bs_get_ue(bs);
if ((v & 0x1) == 0) return (s32) (0 - (v>>1));
return (v + 1) >> 1;
}
u32 gf_media_nalu_is_start_code(GF_BitStream *bs)
{
u8 s1, s2, s3, s4;
Bool is_sc = 0;
u64 pos = gf_bs_get_position(bs);
s1 = gf_bs_read_int(bs, 8);
s2 = gf_bs_read_int(bs, 8);
if (!s1 && !s2) {
s3 = gf_bs_read_int(bs, 8);
if (s3==0x01) is_sc = 3;
else if (!s3) {
s4 = gf_bs_read_int(bs, 8);
if (s4==0x01) is_sc = 4;
}
}
gf_bs_seek(bs, pos+is_sc);
return is_sc;
}
/*read that amount of data at each IO access rather than fetching byte by byte...*/
#define AVC_CACHE_SIZE 4096
static u32 gf_media_nalu_locate_start_code_bs(GF_BitStream *bs, Bool locate_trailing)
{
u32 v, bpos, nb_cons_zeros=0;
char avc_cache[AVC_CACHE_SIZE];
u64 end, cache_start, load_size;
u64 start = gf_bs_get_position(bs);
if (start<3) return 0;
load_size = 0;
bpos = 0;
cache_start = 0;
end = 0;
v = 0xffffffff;
while (!end) {
/*refill cache*/
if (bpos == (u32) load_size) {
if (!gf_bs_available(bs)) break;
load_size = gf_bs_available(bs);
if (load_size>AVC_CACHE_SIZE) load_size=AVC_CACHE_SIZE;
bpos = 0;
cache_start = gf_bs_get_position(bs);
gf_bs_read_data(bs, avc_cache, (u32) load_size);
}
v = ( (v<<8) & 0xFFFFFF00) | ((u32) avc_cache[bpos]);
bpos++;
if (locate_trailing) {
if ( (v & 0x000000FF) == 0) nb_cons_zeros++;
else nb_cons_zeros = 0;
}
if (v == 0x00000001) end = cache_start+bpos-4;
else if ( (v & 0x00FFFFFF) == 0x00000001) end = cache_start+bpos-3;
}
gf_bs_seek(bs, start);
if (!end) end = gf_bs_get_size(bs);
if (locate_trailing) {
if (nb_cons_zeros>=3)
return (u32) (end - start - nb_cons_zeros);
}
return (u32) (end-start);
}
GF_EXPORT
u32 gf_media_nalu_next_start_code_bs(GF_BitStream *bs)
{
return gf_media_nalu_locate_start_code_bs(bs, 0);
}
GF_EXPORT
u32 gf_media_nalu_payload_end_bs(GF_BitStream *bs)
{
return gf_media_nalu_locate_start_code_bs(bs, 1);
}
GF_EXPORT
u32 gf_media_nalu_next_start_code(const u8 *data, u32 data_len, u32 *sc_size)
{
u32 v, bpos;
u32 end;
bpos = 0;
end = 0;
v = 0xffffffff;
while (!end) {
/*refill cache*/
if (bpos == (u32) data_len)
break;
v = ( (v<<8) & 0xFFFFFF00) | ((u32) data[bpos]);
bpos++;
if (v == 0x00000001) {
end = bpos-4;
*sc_size = 4;
return end;
}
else if ( (v & 0x00FFFFFF) == 0x00000001) {
end = bpos-3;
*sc_size = 3;
return end;
}
}
if (!end) end = data_len;
return (u32) (end);
}
Bool gf_media_avc_slice_is_intra(AVCState *avc)
{
switch (avc->s_info.slice_type) {
case GF_AVC_TYPE_I:
case GF_AVC_TYPE2_I:
case GF_AVC_TYPE_SI:
case GF_AVC_TYPE2_SI:
return 1;
default:
return 0;
}
}
Bool gf_media_avc_slice_is_IDR(AVCState *avc)
{
if (avc->sei.recovery_point.valid)
{
avc->sei.recovery_point.valid = 0;
return 1;
}
if (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE)
return 0;
return gf_media_avc_slice_is_intra(avc);
}
static const struct {
u32 w, h;
} avc_sar[14] =
{
{ 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 },
{ 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },
{ 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },
{ 64, 33 }, { 160,99 },
};
/*ISO 14496-10 (N11084) E.1.2*/
static void avc_parse_hrd_parameters(GF_BitStream *bs, AVC_HRD *hrd)
{
int i, cpb_cnt_minus1;
cpb_cnt_minus1 = bs_get_ue(bs); /*cpb_cnt_minus1*/
if (cpb_cnt_minus1 > 31)
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] invalid cpb_cnt_minus1 value: %d (expected in [0;31])\n", cpb_cnt_minus1));
gf_bs_read_int(bs, 4); /*bit_rate_scale*/
gf_bs_read_int(bs, 4); /*cpb_size_scale*/
/*for( SchedSelIdx = 0; SchedSelIdx <= cpb_cnt_minus1; SchedSelIdx++ ) {*/
for (i=0; i<=cpb_cnt_minus1; i++) {
bs_get_ue(bs); /*bit_rate_value_minus1[ SchedSelIdx ]*/
bs_get_ue(bs); /*cpb_size_value_minus1[ SchedSelIdx ]*/
gf_bs_read_int(bs, 1); /*cbr_flag[ SchedSelIdx ]*/
}
gf_bs_read_int(bs, 5); /*initial_cpb_removal_delay_length_minus1*/
hrd->cpb_removal_delay_length_minus1 = gf_bs_read_int(bs, 5); /*cpb_removal_delay_length_minus1*/
hrd->dpb_output_delay_length_minus1 = gf_bs_read_int(bs, 5); /*dpb_output_delay_length_minus1*/
hrd->time_offset_length = gf_bs_read_int(bs, 5); /*time_offset_length*/
return;
}
/*returns the nal_size without emulation prevention bytes*/
static u32 avc_emulation_bytes_add_count(char *buffer, u32 nal_size)
{
u32 i = 0, emulation_bytes_count = 0;
u8 num_zero = 0;
while (i < nal_size) {
/*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
other than the following sequences shall not occur at any byte-aligned position:
\96 0x00000300
\96 0x00000301
\96 0x00000302
\96 0x00000303"
*/
if (num_zero == 2 && buffer[i] < 0x04) {
/*emulation code found*/
num_zero = 0;
emulation_bytes_count++;
if (!buffer[i])
num_zero = 1;
} else {
if (!buffer[i])
num_zero++;
else
num_zero = 0;
}
i++;
}
return emulation_bytes_count;
}
static u32 avc_add_emulation_bytes(const char *buffer_src, char *buffer_dst, u32 nal_size)
{
u32 i = 0, emulation_bytes_count = 0;
u8 num_zero = 0;
while (i < nal_size) {
/*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
other than the following sequences shall not occur at any byte-aligned position:
0x00000300
0x00000301
0x00000302
0x00000303"
*/
if (num_zero == 2 && (u8)buffer_src[i] < 0x04) {
/*add emulation code*/
num_zero = 0;
buffer_dst[i+emulation_bytes_count] = 0x03;
emulation_bytes_count++;
if (!buffer_src[i])
num_zero = 1;
} else {
if (!buffer_src[i])
num_zero++;
else
num_zero = 0;
}
buffer_dst[i+emulation_bytes_count] = buffer_src[i];
i++;
}
return nal_size+emulation_bytes_count;
}
/*returns the nal_size without emulation prevention bytes*/
static u32 avc_emulation_bytes_remove_count(const char *buffer, u32 nal_size)
{
u32 i = 0, emulation_bytes_count = 0;
u8 num_zero = 0;
while (i < nal_size)
{
/*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
other than the following sequences shall not occur at any byte-aligned position:
\96 0x00000300
\96 0x00000301
\96 0x00000302
\96 0x00000303"
*/
if (num_zero == 2
&& buffer[i] == 0x03
&& i+1 < nal_size /*next byte is readable*/
&& buffer[i+1] < 0x04)
{
/*emulation code found*/
num_zero = 0;
emulation_bytes_count++;
i++;
}
if (!buffer[i])
num_zero++;
else
num_zero = 0;
i++;
}
return emulation_bytes_count;
}
/*nal_size is updated to allow better error detection*/
static u32 avc_remove_emulation_bytes(const char *buffer_src, char *buffer_dst, u32 nal_size)
{
u32 i = 0, emulation_bytes_count = 0;
u8 num_zero = 0;
while (i < nal_size)
{
/*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
other than the following sequences shall not occur at any byte-aligned position:
0x00000300
0x00000301
0x00000302
0x00000303"
*/
if (num_zero == 2
&& buffer_src[i] == 0x03
&& i+1 < nal_size /*next byte is readable*/
&& buffer_src[i+1] < 0x04)
{
/*emulation code found*/
num_zero = 0;
emulation_bytes_count++;
i++;
}
buffer_dst[i-emulation_bytes_count] = buffer_src[i];
if (!buffer_src[i])
num_zero++;
else
num_zero = 0;
i++;
}
return nal_size-emulation_bytes_count;
}
GF_EXPORT
s32 gf_media_avc_read_sps(const char *sps_data, u32 sps_size, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos)
{
AVC_SPS *sps;
u32 ChromaArrayType = 0;
s32 mb_width, mb_height, sps_id = -1;
u32 profile_idc, level_idc, pcomp, i, chroma_format_idc, cl=0, cr=0, ct=0, cb=0, luma_bd, chroma_bd;
u8 separate_colour_plane_flag = 0;
GF_BitStream *bs;
char *sps_data_without_emulation_bytes = NULL;
u32 sps_data_without_emulation_bytes_size = 0;
/*SPS still contains emulation bytes*/
sps_data_without_emulation_bytes = gf_malloc(sps_size*sizeof(char));
sps_data_without_emulation_bytes_size = avc_remove_emulation_bytes(sps_data, sps_data_without_emulation_bytes, sps_size);
bs = gf_bs_new(sps_data_without_emulation_bytes, sps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);
if (!bs) {
sps_id = -1;
goto exit;
}
if (vui_flag_pos) *vui_flag_pos = 0;
/*nal hdr*/ gf_bs_read_int(bs, 8);
profile_idc = gf_bs_read_int(bs, 8);
pcomp = gf_bs_read_int(bs, 8);
/*sanity checks*/
if (pcomp & 0x3)
goto exit;
level_idc = gf_bs_read_int(bs, 8);
/*SubsetSps is used to be sure that AVC SPS are not going to be scratched
by subset SPS. According to the SVC standard, subset SPS can have the same sps_id
than its base layer, but it does not refer to the same SPS. */
sps_id = bs_get_ue(bs) + GF_SVC_SSPS_ID_SHIFT * subseq_sps;
if (sps_id >=32) {
sps_id = -1;
goto exit;
}
if (sps_id < 0) {
sps_id = -1;
goto exit;
}
luma_bd = chroma_bd = 0;
chroma_format_idc = ChromaArrayType = 1;
sps = &avc->sps[sps_id];
sps->state |= subseq_sps ? AVC_SUBSPS_PARSED : AVC_SPS_PARSED;
/*High Profile and SVC*/
switch (profile_idc) {
case 100:
case 110:
case 122:
case 244:
case 44:
/*sanity checks: note1 from 7.4.2.1.1 of iso/iec 14496-10-N11084*/
if (pcomp & 0xE0)
goto exit;
case 83:
case 86:
case 118:
case 128:
chroma_format_idc = bs_get_ue(bs);
ChromaArrayType = chroma_format_idc;
if (chroma_format_idc == 3) {
separate_colour_plane_flag = gf_bs_read_int(bs, 1);
/*
Depending on the value of separate_colour_plane_flag, the value of the variable ChromaArrayType is assigned as follows.
\96 If separate_colour_plane_flag is equal to 0, ChromaArrayType is set equal to chroma_format_idc.
\96 Otherwise (separate_colour_plane_flag is equal to 1), ChromaArrayType is set equal to 0.
*/
if (separate_colour_plane_flag) ChromaArrayType = 0;
}
luma_bd = bs_get_ue(bs);
chroma_bd = bs_get_ue(bs);
/*qpprime_y_zero_transform_bypass_flag = */ gf_bs_read_int(bs, 1);
/*seq_scaling_matrix_present_flag*/
if (gf_bs_read_int(bs, 1)) {
u32 k;
for (k=0; k<8; k++) {
if (gf_bs_read_int(bs, 1)) {
u32 z, last = 8, next = 8;
u32 sl = k<6 ? 16 : 64;
for (z=0; z<sl; z++) {
if (next) {
s32 delta = bs_get_se(bs);
next = (last + delta + 256) % 256;
}
last = next ? next : last;
}
}
}
}
break;
}
sps->profile_idc = profile_idc;
sps->level_idc = level_idc;
sps->prof_compat = pcomp;
sps->log2_max_frame_num = bs_get_ue(bs) + 4;
sps->poc_type = bs_get_ue(bs);
sps->chroma_format = chroma_format_idc;
sps->luma_bit_depth_m8 = luma_bd;
sps->chroma_bit_depth_m8 = chroma_bd;
if (sps->poc_type == 0) {
sps->log2_max_poc_lsb = bs_get_ue(bs) + 4;
} else if(sps->poc_type == 1) {
sps->delta_pic_order_always_zero_flag = gf_bs_read_int(bs, 1);
sps->offset_for_non_ref_pic = bs_get_se(bs);
sps->offset_for_top_to_bottom_field = bs_get_se(bs);
sps->poc_cycle_length = bs_get_ue(bs);
for(i=0; i<sps->poc_cycle_length; i++) sps->offset_for_ref_frame[i] = bs_get_se(bs);
}
if (sps->poc_type > 2) {
sps_id = -1;
goto exit;
}
sps->max_num_ref_frames = bs_get_ue(bs);
sps->gaps_in_frame_num_value_allowed_flag = gf_bs_read_int(bs, 1);
mb_width = bs_get_ue(bs) + 1;
mb_height= bs_get_ue(bs) + 1;
sps->frame_mbs_only_flag = gf_bs_read_int(bs, 1);
sps->width = mb_width * 16;
sps->height = (2-sps->frame_mbs_only_flag) * mb_height * 16;
if (!sps->frame_mbs_only_flag) sps->mb_adaptive_frame_field_flag = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 1); /*direct_8x8_inference_flag*/
if (gf_bs_read_int(bs, 1)) { /*crop*/
int CropUnitX, CropUnitY, SubWidthC = -1, SubHeightC = -1;
if (chroma_format_idc == 1) {
SubWidthC = 2, SubHeightC = 2;
} else if (chroma_format_idc == 2) {
SubWidthC = 2, SubHeightC = 1;
} else if ((chroma_format_idc == 3) && (separate_colour_plane_flag == 0)) {
SubWidthC = 1, SubHeightC = 1;
}
if (ChromaArrayType == 0) {
assert(SubWidthC==-1);
CropUnitX = 1;
CropUnitY = 2-sps->frame_mbs_only_flag;
} else {
CropUnitX = SubWidthC;
CropUnitY = SubHeightC * (2-sps->frame_mbs_only_flag);
}
cl = bs_get_ue(bs); /*crop_left*/
cr = bs_get_ue(bs); /*crop_right*/
ct = bs_get_ue(bs); /*crop_top*/
cb = bs_get_ue(bs); /*crop_bottom*/
sps->width -= CropUnitX * (cl + cr);
sps->height -= CropUnitY * (ct + cb);
cl *= CropUnitX;
cr *= CropUnitX;
ct *= CropUnitY;
cb *= CropUnitY;
}
sps->crop.left = cl;
sps->crop.right = cr;
sps->crop.top = ct;
sps->crop.bottom = cb;
if (vui_flag_pos) {
*vui_flag_pos = (u32) gf_bs_get_bit_offset(bs);
}
/*vui_parameters_present_flag*/
sps->vui_parameters_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui_parameters_present_flag) {
sps->vui.aspect_ratio_info_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.aspect_ratio_info_present_flag) {
s32 aspect_ratio_idc = gf_bs_read_int(bs, 8);
if (aspect_ratio_idc == 255) {
sps->vui.par_num = gf_bs_read_int(bs, 16); /*AR num*/
sps->vui.par_den = gf_bs_read_int(bs, 16); /*AR den*/
} else if (aspect_ratio_idc<14) {
sps->vui.par_num = avc_sar[aspect_ratio_idc].w;
sps->vui.par_den = avc_sar[aspect_ratio_idc].h;
}
}
sps->vui.overscan_info_present_flag = gf_bs_read_int(bs, 1);
if(sps->vui.overscan_info_present_flag)
gf_bs_read_int(bs, 1); /* overscan_appropriate_flag */
/* default values */
sps->vui.video_format = 5;
sps->vui.colour_primaries = 2;
sps->vui.transfer_characteristics = 2;
sps->vui.matrix_coefficients = 2;
/* now read values if possible */
sps->vui.video_signal_type_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.video_signal_type_present_flag) {
sps->vui.video_format = gf_bs_read_int(bs, 3);
sps->vui.video_full_range_flag = gf_bs_read_int(bs, 1);
sps->vui.colour_description_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.colour_description_present_flag) {
sps->vui.colour_primaries = gf_bs_read_int(bs, 8);
sps->vui.transfer_characteristics = gf_bs_read_int(bs, 8);
sps->vui.matrix_coefficients = gf_bs_read_int(bs, 8);
}
}
if (gf_bs_read_int(bs, 1)) { /* chroma_location_info_present_flag */
bs_get_ue(bs); /* chroma_sample_location_type_top_field */
bs_get_ue(bs); /* chroma_sample_location_type_bottom_field */
}
sps->vui.timing_info_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.timing_info_present_flag) {
sps->vui.num_units_in_tick = gf_bs_read_int(bs, 32);
sps->vui.time_scale = gf_bs_read_int(bs, 32);
sps->vui.fixed_frame_rate_flag = gf_bs_read_int(bs, 1);
}
sps->vui.nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.nal_hrd_parameters_present_flag)
avc_parse_hrd_parameters(bs, &sps->vui.hrd);
sps->vui.vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.vcl_hrd_parameters_present_flag)
avc_parse_hrd_parameters(bs, &sps->vui.hrd);
if (sps->vui.nal_hrd_parameters_present_flag || sps->vui.vcl_hrd_parameters_present_flag)
sps->vui.low_delay_hrd_flag = gf_bs_read_int(bs, 1);
sps->vui.pic_struct_present_flag = gf_bs_read_int(bs, 1);
}
/*end of seq_parameter_set_data*/
if (subseq_sps) {
if ((profile_idc==83) || (profile_idc==86)) {
u8 extended_spatial_scalability_idc;
/*parsing seq_parameter_set_svc_extension*/
/*inter_layer_deblocking_filter_control_present_flag=*/ gf_bs_read_int(bs, 1);
extended_spatial_scalability_idc = gf_bs_read_int(bs, 2);
if (ChromaArrayType == 1 || ChromaArrayType == 2) {
/*chroma_phase_x_plus1_flag*/ gf_bs_read_int(bs, 1);
}
if( ChromaArrayType == 1 ) {
/*chroma_phase_y_plus1*/ gf_bs_read_int(bs, 2);
}
if (extended_spatial_scalability_idc == 1) {
if( ChromaArrayType > 0 ) {
/*seq_ref_layer_chroma_phase_x_plus1_flag*/gf_bs_read_int(bs, 1);
/*seq_ref_layer_chroma_phase_y_plus1*/gf_bs_read_int(bs, 2);
}
/*seq_scaled_ref_layer_left_offset*/ bs_get_se(bs);
/*seq_scaled_ref_layer_top_offset*/bs_get_se(bs);
/*seq_scaled_ref_layer_right_offset*/bs_get_se(bs);
/*seq_scaled_ref_layer_bottom_offset*/bs_get_se(bs);
}
if (/*seq_tcoeff_level_prediction_flag*/gf_bs_read_int(bs, 1)) {
/*adaptive_tcoeff_level_prediction_flag*/ gf_bs_read_int(bs, 1);
}
/*slice_header_restriction_flag*/gf_bs_read_int(bs, 1);
/*svc_vui_parameters_present*/
if (gf_bs_read_int(bs, 1)) {
u32 i, vui_ext_num_entries_minus1;
vui_ext_num_entries_minus1 = bs_get_ue(bs);
for (i=0; i <= vui_ext_num_entries_minus1; i++) {
u8 vui_ext_nal_hrd_parameters_present_flag, vui_ext_vcl_hrd_parameters_present_flag, vui_ext_timing_info_present_flag;
/*u8 vui_ext_dependency_id =*/ gf_bs_read_int(bs, 3);
/*u8 vui_ext_quality_id =*/ gf_bs_read_int(bs, 4);
/*u8 vui_ext_temporal_id =*/ gf_bs_read_int(bs, 3);
vui_ext_timing_info_present_flag = gf_bs_read_int(bs, 1);
if (vui_ext_timing_info_present_flag) {
/*u32 vui_ext_num_units_in_tick = */gf_bs_read_int(bs, 32);
/*u32 vui_ext_time_scale = */gf_bs_read_int(bs, 32);
/*u8 vui_ext_fixed_frame_rate_flag = */gf_bs_read_int(bs, 1);
}
vui_ext_nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (vui_ext_nal_hrd_parameters_present_flag) {
//hrd_parameters( )
}
vui_ext_vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (vui_ext_vcl_hrd_parameters_present_flag) {
//hrd_parameters( )
}
if ( vui_ext_nal_hrd_parameters_present_flag || vui_ext_vcl_hrd_parameters_present_flag) {
/*vui_ext_low_delay_hrd_flag*/gf_bs_read_int(bs, 1);
}
/*vui_ext_pic_struct_present_flag*/gf_bs_read_int(bs, 1);
}
}
}
else if ((profile_idc==118) || (profile_idc==128)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] MVC not supported - skipping parsing end of Subset SPS\n"));
goto exit;
}
if (gf_bs_read_int(bs, 1)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] skipping parsing end of Subset SPS (additional_extension2)\n"));
goto exit;
}
}
exit:
gf_bs_del(bs);
gf_free(sps_data_without_emulation_bytes);
return sps_id;
}
GF_EXPORT
s32 gf_media_avc_read_pps(const char *pps_data, u32 pps_size, AVCState *avc)
{
GF_BitStream *bs;
char *pps_data_without_emulation_bytes = NULL;
u32 pps_data_without_emulation_bytes_size = 0;
s32 pps_id;
AVC_PPS *pps;
/*PPS still contains emulation bytes*/
pps_data_without_emulation_bytes = gf_malloc(pps_size*sizeof(char));
pps_data_without_emulation_bytes_size = avc_remove_emulation_bytes(pps_data, pps_data_without_emulation_bytes, pps_size);
bs = gf_bs_new(pps_data_without_emulation_bytes, pps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);
if (!bs) {
pps_id = -1;
goto exit;
}
/*nal hdr*/gf_bs_read_u8(bs);
pps_id = bs_get_ue(bs);
if (pps_id>=255) {
pps_id = -1;
goto exit;
}
pps = &avc->pps[pps_id];
pps->id = pps_id;
if (!pps->status) pps->status = 1;
pps->sps_id = bs_get_ue(bs);
if (pps->sps_id >= 32) {
pps->sps_id = 0;
pps_id = -1;
goto exit;
}
/*sps_id may be refer to regular SPS or subseq sps, depending on the coded slice refering to the pps*/
if (!avc->sps[pps->sps_id].state && !avc->sps[pps->sps_id + GF_SVC_SSPS_ID_SHIFT].state) {
pps_id = -1;
goto exit;
}
avc->sps_active_idx = pps->sps_id; /*set active sps*/
pps->entropy_coding_mode_flag = gf_bs_read_int(bs, 1);
pps->pic_order_present= gf_bs_read_int(bs, 1);
pps->slice_group_count= bs_get_ue(bs) + 1;
if (pps->slice_group_count > 1 ) /*pps->mb_slice_group_map_type = */bs_get_ue(bs);
/*pps->ref_count[0]= */bs_get_ue(bs) /*+ 1*/;
/*pps->ref_count[1]= */bs_get_ue(bs) /*+ 1*/;
/*
if ((pps->ref_count[0] > 32) || (pps->ref_count[1] > 32)) goto exit;
*/
/*pps->weighted_pred = */gf_bs_read_int(bs, 1);
/*pps->weighted_bipred_idc = */gf_bs_read_int(bs, 2);
/*pps->init_qp = */bs_get_se(bs) /*+ 26*/;
/*pps->init_qs= */bs_get_se(bs) /*+ 26*/;
/*pps->chroma_qp_index_offset = */bs_get_se(bs);
/*pps->deblocking_filter_parameters_present = */gf_bs_read_int(bs, 1);
/*pps->constrained_intra_pred = */gf_bs_read_int(bs, 1);
pps->redundant_pic_cnt_present = gf_bs_read_int(bs, 1);
exit:
gf_bs_del(bs);
gf_free(pps_data_without_emulation_bytes);
return pps_id;
}
s32 gf_media_avc_read_sps_ext(const char *spse_data, u32 spse_size)
{
GF_BitStream *bs;
char *spse_data_without_emulation_bytes = NULL;
u32 spse_data_without_emulation_bytes_size = 0;
s32 sps_id;
/*PPS still contains emulation bytes*/
spse_data_without_emulation_bytes = gf_malloc(spse_size*sizeof(char));
spse_data_without_emulation_bytes_size = avc_remove_emulation_bytes(spse_data, spse_data_without_emulation_bytes, spse_size);
bs = gf_bs_new(spse_data_without_emulation_bytes, spse_data_without_emulation_bytes_size, GF_BITSTREAM_READ);
/*nal header*/gf_bs_read_u8(bs);
sps_id = bs_get_ue(bs);
gf_bs_del(bs);
gf_free(spse_data_without_emulation_bytes);
return sps_id;
}
static s32 SVC_ReadNal_header_extension(GF_BitStream *bs, SVC_NALUHeader *NalHeader)
{
gf_bs_read_int(bs, 1); //reserved_one_bits
NalHeader->idr_pic_flag = gf_bs_read_int(bs, 1); //idr_flag
NalHeader->priority_id = gf_bs_read_int(bs, 6); //priority_id
gf_bs_read_int(bs, 1); //no_inter_layer_pred_flag
NalHeader->dependency_id = gf_bs_read_int(bs, 3); //DependencyId
NalHeader->quality_id = gf_bs_read_int(bs, 4); //quality_id
NalHeader->temporal_id = gf_bs_read_int(bs, 3); //temporal_id
gf_bs_read_int(bs, 1); //use_ref_base_pic_flag
gf_bs_read_int(bs, 1); //discardable_flag
gf_bs_read_int(bs, 1); //output_flag
gf_bs_read_int(bs, 2); //reserved_three_2bits
return 1;
}
static s32 avc_parse_slice(GF_BitStream *bs, AVCState *avc, Bool svc_idr_flag, AVCSliceInfo *si)
{
s32 pps_id;
/*s->current_picture.reference= h->nal_ref_idc != 0;*/
/*first_mb_in_slice = */bs_get_ue(bs);
si->slice_type = bs_get_ue(bs);
if (si->slice_type > 9) return -1;
pps_id = bs_get_ue(bs);
if (pps_id>255) return -1;
si->pps = &avc->pps[pps_id];
if (!si->pps->slice_group_count) return -2;
si->sps = &avc->sps[si->pps->sps_id];
if (!si->sps->log2_max_frame_num) return -2;
avc->sps_active_idx = si->pps->sps_id;
si->frame_num = gf_bs_read_int(bs, si->sps->log2_max_frame_num);
si->field_pic_flag = 0;
si->bottom_field_flag = 0;
if (!si->sps->frame_mbs_only_flag) {
si->field_pic_flag = gf_bs_read_int(bs, 1);
if (si->field_pic_flag)
si->bottom_field_flag = gf_bs_read_int(bs, 1);
}
if ((si->nal_unit_type==GF_AVC_NALU_IDR_SLICE) || svc_idr_flag)
si->idr_pic_id = bs_get_ue(bs);
if (si->sps->poc_type==0) {
si->poc_lsb = gf_bs_read_int(bs, si->sps->log2_max_poc_lsb);
if (si->pps->pic_order_present && !si->field_pic_flag) {
si->delta_poc_bottom = bs_get_se(bs);
}
} else if ((si->sps->poc_type==1) && !si->sps->delta_pic_order_always_zero_flag) {
si->delta_poc[0] = bs_get_se(bs);
if ((si->pps->pic_order_present==1) && !si->field_pic_flag)
si->delta_poc[1] = bs_get_se(bs);
}
if (si->pps->redundant_pic_cnt_present) {
si->redundant_pic_cnt = bs_get_ue(bs);
}
return 0;
}
static s32 svc_parse_slice(GF_BitStream *bs, AVCState *avc, AVCSliceInfo *si)
{
s32 pps_id;
/*s->current_picture.reference= h->nal_ref_idc != 0;*/
/*first_mb_in_slice = */bs_get_ue(bs);
si->slice_type = bs_get_ue(bs);
if (si->slice_type > 9) return -1;
pps_id = bs_get_ue(bs);
if (pps_id>255)
return -1;
si->pps = &avc->pps[pps_id];
si->pps->id = pps_id;
if (!si->pps->slice_group_count)
return -2;
si->sps = &avc->sps[si->pps->sps_id + GF_SVC_SSPS_ID_SHIFT];
if (!si->sps->log2_max_frame_num)
return -2;
si->frame_num = gf_bs_read_int(bs, si->sps->log2_max_frame_num);
si->field_pic_flag = 0;
if (si->sps->frame_mbs_only_flag) {
/*s->picture_structure= PICT_FRAME;*/
} else {
si->field_pic_flag = gf_bs_read_int(bs, 1);
if (si->field_pic_flag) si->bottom_field_flag = gf_bs_read_int(bs, 1);
}
if (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE || si ->NalHeader.idr_pic_flag)
si->idr_pic_id = bs_get_ue(bs);
if (si->sps->poc_type==0) {
si->poc_lsb = gf_bs_read_int(bs, si->sps->log2_max_poc_lsb);
if (si->pps->pic_order_present && !si->field_pic_flag) {
si->delta_poc_bottom = bs_get_se(bs);
}
} else if ((si->sps->poc_type==1) && !si->sps->delta_pic_order_always_zero_flag) {
si->delta_poc[0] = bs_get_se(bs);
if ((si->pps->pic_order_present==1) && !si->field_pic_flag)
si->delta_poc[1] = bs_get_se(bs);
}
if (si->pps->redundant_pic_cnt_present) {
si->redundant_pic_cnt = bs_get_ue(bs);
}
return 0;
}
static s32 avc_parse_recovery_point_sei(GF_BitStream *bs, AVCState *avc)
{
AVCSeiRecoveryPoint *rp = &avc->sei.recovery_point;
rp->frame_cnt = bs_get_ue(bs);
rp->exact_match_flag = gf_bs_read_int(bs, 1);
rp->broken_link_flag = gf_bs_read_int(bs, 1);
rp->changing_slice_group_idc = gf_bs_read_int(bs, 2);
rp->valid = 1;
return 0;
}
/*for interpretation see ISO 14496-10 N.11084, table D-1*/
static s32 avc_parse_pic_timing_sei(GF_BitStream *bs, AVCState *avc)
{
int i;
int sps_id = avc->sps_active_idx;
const char NumClockTS[] = {1, 1, 1, 2, 2, 3, 3, 2, 3};
AVCSeiPicTiming *pt = &avc->sei.pic_timing;
if (sps_id < 0) {
/*sps_active_idx equals -1 when no sps has been detected. In this case SEI should not be decoded.*/
assert(0);
return 1;
}
if (avc->sps[sps_id].vui.nal_hrd_parameters_present_flag || avc->sps[sps_id].vui.vcl_hrd_parameters_present_flag) { /*CpbDpbDelaysPresentFlag, see 14496-10(2003) E.11*/
gf_bs_read_int(bs, 1+avc->sps[sps_id].vui.hrd.cpb_removal_delay_length_minus1); /*cpb_removal_delay*/
gf_bs_read_int(bs, 1+avc->sps[sps_id].vui.hrd.dpb_output_delay_length_minus1); /*dpb_output_delay*/
}
/*ISO 14496-10 (2003), D.8.2: we need to get pic_struct in order to know if we display top field first or bottom field first*/
if (avc->sps[sps_id].vui.pic_struct_present_flag) {
pt->pic_struct = gf_bs_read_int(bs, 4);
if (pt->pic_struct > 8) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[avc-h264] invalid pic_struct value %d\n", pt->pic_struct));
return 1;
}
for (i=0; i<NumClockTS[pt->pic_struct]; i++) {
if (gf_bs_read_int(bs, 1)) {/*clock_timestamp_flag[i]*/
Bool full_timestamp_flag;
gf_bs_read_int(bs, 2); /*ct_type*/
gf_bs_read_int(bs, 1); /*nuit_field_based_flag*/
gf_bs_read_int(bs, 5); /*counting_type*/
full_timestamp_flag = gf_bs_read_int(bs, 1);/*full_timestamp_flag*/
gf_bs_read_int(bs, 1); /*discontinuity_flag*/
gf_bs_read_int(bs, 1); /*cnt_dropped_flag*/
gf_bs_read_int(bs, 8); /*n_frames*/
if (full_timestamp_flag) {
gf_bs_read_int(bs, 6); /*seconds_value*/
gf_bs_read_int(bs, 6); /*minutes_value*/
gf_bs_read_int(bs, 5); /*hours_value*/
} else {
if (gf_bs_read_int(bs, 1)) { /*seconds_flag*/
gf_bs_read_int(bs, 6); /*seconds_value*/
if (gf_bs_read_int(bs, 1)) { /*minutes_flag*/
gf_bs_read_int(bs, 6); /*minutes_value*/
if (gf_bs_read_int(bs, 1)) { /*hours_flag*/
gf_bs_read_int(bs, 5); /*hours_value*/
}
}
}
if (avc->sps[sps_id].vui.hrd.time_offset_length > 0)
gf_bs_read_int(bs, avc->sps[sps_id].vui.hrd.time_offset_length); /*time_offset*/
}
}
}
}
return 0;
}
static void avc_compute_poc(AVCSliceInfo *si)
{
enum {
AVC_PIC_FRAME,
AVC_PIC_FIELD_TOP,
AVC_PIC_FIELD_BOTTOM,
} pic_type;
s32 field_poc[2] = {0,0};
s32 max_frame_num = 1 << (si->sps->log2_max_frame_num);
/* picture type */
if (si->sps->frame_mbs_only_flag || !si->field_pic_flag) pic_type = AVC_PIC_FRAME;
else if (si->bottom_field_flag) pic_type = AVC_PIC_FIELD_BOTTOM;
else pic_type = AVC_PIC_FIELD_TOP;
/* frame_num_offset */
if (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) {
si->poc_lsb_prev = 0;
si->poc_msb_prev = 0;
si->frame_num_offset = 0;
} else {
if (si->frame_num < si->frame_num_prev)
si->frame_num_offset = si->frame_num_offset_prev + max_frame_num;
else
si->frame_num_offset = si->frame_num_offset_prev;
}
/*ISO 14496-10 N.11084 8.2.1.1*/
if (si->sps->poc_type==0)
{
const u32 max_poc_lsb = 1 << (si->sps->log2_max_poc_lsb);
/*ISO 14496-10 N.11084 eq (8-3)*/
if ((si->poc_lsb < si->poc_lsb_prev) &&
(si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2) )
si->poc_msb = si->poc_msb_prev + max_poc_lsb;
else if ((si->poc_lsb > si->poc_lsb_prev) &&
(si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))
si->poc_msb = si->poc_msb_prev - max_poc_lsb;
else
si->poc_msb = si->poc_msb_prev;
/*ISO 14496-10 N.11084 eq (8-4)*/
if (pic_type != AVC_PIC_FIELD_BOTTOM)
field_poc[0] = si->poc_msb + si->poc_lsb;
/*ISO 14496-10 N.11084 eq (8-5)*/
if (pic_type != AVC_PIC_FIELD_TOP) {
if (!si->field_pic_flag)
field_poc[1] = field_poc[0] + si->delta_poc_bottom;
else
field_poc[1] = si->poc_msb + si->poc_lsb;
}
}
/*ISO 14496-10 N.11084 8.2.1.2*/
else if (si->sps->poc_type==1)
{
u32 i;
s32 abs_frame_num, expected_delta_per_poc_cycle, expected_poc;
if (si->sps->poc_cycle_length)
abs_frame_num = si->frame_num_offset + si->frame_num;
else
abs_frame_num = 0;
if (!si->nal_ref_idc && (abs_frame_num > 0)) abs_frame_num--;
expected_delta_per_poc_cycle = 0;
for (i=0; i < si->sps->poc_cycle_length; i++)
expected_delta_per_poc_cycle += si->sps->offset_for_ref_frame[i];
if (abs_frame_num > 0) {
const u32 poc_cycle_cnt = ( abs_frame_num - 1 ) / si->sps->poc_cycle_length;
const u32 frame_num_in_poc_cycle = ( abs_frame_num - 1 ) % si->sps->poc_cycle_length;
expected_poc = poc_cycle_cnt * expected_delta_per_poc_cycle;
for (i = 0; i<=frame_num_in_poc_cycle; i++)
expected_poc += si->sps->offset_for_ref_frame[i];
} else {
expected_poc = 0;
}
if (!si->nal_ref_idc) expected_poc += si->sps->offset_for_non_ref_pic;
field_poc[0] = expected_poc + si->delta_poc[0];
field_poc[1] = field_poc[0] + si->sps->offset_for_top_to_bottom_field;
if (pic_type == AVC_PIC_FRAME) field_poc[1] += si->delta_poc[1];
}
/*ISO 14496-10 N.11084 8.2.1.3*/
else if (si->sps->poc_type== 2)
{
int poc;
if (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) {
poc = 0;
} else {
const int abs_frame_num = si->frame_num_offset + si->frame_num;
poc = 2 * abs_frame_num;
if (!si->nal_ref_idc) poc -= 1;
}
field_poc[0] = poc;
field_poc[1] = poc;
}
/*ISO 14496-10 N.11084 eq (8-1)*/
if (pic_type == AVC_PIC_FRAME)
si->poc = MIN(field_poc[0], field_poc[1] );
else if (pic_type == AVC_PIC_FIELD_TOP)
si->poc = field_poc[0];
else
si->poc = field_poc[1];
}
GF_EXPORT
s32 gf_media_avc_parse_nalu(GF_BitStream *bs, u32 nal_hdr, AVCState *avc)
{
u8 idr_flag;
s32 slice, ret;
AVCSliceInfo n_state;
slice = 0;
memcpy(&n_state, &avc->s_info, sizeof(AVCSliceInfo));
n_state.nal_unit_type = nal_hdr & 0x1F;
n_state.nal_ref_idc = (nal_hdr>>5) & 0x3;
idr_flag = 0;
switch (n_state.nal_unit_type) {
case GF_AVC_NALU_ACCESS_UNIT:
case GF_AVC_NALU_END_OF_SEQ:
case GF_AVC_NALU_END_OF_STREAM:
ret = 1;
break;
case GF_AVC_NALU_SVC_SLICE:
SVC_ReadNal_header_extension(bs, &n_state.NalHeader);
slice = 1;
// slice buffer - read the info and compare.
/*ret = */svc_parse_slice(bs, avc, &n_state);
if (avc->s_info.nal_ref_idc) {
n_state.poc_lsb_prev = avc->s_info.poc_lsb;
n_state.poc_msb_prev = avc->s_info.poc_msb;
}
if (slice)
avc_compute_poc(&n_state);
if (avc->s_info.poc != n_state.poc) {
memcpy(&avc -> s_info, &n_state, sizeof(AVCSliceInfo));
return 1;
}
memcpy(&avc -> s_info, &n_state, sizeof(AVCSliceInfo));
return 0;
case GF_AVC_NALU_SVC_PREFIX_NALU:
SVC_ReadNal_header_extension(bs, &n_state.NalHeader);
return 0;
case GF_AVC_NALU_NON_IDR_SLICE:
case GF_AVC_NALU_DP_A_SLICE:
case GF_AVC_NALU_DP_B_SLICE:
case GF_AVC_NALU_DP_C_SLICE:
case GF_AVC_NALU_IDR_SLICE:
slice = 1;
/* slice buffer - read the info and compare.*/
ret = avc_parse_slice(bs, avc, idr_flag, &n_state);
if (ret<0) return ret;
ret = 0;
if (
((avc->s_info.nal_unit_type > GF_AVC_NALU_IDR_SLICE) || (avc->s_info.nal_unit_type < GF_AVC_NALU_NON_IDR_SLICE))
&& (avc->s_info.nal_unit_type != GF_AVC_NALU_SVC_SLICE)
) {
break;
}
if (avc->s_info.frame_num != n_state.frame_num) {
ret = 1;
break;
}
if (avc->s_info.field_pic_flag != n_state.field_pic_flag) {
ret = 1;
break;
}
if ((avc->s_info.nal_ref_idc != n_state.nal_ref_idc) &&
(!avc->s_info.nal_ref_idc || !n_state.nal_ref_idc)) {
ret = 1;
break;
}
assert(avc->s_info.sps);
if (avc->s_info.sps->poc_type == n_state.sps->poc_type) {
if (!avc->s_info.sps->poc_type) {
if (!n_state.bottom_field_flag && (avc->s_info.poc_lsb != n_state.poc_lsb)) {
ret = 1;
break;
}
if (avc->s_info.delta_poc_bottom != n_state.delta_poc_bottom) {
ret = 1;
break;
}
} else if (avc->s_info.sps->poc_type==1) {
if (avc->s_info.delta_poc[0] != n_state.delta_poc[0]) {
ret =1;
break;
}
if (avc->s_info.delta_poc[1] != n_state.delta_poc[1]) {
ret = 1;
break;
}
}
}
if (n_state.nal_unit_type == GF_AVC_NALU_IDR_SLICE) {
if (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE) { /*IdrPicFlag differs in value*/
ret = 1;
break;
}
else if (avc->s_info.idr_pic_id != n_state.idr_pic_id) { /*both IDR and idr_pic_id differs*/
ret = 1;
break;
}
}
break;
case GF_AVC_NALU_SEQ_PARAM:
case GF_AVC_NALU_PIC_PARAM:
case GF_AVC_NALU_SVC_SUBSEQ_PARAM:
case GF_AVC_NALU_FILLER_DATA:
return 0;
default:
if (avc->s_info.nal_unit_type <= GF_AVC_NALU_IDR_SLICE) ret = 1;
//To detect change of AU when multiple sps and pps in stream
else if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEI && avc -> s_info .nal_unit_type == GF_AVC_NALU_SVC_SLICE)
ret = 1;
else if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEQ_PARAM && avc -> s_info .nal_unit_type == GF_AVC_NALU_SVC_SLICE)
ret = 1;
else
ret = 0;
break;
}
/* save _prev values */
if (ret && avc->s_info.sps) {
n_state.frame_num_offset_prev = avc->s_info.frame_num_offset;
if ((avc->s_info.sps->poc_type != 2) || (avc->s_info.nal_ref_idc != 0))
n_state.frame_num_prev = avc->s_info.frame_num;
if (avc->s_info.nal_ref_idc) {
n_state.poc_lsb_prev = avc->s_info.poc_lsb;
n_state.poc_msb_prev = avc->s_info.poc_msb;
}
}
if (slice) avc_compute_poc(&n_state);
memcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));
return ret;
}
u32 gf_media_avc_reformat_sei(char *buffer, u32 nal_size, AVCState *avc)
{
u32 ptype, psize, hdr, written, var;
u64 start;
char *new_buffer;
GF_BitStream *bs;
char *sei_without_emulation_bytes = NULL;
u32 sei_without_emulation_bytes_size = 0;
hdr = buffer[0];
if ((hdr & 0x1F) != GF_AVC_NALU_SEI) return 0;
/*PPS still contains emulation bytes*/
sei_without_emulation_bytes = gf_malloc(nal_size + 1/*for SEI null string termination*/);
sei_without_emulation_bytes_size = avc_remove_emulation_bytes(buffer, sei_without_emulation_bytes, nal_size);
bs = gf_bs_new(sei_without_emulation_bytes, sei_without_emulation_bytes_size, GF_BITSTREAM_READ);
gf_bs_read_int(bs, 8);
new_buffer = (char*)gf_malloc(sizeof(char)*nal_size);
new_buffer[0] = (char) hdr;
written = 1;
/*parse SEI*/
while (gf_bs_available(bs)) {
Bool do_copy;
ptype = 0;
while (gf_bs_peek_bits(bs, 8, 0)==0xFF) {
gf_bs_read_int(bs, 8);
ptype += 255;
}
ptype += gf_bs_read_int(bs, 8);
psize = 0;
while (gf_bs_peek_bits(bs, 8, 0)==0xFF) {
gf_bs_read_int(bs, 8);
psize += 255;
}
psize += gf_bs_read_int(bs, 8);
start = gf_bs_get_position(bs);
do_copy = 1;
if (start+psize >= nal_size) {
if (written == 1) written = 0;
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] SEI user message type %d size error (%d but %d remain), skiping %sSEI message\n", ptype, psize, nal_size-start, written ? "end of " : ""));
break;
}
switch (ptype) {
/*remove SEI messages forbidden in MP4*/
case 3: /*filler data*/
case 10: /*sub_seq info*/
case 11: /*sub_seq_layer char*/
case 12: /*sub_seq char*/
do_copy = 0;
break;
case 5: /*user unregistered */
{
char prev;
prev = sei_without_emulation_bytes[start+psize+1];
sei_without_emulation_bytes[start+psize+1] = 0;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CODING, ("[avc-h264] SEI user message %s\n", sei_without_emulation_bytes+start+16));
sei_without_emulation_bytes[start+psize+1] = prev;
}
break;
case 6: /*recovery point*/
{
GF_BitStream *rp_bs = gf_bs_new(sei_without_emulation_bytes + start, psize, GF_BITSTREAM_READ);
avc_parse_recovery_point_sei(rp_bs, avc);
gf_bs_del(rp_bs);
}
break;
case 1: /*pic_timing*/
{
GF_BitStream *pt_bs = gf_bs_new(sei_without_emulation_bytes + start, psize, GF_BITSTREAM_READ);
avc_parse_pic_timing_sei(pt_bs, avc);
gf_bs_del(pt_bs);
}
break;
case 0: /*buffering period*/
case 2: /*pan scan rect*/
case 4: /*user registered ITU t35*/
case 7: /*def_rec_pic_marking_repetition*/
case 8: /*spare_pic*/
case 9: /*scene info*/
case 13: /*full frame freeze*/
case 14: /*full frame freeze release*/
case 15: /*full frame snapshot*/
case 16: /*progressive refinement segment start*/
case 17: /*progressive refinement segment end*/
case 18: /*motion constrained slice group*/
break;
default: /*reserved*/
do_copy = 0;
break;
}
if (do_copy) {
var = ptype;
while (var>=255) {
new_buffer[written] = (char) 0xff;
written++;
var-=255;
}
new_buffer[written] = (char) var;
written++;
var = psize;
while (var>=255) {
new_buffer[written] = (char) 0xff;
written++;
var-=255;
}
new_buffer[written] = (char) var;
written++;
memcpy(new_buffer+written, sei_without_emulation_bytes+start, sizeof(char) * psize);
written += psize;
}
gf_bs_skip_bytes(bs, (u64) psize);
gf_bs_align(bs);
if (gf_bs_available(bs)<=2) {
if (gf_bs_peek_bits(bs, 8, 0)==0x80) {
new_buffer[written] = (char) 0x80;
written += 1;
}
break;
}
}
gf_bs_del(bs);
gf_free(sei_without_emulation_bytes);
if (written) {
var = avc_emulation_bytes_add_count(new_buffer, written);
if (var) {
if (written+var<=nal_size) {
written = avc_add_emulation_bytes(new_buffer, buffer, written);
} else {
written = 0;
}
} else {
if (written<=nal_size) {
memcpy(buffer, new_buffer, sizeof(char)*written);
} else {
written = 0;
}
}
}
gf_free(new_buffer);
/*if only hdr written ignore*/
return (written>1) ? written : 0;
}
#ifndef GPAC_DISABLE_ISOM
static u8 avc_get_sar_idx(u32 w, u32 h)
{
u32 i;
for (i=0; i<14; i++) {
if ((avc_sar[i].w==w) && (avc_sar[i].h==h)) return i;
}
return 0xFF;
}
GF_Err gf_media_avc_change_par(GF_AVCConfig *avcc, s32 ar_n, s32 ar_d)
{
GF_BitStream *orig, *mod;
AVCState avc;
u32 i, bit_offset, flag;
s32 idx;
GF_AVCConfigSlot *slc;
orig = NULL;
memset(&avc, 0, sizeof(AVCState));
avc.sps_active_idx = -1;
i=0;
while ((slc = (GF_AVCConfigSlot *)gf_list_enum(avcc->sequenceParameterSets, &i))) {
char *no_emulation_buf = NULL;
u32 no_emulation_buf_size = 0, emulation_bytes = 0;
idx = gf_media_avc_read_sps(slc->data, slc->size, &avc, 0, &bit_offset);
if (idx<0) {
if ( orig )
gf_bs_del(orig);
continue;
}
/*SPS still contains emulation bytes*/
no_emulation_buf = gf_malloc((slc->size-1)*sizeof(char));
no_emulation_buf_size = avc_remove_emulation_bytes(slc->data+1, no_emulation_buf, slc->size-1);
orig = gf_bs_new(no_emulation_buf, no_emulation_buf_size, GF_BITSTREAM_READ);
gf_bs_read_data(orig, no_emulation_buf, no_emulation_buf_size);
gf_bs_seek(orig, 0);
mod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
/*copy over till vui flag*/
assert(bit_offset>=8);
while (bit_offset-8/*bit_offset doesn't take care of the first byte (NALU type)*/) {
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, flag, 1);
bit_offset--;
}
/*check VUI*/
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, 1, 1); /*vui_parameters_present_flag*/
if (flag) {
/*aspect_ratio_info_present_flag*/
if (gf_bs_read_int(orig, 1)) {
s32 aspect_ratio_idc = gf_bs_read_int(orig, 8);
if (aspect_ratio_idc == 255) {
gf_bs_read_int(orig, 16); /*AR num*/
gf_bs_read_int(orig, 16); /*AR den*/
}
}
}
if ((ar_d<0) || (ar_n<0)) {
/*no AR signaled*/
gf_bs_write_int(mod, 0, 1);
} else {
u32 sarx;
gf_bs_write_int(mod, 1, 1);
sarx = avc_get_sar_idx((u32) ar_n, (u32) ar_d);
gf_bs_write_int(mod, sarx, 8);
if (sarx==0xFF) {
gf_bs_write_int(mod, ar_n, 16);
gf_bs_write_int(mod, ar_d, 16);
}
}
/*no VUI in input bitstream, set all vui flags to 0*/
if (!flag) {
gf_bs_write_int(mod, 0, 1); /*overscan_info_present_flag */
gf_bs_write_int(mod, 0, 1); /*video_signal_type_present_flag */
gf_bs_write_int(mod, 0, 1); /*chroma_location_info_present_flag */
gf_bs_write_int(mod, 0, 1); /*timing_info_present_flag*/
gf_bs_write_int(mod, 0, 1); /*nal_hrd_parameters_present*/
gf_bs_write_int(mod, 0, 1); /*vcl_hrd_parameters_present*/
gf_bs_write_int(mod, 0, 1); /*pic_struct_present*/
gf_bs_write_int(mod, 0, 1); /*bitstream_restriction*/
}
/*finally copy over remaining*/
while (gf_bs_bits_available(orig)) {
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, flag, 1);
}
gf_bs_del(orig);
orig = NULL;
gf_free(no_emulation_buf);
/*set anti-emulation*/
gf_bs_get_content(mod, (char **) &no_emulation_buf, &flag);
emulation_bytes = avc_emulation_bytes_add_count(no_emulation_buf, flag);
if (flag+emulation_bytes+1>slc->size)
slc->data = (char*)gf_realloc(slc->data, flag+emulation_bytes+1);
slc->size = avc_add_emulation_bytes(no_emulation_buf, slc->data+1, flag)+1;
gf_bs_del(mod);
gf_free(no_emulation_buf);
}
return GF_OK;
}
#endif
GF_EXPORT
GF_Err gf_avc_get_sps_info(char *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)
{
AVCState avc;
s32 idx;
memset(&avc, 0, sizeof(AVCState));
avc.sps_active_idx = -1;
idx = gf_media_avc_read_sps(sps_data, sps_size, &avc, 0, NULL);
if (idx<0) {
return GF_NON_COMPLIANT_BITSTREAM;
}
if (sps_id) *sps_id = idx;
if (width) *width = avc.sps[idx].width;
if (height) *height = avc.sps[idx].height;
if (par_n) *par_n = avc.sps[idx].vui.par_num ? avc.sps[idx].vui.par_num : (u32) -1;
if (par_d) *par_d = avc.sps[idx].vui.par_den ? avc.sps[idx].vui.par_den : (u32) -1;
return GF_OK;
}
GF_EXPORT
GF_Err gf_avc_get_pps_info(char *pps_data, u32 pps_size, u32 *pps_id, u32 *sps_id)
{
GF_BitStream *bs;
char *pps_data_without_emulation_bytes = NULL;
u32 pps_data_without_emulation_bytes_size = 0;
GF_Err e = GF_OK;
/*PPS still contains emulation bytes*/
pps_data_without_emulation_bytes = gf_malloc(pps_size*sizeof(char));
pps_data_without_emulation_bytes_size = avc_remove_emulation_bytes(pps_data, pps_data_without_emulation_bytes, pps_size);
bs = gf_bs_new(pps_data_without_emulation_bytes, pps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);
if (!bs) {
e = GF_NON_COMPLIANT_BITSTREAM;
goto exit;
}
/*nal hdr*/ gf_bs_read_int(bs, 8);
*pps_id = bs_get_ue(bs);
*sps_id = bs_get_ue(bs);
exit:
gf_bs_del(bs);
gf_free(pps_data_without_emulation_bytes);
return e;
}
#ifndef GPAC_DISABLE_HEVC
/**********
HEVC parsing
**********/
Bool gf_media_hevc_slice_is_intra(HEVCState *hevc)
{
switch (hevc->s_info.nal_unit_type) {
case GF_HEVC_NALU_SLICE_BLA_W_LP:
case GF_HEVC_NALU_SLICE_BLA_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_N_LP:
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_IDR_N_LP:
case GF_HEVC_NALU_SLICE_CRA:
return GF_TRUE;
default:
return GF_FALSE;
}
}
Bool gf_media_hevc_slice_is_IDR(HEVCState *hevc)
{
if (hevc->sei.recovery_point.valid)
{
hevc->sei.recovery_point.valid = 0;
return GF_TRUE;
}
switch (hevc->s_info.nal_unit_type) {
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_IDR_N_LP:
return GF_TRUE;
default:
return GF_FALSE;
}
}
static Bool parse_short_term_ref_pic_set(GF_BitStream *bs, HEVC_SPS *sps, u32 idx_rps)
{
u32 i;
Bool inter_ref_pic_set_prediction_flag = 0;
if (idx_rps != 0)
inter_ref_pic_set_prediction_flag = gf_bs_read_int(bs, 1);
if (inter_ref_pic_set_prediction_flag ) {
HEVC_ReferencePictureSets *ref_ps, *rps;
u32 delta_idx_minus1 = 0;
u32 ref_idx;
u32 delta_rps_sign;
u32 abs_delta_rps_minus1, nb_ref_pics;
s32 deltaRPS;
u32 k = 0, k0 = 0, k1 = 0;
if (idx_rps == sps->num_short_term_ref_pic_sets)
delta_idx_minus1 = bs_get_ue(bs);
assert(delta_idx_minus1 <= idx_rps - 1);
ref_idx = idx_rps - 1 - delta_idx_minus1;
delta_rps_sign = gf_bs_read_int(bs, 1);
abs_delta_rps_minus1 = bs_get_ue(bs);
deltaRPS = (1 - (delta_rps_sign<<1)) * (abs_delta_rps_minus1 + 1);
rps = &sps->rps[idx_rps];
ref_ps = &sps->rps[ref_idx];
nb_ref_pics = ref_ps->num_negative_pics + ref_ps->num_positive_pics;
for (i=0; i<=nb_ref_pics; i++) {
s32 ref_idc;
s32 used_by_curr_pic_flag = gf_bs_read_int(bs, 1);
ref_idc = used_by_curr_pic_flag ? 1 : 0;
if ( !used_by_curr_pic_flag ) {
used_by_curr_pic_flag = gf_bs_read_int(bs, 1);
ref_idc = used_by_curr_pic_flag << 1;
}
if ((ref_idc==1) || (ref_idc== 2)) {
s32 deltaPOC = deltaRPS;
if (i < nb_ref_pics)
deltaPOC += ref_ps->delta_poc[i];
rps->delta_poc[k] = deltaPOC;
if (deltaPOC < 0) k0++;
else k1++;
k++;
}
}
rps->num_negative_pics = k0;
rps->num_positive_pics = k1;
} else {
s32 prev = 0, poc = 0;
sps->rps[idx_rps].num_negative_pics = bs_get_ue(bs);
sps->rps[idx_rps].num_positive_pics = bs_get_ue(bs);
if (sps->rps[idx_rps].num_negative_pics>16)
return GF_FALSE;
if (sps->rps[idx_rps].num_positive_pics>16)
return GF_FALSE;
for (i=0; i<sps->rps[idx_rps].num_negative_pics; i++) {
u32 delta_poc_s0_minus1 = bs_get_ue(bs);
poc = prev - delta_poc_s0_minus1 - 1;
prev = poc;
sps->rps[idx_rps].delta_poc[i] = poc;
/*used_by_curr_pic_s1_flag[ i ] = */gf_bs_read_int(bs, 1);
}
for (i=0; i<sps->rps[idx_rps].num_positive_pics; i++) {
u32 delta_poc_s1_minus1 = bs_get_ue(bs);
poc = prev + delta_poc_s1_minus1 + 1;
prev = poc;
sps->rps[idx_rps].delta_poc[i] = poc;
/*used_by_curr_pic_s1_flag[ i ] = */gf_bs_read_int(bs, 1);
}
}
return GF_TRUE;
}
void hevc_pred_weight_table(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *si, HEVC_PPS *pps, HEVC_SPS *sps, u32 num_ref_idx_l0_active, u32 num_ref_idx_l1_active)
{
u32 i, num_ref_idx;
Bool first_pass=GF_TRUE;
u8 luma_weights[20], chroma_weights[20];
u32 ChromaArrayType = sps->separate_colour_plane_flag ? 0 : sps->chroma_format_idc;
num_ref_idx = num_ref_idx_l0_active;
/*luma_log2_weight_denom=*/i=bs_get_ue(bs);
if (ChromaArrayType != 0)
/*delta_chroma_log2_weight_denom=*/i=bs_get_se(bs);
parse_weights:
for (i=0; i<num_ref_idx; i++) {
luma_weights[i] = gf_bs_read_int(bs, 1);
//infered to be 0 if not present
chroma_weights[i] = 0;
}
if (ChromaArrayType != 0) {
for (i=0; i<num_ref_idx; i++) {
chroma_weights[i] = gf_bs_read_int(bs, 1);
}
}
for (i=0; i<num_ref_idx; i++) {
if (luma_weights[i]) {
/*delta_luma_weight_l0[ i ]=*/bs_get_se(bs);
/*luma_offset_l0[ i ]=*/bs_get_se(bs);
}
if (chroma_weights[i]) {
/*delta_chroma_weight_l0[ i ][ 0 ]=*/bs_get_se(bs);
/*delta_chroma_offset_l0[ i ][ 0 ]=*/bs_get_se(bs);
/*delta_chroma_weight_l0[ i ][ 1 ]=*/bs_get_se(bs);
/*delta_chroma_offset_l0[ i ][ 1 ]=*/bs_get_se(bs);
}
}
if (si->slice_type==GF_HEVC_SLICE_TYPE_B) {
if (!first_pass) return;
first_pass=GF_FALSE;
num_ref_idx = num_ref_idx_l1_active;
goto parse_weights;
}
}
static
Bool ref_pic_lists_modification(GF_BitStream *bs, u32 slice_type, u32 num_ref_idx_l0_active, u32 num_ref_idx_l1_active)
{
//u32 i;
Bool ref_pic_list_modification_flag_l0 = gf_bs_read_int(bs, 1);
if (ref_pic_list_modification_flag_l0) {
/*for (i=0; i<num_ref_idx_l0_active; i++) {
list_entry_l0[i] = *//*gf_bs_read_int(bs, (u32)ceil(log(getNumPicTotalCurr())/log(2)));
}*/
return GF_FALSE;
}
if (slice_type == GF_HEVC_SLICE_TYPE_B) {
Bool ref_pic_list_modification_flag_l1 = gf_bs_read_int(bs, 1);
if (ref_pic_list_modification_flag_l1) {
/*for (i=0; i<num_ref_idx_l1_active; i++) {
list_entry_l1[i] = *//*gf_bs_read_int(bs, (u32)ceil(log(getNumPicTotalCurr()) / log(2)));
}*/
return GF_FALSE;
}
}
return GF_TRUE;
}
static
s32 hevc_parse_slice_segment(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *si)
{
u32 i, j;
u32 num_ref_idx_l0_active=0, num_ref_idx_l1_active=0;
HEVC_PPS *pps;
HEVC_SPS *sps;
s32 pps_id;
Bool RapPicFlag = GF_FALSE;
Bool IDRPicFlag = GF_FALSE;
si->first_slice_segment_in_pic_flag = gf_bs_read_int(bs, 1);
switch (si->nal_unit_type) {
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_IDR_N_LP:
IDRPicFlag = GF_TRUE;
RapPicFlag = GF_TRUE;
break;
case GF_HEVC_NALU_SLICE_BLA_W_LP:
case GF_HEVC_NALU_SLICE_BLA_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_N_LP:
case GF_HEVC_NALU_SLICE_CRA:
RapPicFlag = GF_TRUE;
break;
}
if (RapPicFlag) {
/*Bool no_output_of_prior_pics_flag = */gf_bs_read_int(bs, 1);
}
pps_id = bs_get_ue(bs);
if (pps_id>=64)
return -1;
pps = &hevc->pps[pps_id];
sps = &hevc->sps[pps->sps_id];
si->sps = sps;
si->pps = pps;
if (!si->first_slice_segment_in_pic_flag && pps->dependent_slice_segments_enabled_flag) {
si->dependent_slice_segment_flag = gf_bs_read_int(bs, 1);
} else {
si->dependent_slice_segment_flag = GF_FALSE;
}
if (!si->first_slice_segment_in_pic_flag) {
si->slice_segment_address = gf_bs_read_int(bs, sps->bitsSliceSegmentAddress);
} else {
si->slice_segment_address = 0;
}
if( !si->dependent_slice_segment_flag ) {
Bool deblocking_filter_override_flag=0;
Bool slice_temporal_mvp_enabled_flag = 0;
Bool slice_sao_luma_flag=0;
Bool slice_sao_chroma_flag=0;
Bool slice_deblocking_filter_disabled_flag=0;
//"slice_reserved_undetermined_flag[]"
gf_bs_read_int(bs, pps->num_extra_slice_header_bits);
si->slice_type = bs_get_ue(bs);
if (si->slice_type == GF_HEVC_SLICE_TYPE_P)
si->slice_type = GF_HEVC_SLICE_TYPE_P;
if(pps->output_flag_present_flag)
/*pic_output_flag = */gf_bs_read_int(bs, 1);
if (sps->separate_colour_plane_flag == 1)
/*colour_plane_id = */gf_bs_read_int(bs, 2);
if (IDRPicFlag) {
si->poc_lsb = 0;
//if not asked to parse full header, abort since we know the poc
if (!hevc->full_slice_header_parse) return 0;
} else {
si->poc_lsb = gf_bs_read_int(bs, sps->log2_max_pic_order_cnt_lsb);
//if not asked to parse full header, abort once we have the poc
if (!hevc->full_slice_header_parse) return 0;
if (/*short_term_ref_pic_set_sps_flag =*/gf_bs_read_int(bs, 1) == 0) {
Bool ret = parse_short_term_ref_pic_set(bs, sps, sps->num_short_term_ref_pic_sets );
if (!ret)
return -1;
} else if( sps->num_short_term_ref_pic_sets > 1 ) {
u32 numbits = 0;
while ( (u32) (1 << numbits) < sps->num_short_term_ref_pic_sets)
numbits++;
if (numbits > 0)
/*s32 short_term_ref_pic_set_idx = */gf_bs_read_int(bs, numbits);
/*else
short_term_ref_pic_set_idx = 0;*/
}
if (sps->long_term_ref_pics_present_flag ) {
u8 DeltaPocMsbCycleLt[32];
u32 num_long_term_sps = 0;
u32 num_long_term_pics = 0;
if (sps->num_long_term_ref_pic_sps > 0 ) {
num_long_term_sps = bs_get_ue(bs);
}
num_long_term_pics = bs_get_ue(bs);
for (i = 0; i < num_long_term_sps + num_long_term_pics; i++ ) {
if( i < num_long_term_sps ) {
if (sps->num_long_term_ref_pic_sps > 1)
/*u8 lt_idx_sps = */gf_bs_read_int(bs, gf_get_bit_size(sps->num_long_term_ref_pic_sps) );
} else {
/*PocLsbLt[ i ] = */ gf_bs_read_int(bs, sps->log2_max_pic_order_cnt_lsb);
/*UsedByCurrPicLt[ i ] = */ gf_bs_read_int(bs, 1);
}
if (/*delta_poc_msb_present_flag[ i ] = */ gf_bs_read_int(bs, 1) ) {
if( i == 0 || i == num_long_term_sps )
DeltaPocMsbCycleLt[i] = bs_get_ue(bs);
else
DeltaPocMsbCycleLt[i] = bs_get_ue(bs) + DeltaPocMsbCycleLt[i-1];
}
}
}
if (sps->temporal_mvp_enable_flag)
slice_temporal_mvp_enabled_flag = gf_bs_read_int(bs, 1);
}
if (sps->sample_adaptive_offset_enabled_flag) {
u32 ChromaArrayType = sps->separate_colour_plane_flag ? 0 : sps->chroma_format_idc;
slice_sao_luma_flag = gf_bs_read_int(bs, 1);
if (ChromaArrayType!=0)
slice_sao_chroma_flag = gf_bs_read_int(bs, 1);
}
if (si->slice_type == GF_HEVC_SLICE_TYPE_P || si->slice_type == GF_HEVC_SLICE_TYPE_B) {
//u32 NumPocTotalCurr;
num_ref_idx_l0_active = pps->num_ref_idx_l0_default_active;
num_ref_idx_l1_active = 0;
if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
num_ref_idx_l1_active = pps->num_ref_idx_l1_default_active;
if ( /*num_ref_idx_active_override_flag =*/gf_bs_read_int(bs, 1) ) {
num_ref_idx_l0_active = 1 + bs_get_ue(bs);
if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
num_ref_idx_l1_active = 1 + bs_get_ue(bs);
}
if (pps->lists_modification_present_flag /*TODO: && NumPicTotalCurr > 1*/) {
if (!ref_pic_lists_modification(bs, si->slice_type, num_ref_idx_l0_active, num_ref_idx_l1_active)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[hevc] ref_pic_lists_modification( ) not implemented\n"));
return -1;
}
}
if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
/*mvd_l1_zero_flag=*/gf_bs_read_int(bs, 1);
if (pps->cabac_init_present_flag)
/*cabac_init_flag=*/gf_bs_read_int(bs, 1);
if (slice_temporal_mvp_enabled_flag) {
// When collocated_from_l0_flag is not present, it is inferred to be equal to 1.
Bool collocated_from_l0_flag = 1;
if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
collocated_from_l0_flag = gf_bs_read_int(bs, 1);
if ( (collocated_from_l0_flag && (num_ref_idx_l0_active>1) )
|| ( !collocated_from_l0_flag && (num_ref_idx_l1_active>1) )
) {
/*collocated_ref_idx=*/bs_get_ue(bs);
}
}
if ( (pps->weighted_pred_flag && si->slice_type == GF_HEVC_SLICE_TYPE_P )
|| ( pps->weighted_bipred_flag && si->slice_type == GF_HEVC_SLICE_TYPE_B)
) {
hevc_pred_weight_table(bs, hevc, si, pps, sps, num_ref_idx_l0_active, num_ref_idx_l1_active);
}
/*five_minus_max_num_merge_cand=*/bs_get_ue(bs);
}
/*slice_qp_delta = */bs_get_se(bs);
if( pps->slice_chroma_qp_offsets_present_flag ) {
/*slice_cb_qp_offset=*/bs_get_se(bs);
/*slice_cr_qp_offset=*/bs_get_se(bs);
}
if ( pps->deblocking_filter_override_enabled_flag ) {
deblocking_filter_override_flag = gf_bs_read_int(bs, 1);
}
if (deblocking_filter_override_flag) {
slice_deblocking_filter_disabled_flag = gf_bs_read_int(bs, 1);
if ( !slice_deblocking_filter_disabled_flag) {
/*slice_beta_offset_div2=*/ bs_get_se(bs);
/*slice_tc_offset_div2=*/bs_get_se(bs);
}
}
if( pps->loop_filter_across_slices_enabled_flag
&& ( slice_sao_luma_flag || slice_sao_chroma_flag || !slice_deblocking_filter_disabled_flag )
) {
/*slice_loop_filter_across_slices_enabled_flag = */gf_bs_read_int(bs, 1);
}
}
//dependent slice segment
else {
//if not asked to parse full header, abort
if (!hevc->full_slice_header_parse) return 0;
}
si->entry_point_start_bits = ((u32)gf_bs_get_position(bs)-1)*8 + gf_bs_get_bit_position(bs);
if (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag ) {
u32 num_entry_point_offsets = bs_get_ue(bs);
if ( num_entry_point_offsets > 0) {
u32 offset = bs_get_ue(bs) + 1;
u32 segments = offset >> 4;
s32 remain = (offset & 15);
for (i=0; i<num_entry_point_offsets; i++) {
u32 res = 0;
for (j=0; j<segments; j++) {
res <<= 16;
res += gf_bs_read_int(bs, 16);
}
if (remain) {
res <<= remain;
res += gf_bs_read_int(bs, remain);
}
// entry_point_offset = val + 1; // +1; // +1 to get the size
}
}
}
if (pps->slice_segment_header_extension_present_flag) {
u32 size_ext = bs_get_ue(bs);
while (size_ext) {
gf_bs_read_int(bs, 8);
size_ext--;
}
}
if (gf_bs_read_int(bs, 1) == 0) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("Error parsing slice header: byte_align not found at end of header !\n"));
}
gf_bs_align(bs);
si->payload_start_offset = (s32)gf_bs_get_position(bs);
return 0;
}
static void hevc_compute_poc(HEVCSliceInfo *si)
{
u32 max_poc_lsb = 1 << (si->sps->log2_max_pic_order_cnt_lsb);
/*POC reset for IDR frames, NOT for CRA*/
switch (si->nal_unit_type) {
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_IDR_N_LP:
si->poc_lsb_prev = 0;
si->poc_msb_prev = 0;
break;
}
if ((si->poc_lsb < si->poc_lsb_prev) && ( si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2) )
si->poc_msb = si->poc_msb_prev + max_poc_lsb;
else if ((si->poc_lsb > si->poc_lsb_prev) && (si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))
si->poc_msb = si->poc_msb_prev - max_poc_lsb;
else
si->poc_msb = si->poc_msb_prev;
switch (si->nal_unit_type) {
case GF_HEVC_NALU_SLICE_BLA_W_LP:
case GF_HEVC_NALU_SLICE_BLA_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_N_LP:
si->poc_msb = 0;
break;
}
si->poc = si->poc_msb + si->poc_lsb;
}
static Bool hevc_parse_nal_header(GF_BitStream *bs, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)
{
u32 val;
val = gf_bs_read_int(bs, 1);
if (val) return GF_FALSE;
val = gf_bs_read_int(bs, 6);
if (nal_unit_type) *nal_unit_type = val;
val = gf_bs_read_int(bs, 6);
if (layer_id) *layer_id = val;
val = gf_bs_read_int(bs, 3);
if (! val)
return GF_FALSE;
val -= 1;
if (temporal_id) *temporal_id = val;
return GF_TRUE;
}
void profile_tier_level(GF_BitStream *bs, Bool ProfilePresentFlag, u8 MaxNumSubLayersMinus1, HEVC_ProfileTierLevel *ptl)
{
u32 i;
if (ProfilePresentFlag) {
ptl->profile_space = gf_bs_read_int(bs, 2);
ptl->tier_flag = gf_bs_read_int(bs, 1);
ptl->profile_idc = gf_bs_read_int(bs, 5);
ptl->profile_compatibility_flag = gf_bs_read_int(bs, 32);
ptl->general_progressive_source_flag = gf_bs_read_int(bs, 1);
ptl->general_interlaced_source_flag = gf_bs_read_int(bs, 1);
ptl->general_non_packed_constraint_flag = gf_bs_read_int(bs, 1);
ptl->general_frame_only_constraint_flag = gf_bs_read_int(bs, 1);
ptl->general_reserved_44bits = gf_bs_read_long_int(bs, 44);
}
ptl->level_idc = gf_bs_read_int(bs, 8);
for (i=0; i<MaxNumSubLayersMinus1; i++) {
ptl->sub_ptl[i].profile_present_flag = gf_bs_read_int(bs, 1);
ptl->sub_ptl[i].level_present_flag = gf_bs_read_int(bs, 1);
}
if (MaxNumSubLayersMinus1>0) {
for (i=MaxNumSubLayersMinus1; i<8; i++) {
/*reserved_zero_2bits*/gf_bs_read_int(bs, 2);
}
}
for (i=0; i<MaxNumSubLayersMinus1; i++) {
if (ptl->sub_ptl[i].profile_present_flag) {
ptl->sub_ptl[i].profile_space = gf_bs_read_int(bs, 2);
ptl->sub_ptl[i].tier_flag = gf_bs_read_int(bs, 1);
ptl->sub_ptl[i].profile_idc = gf_bs_read_int(bs, 5);
ptl->sub_ptl[i].profile_compatibility_flag = gf_bs_read_int(bs, 32);
/*ptl->sub_ptl[i].progressive_source_flag =*/ gf_bs_read_int(bs, 1);
/*ptl->sub_ptl[i].interlaced_source_flag =*/ gf_bs_read_int(bs, 1);
/*ptl->sub_ptl[i].non_packed_constraint_flag =*/ gf_bs_read_int(bs, 1);
/*ptl->sub_ptl[i].frame_only_constraint_flag =*/ gf_bs_read_int(bs, 1);
/*ptl->sub_ptl[i].reserved_44bits =*/ gf_bs_read_long_int(bs, 44);
}
if (ptl->sub_ptl[i].level_present_flag)
ptl->sub_ptl[i].level_idc = gf_bs_read_int(bs, 8);
}
}
static u32 scalability_type_to_idx(HEVC_VPS *vps, u32 scalability_type)
{
u32 idx = 0, type;
for (type=0; type < scalability_type; type++) {
idx += (vps->scalability_mask[type] ? 1 : 0 );
}
return idx;
}
#define LHVC_VIEW_ORDER_INDEX 1
#define LHVC_SCALABILITY_INDEX 2
static u32 lhvc_get_scalability_id(HEVC_VPS *vps, u32 layer_id_in_vps, u32 scalability_type )
{
u32 idx;
if (!vps->scalability_mask[scalability_type]) return 0;
idx = scalability_type_to_idx(vps, scalability_type);
return vps->dimension_id[layer_id_in_vps][idx];
}
static u32 lhvc_get_view_index(HEVC_VPS *vps, u32 id)
{
return lhvc_get_scalability_id(vps, vps->layer_id_in_vps[id], LHVC_VIEW_ORDER_INDEX);
}
static u32 lhvc_get_num_views(HEVC_VPS *vps)
{
u32 numViews = 1, i;
for (i=0; i<vps->max_layers; i++ ) {
u32 layer_id = vps->layer_id_in_nuh[i];
if (i>0 && ( lhvc_get_view_index( vps, layer_id) != lhvc_get_scalability_id( vps, i-1, LHVC_VIEW_ORDER_INDEX) )) {
numViews++;
}
}
return numViews;
}
static void lhvc_parse_rep_format(HEVC_RepFormat *fmt, GF_BitStream *bs)
{
u8 chroma_bitdepth_present_flag;
fmt->pic_width_luma_samples = gf_bs_read_int(bs, 16);
fmt->pic_height_luma_samples = gf_bs_read_int(bs, 16);
chroma_bitdepth_present_flag = gf_bs_read_int(bs, 1);
if (chroma_bitdepth_present_flag) {
fmt->chroma_format_idc = gf_bs_read_int(bs, 2);
if (fmt->chroma_format_idc == 3)
fmt->separate_colour_plane_flag = gf_bs_read_int(bs, 1);
fmt->bit_depth_luma = 8 + gf_bs_read_int(bs, 4);
fmt->bit_depth_chroma = 8 + gf_bs_read_int(bs, 4);
}
if (/*conformance_window_vps_flag*/ gf_bs_read_int(bs, 1)) {
/*conf_win_vps_left_offset*/bs_get_ue(bs);
/*conf_win_vps_right_offset*/bs_get_ue(bs);
/*conf_win_vps_top_offset*/bs_get_ue(bs);
/*conf_win_vps_bottom_offset*/bs_get_ue(bs);
}
}
static Bool hevc_parse_vps_extension(HEVC_VPS *vps, GF_BitStream *bs)
{
u8 splitting_flag, vps_nuh_layer_id_present_flag, view_id_len;
u32 i, j, num_scalability_types, num_add_olss, num_add_layer_set, num_indepentdent_layers, nb_bits, default_output_layer_idc=0;
u8 dimension_id_len[16], dim_bit_offset[16];
u8 /*avc_base_layer_flag, */NumLayerSets, /*default_one_target_output_layer_flag, */rep_format_idx_present_flag, ols_ids_to_ls_idx;
u8 layer_set_idx_for_ols_minus1[MAX_LHVC_LAYERS];
u8 nb_output_layers_in_output_layer_set[MAX_LHVC_LAYERS+1];
u8 ols_highest_output_layer_id[MAX_LHVC_LAYERS+1];
u32 k,d, r, p, iNuhLId, jNuhLId;
u8 num_direct_ref_layers[64], num_pred_layers[64], num_layers_in_tree_partition[MAX_LHVC_LAYERS];
u8 dependency_flag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS], id_pred_layers[64][MAX_LHVC_LAYERS];
// u8 num_ref_layers[64];
// u8 tree_partition_layer_id[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];
// u8 id_ref_layers[64][MAX_LHVC_LAYERS];
// u8 id_direct_ref_layers[64][MAX_LHVC_LAYERS];
u8 layer_id_in_list_flag[64];
Bool OutputLayerFlag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];
vps->vps_extension_found=1;
if ((vps->max_layers > 1) && vps->base_layer_internal_flag)
profile_tier_level(bs, 0, vps->max_sub_layers-1, &vps->ext_ptl[0]);
splitting_flag = gf_bs_read_int(bs, 1);
num_scalability_types = 0;
for (i=0; i<16; i++) {
vps->scalability_mask[i] = gf_bs_read_int(bs, 1);
num_scalability_types += vps->scalability_mask[i];
}
if (num_scalability_types>=16) {
num_scalability_types=16;
}
dimension_id_len[0] = 0;
for (i=0; i<(num_scalability_types - splitting_flag); i++) {
dimension_id_len[i] = 1 + gf_bs_read_int(bs, 3);
}
if (splitting_flag) {
for (i = 0; i < num_scalability_types; i++) {
dim_bit_offset[i] = 0;
for (j = 0; j < i; j++)
dim_bit_offset[i] += dimension_id_len[j];
}
dimension_id_len[num_scalability_types-1] = 1 + (5 - dim_bit_offset[num_scalability_types-1]);
dim_bit_offset[num_scalability_types] = 6;
}
vps_nuh_layer_id_present_flag = gf_bs_read_int(bs, 1);
vps->layer_id_in_nuh[0] = 0;
vps->layer_id_in_vps[0] = 0;
for (i=1; i<vps->max_layers; i++) {
if (vps_nuh_layer_id_present_flag) {
vps->layer_id_in_nuh[i] = gf_bs_read_int(bs, 6);
} else {
vps->layer_id_in_nuh[i] = i;
}
vps->layer_id_in_vps[vps->layer_id_in_nuh[i]] = i;
if (!splitting_flag) {
for (j=0; j<num_scalability_types; j++) {
vps->dimension_id[i][j] = gf_bs_read_int(bs, dimension_id_len[j]);
}
}
}
if (splitting_flag) {
for (i = 0; i<vps->max_layers; i++)
for (j=0; j<num_scalability_types; j++)
vps->dimension_id[i][j] = ((vps->layer_id_in_nuh[i] & ((1 << dim_bit_offset[j+1]) -1)) >> dim_bit_offset[j]);
} else {
for (j=0; j<num_scalability_types; j++)
vps->dimension_id[0][j] = 0;
}
view_id_len = gf_bs_read_int(bs, 4);
if (view_id_len > 0) {
for( i = 0; i < lhvc_get_num_views(vps); i++ ) {
/*m_viewIdVal[i] = */ gf_bs_read_int(bs, view_id_len);
}
}
for (i=1; i<vps->max_layers; i++) {
for (j=0; j<i; j++) {
vps->direct_dependency_flag[i][j] = gf_bs_read_int(bs, 1);
}
}
//we do the test on MAX_LHVC_LAYERS and break in the loop to avoid a wrong GCC 4.8 warning on array bounds
for (i = 0; i < MAX_LHVC_LAYERS; i++) {
if (i >= vps->max_layers) break;
for (j = 0; j < vps->max_layers; j++) {
dependency_flag[i][j] = vps->direct_dependency_flag[i][j];
for (k = 0; k < i; k++)
if (vps->direct_dependency_flag[i][k] && vps->direct_dependency_flag[k][j])
dependency_flag[i][j] = 1;
}
}
for (i = 0; i < vps->max_layers; i++) {
iNuhLId = vps->layer_id_in_nuh[i];
d = r = p = 0;
for (j = 0; j < vps->max_layers; j++) {
jNuhLId = vps->layer_id_in_nuh[j];
if (vps->direct_dependency_flag[i][j]) {
// id_direct_ref_layers[iNuhLId][d] = jNuhLId;
d++;
}
if (dependency_flag[i][j]) {
// id_ref_layers[iNuhLId][r] = jNuhLId;
r++;
}
if (dependency_flag[j][i])
id_pred_layers[iNuhLId][p++] = jNuhLId;
}
num_direct_ref_layers[iNuhLId] = d;
// num_ref_layers[iNuhLId] = r;
num_pred_layers[iNuhLId] = p;
}
memset(layer_id_in_list_flag, 0, 64*sizeof(u8));
k = 0; //num_indepentdent_layers
for (i = 0; i < vps->max_layers; i++) {
iNuhLId = vps->layer_id_in_nuh[i];
if (!num_direct_ref_layers[iNuhLId]) {
u32 h = 1;
//tree_partition_layer_id[k][0] = iNuhLId;
for (j = 0; j < num_pred_layers[iNuhLId]; j++) {
u32 predLId = id_pred_layers[iNuhLId][j];
if (!layer_id_in_list_flag[predLId]) {
//tree_partition_layer_id[k][h++] = predLId;
layer_id_in_list_flag[predLId] = 1;
}
}
num_layers_in_tree_partition[k++] = h;
}
}
num_indepentdent_layers = k;
num_add_layer_set = 0;
if (num_indepentdent_layers > 1)
num_add_layer_set = bs_get_ue(bs);
for (i = 0; i < num_add_layer_set; i++)
for (j = 1; j < num_indepentdent_layers; j++) {
nb_bits =1;
while ((1 << nb_bits) < (num_layers_in_tree_partition[j] + 1))
nb_bits++;
/*highest_layer_idx_plus1[i][j]*/gf_bs_read_int(bs, nb_bits);
}
if (/*vps_sub_layers_max_minus1_present_flag*/gf_bs_read_int(bs, 1)) {
for (i = 0; i < vps->max_layers; i++) {
/*sub_layers_vps_max_minus1[ i ]*/gf_bs_read_int(bs, 3);
}
}
if (/*max_tid_ref_present_flag = */gf_bs_read_int(bs, 1)) {
for (i=0; i<(vps->max_layers-1) ; i++) {
for (j= i+1; j < vps->max_layers; j++) {
if (vps->direct_dependency_flag[j][i])
/*max_tid_il_ref_pics_plus1[ i ][ j ]*/gf_bs_read_int(bs, 3);
}
}
}
/*default_ref_layers_active_flag*/gf_bs_read_int(bs, 1);
vps->num_profile_tier_level = 1+bs_get_ue(bs);
if (vps->num_profile_tier_level > MAX_LHVC_LAYERS) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Wrong number of PTLs in VPS %d\n", vps->num_profile_tier_level));
vps->num_profile_tier_level=1;
return GF_FALSE;
}
for (i=vps->base_layer_internal_flag ? 2 : 1; i < vps->num_profile_tier_level; i++) {
Bool vps_profile_present_flag = gf_bs_read_int(bs, 1);
profile_tier_level(bs, vps_profile_present_flag, vps->max_sub_layers-1, &vps->ext_ptl[i-1] );
}
NumLayerSets = vps->num_layer_sets + num_add_layer_set;
num_add_olss = 0;
if (NumLayerSets > 1) {
num_add_olss = bs_get_ue(bs);
default_output_layer_idc = gf_bs_read_int(bs,2);
default_output_layer_idc = default_output_layer_idc < 2 ? default_output_layer_idc : 2;
}
vps->num_output_layer_sets = num_add_olss + NumLayerSets;
layer_set_idx_for_ols_minus1[0] = 1;
vps->output_layer_flag[0][0] = 1;
for (i = 0; i < vps->num_output_layer_sets; i++) {
if ((NumLayerSets > 2) && (i >= NumLayerSets)) {
nb_bits = 1;
while ((1 << nb_bits) < (NumLayerSets - 1))
nb_bits++;
layer_set_idx_for_ols_minus1[i] = gf_bs_read_int(bs, nb_bits);
}
else
layer_set_idx_for_ols_minus1[i] = 0;
ols_ids_to_ls_idx = i < NumLayerSets ? i : layer_set_idx_for_ols_minus1[i] + 1;
if ((i > (vps->num_layer_sets - 1)) || (default_output_layer_idc == 2)) {
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)
vps->output_layer_flag[i][j] = gf_bs_read_int(bs, 1);
}
if ((default_output_layer_idc == 0) || (default_output_layer_idc == 1)) {
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
if ((default_output_layer_idc == 0) || (vps->LayerSetLayerIdList[i][j] == vps->LayerSetLayerIdListMax[i]))
OutputLayerFlag[i][j] = GF_TRUE;
else
OutputLayerFlag[i][j] = GF_FALSE;
}
}
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
if (OutputLayerFlag[i][j]) {
u32 curLayerID, k;
vps->necessary_layers_flag[i][j] = GF_TRUE;
curLayerID = vps->LayerSetLayerIdList[i][j];
for (k = 0; k < j; k++) {
u32 refLayerId = vps->LayerSetLayerIdList[i][k];
if (dependency_flag[vps->layer_id_in_vps[curLayerID]][vps->layer_id_in_vps[refLayerId]])
vps->necessary_layers_flag[i][k] = GF_TRUE;
}
}
}
vps->num_necessary_layers[i] = 0;
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
if (vps->necessary_layers_flag[i][j])
vps->num_necessary_layers[i] += 1;
}
if (i == 0) {
if (vps->base_layer_internal_flag) {
if (vps->max_layers > 1)
vps->profile_tier_level_idx[0][0] = 1;
else
vps->profile_tier_level_idx[0][0] = 0;
}
continue;
}
nb_bits = 1;
while ((u32)(1 << nb_bits) < vps->num_profile_tier_level)
nb_bits++;
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)
if (vps->necessary_layers_flag[i][j] && vps->num_profile_tier_level)
vps->profile_tier_level_idx[i][j] = gf_bs_read_int(bs, nb_bits);
else
vps->profile_tier_level_idx[i][j] = 0;
nb_output_layers_in_output_layer_set[i] = 0;
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
nb_output_layers_in_output_layer_set[i] += OutputLayerFlag[i][j];
if (OutputLayerFlag[i][j]) {
ols_highest_output_layer_id[i] = vps->LayerSetLayerIdList[ols_ids_to_ls_idx][j];
}
}
if (nb_output_layers_in_output_layer_set[i] == 1 && ols_highest_output_layer_id[i] > 0)
vps->alt_output_layer_flag[i] = gf_bs_read_int(bs, 1);
}
vps->num_rep_formats = 1 + bs_get_ue(bs);
if (vps->num_rep_formats > 16) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Wrong number of rep formats in VPS %d\n", vps->num_rep_formats));
vps->num_rep_formats = 0;
return GF_FALSE;
}
for (i = 0; i < vps->num_rep_formats; i++) {
lhvc_parse_rep_format(&vps->rep_formats[i], bs);
}
if (vps->num_rep_formats > 1)
rep_format_idx_present_flag = gf_bs_read_int(bs, 1);
else
rep_format_idx_present_flag = 0;
vps->rep_format_idx[0] = 0;
nb_bits = 1;
while ((u32)(1 << nb_bits) < vps->num_rep_formats)
nb_bits++;
for (i = vps->base_layer_internal_flag ? 1 : 0; i < vps->max_layers; i++) {
if (rep_format_idx_present_flag) {
vps->rep_format_idx[i] = gf_bs_read_int(bs, nb_bits);
}
else {
vps->rep_format_idx[i] = i < vps->num_rep_formats - 1 ? i : vps->num_rep_formats - 1;
}
}
//TODO - we don't use the rest ...
return GF_TRUE;
}
static void sub_layer_hrd_parameters(GF_BitStream *bs, int subLayerId, u32 cpb_cnt, Bool sub_pic_hrd_params_present_flag) {
u32 i;
for (i = 0; i <= cpb_cnt; i++) {
/*bit_rate_value_minus1[i] = */bs_get_ue(bs);
/*cpb_size_value_minus1[i] = */bs_get_ue(bs);
if (sub_pic_hrd_params_present_flag) {
/*cpb_size_du_value_minus1[i] = */bs_get_ue(bs);
/*bit_rate_du_value_minus1[i] = */bs_get_ue(bs);
}
/*cbr_flag[i] = */gf_bs_read_int(bs, 1);
}
}
static void hevc_parse_hrd_parameters(GF_BitStream *bs, Bool commonInfPresentFlag, int maxNumSubLayersMinus1)
{
int i;
Bool nal_hrd_parameters_present_flag = GF_FALSE;
Bool vcl_hrd_parameters_present_flag = GF_FALSE;
Bool sub_pic_hrd_params_present_flag = GF_FALSE;
if (commonInfPresentFlag) {
nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
sub_pic_hrd_params_present_flag = gf_bs_read_int(bs, 1);
if (sub_pic_hrd_params_present_flag) {
/*tick_divisor_minus2 = */gf_bs_read_int(bs, 8);
/*du_cpb_removal_delay_increment_length_minus1 = */gf_bs_read_int(bs, 5);
/*sub_pic_cpb_params_in_pic_timing_sei_flag = */gf_bs_read_int(bs, 1);
/*dpb_output_delay_du_length_minus1 = */gf_bs_read_int(bs, 5);
}
/*bit_rate_scale = */gf_bs_read_int(bs, 4);
/*cpb_size_scale = */gf_bs_read_int(bs, 4);
if (sub_pic_hrd_params_present_flag) {
/*cpb_size_du_scale = */gf_bs_read_int(bs, 4);
}
/*initial_cpb_removal_delay_length_minus1 = */gf_bs_read_int(bs, 5);
/*au_cpb_removal_delay_length_minus1 = */gf_bs_read_int(bs, 5);
/*dpb_output_delay_length_minus1 = */gf_bs_read_int(bs, 5);
}
}
for (i = 0; i <= maxNumSubLayersMinus1; i++) {
Bool fixed_pic_rate_general_flag_i = gf_bs_read_int(bs, 1);
Bool fixed_pic_rate_within_cvs_flag_i = GF_TRUE;
Bool low_delay_hrd_flag_i = GF_FALSE;
u32 cpb_cnt_minus1_i = 0;
if (!fixed_pic_rate_general_flag_i) {
fixed_pic_rate_within_cvs_flag_i = gf_bs_read_int(bs, 1);
}
if (fixed_pic_rate_within_cvs_flag_i)
/*elemental_duration_in_tc_minus1[i] = */bs_get_ue(bs);
else
low_delay_hrd_flag_i = gf_bs_read_int(bs, 1);
if (!low_delay_hrd_flag_i) {
cpb_cnt_minus1_i = bs_get_ue(bs);
}
if (nal_hrd_parameters_present_flag) {
sub_layer_hrd_parameters(bs, i, cpb_cnt_minus1_i, sub_pic_hrd_params_present_flag);
}
if (vcl_hrd_parameters_present_flag) {
sub_layer_hrd_parameters(bs, i, cpb_cnt_minus1_i, sub_pic_hrd_params_present_flag);
}
}
}
static s32 gf_media_hevc_read_vps_bs(GF_BitStream *bs, HEVCState *hevc, Bool stop_at_vps_ext)
{
u8 vps_sub_layer_ordering_info_present_flag, vps_extension_flag;
u32 i, j;
s32 vps_id = -1;
HEVC_VPS *vps;
u8 layer_id_included_flag[MAX_LHVC_LAYERS][64];
//nalu header already parsed
vps_id = gf_bs_read_int(bs, 4);
if (vps_id>=16) return -1;
vps = &hevc->vps[vps_id];
vps->bit_pos_vps_extensions = -1;
if (!vps->state) {
vps->id = vps_id;
vps->state = 1;
}
vps->base_layer_internal_flag = gf_bs_read_int(bs, 1);
vps->base_layer_available_flag = gf_bs_read_int(bs, 1);
vps->max_layers = 1 + gf_bs_read_int(bs, 6);
if (vps->max_layers>MAX_LHVC_LAYERS) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] sorry, %d layers in VPS but only %d supported\n", vps->max_layers, MAX_LHVC_LAYERS));
return -1;
}
vps->max_sub_layers = gf_bs_read_int(bs, 3) + 1;
vps->temporal_id_nesting = gf_bs_read_int(bs, 1);
/* vps_reserved_ffff_16bits = */ gf_bs_read_int(bs, 16);
profile_tier_level(bs, 1, vps->max_sub_layers-1, &vps->ptl);
vps_sub_layer_ordering_info_present_flag = gf_bs_read_int(bs, 1);
for (i=(vps_sub_layer_ordering_info_present_flag ? 0 : vps->max_sub_layers - 1); i < vps->max_sub_layers; i++) {
/*vps_max_dec_pic_buffering_minus1[i] = */bs_get_ue(bs);
/*vps_max_num_reorder_pics[i] = */bs_get_ue(bs);
/*vps_max_latency_increase_plus1[i] = */bs_get_ue(bs);
}
vps->max_layer_id = gf_bs_read_int(bs, 6);
if (vps->max_layer_id > MAX_LHVC_LAYERS) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] VPS max layer ID %u but GPAC only supports %u\n", vps->max_layer_id, MAX_LHVC_LAYERS));
return -1;
}
vps->num_layer_sets = bs_get_ue(bs) + 1;
if (vps->num_layer_sets > MAX_LHVC_LAYERS) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Wrong number of layer sets in VPS %d\n", vps->num_layer_sets));
return -1;
}
for (i=1; i < vps->num_layer_sets; i++) {
for (j=0; j <= vps->max_layer_id; j++) {
layer_id_included_flag[ i ][ j ] = gf_bs_read_int(bs, 1);
}
}
vps->num_layers_in_id_list[0] = 1;
for (i = 1; i < vps->num_layer_sets; i++) {
u32 n, m;
n = 0;
for (m = 0; m <= vps->max_layer_id; m++)
if (layer_id_included_flag[i][m]) {
vps->LayerSetLayerIdList[i][n++] = m;
if (vps->LayerSetLayerIdListMax[i] < m)
vps->LayerSetLayerIdListMax[i] = m;
}
vps->num_layers_in_id_list[i] = n;
}
if (/*vps_timing_info_present_flag*/gf_bs_read_int(bs, 1)) {
u32 vps_num_hrd_parameters;
/*u32 vps_num_units_in_tick = */gf_bs_read_int(bs, 32);
/*u32 vps_time_scale = */gf_bs_read_int(bs, 32);
if (/*vps_poc_proportional_to_timing_flag*/gf_bs_read_int(bs, 1)) {
/*vps_num_ticks_poc_diff_one_minus1*/bs_get_ue(bs);
}
vps_num_hrd_parameters = bs_get_ue(bs);
for( i = 0; i < vps_num_hrd_parameters; i++ ) {
Bool cprms_present_flag = GF_TRUE;
/*hrd_layer_set_idx[i] = */bs_get_ue(bs);
if (i>0)
cprms_present_flag = gf_bs_read_int(bs, 1) ;
hevc_parse_hrd_parameters(bs, cprms_present_flag, vps->max_sub_layers - 1);
}
}
if (stop_at_vps_ext) {
return vps_id;
}
vps_extension_flag = gf_bs_read_int(bs, 1);
if (vps_extension_flag ) {
Bool res;
gf_bs_align(bs);
res = hevc_parse_vps_extension(vps, bs);
if (res!=GF_TRUE) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Failed to parse VPS extensions\n"));
return -1;
}
if (/*vps_extension2_flag*/gf_bs_read_int(bs, 1)) {
while (gf_bs_available(bs)) {
/*vps_extension_data_flag */ gf_bs_read_int(bs, 1);
}
}
}
return vps_id;
}
GF_EXPORT
s32 gf_media_hevc_read_vps_ex(char *data, u32 *size, HEVCState *hevc, Bool remove_extensions)
{
GF_BitStream *bs;
char *data_without_emulation_bytes = NULL;
u32 data_without_emulation_bytes_size = 0;
s32 vps_id = -1;
/*still contains emulation bytes*/
data_without_emulation_bytes_size = avc_emulation_bytes_remove_count(data, (*size));
if (!data_without_emulation_bytes_size) {
bs = gf_bs_new(data, (*size), GF_BITSTREAM_READ);
} else {
data_without_emulation_bytes = gf_malloc((*size) * sizeof(char));
data_without_emulation_bytes_size = avc_remove_emulation_bytes(data, data_without_emulation_bytes, (*size) );
bs = gf_bs_new(data_without_emulation_bytes, data_without_emulation_bytes_size, GF_BITSTREAM_READ);
}
if (!bs) goto exit;
if (! hevc_parse_nal_header(bs, NULL, NULL, NULL)) goto exit;
vps_id = gf_media_hevc_read_vps_bs(bs, hevc, remove_extensions);
if (vps_id<0) goto exit;
if (remove_extensions) {
char *new_vps;
u32 new_vps_size, emulation_bytes;
u32 bit_pos = gf_bs_get_bit_offset(bs);
GF_BitStream *w_bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
gf_bs_write_u8(w_bs, data[0]);
gf_bs_write_u8(w_bs, data[1]);
gf_bs_write_u8(w_bs, data[2]);
gf_bs_write_u8(w_bs, data[3]);
gf_bs_write_u16(w_bs, 0xFFFF);
gf_bs_seek(bs, 6);
bit_pos-=48;
while (bit_pos) {
u32 v = gf_bs_read_int(bs, 1);
gf_bs_write_int(w_bs, v, 1);
bit_pos--;
}
/*vps extension flag*/
gf_bs_write_int(w_bs, 0, 1);
new_vps=NULL;
gf_bs_get_content(w_bs, &new_vps, &new_vps_size);
gf_bs_del(w_bs);
emulation_bytes = avc_emulation_bytes_add_count(new_vps, new_vps_size);
if (emulation_bytes+new_vps_size > *size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("Buffer too small to rewrite VPS - skipping rewrite\n"));
} else {
*size = avc_add_emulation_bytes(new_vps, data, new_vps_size);
}
}
exit:
if (bs) gf_bs_del(bs);
if (data_without_emulation_bytes) gf_free(data_without_emulation_bytes);
return vps_id;
}
GF_EXPORT
s32 gf_media_hevc_read_vps(char *data, u32 size, HEVCState *hevc)
{
return gf_media_hevc_read_vps_ex(data, &size, hevc, GF_FALSE);
}
static void hevc_scaling_list_data(GF_BitStream *bs)
{
u32 i, sizeId, matrixId;
for (sizeId = 0; sizeId < 4; sizeId++) {
for (matrixId=0; matrixId<6; matrixId += (sizeId == 3) ? 3:1 ) {
u32 scaling_list_pred_mode_flag_sizeId_matrixId = gf_bs_read_int(bs, 1);
if( ! scaling_list_pred_mode_flag_sizeId_matrixId ) {
/*scaling_list_pred_matrix_id_delta[ sizeId ][ matrixId ] =*/ bs_get_ue(bs);
} else {
//u32 nextCoef = 8;
u32 coefNum = MIN(64, (1 << (4+(sizeId << 1))));
if ( sizeId > 1 ) {
/*scaling_list_dc_coef_minus8[ sizeId − 2 ][ matrixId ] = */bs_get_se(bs);
}
for (i = 0; i<coefNum; i++) {
/*scaling_list_delta_coef = */bs_get_se(bs);
}
}
}
}
}
static const struct {
u32 w, h;
} hevc_sar[17] =
{
{ 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 },
{ 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },
{ 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },
{ 64, 33 }, { 160,99 }, { 4,3}, { 3,2}, { 2,1}
};
static s32 gf_media_hevc_read_sps_bs(GF_BitStream *bs, HEVCState *hevc, u8 layer_id, u32 *vui_flag_pos)
{
s32 vps_id, sps_id = -1;
u8 max_sub_layers_minus1, flag;
Bool scaling_list_enable_flag;
u32 i, nb_CTUs, depth;
u32 log2_diff_max_min_luma_coding_block_size;
u32 log2_min_transform_block_size, log2_min_luma_coding_block_size;
Bool sps_sub_layer_ordering_info_present_flag;
HEVC_SPS *sps;
HEVC_VPS *vps;
HEVC_ProfileTierLevel ptl;
u32 sps_ext_or_max_sub_layers_minus1;
Bool multiLayerExtSpsFlag;
if (vui_flag_pos) *vui_flag_pos = 0;
//nalu header already parsed
vps_id = gf_bs_read_int(bs, 4);
if (vps_id>=16) {
return -1;
}
memset(&ptl, 0, sizeof(ptl));
max_sub_layers_minus1 = 0;
sps_ext_or_max_sub_layers_minus1 = 0;
if (layer_id == 0)
max_sub_layers_minus1 = gf_bs_read_int(bs, 3);
else
sps_ext_or_max_sub_layers_minus1 = gf_bs_read_int(bs, 3);
multiLayerExtSpsFlag = (layer_id != 0) && (sps_ext_or_max_sub_layers_minus1 == 7);
if (!multiLayerExtSpsFlag) {
/*temporal_id_nesting_flag = */gf_bs_read_int(bs, 1);
profile_tier_level(bs, 1, max_sub_layers_minus1, &ptl);
}
sps_id = bs_get_ue(bs);
if ((sps_id<0) ||(sps_id>=16)) {
return -1;
}
sps = &hevc->sps[sps_id];
if (!sps->state) {
sps->state = 1;
sps->id = sps_id;
sps->vps_id = vps_id;
}
sps->ptl = ptl;
vps = &hevc->vps[vps_id];
//sps_rep_format_idx = 0;
if (multiLayerExtSpsFlag) {
u8 update_rep_format_flag = gf_bs_read_int(bs, 1);
if (update_rep_format_flag) {
sps->rep_format_idx = gf_bs_read_int(bs, 8);
} else {
sps->rep_format_idx = vps->rep_format_idx[layer_id];
}
sps->width = vps->rep_formats[sps->rep_format_idx].pic_width_luma_samples;
sps->height = vps->rep_formats[sps->rep_format_idx].pic_height_luma_samples;
sps->chroma_format_idc = vps->rep_formats[sps->rep_format_idx].chroma_format_idc;
sps->bit_depth_luma = vps->rep_formats[sps->rep_format_idx].bit_depth_luma;
sps->bit_depth_chroma = vps->rep_formats[sps->rep_format_idx].bit_depth_chroma;
sps->separate_colour_plane_flag = vps->rep_formats[sps->rep_format_idx].separate_colour_plane_flag;
//TODO this is crude ...
sps->ptl = vps->ext_ptl[0];
} else {
sps->chroma_format_idc = bs_get_ue(bs);
if (sps->chroma_format_idc==3)
sps->separate_colour_plane_flag = gf_bs_read_int(bs, 1);
sps->width = bs_get_ue(bs);
sps->height = bs_get_ue(bs);
if (/*conformance_window_flag*/gf_bs_read_int(bs, 1)) {
u32 SubWidthC, SubHeightC;
if (sps->chroma_format_idc==1) {
SubWidthC = SubHeightC = 2;
}
else if (sps->chroma_format_idc==2) {
SubWidthC = 2;
SubHeightC = 1;
} else {
SubWidthC = SubHeightC = 1;
}
sps->cw_left = bs_get_ue(bs);
sps->cw_right = bs_get_ue(bs);
sps->cw_top = bs_get_ue(bs);
sps->cw_bottom = bs_get_ue(bs);
sps->width -= SubWidthC * (sps->cw_left + sps->cw_right);
sps->height -= SubHeightC * (sps->cw_top + sps->cw_bottom);
}
sps->bit_depth_luma = 8 + bs_get_ue(bs);
sps->bit_depth_chroma = 8 + bs_get_ue(bs);
}
sps->log2_max_pic_order_cnt_lsb = 4 + bs_get_ue(bs);
if (!multiLayerExtSpsFlag) {
sps_sub_layer_ordering_info_present_flag = gf_bs_read_int(bs, 1);
for(i=sps_sub_layer_ordering_info_present_flag ? 0 : max_sub_layers_minus1; i<=max_sub_layers_minus1; i++) {
/*max_dec_pic_buffering = */ bs_get_ue(bs);
/*num_reorder_pics = */ bs_get_ue(bs);
/*max_latency_increase = */ bs_get_ue(bs);
}
}
log2_min_luma_coding_block_size = 3 + bs_get_ue(bs);
log2_diff_max_min_luma_coding_block_size = bs_get_ue(bs);
sps->max_CU_width = ( 1<<(log2_min_luma_coding_block_size + log2_diff_max_min_luma_coding_block_size) );
sps->max_CU_height = ( 1<<(log2_min_luma_coding_block_size + log2_diff_max_min_luma_coding_block_size) );
log2_min_transform_block_size = 2 + bs_get_ue(bs);
/*log2_max_transform_block_size = log2_min_transform_block_size + */bs_get_ue(bs);
depth = 0;
/*u32 max_transform_hierarchy_depth_inter = */bs_get_ue(bs);
/*u32 max_transform_hierarchy_depth_intra = */bs_get_ue(bs);
while( (u32) ( sps->max_CU_width >> log2_diff_max_min_luma_coding_block_size ) > (u32) ( 1 << ( log2_min_transform_block_size + depth ) ) )
{
depth++;
}
sps->max_CU_depth = log2_diff_max_min_luma_coding_block_size + depth;
nb_CTUs = ((sps->width + sps->max_CU_width -1) / sps->max_CU_width) * ((sps->height + sps->max_CU_height-1) / sps->max_CU_height);
sps->bitsSliceSegmentAddress = 0;
while (nb_CTUs > (u32) (1 << sps->bitsSliceSegmentAddress)) {
sps->bitsSliceSegmentAddress++;
}
scaling_list_enable_flag = gf_bs_read_int(bs, 1);
if (scaling_list_enable_flag) {
Bool sps_infer_scaling_list_flag = 0;
/*u8 sps_scaling_list_ref_layer_id = 0;*/
if (multiLayerExtSpsFlag) {
sps_infer_scaling_list_flag = gf_bs_read_int(bs, 1);
}
if (sps_infer_scaling_list_flag) {
/*sps_scaling_list_ref_layer_id = */gf_bs_read_int(bs, 6);
} else {
if (/*sps_scaling_list_data_present_flag=*/gf_bs_read_int(bs, 1) ) {
hevc_scaling_list_data(bs);
}
}
}
/*asymmetric_motion_partitions_enabled_flag= */ gf_bs_read_int(bs, 1);
sps->sample_adaptive_offset_enabled_flag = gf_bs_read_int(bs, 1);
if (/*pcm_enabled_flag= */ gf_bs_read_int(bs, 1) ) {
/*pcm_sample_bit_depth_luma_minus1=*/gf_bs_read_int(bs, 4);
/*pcm_sample_bit_depth_chroma_minus1=*/gf_bs_read_int(bs, 4);
/*log2_min_pcm_luma_coding_block_size_minus3= */ bs_get_ue(bs);
/*log2_diff_max_min_pcm_luma_coding_block_size = */ bs_get_ue(bs);
/*pcm_loop_filter_disable_flag=*/gf_bs_read_int(bs, 1);
}
sps->num_short_term_ref_pic_sets = bs_get_ue(bs);
if (sps->num_short_term_ref_pic_sets>64) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Invalid number of short term reference picture sets %d\n", sps->num_short_term_ref_pic_sets));
return -1;
}
for (i=0; i<sps->num_short_term_ref_pic_sets; i++) {
Bool ret = parse_short_term_ref_pic_set(bs, sps, i);
/*cannot parse short_term_ref_pic_set, skip VUI parsing*/
if (!ret) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Invalid short_term_ref_pic_set\n"));
return -1;
}
}
sps->long_term_ref_pics_present_flag = gf_bs_read_int(bs, 1);
if (sps->long_term_ref_pics_present_flag) {
sps->num_long_term_ref_pic_sps = bs_get_ue(bs);
for (i=0; i<sps->num_long_term_ref_pic_sps; i++) {
/*lt_ref_pic_poc_lsb_sps=*/gf_bs_read_int(bs, sps->log2_max_pic_order_cnt_lsb);
/*used_by_curr_pic_lt_sps_flag*/gf_bs_read_int(bs, 1);
}
}
sps->temporal_mvp_enable_flag = gf_bs_read_int(bs, 1);
/*strong_intra_smoothing_enable_flag*/gf_bs_read_int(bs, 1);
if (vui_flag_pos)
*vui_flag_pos = (u32) gf_bs_get_bit_offset(bs);
if (/*vui_parameters_present_flag*/gf_bs_read_int(bs, 1)) {
sps->aspect_ratio_info_present_flag = gf_bs_read_int(bs, 1);
if (sps->aspect_ratio_info_present_flag) {
sps->sar_idc = gf_bs_read_int(bs, 8);
if (sps->sar_idc == 255) {
sps->sar_width = gf_bs_read_int(bs, 16);
sps->sar_height = gf_bs_read_int(bs, 16);
} else if (sps->sar_idc<17) {
sps->sar_width = hevc_sar[sps->sar_idc].w;
sps->sar_height = hevc_sar[sps->sar_idc].h;
}
}
if (/*overscan_info_present = */ gf_bs_read_int(bs, 1))
/*overscan_appropriate = */ gf_bs_read_int(bs, 1);
/*video_signal_type_present_flag = */flag = gf_bs_read_int(bs, 1);
if (flag) {
/*video_format = */gf_bs_read_int(bs, 3);
/*video_full_range_flag = */gf_bs_read_int(bs, 1);
if (/*colour_description_present_flag = */gf_bs_read_int(bs, 1)) {
/*colour_primaries = */ gf_bs_read_int(bs, 8);
/* transfer_characteristic = */ gf_bs_read_int(bs, 8);
/* matrix_coeffs = */ gf_bs_read_int(bs, 8);
}
}
if (/*chroma_loc_info_present_flag = */ gf_bs_read_int(bs, 1)) {
/*chroma_sample_loc_type_top_field = */ bs_get_ue(bs);
/*chroma_sample_loc_type_bottom_field = */bs_get_ue(bs);
}
/*neutra_chroma_indication_flag = */gf_bs_read_int(bs, 1);
/*field_seq_flag = */gf_bs_read_int(bs, 1);
/*frame_field_info_present_flag = */gf_bs_read_int(bs, 1);
if (/*default_display_window_flag=*/gf_bs_read_int(bs, 1)) {
/*left_offset = */bs_get_ue(bs);
/*right_offset = */bs_get_ue(bs);
/*top_offset = */bs_get_ue(bs);
/*bottom_offset = */bs_get_ue(bs);
}
sps->has_timing_info = gf_bs_read_int(bs, 1);
if (sps->has_timing_info ) {
sps->num_units_in_tick = gf_bs_read_int(bs, 32);
sps->time_scale = gf_bs_read_int(bs, 32);
sps->poc_proportional_to_timing_flag = gf_bs_read_int(bs, 1);
if (sps->poc_proportional_to_timing_flag)
sps->num_ticks_poc_diff_one_minus1 = bs_get_ue(bs);
if (/*hrd_parameters_present_flag=*/gf_bs_read_int(bs, 1) ) {
// GF_LOG(GF_LOG_INFO, GF_LOG_CODING, ("[HEVC] HRD param parsing not implemented\n"));
return sps_id;
}
}
if (/*bitstream_restriction_flag=*/gf_bs_read_int(bs, 1)) {
/*tiles_fixed_structure_flag = */gf_bs_read_int(bs, 1);
/*motion_vectors_over_pic_boundaries_flag = */gf_bs_read_int(bs, 1);
/*restricted_ref_pic_lists_flag = */gf_bs_read_int(bs, 1);
/*min_spatial_segmentation_idc = */bs_get_ue(bs);
/*max_bytes_per_pic_denom = */bs_get_ue(bs);
/*max_bits_per_min_cu_denom = */bs_get_ue(bs);
/*log2_max_mv_length_horizontal = */bs_get_ue(bs);
/*log2_max_mv_length_vertical = */bs_get_ue(bs);
}
}
if (/*sps_extension_flag*/gf_bs_read_int(bs, 1)) {
while (gf_bs_available(bs)) {
/*sps_extension_data_flag */ gf_bs_read_int(bs, 1);
}
}
return sps_id;
}
GF_EXPORT
s32 gf_media_hevc_read_sps_ex(char *data, u32 size, HEVCState *hevc, u32 *vui_flag_pos)
{
GF_BitStream *bs;
char *data_without_emulation_bytes = NULL;
u32 data_without_emulation_bytes_size = 0;
s32 sps_id= -1;
u8 layer_id;
if (vui_flag_pos) *vui_flag_pos = 0;
data_without_emulation_bytes_size = avc_emulation_bytes_remove_count(data, size);
if (!data_without_emulation_bytes_size) {
bs = gf_bs_new(data, size, GF_BITSTREAM_READ);
} else {
/*still contains emulation bytes*/
data_without_emulation_bytes = gf_malloc(size*sizeof(char));
data_without_emulation_bytes_size = avc_remove_emulation_bytes(data, data_without_emulation_bytes, size);
bs = gf_bs_new(data_without_emulation_bytes, data_without_emulation_bytes_size, GF_BITSTREAM_READ);
}
if (!bs) goto exit;
if (! hevc_parse_nal_header(bs, NULL, NULL, &layer_id)) goto exit;
sps_id = gf_media_hevc_read_sps_bs(bs, hevc, layer_id, vui_flag_pos);
exit:
if (bs) gf_bs_del(bs);
if (data_without_emulation_bytes) gf_free(data_without_emulation_bytes);
return sps_id;
}
GF_EXPORT
s32 gf_media_hevc_read_sps(char *data, u32 size, HEVCState *hevc)
{
return gf_media_hevc_read_sps_ex(data, size, hevc, NULL);
}
static s32 gf_media_hevc_read_pps_bs(GF_BitStream *bs, HEVCState *hevc)
{
u32 i;
s32 pps_id = -1;
HEVC_PPS *pps;
//NAL header already read
pps_id = bs_get_ue(bs);
if ((pps_id<0) || (pps_id>=64)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] wrong PPS ID %d in PPS\n", pps_id));
return -1;
}
pps = &hevc->pps[pps_id];
if (!pps->state) {
pps->id = pps_id;
pps->state = 1;
}
pps->sps_id = bs_get_ue(bs);
if (pps->sps_id>16) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] wrong SPS ID %d in PPS\n", pps->sps_id));
return -1;
}
hevc->sps_active_idx = pps->sps_id; /*set active sps*/
pps->dependent_slice_segments_enabled_flag = gf_bs_read_int(bs, 1);
pps->output_flag_present_flag = gf_bs_read_int(bs, 1);
pps->num_extra_slice_header_bits = gf_bs_read_int(bs, 3);
/*sign_data_hiding_flag = */gf_bs_read_int(bs, 1);
pps->cabac_init_present_flag = gf_bs_read_int(bs, 1);
pps->num_ref_idx_l0_default_active = 1 + bs_get_ue(bs);
pps->num_ref_idx_l1_default_active = 1 + bs_get_ue(bs);
/*pic_init_qp_minus26 = */bs_get_se(bs);
/*constrained_intra_pred_flag = */gf_bs_read_int(bs, 1);
/*transform_skip_enabled_flag = */gf_bs_read_int(bs, 1);
if (/*cu_qp_delta_enabled_flag = */gf_bs_read_int(bs, 1) )
/*diff_cu_qp_delta_depth = */bs_get_ue(bs);
/*pic_cb_qp_offset = */bs_get_se(bs);
/*pic_cr_qp_offset = */bs_get_se(bs);
pps->slice_chroma_qp_offsets_present_flag = gf_bs_read_int(bs, 1);
pps->weighted_pred_flag = gf_bs_read_int(bs, 1);
pps->weighted_bipred_flag = gf_bs_read_int(bs, 1);
/*transquant_bypass_enable_flag = */gf_bs_read_int(bs, 1);
pps->tiles_enabled_flag = gf_bs_read_int(bs, 1);
pps->entropy_coding_sync_enabled_flag = gf_bs_read_int(bs, 1);
if (pps->tiles_enabled_flag) {
pps->num_tile_columns = 1 + bs_get_ue(bs);
pps->num_tile_rows = 1 + bs_get_ue(bs);
pps->uniform_spacing_flag = gf_bs_read_int(bs, 1);
if (!pps->uniform_spacing_flag ) {
for (i=0; i<pps->num_tile_columns-1; i++) {
pps->column_width[i] = 1 + bs_get_ue(bs);
}
for (i=0; i<pps->num_tile_rows-1; i++) {
pps->row_height[i] = 1+bs_get_ue(bs);
}
}
pps->loop_filter_across_tiles_enabled_flag = gf_bs_read_int(bs, 1);
}
pps->loop_filter_across_slices_enabled_flag = gf_bs_read_int(bs, 1);
if( /*deblocking_filter_control_present_flag = */gf_bs_read_int(bs, 1) ) {
pps->deblocking_filter_override_enabled_flag = gf_bs_read_int(bs, 1);
if (! /*pic_disable_deblocking_filter_flag= */gf_bs_read_int(bs, 1) ) {
/*beta_offset_div2 = */bs_get_se(bs);
/*tc_offset_div2 = */bs_get_se(bs);
}
}
if (/*pic_scaling_list_data_present_flag = */gf_bs_read_int(bs, 1) ) {
hevc_scaling_list_data(bs);
}
pps->lists_modification_present_flag = gf_bs_read_int(bs, 1);
/*log2_parallel_merge_level_minus2 = */bs_get_ue(bs);
pps->slice_segment_header_extension_present_flag = gf_bs_read_int(bs, 1);
if ( /*pps_extension_flag= */gf_bs_read_int(bs, 1) ) {
while (gf_bs_available(bs) ) {
/*pps_extension_data_flag */ gf_bs_read_int(bs, 1);
}
}
return pps_id;
}
GF_EXPORT
s32 gf_media_hevc_read_pps(char *data, u32 size, HEVCState *hevc)
{
GF_BitStream *bs;
char *data_without_emulation_bytes = NULL;
u32 data_without_emulation_bytes_size = 0;
s32 pps_id = -1;
/*still contains emulation bytes*/
data_without_emulation_bytes_size = avc_emulation_bytes_remove_count(data, size);
if (!data_without_emulation_bytes_size) {
bs = gf_bs_new(data, size, GF_BITSTREAM_READ);
} else {
data_without_emulation_bytes = gf_malloc(size*sizeof(char));
data_without_emulation_bytes_size = avc_remove_emulation_bytes(data, data_without_emulation_bytes, size);
bs = gf_bs_new(data_without_emulation_bytes, data_without_emulation_bytes_size, GF_BITSTREAM_READ);
}
if (!bs) goto exit;
if (! hevc_parse_nal_header(bs, NULL, NULL, NULL)) goto exit;
pps_id = gf_media_hevc_read_pps_bs(bs, hevc);
exit:
if (bs) gf_bs_del(bs);
if (data_without_emulation_bytes) gf_free(data_without_emulation_bytes);
return pps_id;
}
GF_EXPORT
s32 gf_media_hevc_parse_nalu(char *data, u32 size, HEVCState *hevc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)
{
GF_BitStream *bs=NULL;
char *data_without_emulation_bytes = NULL;
u32 data_without_emulation_bytes_size = 0;
Bool is_slice = GF_FALSE;
s32 ret = -1;
HEVCSliceInfo n_state;
memcpy(&n_state, &hevc->s_info, sizeof(HEVCSliceInfo));
hevc->last_parsed_vps_id = hevc->last_parsed_sps_id = hevc->last_parsed_pps_id = -1;
hevc->s_info.entry_point_start_bits = -1;
hevc->s_info.payload_start_offset = -1;
data_without_emulation_bytes_size = avc_emulation_bytes_remove_count(data, size);
if (!data_without_emulation_bytes_size) {
bs = gf_bs_new(data, size, GF_BITSTREAM_READ);
} else {
/*still contains emulation bytes*/
data_without_emulation_bytes = gf_malloc(size*sizeof(char));
data_without_emulation_bytes_size = avc_remove_emulation_bytes(data, data_without_emulation_bytes, size);
bs = gf_bs_new(data_without_emulation_bytes, data_without_emulation_bytes_size, GF_BITSTREAM_READ);
}
if (!bs) goto exit;
if (! hevc_parse_nal_header(bs, nal_unit_type, temporal_id, layer_id)) goto exit;
n_state.nal_unit_type = *nal_unit_type;
switch (n_state.nal_unit_type) {
case GF_HEVC_NALU_ACCESS_UNIT:
case GF_HEVC_NALU_END_OF_SEQ:
case GF_HEVC_NALU_END_OF_STREAM:
ret = 1;
break;
/*slice_segment_layer_rbsp*/
case GF_HEVC_NALU_SLICE_TRAIL_N:
case GF_HEVC_NALU_SLICE_TRAIL_R:
case GF_HEVC_NALU_SLICE_TSA_N:
case GF_HEVC_NALU_SLICE_TSA_R:
case GF_HEVC_NALU_SLICE_STSA_N:
case GF_HEVC_NALU_SLICE_STSA_R:
case GF_HEVC_NALU_SLICE_BLA_W_LP:
case GF_HEVC_NALU_SLICE_BLA_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_N_LP:
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_IDR_N_LP:
case GF_HEVC_NALU_SLICE_CRA:
case GF_HEVC_NALU_SLICE_RADL_N:
case GF_HEVC_NALU_SLICE_RADL_R:
case GF_HEVC_NALU_SLICE_RASL_N:
case GF_HEVC_NALU_SLICE_RASL_R:
is_slice = GF_TRUE;
/* slice - read the info and compare.*/
ret = hevc_parse_slice_segment(bs, hevc, &n_state);
if (ret<0) goto exit;
hevc_compute_poc(&n_state);
ret = 0;
if (hevc->s_info.poc != n_state.poc) {
ret=1;
break;
}
if (n_state.first_slice_segment_in_pic_flag) {
if (!(*layer_id) || (n_state.prev_layer_id_plus1 && ((*layer_id) <= n_state.prev_layer_id_plus1 - 1)) ) {
ret = 1;
break;
}
}
break;
case GF_HEVC_NALU_SEQ_PARAM:
hevc->last_parsed_sps_id = gf_media_hevc_read_sps_bs(bs, hevc, *layer_id, NULL);
ret = 0;
break;
case GF_HEVC_NALU_PIC_PARAM:
hevc->last_parsed_pps_id = gf_media_hevc_read_pps_bs(bs, hevc);
ret = 0;
break;
case GF_HEVC_NALU_VID_PARAM:
hevc->last_parsed_vps_id = gf_media_hevc_read_vps_bs(bs, hevc, GF_FALSE);
ret = 0;
break;
default:
ret = 0;
break;
}
/* save _prev values */
if (ret && hevc->s_info.sps) {
n_state.frame_num_offset_prev = hevc->s_info.frame_num_offset;
n_state.frame_num_prev = hevc->s_info.frame_num;
n_state.poc_lsb_prev = hevc->s_info.poc_lsb;
n_state.poc_msb_prev = hevc->s_info.poc_msb;
n_state.prev_layer_id_plus1 = *layer_id + 1;
}
if (is_slice) hevc_compute_poc(&n_state);
memcpy(&hevc->s_info, &n_state, sizeof(HEVCSliceInfo));
exit:
if (bs) gf_bs_del(bs);
if (data_without_emulation_bytes) gf_free(data_without_emulation_bytes);
return ret;
}
static u8 hevc_get_sar_idx(u32 w, u32 h)
{
u32 i;
for (i=0; i<14; i++) {
if ((avc_sar[i].w==w) && (avc_sar[i].h==h)) return i;
}
return 0xFF;
}
GF_Err gf_media_hevc_change_par(GF_HEVCConfig *hvcc, s32 ar_n, s32 ar_d)
{
GF_BitStream *orig, *mod;
HEVCState hevc;
u32 i, bit_offset, flag;
s32 idx;
GF_HEVCParamArray *spss;
GF_AVCConfigSlot *slc;
orig = NULL;
memset(&hevc, 0, sizeof(HEVCState));
hevc.sps_active_idx = -1;
i=0;
spss = NULL;
while ((spss = (GF_HEVCParamArray *)gf_list_enum(hvcc->param_array, &i))) {
if (spss->type==GF_HEVC_NALU_SEQ_PARAM)
break;
spss = NULL;
}
if (!spss) return GF_NON_COMPLIANT_BITSTREAM;
i=0;
while ((slc = (GF_AVCConfigSlot *)gf_list_enum(spss->nalus, &i))) {
char *no_emulation_buf = NULL;
u32 no_emulation_buf_size = 0, emulation_bytes = 0;
/*SPS may still contains emulation bytes*/
no_emulation_buf = gf_malloc((slc->size)*sizeof(char));
no_emulation_buf_size = avc_remove_emulation_bytes(slc->data, no_emulation_buf, slc->size);
idx = gf_media_hevc_read_sps_ex(no_emulation_buf, no_emulation_buf_size, &hevc, &bit_offset);
if (idx<0) {
if ( orig )
gf_bs_del(orig);
gf_free(no_emulation_buf);
continue;
}
orig = gf_bs_new(no_emulation_buf, no_emulation_buf_size, GF_BITSTREAM_READ);
mod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
/*copy over till vui flag*/
assert(bit_offset >= 0);
while (bit_offset) {
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, flag, 1);
bit_offset--;
}
/*check VUI*/
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, 1, 1); /*vui_parameters_present_flag*/
if (flag) {
/*aspect_ratio_info_present_flag*/
if (gf_bs_read_int(orig, 1)) {
s32 aspect_ratio_idc = gf_bs_read_int(orig, 8);
if (aspect_ratio_idc == 255) {
gf_bs_read_int(orig, 16); /*AR num*/
gf_bs_read_int(orig, 16); /*AR den*/
}
}
}
if ((ar_d<0) || (ar_n<0)) {
/*no AR signaled*/
gf_bs_write_int(mod, 0, 1);
} else {
u32 sarx;
gf_bs_write_int(mod, 1, 1);
sarx = hevc_get_sar_idx((u32) ar_n, (u32) ar_d);
gf_bs_write_int(mod, sarx, 8);
if (sarx==0xFF) {
gf_bs_write_int(mod, ar_n, 16);
gf_bs_write_int(mod, ar_d, 16);
}
}
/*no VUI in input bitstream, set all vui flags to 0*/
if (!flag) {
gf_bs_write_int(mod, 0, 1); /*overscan_info_present_flag */
gf_bs_write_int(mod, 0, 1); /*video_signal_type_present_flag */
gf_bs_write_int(mod, 0, 1); /*chroma_location_info_present_flag */
gf_bs_write_int(mod, 0, 1); /*neutra_chroma_indication_flag */;
gf_bs_write_int(mod, 0, 1); /*field_seq_flag */;
gf_bs_write_int(mod, 0, 1); /*frame_field_info_present_flag*/;
gf_bs_write_int(mod, 0, 1); /*default_display_window_flag*/;
gf_bs_write_int(mod, 0, 1); /*timing_info_present_flag*/
gf_bs_write_int(mod, 0, 1); /*bitstream_restriction*/
}
/*finally copy over remaining*/
while (gf_bs_bits_available(orig)) {
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, flag, 1);
}
gf_bs_del(orig);
orig = NULL;
gf_free(no_emulation_buf);
/*set anti-emulation*/
gf_bs_get_content(mod, (char **) &no_emulation_buf, &no_emulation_buf_size);
emulation_bytes = avc_emulation_bytes_add_count(no_emulation_buf, no_emulation_buf_size);
if (no_emulation_buf_size + emulation_bytes > slc->size)
slc->data = (char*)gf_realloc(slc->data, no_emulation_buf_size + emulation_bytes);
slc->size = avc_add_emulation_bytes(no_emulation_buf, slc->data, no_emulation_buf_size);
gf_bs_del(mod);
gf_free(no_emulation_buf);
}
return GF_OK;
}
GF_EXPORT
GF_Err gf_hevc_get_sps_info_with_state(HEVCState *hevc, char *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)
{
s32 idx;
idx = gf_media_hevc_read_sps(sps_data, sps_size, hevc);
if (idx<0) {
return GF_NON_COMPLIANT_BITSTREAM;
}
if (sps_id) *sps_id = idx;
if (width) *width = hevc->sps[idx].width;
if (height) *height = hevc->sps[idx].height;
if (par_n) *par_n = hevc->sps[idx].aspect_ratio_info_present_flag ? hevc->sps[idx].sar_width : (u32) -1;
if (par_d) *par_d = hevc->sps[idx].aspect_ratio_info_present_flag ? hevc->sps[idx].sar_height : (u32) -1;
return GF_OK;
}
GF_EXPORT
GF_Err gf_hevc_get_sps_info(char *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)
{
HEVCState hevc;
memset(&hevc, 0, sizeof(HEVCState));
hevc.sps_active_idx = -1;
return gf_hevc_get_sps_info_with_state(&hevc, sps_data, sps_size, sps_id, width, height, par_n, par_d);
}
#endif //GPAC_DISABLE_HEVC
static u32 AC3_FindSyncCode(u8 *buf, u32 buflen)
{
u32 end = buflen - 6;
u32 offset = 0;
while (offset <= end) {
if (buf[offset] == 0x0b && buf[offset + 1] == 0x77) {
return offset;
}
offset++;
}
return buflen;
}
static Bool AC3_FindSyncCodeBS(GF_BitStream *bs)
{
u8 b1;
u64 pos = gf_bs_get_position(bs);
u64 end = gf_bs_get_size(bs) - 6;
pos += 1;
b1 = gf_bs_read_u8(bs);
while (pos <= end) {
u8 b2 = gf_bs_read_u8(bs);
if ((b1 == 0x0b) && (b2==0x77)) {
gf_bs_seek(bs, pos-1);
return GF_TRUE;
}
pos++;
b1 = b2;
}
return GF_FALSE;
}
static const u32 ac3_sizecod_to_bitrate[] = {
32000, 40000, 48000, 56000, 64000, 80000, 96000,
112000, 128000, 160000, 192000, 224000, 256000,
320000, 384000, 448000, 512000, 576000, 640000
};
static const u32 ac3_sizecod2_to_framesize[] = {
96, 120, 144, 168, 192, 240, 288, 336, 384, 480, 576, 672,
768, 960, 1152, 1344, 1536, 1728, 1920
};
static const u32 ac3_sizecod1_to_framesize[] = {
69, 87, 104, 121, 139, 174, 208, 243, 278, 348, 417, 487,
557, 696, 835, 975, 1114, 1253, 1393
};
static const u32 ac3_sizecod0_to_framesize[] = {
64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448,
512, 640, 768, 896, 1024, 1152, 1280
};
static const u32 ac3_mod_to_chans[] = {
2, 1, 2, 3, 3, 4, 4, 5
};
GF_EXPORT
u32 gf_ac3_get_channels(u32 acmod)
{
u32 nb_ch;
nb_ch = ac3_mod_to_chans[acmod];
return nb_ch;
}
GF_EXPORT
u32 gf_ac3_get_bitrate(u32 brcode)
{
return ac3_sizecod_to_bitrate[brcode];
}
Bool gf_ac3_parser(u8 *buf, u32 buflen, u32 *pos, GF_AC3Header *hdr, Bool full_parse)
{
GF_BitStream *bs;
Bool ret;
if (buflen < 6) return GF_FALSE;
(*pos) = AC3_FindSyncCode(buf, buflen);
if (*pos >= buflen) return GF_FALSE;
bs = gf_bs_new((const char*)(buf+*pos), buflen, GF_BITSTREAM_READ);
ret = gf_ac3_parser_bs(bs, hdr, full_parse);
gf_bs_del(bs);
return ret;
}
GF_EXPORT
Bool gf_ac3_parser_bs(GF_BitStream *bs, GF_AC3Header *hdr, Bool full_parse)
{
u32 fscod, frmsizecod, bsid, ac3_mod, freq, framesize, bsmod, syncword;
u64 pos;
if (!hdr || (gf_bs_available(bs) < 6)) return GF_FALSE;
if (!AC3_FindSyncCodeBS(bs)) return GF_FALSE;
pos = gf_bs_get_position(bs);
syncword = gf_bs_read_u16(bs);
if (syncword != 0x0B77) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AC3] Wrong sync word detected (0x%X - expecting 0x0B77).\n", syncword));
return GF_FALSE;
}
gf_bs_read_u16(bs); //crc1
fscod = gf_bs_read_int(bs, 2);
frmsizecod = gf_bs_read_int(bs, 6);
bsid = gf_bs_read_int(bs, 5);
bsmod = gf_bs_read_int(bs, 3);
ac3_mod = gf_bs_read_int(bs, 3);
hdr->bitrate = ac3_sizecod_to_bitrate[frmsizecod / 2];
if (bsid > 8) hdr->bitrate = hdr->bitrate >> (bsid - 8);
switch (fscod) {
case 0:
freq = 48000;
framesize = ac3_sizecod0_to_framesize[frmsizecod / 2] * 2;
break;
case 1:
freq = 44100;
framesize = (ac3_sizecod1_to_framesize[frmsizecod / 2] + (frmsizecod & 0x1)) * 2;
break;
case 2:
freq = 32000;
framesize = ac3_sizecod2_to_framesize[frmsizecod / 2] * 2;
break;
default:
return GF_FALSE;
}
hdr->sample_rate = freq;
hdr->framesize = framesize;
if (full_parse) {
hdr->bsid = bsid;
hdr->bsmod = bsmod;
hdr->acmod = ac3_mod;
hdr->lfon = 0;
hdr->fscod = fscod;
hdr->brcode = frmsizecod / 2;
}
hdr->channels = ac3_mod_to_chans[ac3_mod];
if ((ac3_mod & 0x1) && (ac3_mod != 1)) gf_bs_read_int(bs, 2);
if (ac3_mod & 0x4) gf_bs_read_int(bs, 2);
if (ac3_mod == 0x2) gf_bs_read_int(bs, 2);
/*LFEon*/
if (gf_bs_read_int(bs, 1)) {
hdr->channels += 1;
hdr->lfon = 1;
}
gf_bs_seek(bs, pos);
return GF_TRUE;
}
GF_EXPORT
Bool gf_eac3_parser_bs(GF_BitStream *bs, GF_AC3Header *hdr, Bool full_parse)
{
u32 fscod, bsid, ac3_mod, freq, framesize, syncword, substreamid, lfon, channels, numblkscod;
u64 pos;
restart:
if (!hdr || (gf_bs_available(bs) < 6))
return GF_FALSE;
if (!AC3_FindSyncCodeBS(bs))
return GF_FALSE;
pos = gf_bs_get_position(bs);
framesize = 0;
numblkscod = 0;
block:
syncword = gf_bs_read_u16(bs);
if (syncword != 0x0B77) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[E-AC3] Wrong sync word detected (0x%X - expecting 0x0B77).\n", syncword));
return GF_FALSE;
}
gf_bs_read_int(bs, 2); //strmtyp
substreamid = gf_bs_read_int(bs, 3);
framesize += gf_bs_read_int(bs, 11);
fscod = gf_bs_read_int(bs, 2);
if (fscod == 0x3) {
fscod = gf_bs_read_int(bs, 2);
numblkscod += 6;
} else {
numblkscod += gf_bs_read_int(bs, 2);
}
assert(numblkscod <= 9);
if ((hdr->substreams >> substreamid) & 0x1) {
if (!substreamid) {
hdr->framesize = framesize;
if (numblkscod < 6) { //we need 6 blocks to make a sample
gf_bs_seek(bs, pos+2*framesize);
if ((gf_bs_available(bs) < 6) || !AC3_FindSyncCodeBS(bs))
return GF_FALSE;
goto block;
}
gf_bs_seek(bs, pos);
return GF_TRUE;
} else {
GF_LOG(GF_LOG_INFO, GF_LOG_CODING, ("[E-AC3] Detected sample in substream id=%u. Skipping.\n", substreamid));
gf_bs_seek(bs, pos+framesize);
goto restart;
}
}
hdr->substreams |= (1 << substreamid);
switch (fscod) {
case 0:
freq = 48000;
break;
case 1:
freq = 44100;
break;
case 2:
freq = 32000;
break;
default:
return GF_FALSE;
}
ac3_mod = gf_bs_read_int(bs, 3);
lfon = gf_bs_read_int(bs, 1);
bsid = gf_bs_read_int(bs, 5);
if (!substreamid && (bsid!=16/*E-AC3*/))
return GF_FALSE;
channels = ac3_mod_to_chans[ac3_mod];
if (lfon)
channels += 1;
if (substreamid) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[E-AC3] Detected additional %u channels in substream id=%u - may not be handled correctly. Skipping.\n", channels, substreamid));
gf_bs_seek(bs, pos+framesize);
goto restart;
} else {
hdr->bitrate = 0;
hdr->sample_rate = freq;
hdr->framesize = framesize;
hdr->lfon = lfon;
hdr->channels = channels;
if (full_parse) {
hdr->bsid = bsid;
hdr->bsmod = 0;
hdr->acmod = ac3_mod;
hdr->fscod = fscod;
hdr->brcode = 0;
}
}
if (numblkscod < 6) { //we need 6 blocks to make a sample
gf_bs_seek(bs, pos+2*framesize);
if ((gf_bs_available(bs) < 6) || !AC3_FindSyncCodeBS(bs))
return GF_FALSE;
goto block;
}
gf_bs_seek(bs, pos);
return GF_TRUE;
}
#endif /*GPAC_DISABLE_AV_PARSERS*/
#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined (GPAC_DISABLE_OGG)
/*
Vorbis parser
*/
static u32 vorbis_book_maptype1_quantvals(u32 entries, u32 dim)
{
u32 vals = (u32) floor(pow(entries, 1.0/dim));
while(1) {
u32 acc=1;
u32 acc1=1;
u32 i;
for (i=0; i<dim; i++) {
acc*=vals;
acc1*=vals+1;
}
if(acc<=entries && acc1>entries) return (vals);
else {
if (acc>entries) vals--;
else vals++;
}
}
}
u32 _ilog_(u32 v)
{
u32 ret=0;
while(v) {
ret++;
v>>=1;
}
return(ret);
}
static u32 ilog(u32 v)
{
u32 ret=0;
if(v) --v;
while(v) {
ret++;
v>>=1;
}
return (ret);
}
static u32 icount(u32 v)
{
u32 ret=0;
while(v) {
ret += v&1;
v>>=1;
}
return(ret);
}
GF_EXPORT
Bool gf_vorbis_parse_header(GF_VorbisParser *vp, char *data, u32 data_len)
{
u32 pack_type, i, j, k, times, nb_part, nb_books, nb_modes;
char szNAME[8];
oggpack_buffer opb;
oggpack_readinit(&opb, (u8*)data, data_len);
pack_type = oggpack_read(&opb, 8);
i=0;
while (i<6) {
szNAME[i] = oggpack_read(&opb, 8);
i++;
}
szNAME[i] = 0;
if (strcmp(szNAME, "vorbis")) return vp->is_init = 0;
switch (pack_type) {
case 0x01:
vp->version = oggpack_read(&opb, 32);
if (vp->version!=0) return 0;
vp->channels = oggpack_read(&opb, 8);
vp->sample_rate = oggpack_read(&opb, 32);
vp->max_r = oggpack_read(&opb, 32);
vp->avg_r = oggpack_read(&opb, 32);
vp->low_r = oggpack_read(&opb, 32);
vp->min_block = 1<<oggpack_read(&opb, 4);
vp->max_block = 1<<oggpack_read(&opb, 4);
if (vp->sample_rate < 1) return vp->is_init = 0;
if (vp->channels < 1) return vp->is_init = 0;
if (vp->min_block<8) return vp->is_init = 0;
if (vp->max_block < vp->min_block) return vp->is_init = 0;
if (oggpack_read(&opb, 1) != 1) return vp->is_init = 0;
vp->is_init = 1;
return 1;
case 0x03:
/*trash comments*/
vp->is_init ++;
return 1;
case 0x05:
/*need at least bitstream header to make sure we're parsing the right thing*/
if (!vp->is_init) return 0;
break;
default:
vp->is_init = 0;
return 0;
}
/*OK parse codebook*/
nb_books = oggpack_read(&opb, 8) + 1;
/*skip vorbis static books*/
for (i=0; i<nb_books; i++) {
u32 j, map_type, qb, qq;
u32 entries, dim;
oggpack_read(&opb, 24);
dim = oggpack_read(&opb, 16);
entries = oggpack_read(&opb, 24);
if ( (s32) entries < 0) entries = 0;
if (oggpack_read(&opb, 1) == 0) {
if (oggpack_read(&opb, 1)) {
for (j=0; j<entries; j++) {
if (oggpack_read(&opb, 1)) {
oggpack_read(&opb, 5);
}
}
} else {
for (j=0; j<entries; j++)
oggpack_read(&opb, 5);
}
} else {
oggpack_read(&opb, 5);
for (j=0; j<entries;) {
u32 num = oggpack_read(&opb, _ilog_(entries-j));
for (k=0; k<num && j<entries; k++, j++) {
}
}
}
switch ((map_type=oggpack_read(&opb, 4))) {
case 0:
break;
case 1:
case 2:
oggpack_read(&opb, 32);
oggpack_read(&opb, 32);
qq = oggpack_read(&opb, 4)+1;
oggpack_read(&opb, 1);
if (map_type==1) qb = vorbis_book_maptype1_quantvals(entries, dim);
else if (map_type==2) qb = entries * dim;
else qb = 0;
for (j=0; j<qb; j++) oggpack_read(&opb, qq);
break;
}
}
times = oggpack_read(&opb, 6)+1;
for (i=0; i<times; i++) oggpack_read(&opb, 16);
times = oggpack_read(&opb, 6)+1;
for (i=0; i<times; i++) {
u32 type = oggpack_read(&opb, 16);
if (type) {
u32 *parts, *class_dims, count, rangebits;
u32 max_class = 0;
nb_part = oggpack_read(&opb, 5);
parts = (u32*)gf_malloc(sizeof(u32) * nb_part);
for (j=0; j<nb_part; j++) {
parts[j] = oggpack_read(&opb, 4);
if (max_class<parts[j]) max_class = parts[j];
}
class_dims = (u32*)gf_malloc(sizeof(u32) * (max_class+1));
for (j=0; j<max_class+1; j++) {
u32 class_sub;
class_dims[j] = oggpack_read(&opb, 3) + 1;
class_sub = oggpack_read(&opb, 2);
if (class_sub) oggpack_read(&opb, 8);
for (k=0; k < (u32) (1<<class_sub); k++) oggpack_read(&opb, 8);
}
oggpack_read(&opb, 2);
rangebits=oggpack_read(&opb, 4);
count = 0;
for (j=0,k=0; j<nb_part; j++) {
count+=class_dims[parts[j]];
for (; k<count; k++) oggpack_read(&opb, rangebits);
}
gf_free(parts);
gf_free(class_dims);
} else {
u32 j, nb_books;
oggpack_read(&opb, 8+16+16+6+8);
nb_books = oggpack_read(&opb, 4)+1;
for (j=0; j<nb_books; j++) oggpack_read(&opb, 8);
}
}
times = oggpack_read(&opb, 6)+1;
for (i=0; i<times; i++) {
u32 acc = 0;
oggpack_read(&opb, 16);/*type*/
oggpack_read(&opb, 24);
oggpack_read(&opb,24);
oggpack_read(&opb,24);
nb_part = oggpack_read(&opb, 6)+1;
oggpack_read(&opb, 8);
for (j=0; j<nb_part; j++) {
u32 cascade = oggpack_read(&opb, 3);
if (oggpack_read(&opb, 1)) cascade |= (oggpack_read(&opb, 5)<<3);
acc += icount(cascade);
}
for (j=0; j<acc; j++) oggpack_read(&opb, 8);
}
times = oggpack_read(&opb, 6)+1;
for (i=0; i<times; i++) {
u32 sub_maps = 1;
oggpack_read(&opb, 16);
if (oggpack_read(&opb, 1)) sub_maps = oggpack_read(&opb, 4)+1;
if (oggpack_read(&opb, 1)) {
u32 nb_steps = oggpack_read(&opb, 8)+1;
for (j=0; j<nb_steps; j++) {
oggpack_read(&opb, ilog(vp->channels));
oggpack_read(&opb, ilog(vp->channels));
}
}
oggpack_read(&opb, 2);
if (sub_maps>1) {
for(j=0; j<vp->channels; j++) oggpack_read(&opb, 4);
}
for (j=0; j<sub_maps; j++) {
oggpack_read(&opb, 8);
oggpack_read(&opb, 8);
oggpack_read(&opb, 8);
}
}
nb_modes = oggpack_read(&opb, 6)+1;
for (i=0; i<nb_modes; i++) {
vp->mode_flag[i] = oggpack_read(&opb, 1);
oggpack_read(&opb, 16);
oggpack_read(&opb, 16);
oggpack_read(&opb, 8);
}
vp->modebits = 0;
j = nb_modes;
while(j>1) {
vp->modebits++;
j>>=1;
}
return 1;
}
GF_EXPORT
u32 gf_vorbis_check_frame(GF_VorbisParser *vp, char *data, u32 data_length)
{
s32 block_size;
oggpack_buffer opb;
if (!vp->is_init) return 0;
oggpack_readinit(&opb, (unsigned char*)data, data_length);
/*not audio*/
if (oggpack_read(&opb, 1) !=0) return 0;
block_size = oggpack_read(&opb, vp->modebits);
if (block_size == -1) return 0;
return ((vp->mode_flag[block_size]) ? vp->max_block : vp->min_block) / (2);
}
#endif /*!defined(GPAC_DISABLE_AV_PARSERS) && !defined (GPAC_DISABLE_OGG)*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_651_2 |
crossvul-cpp_data_bad_525_0 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / mp4box application
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/tools.h>
#include <gpac/media_tools.h>
#include <gpac/constants.h>
#include <gpac/scene_manager.h>
#include <gpac/network.h>
#include <gpac/base_coding.h>
#if !defined(GPAC_DISABLE_VRML) && !defined(GPAC_DISABLE_X3D) && !defined(GPAC_DISABLE_SVG)
#include <gpac/scenegraph.h>
#endif
#ifndef GPAC_DISABLE_BIFS
#include <gpac/bifs.h>
#endif
#ifndef GPAC_DISABLE_VRML
#include <gpac/nodes_mpeg4.h>
#endif
#ifndef GPAC_DISABLE_ISOM_WRITE
#include <gpac/xml.h>
#include <gpac/internal/isomedia_dev.h>
typedef struct
{
const char *root_file;
const char *dir;
GF_List *imports;
} WGTEnum;
GF_Err set_file_udta(GF_ISOFile *dest, u32 tracknum, u32 udta_type, char *src, Bool is_box_array)
{
char *data = NULL;
GF_Err res = GF_OK;
u32 size;
bin128 uuid;
memset(uuid, 0 , 16);
if (!udta_type && !is_box_array) return GF_BAD_PARAM;
if (!src) {
return gf_isom_remove_user_data(dest, tracknum, udta_type, uuid);
}
#ifndef GPAC_DISABLE_CORE_TOOLS
if (!strnicmp(src, "base64", 6)) {
src += 7;
size = (u32) strlen(src);
data = gf_malloc(sizeof(char) * size);
size = gf_base64_decode(src, size, data, size);
} else
#endif
{
FILE *t = gf_fopen(src, "rb");
if (!t) return GF_IO_ERR;
fseek(t, 0, SEEK_END);
size = ftell(t);
fseek(t, 0, SEEK_SET);
data = gf_malloc(sizeof(char)*size);
if (size != fread(data, 1, size, t) ) {
gf_free(data);
gf_fclose(t);
return GF_IO_ERR;
}
gf_fclose(t);
}
if (size && data) {
if (is_box_array) {
res = gf_isom_add_user_data_boxes(dest, tracknum, data, size);
} else {
res = gf_isom_add_user_data(dest, tracknum, udta_type, uuid, data, size);
}
gf_free(data);
}
return res;
}
#ifndef GPAC_DISABLE_MEDIA_IMPORT
extern u32 swf_flags;
extern Float swf_flatten_angle;
extern Bool keep_sys_tracks;
void scene_coding_log(void *cbk, GF_LOG_Level log_level, GF_LOG_Tool log_tool, const char *fmt, va_list vlist);
void convert_file_info(char *inName, u32 trackID)
{
GF_Err e;
u32 i;
Bool found;
GF_MediaImporter import;
memset(&import, 0, sizeof(GF_MediaImporter));
import.trackID = trackID;
import.in_name = inName;
import.flags = GF_IMPORT_PROBE_ONLY;
e = gf_media_import(&import);
if (e) {
fprintf(stderr, "Error probing file %s: %s\n", inName, gf_error_to_string(e));
return;
}
if (trackID) {
fprintf(stderr, "Import probing results for track %s#%d:\n", inName, trackID);
} else {
fprintf(stderr, "Import probing results for %s:\n", inName);
if (!import.nb_tracks) {
fprintf(stderr, "File has no selectable tracks\n");
return;
}
fprintf(stderr, "File has %d tracks\n", import.nb_tracks);
}
if (import.probe_duration) {
fprintf(stderr, "Duration: %g s\n", (Double) (import.probe_duration/1000.0));
}
found = 0;
for (i=0; i<import.nb_tracks; i++) {
if (trackID && (trackID != import.tk_info[i].track_num)) continue;
if (!trackID) fprintf(stderr, "\tTrack %d type: ", import.tk_info[i].track_num);
else fprintf(stderr, "Track type: ");
switch (import.tk_info[i].type) {
case GF_ISOM_MEDIA_VISUAL:
fprintf(stderr, "Video (%s)", gf_4cc_to_str(import.tk_info[i].media_type));
if (import.tk_info[i].video_info.temporal_enhancement) fprintf(stderr, " Temporal Enhancement");
break;
case GF_ISOM_MEDIA_AUXV:
fprintf(stderr, "Auxiliary Video (%s)", gf_4cc_to_str(import.tk_info[i].media_type));
break;
case GF_ISOM_MEDIA_PICT:
fprintf(stderr, "Picture Sequence (%s)", gf_4cc_to_str(import.tk_info[i].media_type));
break;
case GF_ISOM_MEDIA_AUDIO:
fprintf(stderr, "Audio (%s)", gf_4cc_to_str(import.tk_info[i].media_type));
break;
case GF_ISOM_MEDIA_TEXT:
fprintf(stderr, "Text (%s)", gf_4cc_to_str(import.tk_info[i].media_type));
break;
case GF_ISOM_MEDIA_SCENE:
fprintf(stderr, "Scene (%s)", gf_4cc_to_str(import.tk_info[i].media_type));
break;
case GF_ISOM_MEDIA_OD:
fprintf(stderr, "OD (%s)", gf_4cc_to_str(import.tk_info[i].media_type));
break;
case GF_ISOM_MEDIA_META:
fprintf(stderr, "Metadata (%s)", gf_4cc_to_str(import.tk_info[i].media_type));
break;
default:
fprintf(stderr, "Other (4CC: %s)", gf_4cc_to_str(import.tk_info[i].type));
break;
}
if (import.tk_info[i].lang) fprintf(stderr, " - lang %s", gf_4cc_to_str(import.tk_info[i].lang));
if (import.tk_info[i].mpeg4_es_id) fprintf(stderr, " - MPEG-4 ESID %d", import.tk_info[i].mpeg4_es_id);
if (import.tk_info[i].prog_num) {
if (!import.nb_progs) {
fprintf(stderr, " - Program %d", import.tk_info[i].prog_num);
} else {
u32 j;
for (j=0; j<import.nb_progs; j++) {
if (import.tk_info[i].prog_num != import.pg_info[j].number) continue;
fprintf(stderr, " - Program %s", import.pg_info[j].name);
break;
}
}
}
fprintf(stderr, "\n");
if (!trackID) continue;
if (gf_isom_is_video_subtype(import.tk_info[i].type) && import.tk_info[i].video_info.width && import.tk_info[i].video_info.height
) {
fprintf(stderr, "Source: %s %dx%d", gf_4cc_to_str(import.tk_info[i].media_type), import.tk_info[i].video_info.width, import.tk_info[i].video_info.height);
if (import.tk_info[i].video_info.FPS) fprintf(stderr, " @ %g FPS", import.tk_info[i].video_info.FPS);
if (import.tk_info[i].video_info.par) fprintf(stderr, " PAR: %d:%d", import.tk_info[i].video_info.par >> 16, import.tk_info[i].video_info.par & 0xFFFF);
fprintf(stderr, "\n");
}
else if ((import.tk_info[i].type==GF_ISOM_MEDIA_AUDIO) && import.tk_info[i].audio_info.sample_rate) {
fprintf(stderr, "Source: %s - SampleRate %d - %d channels\n", gf_4cc_to_str(import.tk_info[i].media_type), import.tk_info[i].audio_info.sample_rate, import.tk_info[i].audio_info.nb_channels);
} else {
fprintf(stderr, "Source: %s\n", gf_4cc_to_str(import.tk_info[i].media_type));
}
fprintf(stderr, "\nImport Capabilities:\n");
if (import.tk_info[i].flags & GF_IMPORT_USE_DATAREF) fprintf(stderr, "\tCan use data referencing\n");
if (import.tk_info[i].flags & GF_IMPORT_NO_FRAME_DROP) fprintf(stderr, "\tCan use fixed FPS import\n");
if (import.tk_info[i].flags & GF_IMPORT_FORCE_PACKED) fprintf(stderr, "\tCan force packed bitstream import\n");
if (import.tk_info[i].flags & GF_IMPORT_OVERRIDE_FPS) fprintf(stderr, "\tCan override source frame rate\n");
if (import.tk_info[i].flags & (GF_IMPORT_SBR_IMPLICIT|GF_IMPORT_SBR_EXPLICIT)) fprintf(stderr, "\tCan use AAC-SBR signaling\n");
if (import.tk_info[i].flags & (GF_IMPORT_PS_IMPLICIT|GF_IMPORT_PS_EXPLICIT)) fprintf(stderr, "\tCan use AAC-PS signaling\n");
if (import.tk_info[i].flags & GF_IMPORT_FORCE_MPEG4) fprintf(stderr, "\tCan force MPEG-4 Systems signaling\n");
if (import.tk_info[i].flags & GF_IMPORT_3GPP_AGGREGATION) fprintf(stderr, "\tCan use 3GPP frame aggregation\n");
if (import.tk_info[i].flags & GF_IMPORT_NO_DURATION) fprintf(stderr, "\tCannot use duration-based import\n");
found = 1;
break;
}
fprintf(stderr, "\n");
if (!found && trackID) fprintf(stderr, "Cannot find track %d in file\n", trackID);
}
static void set_chapter_track(GF_ISOFile *file, u32 track, u32 chapter_ref_trak)
{
u64 ref_duration, chap_duration;
Double scale;
gf_isom_set_track_reference(file, chapter_ref_trak, GF_ISOM_REF_CHAP, gf_isom_get_track_id(file, track) );
gf_isom_set_track_enabled(file, track, 0);
ref_duration = gf_isom_get_media_duration(file, chapter_ref_trak);
chap_duration = gf_isom_get_media_duration(file, track);
scale = (Double) (s64) gf_isom_get_media_timescale(file, track);
scale /= gf_isom_get_media_timescale(file, chapter_ref_trak);
ref_duration = (u64) (ref_duration * scale);
if (chap_duration < ref_duration) {
chap_duration -= gf_isom_get_sample_duration(file, track, gf_isom_get_sample_count(file, track));
chap_duration = ref_duration - chap_duration;
gf_isom_set_last_sample_duration(file, track, (u32) chap_duration);
}
}
GF_Err import_file(GF_ISOFile *dest, char *inName, u32 import_flags, Double force_fps, u32 frames_per_sample)
{
u32 track_id, i, j, timescale, track, stype, profile, level, new_timescale, rescale, svc_mode, txt_flags, split_tile_mode, temporal_mode;
s32 par_d, par_n, prog_id, delay, force_rate;
s32 tw, th, tx, ty, txtw, txth, txtx, txty;
Bool do_audio, do_video, do_auxv,do_pict, do_all, disable, track_layout, text_layout, chap_ref, is_chap, is_chap_file, keep_handler, negative_cts_offset, rap_only, refs_only;
u32 group, handler, rvc_predefined, check_track_for_svc, check_track_for_lhvc, check_track_for_hevc;
const char *szLan;
GF_Err e;
GF_MediaImporter import;
char *ext, szName[1000], *handler_name, *rvc_config, *chapter_name;
GF_List *kinds;
GF_TextFlagsMode txt_mode = GF_ISOM_TEXT_FLAGS_OVERWRITE;
u8 max_layer_id_plus_one, max_temporal_id_plus_one;
rvc_predefined = 0;
chapter_name = NULL;
new_timescale = 1;
rescale = 0;
text_layout = 0;
/*0: merge all
1: split base and all SVC in two tracks
2: split all base and SVC layers in dedicated tracks
*/
svc_mode = 0;
memset(&import, 0, sizeof(GF_MediaImporter));
strcpy(szName, inName);
#ifdef WIN32
/*dirty hack for msys&mingw: when we use import options, the ':' separator used prevents msys from translating the path
we do this for regular cases where the path starts with the drive letter. If the path start with anything else (/home , /opt, ...) we're screwed :( */
if ( (szName[0]=='/') && (szName[2]=='/')) {
szName[0] = szName[1];
szName[1] = ':';
}
#endif
is_chap_file = 0;
handler = 0;
disable = 0;
chap_ref = 0;
is_chap = 0;
kinds = gf_list_new();
track_layout = 0;
szLan = NULL;
delay = 0;
group = 0;
stype = 0;
profile = level = 0;
negative_cts_offset = 0;
split_tile_mode = 0;
temporal_mode = 0;
rap_only = 0;
refs_only = 0;
txt_flags = 0;
max_layer_id_plus_one = max_temporal_id_plus_one = 0;
force_rate = -1;
tw = th = tx = ty = txtw = txth = txtx = txty = 0;
par_d = par_n = -2;
/*use ':' as separator, but beware DOS paths...*/
ext = strchr(szName, ':');
if (ext && ext[1]=='\\') ext = strchr(szName+2, ':');
handler_name = NULL;
rvc_config = NULL;
while (ext) {
char *ext2 = strchr(ext+1, ':');
// if the colon is part of a file path/url we keep it
if (ext2 && !strncmp(ext2, "://", 3) ) {
ext2[0] = ':';
ext2 = strchr(ext2+1, ':');
}
// keep windows drive: path, can be after a file://
if (ext2 && ( !strncmp(ext2, ":\\", 2) || !strncmp(ext2, ":/", 2) ) ) {
ext2[0] = ':';
ext2 = strchr(ext2+1, ':');
}
if (ext2) ext2[0] = 0;
/*all extensions for track-based importing*/
if (!strnicmp(ext+1, "dur=", 4)) import.duration = (u32)( (atof(ext+5) * 1000) + 0.5 );
else if (!strnicmp(ext+1, "lang=", 5)) {
/* prevent leak if param is set twice */
if (szLan)
gf_free((char*) szLan);
szLan = gf_strdup(ext+6);
}
else if (!strnicmp(ext+1, "delay=", 6)) delay = atoi(ext+7);
else if (!strnicmp(ext+1, "par=", 4)) {
if (!stricmp(ext+5, "none")) {
par_n = par_d = -1;
} else {
if (ext2) ext2[0] = ':';
if (ext2) ext2 = strchr(ext2+1, ':');
if (ext2) ext2[0] = 0;
sscanf(ext+5, "%d:%d", &par_n, &par_d);
}
}
else if (!strnicmp(ext+1, "name=", 5)) {
handler_name = gf_strdup(ext+6);
}
else if (!strnicmp(ext+1, "ext=", 4)) {
/*extensions begin with '.'*/
if (*(ext+5) == '.')
import.force_ext = gf_strdup(ext+5);
else {
import.force_ext = gf_calloc(1+strlen(ext+5)+1, 1);
import.force_ext[0] = '.';
strcat(import.force_ext+1, ext+5);
}
}
else if (!strnicmp(ext+1, "hdlr=", 5)) handler = GF_4CC(ext[6], ext[7], ext[8], ext[9]);
else if (!strnicmp(ext+1, "disable", 7)) disable = 1;
else if (!strnicmp(ext+1, "group=", 6)) {
group = atoi(ext+7);
if (!group) group = gf_isom_get_next_alternate_group_id(dest);
}
else if (!strnicmp(ext+1, "fps=", 4)) {
if (!strcmp(ext+5, "auto")) force_fps = GF_IMPORT_AUTO_FPS;
else if (strchr(ext+5, '-')) {
u32 ticks, dts_inc;
sscanf(ext+5, "%u-%u", &ticks, &dts_inc);
if (!dts_inc) dts_inc=1;
force_fps = ticks;
force_fps /= dts_inc;
}
else force_fps = atof(ext+5);
}
else if (!stricmp(ext+1, "rap")) rap_only = 1;
else if (!stricmp(ext+1, "refs")) refs_only = 1;
else if (!stricmp(ext+1, "trailing")) import_flags |= GF_IMPORT_KEEP_TRAILING;
else if (!strnicmp(ext+1, "agg=", 4)) frames_per_sample = atoi(ext+5);
else if (!stricmp(ext+1, "dref")) import_flags |= GF_IMPORT_USE_DATAREF;
else if (!stricmp(ext+1, "keep_refs")) import_flags |= GF_IMPORT_KEEP_REFS;
else if (!stricmp(ext+1, "nodrop")) import_flags |= GF_IMPORT_NO_FRAME_DROP;
else if (!stricmp(ext+1, "packed")) import_flags |= GF_IMPORT_FORCE_PACKED;
else if (!stricmp(ext+1, "sbr")) import_flags |= GF_IMPORT_SBR_IMPLICIT;
else if (!stricmp(ext+1, "sbrx")) import_flags |= GF_IMPORT_SBR_EXPLICIT;
else if (!stricmp(ext+1, "ovsbr")) import_flags |= GF_IMPORT_OVSBR;
else if (!stricmp(ext+1, "ps")) import_flags |= GF_IMPORT_PS_IMPLICIT;
else if (!stricmp(ext+1, "psx")) import_flags |= GF_IMPORT_PS_EXPLICIT;
else if (!stricmp(ext+1, "mpeg4")) import_flags |= GF_IMPORT_FORCE_MPEG4;
else if (!stricmp(ext+1, "nosei")) import_flags |= GF_IMPORT_NO_SEI;
else if (!stricmp(ext+1, "svc") || !stricmp(ext+1, "lhvc") ) import_flags |= GF_IMPORT_SVC_EXPLICIT;
else if (!stricmp(ext+1, "nosvc") || !stricmp(ext+1, "nolhvc")) import_flags |= GF_IMPORT_SVC_NONE;
/*split SVC layers*/
else if (!strnicmp(ext+1, "svcmode=", 8) || !strnicmp(ext+1, "lhvcmode=", 9)) {
char *mode = ext+9;
if (mode[0]=='=') mode = ext+10;
if (!stricmp(mode, "splitnox"))
svc_mode = 3;
else if (!stricmp(mode, "splitnoxib"))
svc_mode = 4;
else if (!stricmp(mode, "splitall") || !stricmp(mode, "split"))
svc_mode = 2;
else if (!stricmp(mode, "splitbase"))
svc_mode = 1;
else if (!stricmp(mode, "merged"))
svc_mode = 0;
}
/*split SVC layers*/
else if (!strnicmp(ext+1, "temporal=", 9)) {
char *mode = ext+10;
if (!stricmp(mode, "split"))
temporal_mode = 2;
else if (!stricmp(mode, "splitnox"))
temporal_mode = 3;
else if (!stricmp(mode, "splitbase"))
temporal_mode = 1;
else {
fprintf(stderr, "Unrecognized temporal mode %s, ignoring\n", mode);
temporal_mode = 0;
}
}
else if (!stricmp(ext+1, "subsamples")) import_flags |= GF_IMPORT_SET_SUBSAMPLES;
else if (!stricmp(ext+1, "deps")) import_flags |= GF_IMPORT_SAMPLE_DEPS;
else if (!stricmp(ext+1, "forcesync")) import_flags |= GF_IMPORT_FORCE_SYNC;
else if (!stricmp(ext+1, "xps_inband")) import_flags |= GF_IMPORT_FORCE_XPS_INBAND;
else if (!strnicmp(ext+1, "max_lid=", 8) || !strnicmp(ext+1, "max_tid=", 8)) {
s32 val = atoi(ext+9);
if (val < 0) {
fprintf(stderr, "Warning: request max layer/temporal id is negative - ignoring\n");
} else {
if (!strnicmp(ext+1, "max_lid=", 8))
max_layer_id_plus_one = 1 + (u8) val;
else
max_temporal_id_plus_one = 1 + (u8) val;
}
}
else if (!stricmp(ext+1, "tiles")) split_tile_mode = 2;
else if (!stricmp(ext+1, "tiles_rle")) split_tile_mode = 3;
else if (!stricmp(ext+1, "split_tiles")) split_tile_mode = 1;
/*force all composition offsets to be positive*/
else if (!strnicmp(ext+1, "negctts", 7)) negative_cts_offset = 1;
else if (!strnicmp(ext+1, "stype=", 6)) {
stype = GF_4CC(ext[7], ext[8], ext[9], ext[10]);
}
else if (!stricmp(ext+1, "chap")) is_chap = 1;
else if (!strnicmp(ext+1, "chapter=", 8)) {
chapter_name = gf_strdup(ext+9);
}
else if (!strnicmp(ext+1, "chapfile=", 9)) {
chapter_name = gf_strdup(ext+10);
is_chap_file=1;
}
else if (!strnicmp(ext+1, "layout=", 7)) {
if ( sscanf(ext+8, "%dx%dx%dx%d", &tw, &th, &tx, &ty)==4) {
track_layout = 1;
} else if ( sscanf(ext+8, "%dx%d", &tw, &th)==2) {
track_layout = 1;
tx = ty = 0;
}
}
else if (!strnicmp(ext+1, "rescale=", 8)) {
rescale = atoi(ext+9);
}
else if (!strnicmp(ext+1, "timescale=", 10)) {
new_timescale = atoi(ext+11);
}
else if (!stricmp(ext+1, "noedit")) import_flags |= GF_IMPORT_NO_EDIT_LIST;
else if (!strnicmp(ext+1, "rvc=", 4)) {
if (sscanf(ext+5, "%d", &rvc_predefined) != 1) {
rvc_config = gf_strdup(ext+5);
}
}
else if (!strnicmp(ext+1, "fmt=", 4)) import.streamFormat = gf_strdup(ext+5);
else if (!strnicmp(ext+1, "profile=", 8)) profile = atoi(ext+9);
else if (!strnicmp(ext+1, "level=", 6)) level = atoi(ext+7);
else if (!strnicmp(ext+1, "novpsext", 8)) import_flags |= GF_IMPORT_NO_VPS_EXTENSIONS;
else if (!strnicmp(ext+1, "keepav1t", 8)) import_flags |= GF_IMPORT_KEEP_AV1_TEMPORAL_OBU;
else if (!strnicmp(ext+1, "font=", 5)) import.fontName = gf_strdup(ext+6);
else if (!strnicmp(ext+1, "size=", 5)) import.fontSize = atoi(ext+6);
else if (!strnicmp(ext+1, "text_layout=", 12)) {
if ( sscanf(ext+13, "%dx%dx%dx%d", &txtw, &txth, &txtx, &txty)==4) {
text_layout = 1;
} else if ( sscanf(ext+8, "%dx%d", &txtw, &txth)==2) {
track_layout = 1;
txtx = txty = 0;
}
}
#ifndef GPAC_DISABLE_SWF_IMPORT
else if (!stricmp(ext+1, "swf-global")) import.swf_flags |= GF_SM_SWF_STATIC_DICT;
else if (!stricmp(ext+1, "swf-no-ctrl")) import.swf_flags &= ~GF_SM_SWF_SPLIT_TIMELINE;
else if (!stricmp(ext+1, "swf-no-text")) import.swf_flags |= GF_SM_SWF_NO_TEXT;
else if (!stricmp(ext+1, "swf-no-font")) import.swf_flags |= GF_SM_SWF_NO_FONT;
else if (!stricmp(ext+1, "swf-no-line")) import.swf_flags |= GF_SM_SWF_NO_LINE;
else if (!stricmp(ext+1, "swf-no-grad")) import.swf_flags |= GF_SM_SWF_NO_GRADIENT;
else if (!stricmp(ext+1, "swf-quad")) import.swf_flags |= GF_SM_SWF_QUAD_CURVE;
else if (!stricmp(ext+1, "swf-xlp")) import.swf_flags |= GF_SM_SWF_SCALABLE_LINE;
else if (!stricmp(ext+1, "swf-ic2d")) import.swf_flags |= GF_SM_SWF_USE_IC2D;
else if (!stricmp(ext+1, "swf-same-app")) import.swf_flags |= GF_SM_SWF_REUSE_APPEARANCE;
else if (!strnicmp(ext+1, "swf-flatten=", 12)) import.swf_flatten_angle = (Float) atof(ext+13);
#endif
else if (!strnicmp(ext+1, "kind=", 5)) {
char *kind_scheme, *kind_value;
char *kind_data = ext+6;
char *sep = strchr(kind_data, '=');
if (sep) {
*sep = 0;
}
kind_scheme = gf_strdup(kind_data);
if (sep) {
*sep = '=';
kind_value = gf_strdup(sep+1);
} else {
kind_value = NULL;
}
gf_list_add(kinds, kind_scheme);
gf_list_add(kinds, kind_value);
}
else if (!strnicmp(ext+1, "txtflags", 8)) {
if (!strnicmp(ext+1, "txtflags=", 9)) {
sscanf(ext+10, "%x", &txt_flags);
}
else if (!strnicmp(ext+1, "txtflags+=", 10)) {
sscanf(ext+11, "%x", &txt_flags);
txt_mode = GF_ISOM_TEXT_FLAGS_TOGGLE;
}
else if (!strnicmp(ext+1, "txtflags-=", 10)) {
sscanf(ext+11, "%x", &txt_flags);
txt_mode = GF_ISOM_TEXT_FLAGS_UNTOGGLE;
}
}
else if (!strnicmp(ext+1, "rate=", 5)) {
force_rate = atoi(ext+6);
}
else if (!strnicmp(ext+1, "asemode=", 8)){
char *mode = ext+9;
if (!stricmp(mode, "v0-bs"))
import.asemode = GF_IMPORT_AUDIO_SAMPLE_ENTRY_v0_BS;
else if (!stricmp(mode, "v0-2"))
import.asemode = GF_IMPORT_AUDIO_SAMPLE_ENTRY_v0_2;
else if (!stricmp(mode, "v1"))
import.asemode = GF_IMPORT_AUDIO_SAMPLE_ENTRY_v1_MPEG;
else if (!stricmp(mode, "v1-qt"))
import.asemode = GF_IMPORT_AUDIO_SAMPLE_ENTRY_v1_QTFF;
}
else if (!strnicmp(ext+1, "audio_roll=", 11)) {
import.audio_roll_change = GF_TRUE;
import.audio_roll = atoi(ext+12);
}
/*unrecognized, assume name has colon in it*/
else {
fprintf(stderr, "Unrecognized import option %s, ignoring\n", ext+1);
ext = ext2;
continue;
}
if (ext2) ext2[0] = ':';
ext[0] = 0;
/* restart from where we stopped
* if we didn't stop (ext2 null) then the end has been reached
* so we can stop the whole thing */
ext = ext2;
}
/*check duration import (old syntax)*/
ext = strrchr(szName, '%');
if (ext) {
import.duration = (u32) (atof(ext+1) * 1000);
ext[0] = 0;
}
/*select switches for av containers import*/
do_audio = do_video = do_auxv = do_pict = 0;
track_id = prog_id = 0;
do_all = 1;
ext = strrchr(szName, '#');
if (ext) ext[0] = 0;
keep_handler = gf_isom_probe_file(szName);
import.in_name = szName;
import.flags = GF_IMPORT_PROBE_ONLY;
e = gf_media_import(&import);
if (e) goto exit;
if (ext) {
ext++;
if (!strnicmp(ext, "audio", 5)) do_audio = 1;
else if (!strnicmp(ext, "video", 5)) do_video = 1;
else if (!strnicmp(ext, "auxv", 4)) do_auxv = 1;
else if (!strnicmp(ext, "pict", 4)) do_pict = 1;
else if (!strnicmp(ext, "trackID=", 8)) track_id = atoi(&ext[8]);
else if (!strnicmp(ext, "PID=", 4)) track_id = atoi(&ext[4]);
else if (!strnicmp(ext, "program=", 8)) {
for (i=0; i<import.nb_progs; i++) {
if (!stricmp(import.pg_info[i].name, ext+8)) {
prog_id = import.pg_info[i].number;
do_all = 0;
break;
}
}
}
else if (!strnicmp(ext, "prog_id=", 8)) {
prog_id = atoi(ext+8);
do_all = 0;
}
else track_id = atoi(ext);
}
if (do_audio || do_video || do_auxv || do_pict || track_id) do_all = 0;
if (track_layout || is_chap) {
u32 w, h, sw, sh, fw, fh, i;
w = h = sw = sh = fw = fh = 0;
chap_ref = 0;
for (i=0; i<gf_isom_get_track_count(dest); i++) {
switch (gf_isom_get_media_type(dest, i+1)) {
case GF_ISOM_MEDIA_SCENE:
case GF_ISOM_MEDIA_VISUAL:
case GF_ISOM_MEDIA_AUXV:
case GF_ISOM_MEDIA_PICT:
if (!chap_ref && gf_isom_is_track_enabled(dest, i+1) ) chap_ref = i+1;
gf_isom_get_visual_info(dest, i+1, 1, &sw, &sh);
gf_isom_get_track_layout_info(dest, i+1, &fw, &fh, NULL, NULL, NULL);
if (w<sw) w = sw;
if (w<fw) w = fw;
if (h<sh) h = sh;
if (h<fh) h = fh;
break;
case GF_ISOM_MEDIA_AUDIO:
if (!chap_ref && gf_isom_is_track_enabled(dest, i+1) ) chap_ref = i+1;
break;
}
}
if (track_layout) {
if (!tw) tw = w;
if (!th) th = h;
if (ty==-1) ty = (h>(u32)th) ? h-th : 0;
import.text_width = tw;
import.text_height = th;
}
if (is_chap && chap_ref) import_flags |= GF_IMPORT_NO_TEXT_FLUSH;
}
if (text_layout && txtw && txth) {
import.text_track_width = import.text_width ? import.text_width : txtw;
import.text_track_height = import.text_height ? import.text_height : txth;
import.text_width = txtw;
import.text_height = txth;
import.text_x = txtx;
import.text_y = txty;
}
check_track_for_svc = check_track_for_lhvc = check_track_for_hevc = 0;
import.dest = dest;
import.video_fps = force_fps;
import.frames_per_sample = frames_per_sample;
import.flags = import_flags;
if (!import.nb_tracks) {
u32 count, o_count;
o_count = gf_isom_get_track_count(import.dest);
e = gf_media_import(&import);
if (e) return e;
count = gf_isom_get_track_count(import.dest);
timescale = gf_isom_get_timescale(dest);
for (i=o_count; i<count; i++) {
if (szLan) gf_isom_set_media_language(import.dest, i+1, (char *) szLan);
if (delay) {
u64 tk_dur;
gf_isom_remove_edit_segments(import.dest, i+1);
tk_dur = gf_isom_get_track_duration(import.dest, i+1);
if (delay>0) {
gf_isom_append_edit_segment(import.dest, i+1, (timescale*delay)/1000, 0, GF_ISOM_EDIT_EMPTY);
gf_isom_append_edit_segment(import.dest, i+1, tk_dur, 0, GF_ISOM_EDIT_NORMAL);
} else if (delay<0) {
u64 to_skip = (timescale*(-delay))/1000;
if (to_skip<tk_dur) {
//u64 seg_dur = (-delay)*gf_isom_get_media_timescale(import.dest, i+1) / 1000;
gf_isom_append_edit_segment(import.dest, i+1, tk_dur-to_skip, to_skip, GF_ISOM_EDIT_NORMAL);
} else {
fprintf(stderr, "Warning: request negative delay longer than track duration - ignoring\n");
}
}
}
if ((par_n>=0) && (par_d>=0)) {
e = gf_media_change_par(import.dest, i+1, par_n, par_d);
}
if (rap_only || refs_only) {
e = gf_media_remove_non_rap(import.dest, i+1, refs_only);
}
if (handler_name) gf_isom_set_handler_name(import.dest, i+1, handler_name);
else if (!keep_handler) {
char szHName[1024];
const char *fName = gf_url_get_resource_name((const char *)inName);
fName = strchr(fName, '.');
if (fName) fName += 1;
else fName = "?";
sprintf(szHName, "*%s@GPAC%s", fName, GPAC_FULL_VERSION);
gf_isom_set_handler_name(import.dest, i+1, szHName);
}
if (handler) gf_isom_set_media_type(import.dest, i+1, handler);
if (disable) gf_isom_set_track_enabled(import.dest, i+1, 0);
if (group) {
gf_isom_set_alternate_group_id(import.dest, i+1, group);
}
if (track_layout) {
gf_isom_set_track_layout_info(import.dest, i+1, tw<<16, th<<16, tx<<16, ty<<16, 0);
}
if (stype)
gf_isom_set_media_subtype(import.dest, i+1, 1, stype);
if (is_chap && chap_ref) {
set_chapter_track(import.dest, i+1, chap_ref);
}
for (j = 0; j < gf_list_count(kinds); j+=2) {
char *kind_scheme = (char *)gf_list_get(kinds, j);
char *kind_value = (char *)gf_list_get(kinds, j+1);
gf_isom_add_track_kind(import.dest, i+1, kind_scheme, kind_value);
}
if (profile || level)
gf_media_change_pl(import.dest, i+1, profile, level);
if (gf_isom_get_media_subtype(import.dest, i+1, 1)== GF_ISOM_BOX_TYPE_MP4S)
keep_sys_tracks = 1;
gf_isom_set_composition_offset_mode(import.dest, i+1, negative_cts_offset);
if (gf_isom_get_avc_svc_type(import.dest, i+1, 1)>=GF_ISOM_AVCTYPE_AVC_SVC)
check_track_for_svc = i+1;
switch (gf_isom_get_hevc_lhvc_type(import.dest, i+1, 1)) {
case GF_ISOM_HEVCTYPE_HEVC_LHVC:
case GF_ISOM_HEVCTYPE_LHVC_ONLY:
check_track_for_lhvc = i+1;
break;
case GF_ISOM_HEVCTYPE_HEVC_ONLY:
check_track_for_hevc=1;
break;
}
if (txt_flags) {
gf_isom_text_set_display_flags(import.dest, i+1, 0, txt_flags, txt_mode);
}
if (force_rate>=0) {
gf_isom_update_bitrate(import.dest, i+1, 1, force_rate, force_rate, 0);
}
if (split_tile_mode) {
switch (gf_isom_get_media_subtype(import.dest, i+1, 1)) {
case GF_ISOM_SUBTYPE_HVC1:
case GF_ISOM_SUBTYPE_HEV1:
case GF_ISOM_SUBTYPE_HVC2:
case GF_ISOM_SUBTYPE_HEV2:
break;
default:
split_tile_mode = 0;
break;
}
}
}
} else {
if (do_all)
import.flags |= GF_IMPORT_KEEP_REFS;
for (i=0; i<import.nb_tracks; i++) {
import.trackID = import.tk_info[i].track_num;
if (prog_id) {
if (import.tk_info[i].prog_num!=prog_id) continue;
e = gf_media_import(&import);
}
else if (do_all) e = gf_media_import(&import);
else if (track_id && (track_id==import.trackID)) {
track_id = 0;
e = gf_media_import(&import);
}
else if (do_audio && (import.tk_info[i].type==GF_ISOM_MEDIA_AUDIO)) {
do_audio = 0;
e = gf_media_import(&import);
}
else if (do_video && (import.tk_info[i].type==GF_ISOM_MEDIA_VISUAL)) {
do_video = 0;
e = gf_media_import(&import);
}
else if (do_auxv && (import.tk_info[i].type==GF_ISOM_MEDIA_AUXV)) {
do_auxv = 0;
e = gf_media_import(&import);
}
else if (do_pict && (import.tk_info[i].type==GF_ISOM_MEDIA_PICT)) {
do_pict = 0;
e = gf_media_import(&import);
}
else continue;
if (e) goto exit;
timescale = gf_isom_get_timescale(dest);
track = gf_isom_get_track_by_id(import.dest, import.final_trackID);
if (szLan) gf_isom_set_media_language(import.dest, track, (char *) szLan);
if (disable) gf_isom_set_track_enabled(import.dest, track, 0);
if (delay) {
u64 tk_dur;
gf_isom_remove_edit_segments(import.dest, track);
tk_dur = gf_isom_get_track_duration(import.dest, track);
if (delay>0) {
gf_isom_append_edit_segment(import.dest, track, (timescale*delay)/1000, 0, GF_ISOM_EDIT_EMPTY);
gf_isom_append_edit_segment(import.dest, track, tk_dur, 0, GF_ISOM_EDIT_NORMAL);
} else {
u64 to_skip = (timescale*(-delay))/1000;
if (to_skip<tk_dur) {
u64 media_time = (-delay)*gf_isom_get_media_timescale(import.dest, track) / 1000;
gf_isom_append_edit_segment(import.dest, track, tk_dur-to_skip, media_time, GF_ISOM_EDIT_NORMAL);
} else {
fprintf(stderr, "Warning: request negative delay longer than track duration - ignoring\n");
}
}
}
if (gf_isom_is_video_subtype(import.tk_info[i].type) && (par_n>=-1) && (par_d>=-1)) {
e = gf_media_change_par(import.dest, track, par_n, par_d);
}
if (rap_only || refs_only) {
e = gf_media_remove_non_rap(import.dest, track, refs_only);
}
if (handler_name) gf_isom_set_handler_name(import.dest, track, handler_name);
else if (!keep_handler) {
char szHName[1024];
const char *fName = gf_url_get_resource_name((const char *)inName);
fName = strchr(fName, '.');
if (fName) fName += 1;
else fName = "?";
sprintf(szHName, "%s@GPAC%s", fName, GPAC_FULL_VERSION);
gf_isom_set_handler_name(import.dest, track, szHName);
}
if (handler) gf_isom_set_media_type(import.dest, track, handler);
if (group) {
gf_isom_set_alternate_group_id(import.dest, track, group);
}
if (track_layout) {
gf_isom_set_track_layout_info(import.dest, track, tw<<16, th<<16, tx<<16, ty<<16, 0);
}
if (stype)
gf_isom_set_media_subtype(import.dest, track, 1, stype);
if (is_chap && chap_ref) {
set_chapter_track(import.dest, track, chap_ref);
}
for (j = 0; j < gf_list_count(kinds); j+=2) {
char *kind_scheme = (char *)gf_list_get(kinds, j);
char *kind_value = (char *)gf_list_get(kinds, j+1);
gf_isom_add_track_kind(import.dest, i+1, kind_scheme, kind_value);
}
if (profile || level)
gf_media_change_pl(import.dest, track, profile, level);
if (gf_isom_get_mpeg4_subtype(import.dest, track, 1))
keep_sys_tracks = 1;
if (new_timescale>1) {
gf_isom_set_media_timescale(import.dest, track, new_timescale, 0);
}
if (rescale>1) {
switch (gf_isom_get_media_type(import.dest, track)) {
case GF_ISOM_MEDIA_AUDIO:
fprintf(stderr, "Cannot force media timescale for audio media types - ignoring\n");
break;
default:
gf_isom_set_media_timescale(import.dest, track, rescale, 1);
break;
}
}
if (rvc_config) {
FILE *f = gf_fopen(rvc_config, "rb");
if (f) {
char *data;
u32 size;
size_t read;
gf_fseek(f, 0, SEEK_END);
size = (u32) gf_ftell(f);
gf_fseek(f, 0, SEEK_SET);
data = gf_malloc(sizeof(char)*size);
read = fread(data, 1, size, f);
gf_fclose(f);
if (read != size) {
fprintf(stderr, "Error: could not read rvc config from %s\n", rvc_config);
e = GF_IO_ERR;
goto exit;
}
#ifdef GPAC_DISABLE_ZLIB
fprintf(stderr, "Error: no zlib support - RVC not available\n");
e = GF_NOT_SUPPORTED;
goto exit;
#else
gf_gz_compress_payload(&data, size, &size);
#endif
gf_isom_set_rvc_config(import.dest, track, 1, 0, "application/rvc-config+xml+gz", data, size);
gf_free(data);
}
} else if (rvc_predefined>0) {
gf_isom_set_rvc_config(import.dest, track, 1, rvc_predefined, NULL, NULL, 0);
}
gf_isom_set_composition_offset_mode(import.dest, track, negative_cts_offset);
if (gf_isom_get_avc_svc_type(import.dest, track, 1)>=GF_ISOM_AVCTYPE_AVC_SVC)
check_track_for_svc = track;
switch (gf_isom_get_hevc_lhvc_type(import.dest, track, 1)) {
case GF_ISOM_HEVCTYPE_HEVC_LHVC:
case GF_ISOM_HEVCTYPE_LHVC_ONLY:
check_track_for_lhvc = i+1;
break;
case GF_ISOM_HEVCTYPE_HEVC_ONLY:
check_track_for_hevc=1;
break;
}
if (txt_flags) {
gf_isom_text_set_display_flags(import.dest, track, 0, txt_flags, txt_mode);
}
if (force_rate>=0) {
gf_isom_update_bitrate(import.dest, i+1, 1, force_rate, force_rate, 0);
}
if (split_tile_mode) {
switch (gf_isom_get_media_subtype(import.dest, track, 1)) {
case GF_ISOM_SUBTYPE_HVC1:
case GF_ISOM_SUBTYPE_HEV1:
case GF_ISOM_SUBTYPE_HVC2:
case GF_ISOM_SUBTYPE_HEV2:
break;
default:
split_tile_mode = 0;
break;
}
}
}
if (track_id) fprintf(stderr, "WARNING: Track ID %d not found in file\n", track_id);
else if (do_video) fprintf(stderr, "WARNING: Video track not found\n");
else if (do_auxv) fprintf(stderr, "WARNING: Auxiliary Video track not found\n");
else if (do_pict) fprintf(stderr, "WARNING: Picture sequence track not found\n");
else if (do_audio) fprintf(stderr, "WARNING: Audio track not found\n");
}
if (chapter_name) {
if (is_chap_file) {
e = gf_media_import_chapters(import.dest, chapter_name, 0);
} else {
e = gf_isom_add_chapter(import.dest, 0, 0, chapter_name);
}
}
/*force to rewrite all dependencies*/
for (i = 1; i <= gf_isom_get_track_count(import.dest); i++)
{
e = gf_isom_rewrite_track_dependencies(import.dest, i);
if (e) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("Warning: track ID %d has references to a track not imported\n", gf_isom_get_track_id(import.dest, i) ));
e = GF_OK;
}
}
if (max_layer_id_plus_one || max_temporal_id_plus_one) {
for (i = 1; i <= gf_isom_get_track_count(import.dest); i++)
{
e = gf_media_filter_hevc(import.dest, i, max_temporal_id_plus_one, max_layer_id_plus_one);
if (e) {
fprintf(stderr, "Warning: track ID %d: error while filtering LHVC layers\n", gf_isom_get_track_id(import.dest, i));
e = GF_OK;
}
}
}
if (check_track_for_svc) {
if (svc_mode) {
e = gf_media_split_svc(import.dest, check_track_for_svc, (svc_mode==2) ? 1 : 0);
if (e) goto exit;
} else {
e = gf_media_merge_svc(import.dest, check_track_for_svc, 1);
if (e) goto exit;
}
}
#ifndef GPAC_DISABLE_HEVC
if (check_track_for_lhvc) {
if (svc_mode) {
GF_LHVCExtractoreMode xmode = GF_LHVC_EXTRACTORS_ON;
if (svc_mode==3) xmode = GF_LHVC_EXTRACTORS_OFF;
else if (svc_mode==4) xmode = GF_LHVC_EXTRACTORS_OFF_FORCE_INBAND;
e = gf_media_split_lhvc(import.dest, check_track_for_lhvc, GF_FALSE, (svc_mode==1) ? 0 : 1, xmode );
if (e) goto exit;
} else {
//TODO - merge, temporal sublayers
}
}
if (check_track_for_hevc) {
if (split_tile_mode) {
e = gf_media_split_hevc_tiles(import.dest, split_tile_mode - 1);
if (e) goto exit;
}
if (temporal_mode) {
GF_LHVCExtractoreMode xmode = (temporal_mode==3) ? GF_LHVC_EXTRACTORS_OFF : GF_LHVC_EXTRACTORS_ON;
e = gf_media_split_lhvc(import.dest, check_track_for_hevc, GF_TRUE, (temporal_mode==1) ? GF_FALSE : GF_TRUE, xmode );
if (e) goto exit;
}
}
#endif /*GPAC_DISABLE_HEVC*/
exit:
while (gf_list_count(kinds)) {
char *kind = (char *)gf_list_get(kinds, 0);
gf_list_rem(kinds, 0);
if (kind) gf_free(kind);
}
gf_list_del(kinds);
if (handler_name) gf_free(handler_name);
if (chapter_name ) gf_free(chapter_name);
if (import.fontName) gf_free(import.fontName);
if (import.streamFormat) gf_free(import.streamFormat);
if (import.force_ext) gf_free(import.force_ext);
if (rvc_config) gf_free(rvc_config);
if (szLan) gf_free((char *)szLan);
return e;
}
typedef struct
{
u32 tk;
Bool has_non_raps;
u32 last_sample;
u32 sample_count;
u32 time_scale;
u64 firstDTS, lastDTS;
u32 dst_tk;
/*set if media can be duplicated at split boundaries - only used for text tracks and provate tracks, this assumes all
samples are RAP*/
Bool can_duplicate;
/*controls import by time rather than by sample (otherwise we would have to remove much more samples video vs audio for example*/
Bool first_sample_done;
Bool next_sample_is_rap;
u32 stop_state;
} TKInfo;
GF_Err split_isomedia_file(GF_ISOFile *mp4, Double split_dur, u64 split_size_kb, char *inName, Double InterleavingTime, Double chunk_start_time, Bool adjust_split_end, char *outName, const char *tmpdir)
{
u32 i, count, nb_tk, needs_rap_sync, cur_file, conv_type, nb_tk_done, nb_samp, nb_done, di;
Double max_dur, cur_file_time;
Bool do_add, all_duplicatable, size_exceeded, chunk_extraction, rap_split, split_until_end;
GF_ISOFile *dest;
GF_ISOSample *samp;
GF_Err e;
TKInfo *tks, *tki;
char *ext, szName[1000], szFile[1000];
Double chunk_start = (Double) chunk_start_time;
chunk_extraction = (chunk_start>=0) ? 1 : 0;
split_until_end = 0;
rap_split = 0;
if (split_size_kb == (u64)-1) rap_split = 1;
if (split_dur == -1) rap_split = 1;
else if (split_dur <= -2) {
split_size_kb = 0;
split_until_end = 1;
}
if (rap_split) {
split_size_kb = 0;
split_dur = (double) GF_MAX_FLOAT;
}
ext = strrchr(inName, '/');
if (!ext) ext = strrchr(inName, '\\');
strcpy(szName, ext ? ext+1 : inName);
ext = strrchr(szName, '.');
if (ext) ext[0] = 0;
ext = strrchr(inName, '.');
dest = NULL;
conv_type = 0;
switch (gf_isom_guess_specification(mp4)) {
case GF_ISOM_BRAND_ISMA:
conv_type = 1;
break;
case GF_ISOM_BRAND_3GP4:
case GF_ISOM_BRAND_3GP5:
case GF_ISOM_BRAND_3GP6:
case GF_ISOM_BRAND_3GG6:
case GF_ISOM_BRAND_3G2A:
conv_type = 2;
break;
}
if (!stricmp(ext, ".3gp") || !stricmp(ext, ".3g2")) conv_type = 2;
count = gf_isom_get_track_count(mp4);
tks = (TKInfo *)gf_malloc(sizeof(TKInfo)*count);
memset(tks, 0, sizeof(TKInfo)*count);
e = GF_OK;
max_dur = 0;
nb_tk = 0;
all_duplicatable = 1;
needs_rap_sync = 0;
nb_samp = 0;
for (i=0; i<count; i++) {
u32 mtype;
Double dur;
tks[nb_tk].tk = i+1;
tks[nb_tk].can_duplicate = 0;
mtype = gf_isom_get_media_type(mp4, i+1);
switch (mtype) {
/*we duplicate text samples at boundaries*/
case GF_ISOM_MEDIA_TEXT:
case GF_ISOM_MEDIA_SUBT:
case GF_ISOM_MEDIA_MPEG_SUBT:
tks[nb_tk].can_duplicate = 1;
case GF_ISOM_MEDIA_AUDIO:
break;
case GF_ISOM_MEDIA_VISUAL:
case GF_ISOM_MEDIA_AUXV:
case GF_ISOM_MEDIA_PICT:
if (gf_isom_get_sample_count(mp4, i+1)>1) {
break;
}
continue;
case GF_ISOM_MEDIA_HINT:
case GF_ISOM_MEDIA_SCENE:
case GF_ISOM_MEDIA_OCR:
case GF_ISOM_MEDIA_OD:
case GF_ISOM_MEDIA_OCI:
case GF_ISOM_MEDIA_IPMP:
case GF_ISOM_MEDIA_MPEGJ:
case GF_ISOM_MEDIA_MPEG7:
case GF_ISOM_MEDIA_FLASH:
fprintf(stderr, "WARNING: Track ID %d (type %s) not handled by splitter - skipping\n", gf_isom_get_track_id(mp4, i+1), gf_4cc_to_str(mtype));
continue;
default:
/*for all other track types, only split if more than one sample*/
if (gf_isom_get_sample_count(mp4, i+1)==1) {
fprintf(stderr, "WARNING: Track ID %d (type %s) not handled by splitter - skipping\n", gf_isom_get_track_id(mp4, i+1), gf_4cc_to_str(mtype));
continue;
}
tks[nb_tk].can_duplicate = 1;
}
tks[nb_tk].sample_count = gf_isom_get_sample_count(mp4, i+1);
nb_samp += tks[nb_tk].sample_count;
tks[nb_tk].last_sample = 0;
tks[nb_tk].firstDTS = 0;
tks[nb_tk].time_scale = gf_isom_get_media_timescale(mp4, i+1);
tks[nb_tk].has_non_raps = gf_isom_has_sync_points(mp4, i+1);
/*seen that on some 3gp files from nokia ...*/
if (mtype==GF_ISOM_MEDIA_AUDIO) tks[nb_tk].has_non_raps = 0;
dur = (Double) (s64) gf_isom_get_media_duration(mp4, i+1);
dur /= tks[nb_tk].time_scale;
if (max_dur<dur) max_dur=dur;
if (tks[nb_tk].has_non_raps) {
/*we don't support that*/
if (needs_rap_sync) {
fprintf(stderr, "More than one track has non-sync points - cannot split file\n");
gf_free(tks);
return GF_NOT_SUPPORTED;
}
needs_rap_sync = nb_tk+1;
}
if (!tks[nb_tk].can_duplicate) all_duplicatable = 0;
nb_tk++;
}
if (!nb_tk) {
fprintf(stderr, "No suitable tracks found for splitting file\n");
gf_free(tks);
return GF_NOT_SUPPORTED;
}
if (chunk_start>=max_dur) {
fprintf(stderr, "Input file (%f) shorter than requested split start offset (%f)\n", max_dur, chunk_start);
gf_free(tks);
return GF_NOT_SUPPORTED;
}
if (split_until_end) {
if (split_dur < -2) {
split_dur = - (split_dur + 2 - chunk_start);
if (max_dur < split_dur) {
fprintf(stderr, "Split duration till end %lf longer than track duration %lf\n", split_dur, max_dur);
gf_free(tks);
return GF_NOT_SUPPORTED;
} else {
split_dur = max_dur - split_dur;
}
} else {
split_dur = max_dur;
}
} else if (!rap_split && (max_dur<=split_dur)) {
fprintf(stderr, "Input file (%f) shorter than requested split duration (%f)\n", max_dur, split_dur);
gf_free(tks);
return GF_NOT_SUPPORTED;
}
if (needs_rap_sync) {
Bool has_enough_sync = GF_FALSE;
tki = &tks[needs_rap_sync-1];
if (chunk_start == 0.0f)
has_enough_sync = GF_TRUE;
else if (gf_isom_get_sync_point_count(mp4, tki->tk) > 1)
has_enough_sync = GF_TRUE;
else if (gf_isom_get_sample_group_info(mp4, tki->tk, 1, GF_ISOM_SAMPLE_GROUP_RAP, NULL, NULL, NULL))
has_enough_sync = GF_TRUE;
else if (gf_isom_get_sample_group_info(mp4, tki->tk, 1, GF_ISOM_SAMPLE_GROUP_SYNC, NULL, NULL, NULL))
has_enough_sync = GF_TRUE;
if (!has_enough_sync) {
fprintf(stderr, "Not enough Random Access points in input file - cannot split\n");
gf_free(tks);
return GF_NOT_SUPPORTED;
}
}
split_size_kb *= 1024;
cur_file_time = 0;
if (chunk_start>0) {
if (needs_rap_sync) {
u32 sample_num;
Double start;
tki = &tks[needs_rap_sync-1];
start = (Double) (s64) gf_isom_get_sample_dts(mp4, tki->tk, tki->sample_count);
start /= tki->time_scale;
if (start<chunk_start) {
tki->stop_state = 2;
} else {
e = gf_isom_get_sample_for_media_time(mp4, tki->tk, (u64) (chunk_start*tki->time_scale), &di, GF_ISOM_SEARCH_SYNC_BACKWARD, &samp, &sample_num);
if (e!=GF_OK) {
fprintf(stderr, "Cannot locate RAP in track ID %d for chunk extraction from %02.2f sec\n", gf_isom_get_track_id(mp4, tki->tk), chunk_start);
gf_free(tks);
return GF_NOT_SUPPORTED;
}
start = (Double) (s64) samp->DTS;
start /= tki->time_scale;
gf_isom_sample_del(&samp);
fprintf(stderr, "Adjusting chunk start time to previous random access at %02.2f sec\n", start);
split_dur += (chunk_start - start);
chunk_start = start;
}
}
/*sync all tracks*/
for (i=0; i<nb_tk; i++) {
tki = &tks[i];
while (tki->last_sample<tki->sample_count) {
Double time;
u64 dts;
dts = gf_isom_get_sample_dts(mp4, tki->tk, tki->last_sample+1);
time = (Double) (s64) dts;
time /= tki->time_scale;
if (time>=chunk_start) {
/*rewind one sample (text tracks & co)*/
if (tki->can_duplicate && tki->last_sample) {
tki->last_sample--;
tki->firstDTS = (u64) (chunk_start*tki->time_scale);
} else {
tki->firstDTS = dts;
}
break;
}
tki->last_sample++;
}
}
cur_file_time = chunk_start;
} else {
chunk_start = 0;
}
dest = NULL;
nb_done = 0;
nb_tk_done = 0;
cur_file = 0;
while (nb_tk_done<nb_tk) {
Double last_rap_sample_time, max_dts, file_split_dur;
Bool is_last_rap;
Bool all_av_done = GF_FALSE;
if (chunk_extraction) {
sprintf(szFile, "%s_%d_%d%s", szName, (u32) chunk_start, (u32) (chunk_start+split_dur), ext);
if (outName) strcpy(szFile, outName);
} else {
sprintf(szFile, "%s_%03d%s", szName, cur_file+1, ext);
if (outName) {
char *the_file = gf_url_concatenate(outName, szFile);
if (the_file) {
strcpy(szFile, the_file);
gf_free(the_file);
}
}
}
dest = gf_isom_open(szFile, GF_ISOM_WRITE_EDIT, tmpdir);
/*clone all tracks*/
for (i=0; i<nb_tk; i++) {
tki = &tks[i];
/*track done - we remove the track from destination, an empty video track could cause pbs to some players*/
if (tki->stop_state==2) continue;
e = gf_isom_clone_track(mp4, tki->tk, dest, GF_FALSE, &tki->dst_tk);
if (e) {
fprintf(stderr, "Error cloning track %d\n", tki->tk);
goto err_exit;
}
/*use non-packet CTS offsets (faster add/remove)*/
if (gf_isom_has_time_offset(mp4, tki->tk)) {
gf_isom_set_cts_packing(dest, tki->dst_tk, GF_TRUE);
}
gf_isom_remove_edit_segments(dest, tki->dst_tk);
}
do_add = 1;
is_last_rap = 0;
last_rap_sample_time = 0;
file_split_dur = split_dur;
size_exceeded = 0;
max_dts = 0;
while (do_add) {
Bool is_rap;
Double time;
u32 nb_over, nb_av = 0;
/*perfom basic de-interleaving to make sure we're not importing too much of a given track*/
u32 nb_add = 0;
/*add one sample of each track*/
for (i=0; i<nb_tk; i++) {
Double t;
u64 dts;
tki = &tks[i];
if (!tki->can_duplicate) nb_av++;
if (tki->stop_state)
continue;
if (tki->last_sample==tki->sample_count)
continue;
/*get sample info, see if we need to check it (basic de-interleaver)*/
dts = gf_isom_get_sample_dts(mp4, tki->tk, tki->last_sample+1);
/*reinsertion (timed text)*/
if (dts < tki->firstDTS) {
samp = gf_isom_get_sample(mp4, tki->tk, tki->last_sample+1, &di);
samp->DTS = 0;
e = gf_isom_add_sample(dest, tki->dst_tk, di, samp);
if (!e) {
e = gf_isom_copy_sample_info(dest, tki->dst_tk, mp4, tki->tk, tki->last_sample+1);
}
gf_isom_sample_del(&samp);
tki->last_sample += 1;
dts = gf_isom_get_sample_dts(mp4, tki->tk, tki->last_sample+1);
}
dts -= tki->firstDTS;
t = (Double) (s64) dts;
t /= tki->time_scale;
if (tki->first_sample_done) {
if (!all_av_done && (t>max_dts)) continue;
} else {
/*here's the trick: only take care of a/v media for splitting, and add other media
only if thir dts is less than the max AV dts found. Otherwise with some text streams we will end up importing
too much video and corrupting the last sync point indication*/
if (!tki->can_duplicate && (t>max_dts)) max_dts = t;
tki->first_sample_done = 1;
}
samp = gf_isom_get_sample(mp4, tki->tk, tki->last_sample+1, &di);
samp->DTS -= tki->firstDTS;
nb_add += 1;
is_rap = GF_FALSE;
if (samp->IsRAP) {
is_rap = GF_TRUE;
} else {
Bool has_roll;
gf_isom_get_sample_rap_roll_info(mp4, tki->tk, tki->last_sample+1, &is_rap, &has_roll, NULL);
}
if (tki->has_non_raps && is_rap) {
GF_ISOSample *next_rap;
u32 next_rap_num, sdi;
last_rap_sample_time = (Double) (s64) samp->DTS;
last_rap_sample_time /= tki->time_scale;
e = gf_isom_get_sample_for_media_time(mp4, tki->tk, samp->DTS+tki->firstDTS+2, &sdi, GF_ISOM_SEARCH_SYNC_FORWARD, &next_rap, &next_rap_num);
if (e==GF_EOS)
is_last_rap = 1;
if (next_rap) {
if (!next_rap->IsRAP)
is_last_rap = 1;
gf_isom_sample_del(&next_rap);
}
}
tki->lastDTS = samp->DTS;
e = gf_isom_add_sample(dest, tki->dst_tk, di, samp);
gf_isom_sample_del(&samp);
if (!e) {
e = gf_isom_copy_sample_info(dest, tki->dst_tk, mp4, tki->tk, tki->last_sample+1);
}
tki->last_sample += 1;
gf_set_progress("Splitting", nb_done, nb_samp);
nb_done++;
if (e) {
fprintf(stderr, "Error cloning track %d sample %d\n", tki->tk, tki->last_sample);
goto err_exit;
}
tki->next_sample_is_rap = 0;
if (rap_split && tki->has_non_raps) {
if ( gf_isom_get_sample_sync(mp4, tki->tk, tki->last_sample+1))
tki->next_sample_is_rap = 1;
}
}
/*test by size/duration*/
nb_over = 0;
/*test by file size: same as duration test, only dynamically increment import duration*/
if (split_size_kb) {
u64 est_size = gf_isom_estimate_size(dest);
/*while below desired size keep importing*/
if (est_size<split_size_kb)
file_split_dur = (Double) GF_MAX_FLOAT;
else {
size_exceeded = 1;
}
}
for (i=0; i<nb_tk; i++) {
tki = &tks[i];
if (tki->stop_state) {
nb_over++;
if (!tki->can_duplicate && (tki->last_sample==tki->sample_count) )
nb_av--;
continue;
}
time = (Double) (s64) tki->lastDTS;
time /= tki->time_scale;
if (size_exceeded
|| (tki->last_sample==tki->sample_count)
|| (!tki->can_duplicate && (time>file_split_dur))
|| (rap_split && tki->has_non_raps && tki->next_sample_is_rap)
) {
nb_over++;
tki->stop_state = 1;
if (tki->last_sample<tki->sample_count)
is_last_rap = 0;
else if (tki->first_sample_done)
is_last_rap = 0;
if (rap_split && tki->next_sample_is_rap) {
file_split_dur = (Double) ( gf_isom_get_sample_dts(mp4, tki->tk, tki->last_sample+1) - tki->firstDTS);
file_split_dur /= tki->time_scale;
}
}
/*special tracks (not audio, not video)*/
else if (tki->can_duplicate) {
u64 dts = gf_isom_get_sample_dts(mp4, tki->tk, tki->last_sample+1);
time = (Double) (s64) (dts - tki->firstDTS);
time /= tki->time_scale;
if (time>file_split_dur) {
nb_over++;
tki->stop_state = 1;
}
}
if (!nb_add && (!max_dts || (tki->lastDTS <= 1 + (u64) (tki->time_scale*max_dts) )))
tki->first_sample_done = 0;
}
if (nb_over==nb_tk) do_add = 0;
if (!nb_av)
all_av_done = GF_TRUE;
}
/*remove samples - first figure out smallest duration*/
file_split_dur = (Double) GF_MAX_FLOAT;
for (i=0; i<nb_tk; i++) {
Double time;
tki = &tks[i];
/*track done*/
if ((tki->stop_state==2) || (!is_last_rap && (tki->sample_count == tki->last_sample)) ) {
if (tki->has_non_raps) last_rap_sample_time = 0;
time = (Double) (s64) ( gf_isom_get_sample_dts(mp4, tki->tk, tki->last_sample+1) - tki->firstDTS);
time /= tki->time_scale;
if (file_split_dur==(Double)GF_MAX_FLOAT || file_split_dur<time) file_split_dur = time;
continue;
}
//if (tki->lastDTS)
{
//time = (Double) (s64) tki->lastDTS;
time = (Double) (s64) ( gf_isom_get_sample_dts(mp4, tki->tk, tki->last_sample+1) - tki->firstDTS);
time /= tki->time_scale;
if ((!tki->can_duplicate || all_duplicatable) && time<file_split_dur) file_split_dur = time;
else if (rap_split && tki->next_sample_is_rap) file_split_dur = time;
}
}
if (file_split_dur == (Double) GF_MAX_FLOAT) {
fprintf(stderr, "Cannot split file (duration too small or size too small)\n");
goto err_exit;
}
if (chunk_extraction) {
if (adjust_split_end) {
fprintf(stderr, "Adjusting chunk end time to previous random access at %02.2f sec\n", chunk_start + last_rap_sample_time);
file_split_dur = last_rap_sample_time;
if (outName) strcpy(szFile, outName);
else sprintf(szFile, "%s_%d_%d%s", szName, (u32) chunk_start, (u32) (chunk_start+file_split_dur), ext);
gf_isom_set_final_name(dest, szFile);
}
else file_split_dur = split_dur;
}
/*don't split if eq to copy...*/
if (is_last_rap && !cur_file && !chunk_start) {
fprintf(stderr, "Cannot split file (Not enough sync samples, duration too large or size too big)\n");
goto err_exit;
}
/*if not last chunk and longer duration adjust to previous RAP point*/
if ( (size_exceeded || !split_size_kb) && (file_split_dur>split_dur) && !chunk_start) {
/*if larger than last RAP, rewind till it*/
if (last_rap_sample_time && (last_rap_sample_time<file_split_dur) ) {
file_split_dur = last_rap_sample_time;
is_last_rap = 0;
}
}
nb_tk_done = 0;
if (!is_last_rap || chunk_extraction) {
for (i=0; i<nb_tk; i++) {
Double time = 0;
u32 last_samp;
tki = &tks[i];
while (1) {
last_samp = gf_isom_get_sample_count(dest, tki->dst_tk);
time = (Double) (s64) gf_isom_get_media_duration(dest, tki->dst_tk);
//time could get slightly higher than requests dur due to rounding precision. We use 1/4 of the last sample dur as safety marge
time -= (Double) (s64) gf_isom_get_sample_duration(dest, tki->dst_tk, tki->last_sample) / 4;
time /= tki->time_scale;
if (last_samp<=1) break;
/*done*/
if (tki->last_sample==tki->sample_count) {
if (!chunk_extraction && !tki->can_duplicate) {
tki->stop_state=2;
break;
}
}
if (time <= file_split_dur) break;
gf_isom_remove_sample(dest, tki->dst_tk, last_samp);
tki->last_sample--;
assert(tki->last_sample);
nb_done--;
gf_set_progress("Splitting", nb_done, nb_samp);
}
if (tki->last_sample<tki->sample_count) {
u64 dts;
tki->stop_state = 0;
dts = gf_isom_get_sample_dts(mp4, tki->tk, tki->last_sample+1);
time = (Double) (s64) (dts - tki->firstDTS);
time /= tki->time_scale;
/*re-insert prev sample*/
if (tki->can_duplicate && (time>file_split_dur) ) {
Bool was_insert = GF_FALSE;
tki->last_sample--;
dts = gf_isom_get_sample_dts(mp4, tki->tk, tki->last_sample+1);
if (dts < tki->firstDTS) was_insert = GF_TRUE;
tki->firstDTS += (u64) (file_split_dur*tki->time_scale);
//the original, last sample added starts before the first sample in the file: we have re-inserted
//a single sample, use split duration as target duration
if (was_insert) {
gf_isom_set_last_sample_duration(dest, tki->dst_tk, (u32) (file_split_dur*tki->time_scale));
} else {
gf_isom_set_last_sample_duration(dest, tki->dst_tk, (u32) (tki->firstDTS - dts) );
}
} else {
tki->firstDTS = dts;
}
tki->first_sample_done = 0;
} else {
nb_tk_done++;
}
}
}
if (chunk_extraction) {
fprintf(stderr, "Extracting chunk %s - duration %02.2fs (%02.2fs->%02.2fs)\n", szFile, file_split_dur, chunk_start, (chunk_start+split_dur));
} else {
fprintf(stderr, "Storing split-file %s - duration %02.2f seconds\n", szFile, file_split_dur);
}
/*repack CTSs*/
for (i=0; i<nb_tk; i++) {
u32 j;
u64 new_track_dur;
tki = &tks[i];
if (tki->stop_state == 2) continue;
if (!gf_isom_get_sample_count(dest, tki->dst_tk)) {
gf_isom_remove_track(dest, tki->dst_tk);
continue;
}
if (gf_isom_has_time_offset(mp4, tki->tk)) {
gf_isom_set_cts_packing(dest, tki->dst_tk, GF_FALSE);
}
if (is_last_rap && tki->can_duplicate) {
gf_isom_set_last_sample_duration(dest, tki->dst_tk, gf_isom_get_sample_duration(mp4, tki->tk, tki->sample_count));
}
/*rewrite edit list*/
new_track_dur = gf_isom_get_track_duration(dest, tki->dst_tk);
count = gf_isom_get_edit_segment_count(mp4, tki->tk);
if (count>2) {
fprintf(stderr, "Warning: %d edit segments - not supported while splitting (max 2) - ignoring extra\n", count);
count=2;
}
for (j=0; j<count; j++) {
u64 editTime, segDur, MediaTime;
u8 mode;
gf_isom_get_edit_segment(mp4, tki->tk, j+1, &editTime, &segDur, &MediaTime, &mode);
if (!j && (mode!=GF_ISOM_EDIT_EMPTY) ) {
fprintf(stderr, "Warning: Edit list doesn't look like a track delay scheme - ignoring\n");
break;
}
if (mode==GF_ISOM_EDIT_NORMAL) {
segDur = new_track_dur;
}
gf_isom_set_edit_segment(dest, tki->dst_tk, editTime, segDur, MediaTime, mode);
}
}
/*check chapters*/
do_add = 1;
for (i=0; i<gf_isom_get_chapter_count(mp4, 0); i++) {
char *name;
u64 chap_time;
gf_isom_get_chapter(mp4, 0, i+1, &chap_time, (const char **) &name);
max_dts = (Double) (s64) chap_time;
max_dts /= 1000;
if (max_dts<cur_file_time) continue;
if (max_dts>cur_file_time+file_split_dur) break;
max_dts-=cur_file_time;
chap_time = (u64) (max_dts*1000);
gf_isom_add_chapter(dest, 0, chap_time, name);
/*add prev*/
if (do_add && i) {
gf_isom_get_chapter(mp4, 0, i, &chap_time, (const char **) &name);
gf_isom_add_chapter(dest, 0, 0, name);
do_add = 0;
}
}
cur_file_time += file_split_dur;
if (conv_type==1) gf_media_make_isma(dest, 1, 0, 0);
else if (conv_type==2) gf_media_make_3gpp(dest);
if (InterleavingTime) {
gf_isom_make_interleave(dest, InterleavingTime);
} else {
gf_isom_set_storage_mode(dest, GF_ISOM_STORE_STREAMABLE);
}
gf_isom_clone_pl_indications(mp4, dest);
e = gf_isom_close(dest);
dest = NULL;
if (e) fprintf(stderr, "Error storing file %s\n", gf_error_to_string(e));
if (is_last_rap || chunk_extraction) break;
cur_file++;
}
gf_set_progress("Splitting", nb_samp, nb_samp);
err_exit:
if (dest) gf_isom_delete(dest);
gf_free(tks);
return e;
}
GF_Err cat_multiple_files(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command);
static Bool merge_parameter_set(GF_List *src, GF_List *dst, const char *name)
{
u32 j, k;
for (j=0; j<gf_list_count(src); j++) {
Bool found = 0;
GF_AVCConfigSlot *slc = gf_list_get(src, j);
for (k=0; k<gf_list_count(dst); k++) {
GF_AVCConfigSlot *slc_dst = gf_list_get(dst, k);
if ( (slc->size==slc_dst->size) && !memcmp(slc->data, slc_dst->data, slc->size) ) {
found = 1;
break;
}
}
if (!found) {
return GF_FALSE;
}
}
return GF_TRUE;
}
static u32 merge_avc_config(GF_ISOFile *dest, u32 tk_id, GF_ISOFile *orig, u32 src_track, Bool force_cat)
{
GF_AVCConfig *avc_src, *avc_dst;
u32 dst_tk = gf_isom_get_track_by_id(dest, tk_id);
avc_src = gf_isom_avc_config_get(orig, src_track, 1);
avc_dst = gf_isom_avc_config_get(dest, dst_tk, 1);
if (avc_src->AVCLevelIndication!=avc_dst->AVCLevelIndication) {
dst_tk = 0;
} else if (avc_src->AVCProfileIndication!=avc_dst->AVCProfileIndication) {
dst_tk = 0;
}
else {
/*rewrite all samples if using different NALU size*/
if (avc_src->nal_unit_size > avc_dst->nal_unit_size) {
gf_media_avc_rewrite_samples(dest, dst_tk, 8*avc_dst->nal_unit_size, 8*avc_src->nal_unit_size);
avc_dst->nal_unit_size = avc_src->nal_unit_size;
} else if (avc_src->nal_unit_size < avc_dst->nal_unit_size) {
gf_media_avc_rewrite_samples(orig, src_track, 8*avc_src->nal_unit_size, 8*avc_dst->nal_unit_size);
}
/*merge PS*/
if (!merge_parameter_set(avc_src->sequenceParameterSets, avc_dst->sequenceParameterSets, "SPS"))
dst_tk = 0;
if (!merge_parameter_set(avc_src->pictureParameterSets, avc_dst->pictureParameterSets, "PPS"))
dst_tk = 0;
gf_isom_avc_config_update(dest, dst_tk, 1, avc_dst);
}
gf_odf_avc_cfg_del(avc_src);
gf_odf_avc_cfg_del(avc_dst);
if (!dst_tk) {
dst_tk = gf_isom_get_track_by_id(dest, tk_id);
gf_isom_set_nalu_extract_mode(orig, src_track, GF_ISOM_NALU_EXTRACT_INBAND_PS_FLAG);
if (!force_cat) {
gf_isom_avc_set_inband_config(dest, dst_tk, 1);
} else {
fprintf(stderr, "WARNING: Concatenating track ID %d even though sample descriptions do not match\n", tk_id);
}
}
return dst_tk;
}
#ifndef GPAC_DISABLE_HEVC
static u32 merge_hevc_config(GF_ISOFile *dest, u32 tk_id, GF_ISOFile *orig, u32 src_track, Bool force_cat)
{
u32 i;
GF_HEVCConfig *hevc_src, *hevc_dst;
u32 dst_tk = gf_isom_get_track_by_id(dest, tk_id);
hevc_src = gf_isom_hevc_config_get(orig, src_track, 1);
hevc_dst = gf_isom_hevc_config_get(dest, dst_tk, 1);
if (hevc_src->profile_idc != hevc_dst->profile_idc) dst_tk = 0;
else if (hevc_src->level_idc != hevc_dst->level_idc) dst_tk = 0;
else if (hevc_src->general_profile_compatibility_flags != hevc_dst->general_profile_compatibility_flags ) dst_tk = 0;
else {
/*rewrite all samples if using different NALU size*/
if (hevc_src->nal_unit_size > hevc_dst->nal_unit_size) {
gf_media_avc_rewrite_samples(dest, dst_tk, 8*hevc_dst->nal_unit_size, 8*hevc_src->nal_unit_size);
hevc_dst->nal_unit_size = hevc_src->nal_unit_size;
} else if (hevc_src->nal_unit_size < hevc_dst->nal_unit_size) {
gf_media_avc_rewrite_samples(orig, src_track, 8*hevc_src->nal_unit_size, 8*hevc_dst->nal_unit_size);
}
/*merge PS*/
for (i=0; i<gf_list_count(hevc_src->param_array); i++) {
u32 k;
GF_HEVCParamArray *src_ar = gf_list_get(hevc_src->param_array, i);
for (k=0; k<gf_list_count(hevc_dst->param_array); k++) {
GF_HEVCParamArray *dst_ar = gf_list_get(hevc_dst->param_array, k);
if (dst_ar->type==src_ar->type) {
if (!merge_parameter_set(src_ar->nalus, dst_ar->nalus, "SPS"))
dst_tk = 0;
break;
}
}
}
gf_isom_hevc_config_update(dest, dst_tk, 1, hevc_dst);
}
gf_odf_hevc_cfg_del(hevc_src);
gf_odf_hevc_cfg_del(hevc_dst);
if (!dst_tk) {
dst_tk = gf_isom_get_track_by_id(dest, tk_id);
gf_isom_set_nalu_extract_mode(orig, src_track, GF_ISOM_NALU_EXTRACT_INBAND_PS_FLAG);
if (!force_cat) {
gf_isom_hevc_set_inband_config(dest, dst_tk, 1);
} else {
fprintf(stderr, "WARNING: Concatenating track ID %d even though sample descriptions do not match\n", tk_id);
}
}
return dst_tk;
}
#endif /*GPAC_DISABLE_HEVC */
GF_Err cat_isomedia_file(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command)
{
u32 i, j, count, nb_tracks, nb_samp, nb_done;
GF_ISOFile *orig;
GF_Err e;
char *opts, *multi_cat;
Double ts_scale;
Double dest_orig_dur;
u32 dst_tk, tk_id, mtype;
u64 insert_dts;
Bool is_isom;
GF_ISOSample *samp;
Double aligned_to_DTS = 0;
if (strchr(fileName, '*')) return cat_multiple_files(dest, fileName, import_flags, force_fps, frames_per_sample, tmp_dir, force_cat, align_timelines, allow_add_in_command);
multi_cat = allow_add_in_command ? strchr(fileName, '+') : NULL;
if (multi_cat) {
multi_cat[0] = 0;
multi_cat = &multi_cat[1];
}
opts = strchr(fileName, ':');
if (opts && (opts[1]=='\\'))
opts = strchr(fileName, ':');
e = GF_OK;
/*if options are specified, reimport the file*/
is_isom = opts ? 0 : gf_isom_probe_file(fileName);
if (!is_isom || opts) {
orig = gf_isom_open("temp", GF_ISOM_WRITE_EDIT, tmp_dir);
e = import_file(orig, fileName, import_flags, force_fps, frames_per_sample);
if (e) return e;
} else {
/*we open the original file in edit mode since we may have to rewrite AVC samples*/
orig = gf_isom_open(fileName, GF_ISOM_OPEN_EDIT, tmp_dir);
}
while (multi_cat) {
char *sep = strchr(multi_cat, '+');
if (sep) sep[0] = 0;
e = import_file(orig, multi_cat, import_flags, force_fps, frames_per_sample);
if (e) {
gf_isom_delete(orig);
return e;
}
if (!sep) break;
sep[0]=':';
multi_cat = sep+1;
}
nb_samp = 0;
nb_tracks = gf_isom_get_track_count(orig);
for (i=0; i<nb_tracks; i++) {
u32 mtype = gf_isom_get_media_type(orig, i+1);
switch (mtype) {
case GF_ISOM_MEDIA_HINT:
case GF_ISOM_MEDIA_OD:
case GF_ISOM_MEDIA_FLASH:
fprintf(stderr, "WARNING: Track ID %d (type %s) not handled by concatenation - removing from destination\n", gf_isom_get_track_id(orig, i+1), gf_4cc_to_str(mtype));
continue;
case GF_ISOM_MEDIA_AUDIO:
case GF_ISOM_MEDIA_TEXT:
case GF_ISOM_MEDIA_SUBT:
case GF_ISOM_MEDIA_MPEG_SUBT:
case GF_ISOM_MEDIA_VISUAL:
case GF_ISOM_MEDIA_AUXV:
case GF_ISOM_MEDIA_PICT:
case GF_ISOM_MEDIA_SCENE:
case GF_ISOM_MEDIA_OCR:
case GF_ISOM_MEDIA_OCI:
case GF_ISOM_MEDIA_IPMP:
case GF_ISOM_MEDIA_MPEGJ:
case GF_ISOM_MEDIA_MPEG7:
default:
/*only cat self-contained files*/
if (gf_isom_is_self_contained(orig, i+1, 1)) {
nb_samp+= gf_isom_get_sample_count(orig, i+1);
break;
}
break;
}
}
if (!nb_samp) {
fprintf(stderr, "No suitable media tracks to cat in %s - skipping\n", fileName);
goto err_exit;
}
dest_orig_dur = (Double) (s64) gf_isom_get_duration(dest);
if (!gf_isom_get_timescale(dest)) {
gf_isom_set_timescale(dest, gf_isom_get_timescale(orig));
}
dest_orig_dur /= gf_isom_get_timescale(dest);
aligned_to_DTS = 0;
for (i=0; i<gf_isom_get_track_count(dest); i++) {
Double track_dur = (Double) gf_isom_get_media_duration(dest, i+1);
track_dur /= gf_isom_get_media_timescale(dest, i+1);
if (aligned_to_DTS < track_dur) {
aligned_to_DTS = track_dur;
}
}
fprintf(stderr, "Appending file %s\n", fileName);
nb_done = 0;
for (i=0; i<nb_tracks; i++) {
u64 last_DTS, dest_track_dur_before_cat;
u32 nb_edits = 0;
Bool skip_lang_test = 1;
Bool use_ts_dur = 1;
Bool merge_edits = 0;
Bool new_track = 0;
mtype = gf_isom_get_media_type(orig, i+1);
switch (mtype) {
case GF_ISOM_MEDIA_HINT:
case GF_ISOM_MEDIA_OD:
case GF_ISOM_MEDIA_FLASH:
continue;
case GF_ISOM_MEDIA_TEXT:
case GF_ISOM_MEDIA_SUBT:
case GF_ISOM_MEDIA_MPEG_SUBT:
case GF_ISOM_MEDIA_SCENE:
use_ts_dur = 0;
case GF_ISOM_MEDIA_AUDIO:
case GF_ISOM_MEDIA_VISUAL:
case GF_ISOM_MEDIA_PICT:
case GF_ISOM_MEDIA_OCR:
case GF_ISOM_MEDIA_OCI:
case GF_ISOM_MEDIA_IPMP:
case GF_ISOM_MEDIA_MPEGJ:
case GF_ISOM_MEDIA_MPEG7:
default:
if (!gf_isom_is_self_contained(orig, i+1, 1)) continue;
break;
}
dst_tk = 0;
/*if we had a temporary import of the file, check if the original track ID matches the dst one. If so, skip all language detection code*/
tk_id = gf_isom_get_track_original_id(orig, i+1);
if (!tk_id) {
tk_id = gf_isom_get_track_id(orig, i+1);
skip_lang_test = 0;
}
dst_tk = gf_isom_get_track_by_id(dest, tk_id);
if (dst_tk) {
if (mtype != gf_isom_get_media_type(dest, dst_tk))
dst_tk = 0;
else if (gf_isom_get_media_subtype(dest, dst_tk, 1) != gf_isom_get_media_subtype(orig, i+1, 1))
dst_tk = 0;
}
if (!dst_tk) {
for (j=0; j<gf_isom_get_track_count(dest); j++) {
if (mtype != gf_isom_get_media_type(dest, j+1)) continue;
if (gf_isom_is_same_sample_description(orig, i+1, 0, dest, j+1, 0)) {
if (gf_isom_is_video_subtype(mtype) ) {
u32 w, h, ow, oh;
gf_isom_get_visual_info(orig, i+1, 1, &ow, &oh);
gf_isom_get_visual_info(dest, j+1, 1, &w, &h);
if ((ow==w) && (oh==h)) {
dst_tk = j+1;
break;
}
}
/*check language code*/
else if (!skip_lang_test && (mtype==GF_ISOM_MEDIA_AUDIO)) {
u32 lang_src, lang_dst;
char *lang = NULL;
gf_isom_get_media_language(orig, i+1, &lang);
if (lang) {
lang_src = GF_4CC(lang[0], lang[1], lang[2], lang[3]);
gf_free(lang);
} else {
lang_src = 0;
}
gf_isom_get_media_language(dest, j+1, &lang);
if (lang) {
lang_dst = GF_4CC(lang[0], lang[1], lang[2], lang[3]);
gf_free(lang);
} else {
lang_dst = 0;
}
if (lang_dst==lang_src) {
dst_tk = j+1;
break;
}
} else {
dst_tk = j+1;
break;
}
}
}
}
if (dst_tk) {
u32 found_dst_tk = dst_tk;
u32 stype = gf_isom_get_media_subtype(dest, dst_tk, 1);
/*we MUST have the same codec*/
if (gf_isom_get_media_subtype(orig, i+1, 1) != stype) dst_tk = 0;
/*we only support cat with the same number of sample descriptions*/
if (gf_isom_get_sample_description_count(orig, i+1) != gf_isom_get_sample_description_count(dest, dst_tk)) dst_tk = 0;
/*if not forcing cat, check the media codec config is the same*/
if (!gf_isom_is_same_sample_description(orig, i+1, 0, dest, dst_tk, 0)) {
dst_tk = 0;
}
/*we force the same visual resolution*/
else if (gf_isom_is_video_subtype(mtype) ) {
u32 w, h, ow, oh;
gf_isom_get_visual_info(orig, i+1, 1, &ow, &oh);
gf_isom_get_visual_info(dest, dst_tk, 1, &w, &h);
if ((ow!=w) || (oh!=h)) {
dst_tk = 0;
}
}
if (!dst_tk) {
/*merge AVC config if possible*/
if ((stype == GF_ISOM_SUBTYPE_AVC_H264)
|| (stype == GF_ISOM_SUBTYPE_AVC2_H264)
|| (stype == GF_ISOM_SUBTYPE_AVC3_H264)
|| (stype == GF_ISOM_SUBTYPE_AVC4_H264) ) {
dst_tk = merge_avc_config(dest, tk_id, orig, i+1, force_cat);
}
#ifndef GPAC_DISABLE_HEVC
/*merge HEVC config if possible*/
else if ((stype == GF_ISOM_SUBTYPE_HVC1)
|| (stype == GF_ISOM_SUBTYPE_HEV1)
|| (stype == GF_ISOM_SUBTYPE_HVC2)
|| (stype == GF_ISOM_SUBTYPE_HEV2)) {
dst_tk = merge_hevc_config(dest, tk_id, orig, i+1, force_cat);
}
#endif /*GPAC_DISABLE_HEVC*/
else if (force_cat) {
dst_tk = found_dst_tk;
}
}
}
/*looks like a new track*/
if (!dst_tk) {
fprintf(stderr, "No suitable destination track found - creating new one (type %s)\n", gf_4cc_to_str(mtype));
e = gf_isom_clone_track(orig, i+1, dest, GF_FALSE, &dst_tk);
if (e) goto err_exit;
gf_isom_clone_pl_indications(orig, dest);
new_track = 1;
if (align_timelines) {
u32 max_timescale = 0;
// u32 dst_timescale = 0;
u32 idx;
for (idx=0; idx<nb_tracks; idx++) {
if (max_timescale < gf_isom_get_media_timescale(orig, idx+1))
max_timescale = gf_isom_get_media_timescale(orig, idx+1);
}
#if 0
if (dst_timescale < max_timescale) {
dst_timescale = gf_isom_get_media_timescale(dest, dst_tk);
idx = max_timescale / dst_timescale;
if (dst_timescale * idx < max_timescale) idx ++;
dst_timescale *= idx;
gf_isom_set_media_timescale(dest, dst_tk, max_timescale, 0);
}
#else
gf_isom_set_media_timescale(dest, dst_tk, max_timescale, 0);
#endif
}
/*remove cloned edit list, as it will be rewritten after import*/
gf_isom_remove_edit_segments(dest, dst_tk);
} else {
nb_edits = gf_isom_get_edit_segment_count(orig, i+1);
}
dest_track_dur_before_cat = gf_isom_get_media_duration(dest, dst_tk);
count = gf_isom_get_sample_count(dest, dst_tk);
if (align_timelines) {
insert_dts = (u64) (aligned_to_DTS * gf_isom_get_media_timescale(dest, dst_tk));
} else if (use_ts_dur && (count>1)) {
insert_dts = 2*gf_isom_get_sample_dts(dest, dst_tk, count) - gf_isom_get_sample_dts(dest, dst_tk, count-1);
} else {
insert_dts = dest_track_dur_before_cat;
if (!count) insert_dts = 0;
}
ts_scale = gf_isom_get_media_timescale(dest, dst_tk);
ts_scale /= gf_isom_get_media_timescale(orig, i+1);
/*if not a new track, see if we can merge the edit list - this is a crude test that only checks
we have the same edit types*/
if (nb_edits && (nb_edits == gf_isom_get_edit_segment_count(dest, dst_tk)) ) {
u64 editTime, segmentDuration, mediaTime, dst_editTime, dst_segmentDuration, dst_mediaTime;
u8 dst_editMode, editMode;
u32 j;
merge_edits = 1;
for (j=0; j<nb_edits; j++) {
gf_isom_get_edit_segment(orig, i+1, j+1, &editTime, &segmentDuration, &mediaTime, &editMode);
gf_isom_get_edit_segment(dest, dst_tk, j+1, &dst_editTime, &dst_segmentDuration, &dst_mediaTime, &dst_editMode);
if (dst_editMode!=editMode) {
merge_edits=0;
break;
}
}
}
last_DTS = 0;
count = gf_isom_get_sample_count(orig, i+1);
for (j=0; j<count; j++) {
u32 di;
samp = gf_isom_get_sample(orig, i+1, j+1, &di);
last_DTS = samp->DTS;
samp->DTS = (u64) (ts_scale * samp->DTS + (new_track ? 0 : insert_dts));
samp->CTS_Offset = (u32) (samp->CTS_Offset * ts_scale);
if (gf_isom_is_self_contained(orig, i+1, di)) {
e = gf_isom_add_sample(dest, dst_tk, di, samp);
} else {
u64 offset;
GF_ISOSample *s = gf_isom_get_sample_info(orig, i+1, j+1, &di, &offset);
e = gf_isom_add_sample_reference(dest, dst_tk, di, samp, offset);
gf_isom_sample_del(&s);
}
gf_isom_sample_del(&samp);
if (e) goto err_exit;
e = gf_isom_copy_sample_info(dest, dst_tk, orig, i+1, j+1);
if (e) goto err_exit;
gf_set_progress("Appending", nb_done, nb_samp);
nb_done++;
}
/*scene description and text: compute last sample duration based on original media duration*/
if (!use_ts_dur) {
insert_dts = gf_isom_get_media_duration(orig, i+1) - last_DTS;
gf_isom_set_last_sample_duration(dest, dst_tk, (u32) insert_dts);
}
if (new_track && insert_dts) {
u64 media_dur = gf_isom_get_media_duration(orig, i+1);
/*convert from media time to track time*/
Double rescale = (Float) gf_isom_get_timescale(dest);
rescale /= (Float) gf_isom_get_media_timescale(dest, dst_tk);
/*convert from orig to dst time scale*/
rescale *= ts_scale;
gf_isom_set_edit_segment(dest, dst_tk, 0, (u64) (s64) (insert_dts*rescale), 0, GF_ISOM_EDIT_EMPTY);
gf_isom_set_edit_segment(dest, dst_tk, (u64) (s64) (insert_dts*rescale), (u64) (s64) (media_dur*rescale), 0, GF_ISOM_EDIT_NORMAL);
} else if (merge_edits) {
/*convert from media time to track time*/
Double rescale = (Float) gf_isom_get_timescale(dest);
rescale /= (Float) gf_isom_get_media_timescale(dest, dst_tk);
/*convert from orig to dst time scale*/
rescale *= ts_scale;
/*get the first edit normal mode and add the new track dur*/
for (j=nb_edits; j>0; j--) {
u64 editTime, segmentDuration, mediaTime;
u8 editMode;
gf_isom_get_edit_segment(dest, dst_tk, j, &editTime, &segmentDuration, &mediaTime, &editMode);
if (editMode==GF_ISOM_EDIT_NORMAL) {
Double prev_dur = (Double) (s64) dest_track_dur_before_cat;
Double dur = (Double) (s64) gf_isom_get_media_duration(orig, i+1);
dur *= rescale;
prev_dur *= rescale;
/*safety test: some files have broken edit lists. If no more than 2 entries, check that the segment duration
is less or equal to the movie duration*/
if (prev_dur < segmentDuration) {
fprintf(stderr, "Warning: suspicious edit list entry found: duration %g sec but longest track duration before cat is %g - fixing it\n", (Double) (s64) segmentDuration/1000.0, prev_dur/1000);
segmentDuration = (u64) (s64) ( (Double) (s64) (dest_track_dur_before_cat - mediaTime) * rescale );
}
segmentDuration += (u64) (s64) dur;
gf_isom_modify_edit_segment(dest, dst_tk, j, segmentDuration, mediaTime, editMode);
break;
}
}
} else {
u64 editTime, segmentDuration, mediaTime, edit_offset;
Double t;
u8 editMode;
u32 j, count;
count = gf_isom_get_edit_segment_count(dest, dst_tk);
if (count) {
e = gf_isom_get_edit_segment(dest, dst_tk, count, &editTime, &segmentDuration, &mediaTime, &editMode);
if (e) {
fprintf(stderr, "Error: edit segment error on destination track %u could not be retrieved.\n", dst_tk);
goto err_exit;
}
} else if (gf_isom_get_edit_segment_count(orig, i+1)) {
/*fake empty edit segment*/
/*convert from media time to track time*/
Double rescale = (Float) gf_isom_get_timescale(dest);
rescale /= (Float) gf_isom_get_media_timescale(dest, dst_tk);
segmentDuration = (u64) (dest_track_dur_before_cat * rescale);
editTime = 0;
mediaTime = 0;
gf_isom_set_edit_segment(dest, dst_tk, editTime, segmentDuration, mediaTime, GF_ISOM_EDIT_NORMAL);
} else {
editTime = 0;
segmentDuration = 0;
}
/*convert to dst time scale*/
ts_scale = (Float) gf_isom_get_timescale(dest);
ts_scale /= (Float) gf_isom_get_timescale(orig);
edit_offset = editTime + segmentDuration;
count = gf_isom_get_edit_segment_count(orig, i+1);
for (j=0; j<count; j++) {
gf_isom_get_edit_segment(orig, i+1, j+1, &editTime, &segmentDuration, &mediaTime, &editMode);
t = (Double) (s64) editTime;
t *= ts_scale;
t += (s64) edit_offset;
editTime = (s64) t;
t = (Double) (s64) segmentDuration;
t *= ts_scale;
segmentDuration = (s64) t;
t = (Double) (s64) mediaTime;
t *= ts_scale;
t+= (s64) dest_track_dur_before_cat;
mediaTime = (s64) t;
if ((editMode == GF_ISOM_EDIT_EMPTY) && (mediaTime > 0)) {
editMode = GF_ISOM_EDIT_NORMAL;
}
gf_isom_set_edit_segment(dest, dst_tk, editTime, segmentDuration, mediaTime, editMode);
}
}
}
gf_set_progress("Appending", nb_samp, nb_samp);
/*check chapters*/
for (i=0; i<gf_isom_get_chapter_count(orig, 0); i++) {
char *name;
Double c_time;
u64 chap_time;
gf_isom_get_chapter(orig, 0, i+1, &chap_time, (const char **) &name);
c_time = (Double) (s64) chap_time;
c_time /= 1000;
c_time += dest_orig_dur;
/*check last file chapter*/
if (!i && gf_isom_get_chapter_count(dest, 0)) {
const char *last_name;
u64 last_chap_time;
gf_isom_get_chapter(dest, 0, gf_isom_get_chapter_count(dest, 0), &last_chap_time, &last_name);
/*last and first chapters are the same, don't duplicate*/
if (last_name && name && !stricmp(last_name, name)) continue;
}
chap_time = (u64) (c_time*1000);
gf_isom_add_chapter(dest, 0, chap_time, name);
}
err_exit:
gf_isom_delete(orig);
return e;
}
typedef struct
{
char szPath[GF_MAX_PATH];
char szRad1[1024], szRad2[1024], szOpt[200];
GF_ISOFile *dest;
u32 import_flags;
Double force_fps;
u32 frames_per_sample;
char *tmp_dir;
Bool force_cat, align_timelines, allow_add_in_command;
} CATEnum;
Bool cat_enumerate(void *cbk, char *szName, char *szPath, GF_FileEnumInfo *file_info)
{
GF_Err e;
u32 len_rad1;
char szFileName[GF_MAX_PATH];
CATEnum *cat_enum = (CATEnum *)cbk;
len_rad1 = (u32) strlen(cat_enum->szRad1);
if (strnicmp(szName, cat_enum->szRad1, len_rad1)) return 0;
if (strlen(cat_enum->szRad2) && !strstr(szName + len_rad1, cat_enum->szRad2) ) return 0;
strcpy(szFileName, szName);
strcat(szFileName, cat_enum->szOpt);
e = cat_isomedia_file(cat_enum->dest, szFileName, cat_enum->import_flags, cat_enum->force_fps, cat_enum->frames_per_sample, cat_enum->tmp_dir, cat_enum->force_cat, cat_enum->align_timelines, cat_enum->allow_add_in_command);
if (e) return 1;
return 0;
}
GF_Err cat_multiple_files(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command)
{
CATEnum cat_enum;
char *sep;
cat_enum.dest = dest;
cat_enum.import_flags = import_flags;
cat_enum.force_fps = force_fps;
cat_enum.frames_per_sample = frames_per_sample;
cat_enum.tmp_dir = tmp_dir;
cat_enum.force_cat = force_cat;
cat_enum.align_timelines = align_timelines;
cat_enum.allow_add_in_command = allow_add_in_command;
strcpy(cat_enum.szPath, fileName);
sep = strrchr(cat_enum.szPath, GF_PATH_SEPARATOR);
if (!sep) sep = strrchr(cat_enum.szPath, '/');
if (!sep) {
strcpy(cat_enum.szPath, ".");
strcpy(cat_enum.szRad1, fileName);
} else {
strcpy(cat_enum.szRad1, sep+1);
sep[0] = 0;
}
sep = strchr(cat_enum.szRad1, '*');
strcpy(cat_enum.szRad2, sep+1);
sep[0] = 0;
sep = strchr(cat_enum.szRad2, '%');
if (!sep) sep = strchr(cat_enum.szRad2, '#');
if (!sep) sep = strchr(cat_enum.szRad2, ':');
strcpy(cat_enum.szOpt, "");
if (sep) {
strcpy(cat_enum.szOpt, sep);
sep[0] = 0;
}
return gf_enum_directory(cat_enum.szPath, 0, cat_enumerate, &cat_enum, NULL);
}
#ifndef GPAC_DISABLE_SCENE_ENCODER
/*
MPEG-4 encoding
*/
GF_Err EncodeFile(char *in, GF_ISOFile *mp4, GF_SMEncodeOptions *opts, FILE *logs)
{
#ifdef GPAC_DISABLE_SMGR
return GF_NOT_SUPPORTED;
#else
GF_Err e;
GF_SceneLoader load;
GF_SceneManager *ctx;
GF_SceneGraph *sg;
#ifndef GPAC_DISABLE_SCENE_STATS
GF_StatManager *statsman = NULL;
#endif
sg = gf_sg_new();
ctx = gf_sm_new(sg);
memset(&load, 0, sizeof(GF_SceneLoader));
load.fileName = in;
load.ctx = ctx;
load.swf_import_flags = swf_flags;
load.swf_flatten_limit = swf_flatten_angle;
/*since we're encoding we must get MPEG4 nodes only*/
load.flags = GF_SM_LOAD_MPEG4_STRICT;
e = gf_sm_load_init(&load);
if (e<0) {
gf_sm_load_done(&load);
fprintf(stderr, "Cannot load context %s - %s\n", in, gf_error_to_string(e));
goto err_exit;
}
e = gf_sm_load_run(&load);
gf_sm_load_done(&load);
#ifndef GPAC_DISABLE_SCENE_STATS
if (opts->auto_quant) {
fprintf(stderr, "Analysing Scene for Automatic Quantization\n");
statsman = gf_sm_stats_new();
e = gf_sm_stats_for_scene(statsman, ctx);
if (!e) {
GF_SceneStatistics *stats = gf_sm_stats_get(statsman);
/*LASeR*/
if (opts->auto_quant==1) {
if (opts->resolution > (s32)stats->frac_res_2d) {
fprintf(stderr, " Given resolution %d is (unnecessarily) too high, using %d instead.\n", opts->resolution, stats->frac_res_2d);
opts->resolution = stats->frac_res_2d;
} else if (stats->int_res_2d + opts->resolution <= 0) {
fprintf(stderr, " Given resolution %d is too low, using %d instead.\n", opts->resolution, stats->int_res_2d - 1);
opts->resolution = 1 - stats->int_res_2d;
}
opts->coord_bits = stats->int_res_2d + opts->resolution;
fprintf(stderr, " Coordinates & Lengths encoded using ");
if (opts->resolution < 0) fprintf(stderr, "only the %d most significant bits (of %d).\n", opts->coord_bits, stats->int_res_2d);
else fprintf(stderr, "a %d.%d representation\n", stats->int_res_2d, opts->resolution);
fprintf(stderr, " Matrix Scale & Skew Coefficients ");
if (opts->coord_bits - 8 < stats->scale_int_res_2d) {
opts->scale_bits = stats->scale_int_res_2d - opts->coord_bits + 8;
fprintf(stderr, "encoded using a %d.8 representation\n", stats->scale_int_res_2d);
} else {
opts->scale_bits = 0;
fprintf(stderr, "encoded using a %d.8 representation\n", opts->coord_bits - 8);
}
}
#ifndef GPAC_DISABLE_VRML
/*BIFS*/
else if (stats->base_layer) {
GF_AUContext *au;
GF_CommandField *inf;
M_QuantizationParameter *qp;
GF_Command *com = gf_sg_command_new(ctx->scene_graph, GF_SG_GLOBAL_QUANTIZER);
qp = (M_QuantizationParameter *) gf_node_new(ctx->scene_graph, TAG_MPEG4_QuantizationParameter);
inf = gf_sg_command_field_new(com);
inf->new_node = (GF_Node *)qp;
inf->field_ptr = &inf->new_node;
inf->fieldType = GF_SG_VRML_SFNODE;
gf_node_register(inf->new_node, NULL);
au = gf_list_get(stats->base_layer->AUs, 0);
gf_list_insert(au->commands, com, 0);
qp->useEfficientCoding = 1;
qp->textureCoordinateQuant = 0;
if ((stats->count_2f+stats->count_2d) && opts->resolution) {
qp->position2DMin = stats->min_2d;
qp->position2DMax = stats->max_2d;
qp->position2DNbBits = opts->resolution;
qp->position2DQuant = 1;
}
if ((stats->count_3f+stats->count_3d) && opts->resolution) {
qp->position3DMin = stats->min_3d;
qp->position3DMax = stats->max_3d;
qp->position3DQuant = opts->resolution;
qp->position3DQuant = 1;
qp->textureCoordinateQuant = 1;
}
//float quantif is disabled since 2008, check if we want to re-enable it
#if 0
if (stats->count_float && opts->resolution) {
qp->scaleMin = stats->min_fixed;
qp->scaleMax = stats->max_fixed;
qp->scaleNbBits = 2*opts->resolution;
qp->scaleQuant = 1;
}
#endif
}
#endif
}
}
#endif /*GPAC_DISABLE_SCENE_STATS*/
if (e<0) {
fprintf(stderr, "Error loading file %s\n", gf_error_to_string(e));
goto err_exit;
} else {
gf_log_cbk prev_logs = NULL;
if (logs) {
gf_log_set_tool_level(GF_LOG_CODING, GF_LOG_DEBUG);
prev_logs = gf_log_set_callback(logs, scene_coding_log);
}
opts->src_url = in;
e = gf_sm_encode_to_file(ctx, mp4, opts);
if (logs) {
gf_log_set_tool_level(GF_LOG_CODING, GF_LOG_ERROR);
gf_log_set_callback(NULL, prev_logs);
}
}
gf_isom_set_brand_info(mp4, GF_ISOM_BRAND_MP42, 1);
gf_isom_modify_alternate_brand(mp4, GF_ISOM_BRAND_ISOM, 1);
err_exit:
#ifndef GPAC_DISABLE_SCENE_STATS
if (statsman) gf_sm_stats_del(statsman);
#endif
gf_sm_del(ctx);
gf_sg_del(sg);
return e;
#endif /*GPAC_DISABLE_SMGR*/
}
#endif /*GPAC_DISABLE_SCENE_ENCODER*/
#ifndef GPAC_DISABLE_BIFS_ENC
/*
MPEG-4 chunk encoding
*/
static u32 GetNbBits(u32 MaxVal)
{
u32 k=0;
while ((s32) MaxVal > ((1<<k)-1) ) k+=1;
return k;
}
#ifndef GPAC_DISABLE_SMGR
GF_Err EncodeBIFSChunk(GF_SceneManager *ctx, char *bifsOutputFile, GF_Err (*AUCallback)(GF_ISOSample *))
{
GF_Err e;
char *data;
u32 data_len;
GF_BifsEncoder *bifsenc;
GF_InitialObjectDescriptor *iod;
u32 i, j, count;
GF_StreamContext *sc;
GF_ESD *esd;
Bool encode_names, delete_bcfg;
GF_BIFSConfig *bcfg;
GF_AUContext *au;
char szRad[GF_MAX_PATH], *ext;
char szName[1024];
FILE *f;
strcpy(szRad, bifsOutputFile);
ext = strrchr(szRad, '.');
if (ext) ext[0] = 0;
/* step3: encoding all AUs in ctx->streams starting at AU index 1 (0 is SceneReplace from previous context) */
bifsenc = gf_bifs_encoder_new(ctx->scene_graph);
e = GF_OK;
iod = (GF_InitialObjectDescriptor *) ctx->root_od;
/*if no iod check we only have one bifs*/
if (!iod) {
count = 0;
for (i=0; i<gf_list_count(ctx->streams); i++) {
sc = gf_list_get(ctx->streams, i);
if (sc->streamType == GF_STREAM_OD) count++;
}
if (!iod && count>1) return GF_NOT_SUPPORTED;
}
count = gf_list_count(ctx->streams);
for (i=0; i<count; i++) {
u32 nbb;
GF_StreamContext *sc = gf_list_get(ctx->streams, i);
esd = NULL;
if (sc->streamType != GF_STREAM_SCENE) continue;
esd = NULL;
if (iod) {
for (j=0; j<gf_list_count(iod->ESDescriptors); j++) {
esd = gf_list_get(iod->ESDescriptors, j);
if (esd->decoderConfig && esd->decoderConfig->streamType == GF_STREAM_SCENE) {
if (!sc->ESID) sc->ESID = esd->ESID;
if (sc->ESID == esd->ESID) {
break;
}
}
/*special BIFS direct import from NHNT*/
else if (gf_list_count(iod->ESDescriptors)==1) {
sc->ESID = esd->ESID;
break;
}
esd = NULL;
}
}
if (!esd) {
esd = gf_odf_desc_esd_new(2);
if (!esd) return GF_OUT_OF_MEM;
gf_odf_desc_del((GF_Descriptor *) esd->decoderConfig->decoderSpecificInfo);
esd->decoderConfig->decoderSpecificInfo = NULL;
esd->ESID = sc->ESID;
esd->decoderConfig->streamType = GF_STREAM_SCENE;
}
if (!esd->decoderConfig) return GF_OUT_OF_MEM;
/*should NOT happen (means inputctx is not properly setup)*/
if (!esd->decoderConfig->decoderSpecificInfo) {
bcfg = (GF_BIFSConfig*)gf_odf_desc_new(GF_ODF_BIFS_CFG_TAG);
delete_bcfg = 1;
}
/*regular retrieve from ctx*/
else if (esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_BIFS_CFG_TAG) {
bcfg = (GF_BIFSConfig *)esd->decoderConfig->decoderSpecificInfo;
delete_bcfg = 0;
}
/*should not happen either (unless loading from MP4 in which case BIFSc is not decoded)*/
else {
bcfg = gf_odf_get_bifs_config(esd->decoderConfig->decoderSpecificInfo, esd->decoderConfig->objectTypeIndication);
delete_bcfg = 1;
}
/*NO CHANGE TO BIFSC otherwise the generated update will not match the input context*/
nbb = GetNbBits(ctx->max_node_id);
if (!bcfg->nodeIDbits) bcfg->nodeIDbits=nbb;
if (bcfg->nodeIDbits<nbb) fprintf(stderr, "Warning: BIFSConfig.NodeIDBits TOO SMALL\n");
nbb = GetNbBits(ctx->max_route_id);
if (!bcfg->routeIDbits) bcfg->routeIDbits = nbb;
if (bcfg->routeIDbits<nbb) fprintf(stderr, "Warning: BIFSConfig.RouteIDBits TOO SMALL\n");
nbb = GetNbBits(ctx->max_proto_id);
if (!bcfg->protoIDbits) bcfg->protoIDbits=nbb;
if (bcfg->protoIDbits<nbb) fprintf(stderr, "Warning: BIFSConfig.ProtoIDBits TOO SMALL\n");
/*this is the real pb, not stored in cfg or file level, set at EACH replaceScene*/
encode_names = 0;
/* The BIFS Config that is passed here should be the BIFSConfig from the IOD */
gf_bifs_encoder_new_stream(bifsenc, sc->ESID, bcfg, encode_names, 0);
if (delete_bcfg) gf_odf_desc_del((GF_Descriptor *)bcfg);
/*setup MP4 track*/
if (!esd->slConfig) esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
if (sc->timeScale) esd->slConfig->timestampResolution = sc->timeScale;
if (!esd->slConfig->timestampResolution) esd->slConfig->timestampResolution = 1000;
esd->ESID = sc->ESID;
gf_bifs_encoder_get_config(bifsenc, sc->ESID, &data, &data_len);
if (esd->decoderConfig->decoderSpecificInfo) gf_odf_desc_del((GF_Descriptor *) esd->decoderConfig->decoderSpecificInfo);
esd->decoderConfig->decoderSpecificInfo = (GF_DefaultDescriptor *) gf_odf_desc_new(GF_ODF_DSI_TAG);
esd->decoderConfig->decoderSpecificInfo->data = data;
esd->decoderConfig->decoderSpecificInfo->dataLength = data_len;
esd->decoderConfig->objectTypeIndication = gf_bifs_encoder_get_version(bifsenc, sc->ESID);
for (j=1; j<gf_list_count(sc->AUs); j++) {
char *data;
u32 data_len;
au = gf_list_get(sc->AUs, j);
e = gf_bifs_encode_au(bifsenc, sc->ESID, au->commands, &data, &data_len);
if (data) {
sprintf(szName, "%s%02d.bifs", szRad, j);
f = gf_fopen(szName, "wb");
gf_fwrite(data, data_len, 1, f);
gf_fclose(f);
gf_free(data);
}
}
}
gf_bifs_encoder_del(bifsenc);
return e;
}
#endif /*GPAC_DISABLE_SMGR*/
#endif /*GPAC_DISABLE_BIFS_ENC*/
/**
* \param chunkFile BT chunk to be encoded
* \param bifs output file name for the BIFS data
* \param inputContext initial BT upon which the chunk is based (shall not be NULL)
* \param outputContext: file name to dump the context after applying the new chunk to the input context
can be NULL, without .bt
* \param tmpdir can be NULL
*/
GF_Err EncodeFileChunk(char *chunkFile, char *bifs, char *inputContext, char *outputContext, const char *tmpdir)
{
#if defined(GPAC_DISABLE_SMGR) || defined(GPAC_DISABLE_BIFS_ENC) || defined(GPAC_DISABLE_SCENE_ENCODER) || defined (GPAC_DISABLE_SCENE_DUMP)
fprintf(stderr, "BIFS encoding is not supported in this build of GPAC\n");
return GF_NOT_SUPPORTED;
#else
GF_Err e;
GF_SceneGraph *sg;
GF_SceneManager *ctx;
GF_SceneLoader load;
/*Step 1: create context and load input*/
sg = gf_sg_new();
ctx = gf_sm_new(sg);
memset(&load, 0, sizeof(GF_SceneLoader));
load.fileName = inputContext;
load.ctx = ctx;
/*since we're encoding we must get MPEG4 nodes only*/
load.flags = GF_SM_LOAD_MPEG4_STRICT;
e = gf_sm_load_init(&load);
if (!e) e = gf_sm_load_run(&load);
gf_sm_load_done(&load);
if (e) {
fprintf(stderr, "Cannot load context %s - %s\n", inputContext, gf_error_to_string(e));
goto exit;
}
/* Step 2: make sure we have only ONE RAP for each stream*/
e = gf_sm_aggregate(ctx, 0);
if (e) goto exit;
/*Step 3: loading the chunk into the context*/
memset(&load, 0, sizeof(GF_SceneLoader));
load.fileName = chunkFile;
load.ctx = ctx;
load.flags = GF_SM_LOAD_MPEG4_STRICT | GF_SM_LOAD_CONTEXT_READY;
e = gf_sm_load_init(&load);
if (!e) e = gf_sm_load_run(&load);
gf_sm_load_done(&load);
if (e) {
fprintf(stderr, "Cannot load chunk context %s - %s\n", chunkFile, gf_error_to_string(e));
goto exit;
}
fprintf(stderr, "Context and chunks loaded\n");
/* Assumes that the first AU contains only one command a SceneReplace and
that is not part of the current chunk */
/* Last argument is a callback to pass the encoded AUs: not needed here
Saving is not handled correctly */
e = EncodeBIFSChunk(ctx, bifs, NULL);
if (e) goto exit;
if (outputContext) {
u32 d_mode, do_enc;
char szF[GF_MAX_PATH], *ext;
/*make random access for storage*/
e = gf_sm_aggregate(ctx, 0);
if (e) goto exit;
/*check if we dump to BT, XMT or encode to MP4*/
strcpy(szF, outputContext);
ext = strrchr(szF, '.');
d_mode = GF_SM_DUMP_BT;
do_enc = 0;
if (ext) {
if (!stricmp(ext, ".xmt") || !stricmp(ext, ".xmta")) d_mode = GF_SM_DUMP_XMTA;
else if (!stricmp(ext, ".mp4")) do_enc = 1;
ext[0] = 0;
}
if (do_enc) {
GF_ISOFile *mp4;
strcat(szF, ".mp4");
mp4 = gf_isom_open(szF, GF_ISOM_WRITE_EDIT, tmpdir);
e = gf_sm_encode_to_file(ctx, mp4, NULL);
if (e) gf_isom_delete(mp4);
else gf_isom_close(mp4);
}
else e = gf_sm_dump(ctx, szF, GF_FALSE, d_mode);
}
exit:
if (ctx) {
sg = ctx->scene_graph;
gf_sm_del(ctx);
gf_sg_del(sg);
}
return e;
#endif /*defined(GPAC_DISABLE_BIFS_ENC) || defined(GPAC_DISABLE_SCENE_ENCODER) || defined (GPAC_DISABLE_SCENE_DUMP)*/
}
#endif /*GPAC_DISABLE_MEDIA_IMPORT*/
#ifndef GPAC_DISABLE_CORE_TOOLS
void sax_node_start(void *sax_cbck, const char *node_name, const char *name_space, const GF_XMLAttribute *attributes, u32 nb_attributes)
{
char szCheck[100];
GF_List *imports = sax_cbck;
GF_XMLAttribute *att;
u32 i=0;
/*do not process hyperlinks*/
if (!strcmp(node_name, "a") || !strcmp(node_name, "Anchor")) return;
for (i=0; i<nb_attributes; i++) {
att = (GF_XMLAttribute *) &attributes[i];
if (stricmp(att->name, "xlink:href") && stricmp(att->name, "url")) continue;
if (att->value[0]=='#') continue;
if (!strnicmp(att->value, "od:", 3)) continue;
sprintf(szCheck, "%d", atoi(att->value));
if (!strcmp(szCheck, att->value)) continue;
gf_list_add(imports, gf_strdup(att->value) );
}
}
static Bool wgt_enum_files(void *cbck, char *file_name, char *file_path, GF_FileEnumInfo *file_info)
{
WGTEnum *wgt = (WGTEnum *)cbck;
if (!strcmp(wgt->root_file, file_path)) return 0;
/*remove CVS stuff*/
if (strstr(file_path, ".#")) return 0;
gf_list_add(wgt->imports, gf_strdup(file_path) );
return 0;
}
static Bool wgt_enum_dir(void *cbck, char *file_name, char *file_path, GF_FileEnumInfo *file_info)
{
if (!stricmp(file_name, "cvs") || !stricmp(file_name, ".svn") || !stricmp(file_name, ".git")) return 0;
gf_enum_directory(file_path, 0, wgt_enum_files, cbck, NULL);
return gf_enum_directory(file_path, 1, wgt_enum_dir, cbck, NULL);
}
GF_ISOFile *package_file(char *file_name, char *fcc, const char *tmpdir, Bool make_wgt)
{
GF_ISOFile *file = NULL;
GF_Err e;
GF_SAXParser *sax;
GF_List *imports;
Bool ascii;
char root_dir[GF_MAX_PATH];
char *isom_src = NULL;
u32 i, count, mtype, skip_chars;
char *type;
type = gf_xml_get_root_type(file_name, &e);
if (!type) {
fprintf(stderr, "Cannot process XML file %s: %s\n", file_name, gf_error_to_string(e) );
return NULL;
}
if (make_wgt) {
if (strcmp(type, "widget")) {
fprintf(stderr, "XML Root type %s differs from \"widget\" \n", type);
gf_free(type);
return NULL;
}
gf_free(type);
type = gf_strdup("application/mw-manifest+xml");
fcc = "mwgt";
}
imports = gf_list_new();
root_dir[0] = 0;
if (make_wgt) {
WGTEnum wgt;
char *sep = strrchr(file_name, '\\');
if (!sep) sep = strrchr(file_name, '/');
if (sep) {
char c = sep[1];
sep[1]=0;
strcpy(root_dir, file_name);
sep[1] = c;
} else {
strcpy(root_dir, "./");
}
wgt.dir = root_dir;
wgt.root_file = file_name;
wgt.imports = imports;
gf_enum_directory(wgt.dir, 0, wgt_enum_files, &wgt, NULL);
gf_enum_directory(wgt.dir, 1, wgt_enum_dir, &wgt, NULL);
ascii = 1;
} else {
sax = gf_xml_sax_new(sax_node_start, NULL, NULL, imports);
e = gf_xml_sax_parse_file(sax, file_name, NULL);
ascii = !gf_xml_sax_binary_file(sax);
gf_xml_sax_del(sax);
if (e<0) goto exit;
e = GF_OK;
}
if (fcc) {
mtype = GF_4CC(fcc[0],fcc[1],fcc[2],fcc[3]);
} else {
mtype = 0;
if (!stricmp(type, "svg")) mtype = ascii ? GF_META_TYPE_SVG : GF_META_TYPE_SVGZ;
else if (!stricmp(type, "smil")) mtype = ascii ? GF_META_TYPE_SMIL : GF_META_TYPE_SMLZ;
else if (!stricmp(type, "x3d")) mtype = ascii ? GF_META_TYPE_X3D : GF_META_TYPE_X3DZ ;
else if (!stricmp(type, "xmt-a")) mtype = ascii ? GF_META_TYPE_XMTA : GF_META_TYPE_XMTZ;
}
if (!mtype) {
fprintf(stderr, "Missing 4CC code for meta name - please use ABCD:fileName\n");
e = GF_BAD_PARAM;
goto exit;
}
if (!make_wgt) {
count = gf_list_count(imports);
for (i=0; i<count; i++) {
char *item = gf_list_get(imports, i);
FILE *test = gf_fopen(item, "rb");
if (!test) {
gf_list_rem(imports, i);
i--;
count--;
gf_free(item);
continue;
}
gf_fclose(test);
if (gf_isom_probe_file(item)) {
if (isom_src) {
fprintf(stderr, "Cannot package several IsoMedia files together\n");
e = GF_NOT_SUPPORTED;
goto exit;
}
gf_list_rem(imports, i);
i--;
count--;
isom_src = item;
continue;
}
}
}
if (isom_src) {
file = gf_isom_open(isom_src, GF_ISOM_OPEN_EDIT, tmpdir);
} else {
file = gf_isom_open("package", GF_ISOM_WRITE_EDIT, tmpdir);
}
e = gf_isom_set_meta_type(file, 1, 0, mtype);
if (e) goto exit;
/*add self ref*/
if (isom_src) {
e = gf_isom_add_meta_item(file, 1, 0, 1, NULL, isom_src, 0, 0, NULL, NULL, NULL, NULL, NULL);
if (e) goto exit;
}
e = gf_isom_set_meta_xml(file, 1, 0, file_name, !ascii);
if (e) goto exit;
skip_chars = (u32) strlen(root_dir);
count = gf_list_count(imports);
for (i=0; i<count; i++) {
char *ext, *mime, *encoding, *name = NULL;
char *item = gf_list_get(imports, i);
name = gf_strdup(item + skip_chars);
if (make_wgt) {
char *sep;
while (1) {
sep = strchr(name, '\\');
if (!sep) break;
sep[0] = '/';
}
}
mime = encoding = NULL;
ext = strrchr(item, '.');
if (!stricmp(ext, ".gz")) ext = strrchr(ext-1, '.');
if (!stricmp(ext, ".jpg") || !stricmp(ext, ".jpeg")) mime = "image/jpeg";
else if (!stricmp(ext, ".png")) mime = "image/png";
else if (!stricmp(ext, ".svg")) mime = "image/svg+xml";
else if (!stricmp(ext, ".x3d")) mime = "model/x3d+xml";
else if (!stricmp(ext, ".xmt")) mime = "application/x-xmt";
else if (!stricmp(ext, ".js")) {
mime = "application/javascript";
}
else if (!stricmp(ext, ".svgz") || !stricmp(ext, ".svg.gz")) {
mime = "image/svg+xml";
encoding = "binary-gzip";
}
else if (!stricmp(ext, ".x3dz") || !stricmp(ext, ".x3d.gz")) {
mime = "model/x3d+xml";
encoding = "binary-gzip";
}
else if (!stricmp(ext, ".xmtz") || !stricmp(ext, ".xmt.gz")) {
mime = "application/x-xmt";
encoding = "binary-gzip";
}
e = gf_isom_add_meta_item(file, 1, 0, 0, item, name, 0, GF_META_ITEM_TYPE_MIME, mime, encoding, NULL, NULL, NULL);
gf_free(name);
if (e) goto exit;
}
exit:
while (gf_list_count(imports)) {
char *item = gf_list_last(imports);
gf_list_rem_last(imports);
gf_free(item);
}
gf_list_del(imports);
if (isom_src) gf_free(isom_src);
if (type) gf_free(type);
if (e) {
if (file) gf_isom_delete(file);
return NULL;
}
return file;
}
#else
GF_ISOFile *package_file(char *file_name, char *fcc, const char *tmpdir, Bool make_wgt)
{
fprintf(stderr, "XML Not supported in this build of GPAC - cannot package file\n");
return NULL;
}
#endif //#ifndef GPAC_DISABLE_CORE_TOOLS
#endif /*GPAC_DISABLE_ISOM_WRITE*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_525_0 |
crossvul-cpp_data_good_342_9 | /*
* Copyright (C) 2017 Frank Morgner <frankmorgner@gmail.com>
*
* This file is part of OpenSC.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "egk-tool-cmdline.h"
#include "libopensc/log.h"
#include "libopensc/opensc.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif
#ifdef ENABLE_ZLIB
#include <zlib.h>
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
z_stream stream;
memset(&stream, 0, sizeof stream);
stream.total_in = compressed_len;
stream.avail_in = compressed_len;
stream.total_out = *uncompressed_len;
stream.avail_out = *uncompressed_len;
stream.next_in = (Bytef *) compressed;
stream.next_out = (Bytef *) uncompressed;
/* 15 window bits, and the +32 tells zlib to to detect if using gzip or zlib */
if (Z_OK == inflateInit2(&stream, (15 + 32))
&& Z_STREAM_END == inflate(&stream, Z_FINISH)) {
*uncompressed_len = stream.total_out;
} else {
return SC_ERROR_INVALID_DATA;
}
inflateEnd(&stream);
return SC_SUCCESS;
}
#else
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
return SC_ERROR_NOT_SUPPORTED;
}
#endif
#define PRINT(c) (isprint(c) ? c : '?')
void dump_binary(void *buf, size_t buf_len)
{
#ifdef _WIN32
_setmode(fileno(stdout), _O_BINARY);
#endif
fwrite(buf, 1, buf_len, stdout);
#ifdef _WIN32
_setmode(fileno(stdout), _O_TEXT);
#endif
}
const unsigned char aid_hca[] = {0xD2, 0x76, 0x00, 0x00, 0x01, 0x02};
static int initialize(int reader_id, int verbose,
sc_context_t **ctx, sc_reader_t **reader)
{
unsigned int i, reader_count;
int r;
if (!ctx || !reader)
return SC_ERROR_INVALID_ARGUMENTS;
r = sc_establish_context(ctx, "");
if (r < 0 || !*ctx) {
fprintf(stderr, "Failed to create initial context: %s", sc_strerror(r));
return r;
}
(*ctx)->debug = verbose;
(*ctx)->flags |= SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER;
reader_count = sc_ctx_get_reader_count(*ctx);
if (reader_count == 0) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No reader not found.\n");
return SC_ERROR_NO_READERS_FOUND;
}
if (reader_id < 0) {
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < reader_count; i++) {
*reader = sc_ctx_get_reader(*ctx, i);
if (sc_detect_card_presence(*reader) & SC_READER_CARD_PRESENT) {
reader_id = i;
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Using the first reader"
" with a card: %s", (*reader)->name);
break;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No card found, using the first reader.");
reader_id = 0;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Invalid reader number "
"(%d), only %d available.\n", reader_id, reader_count);
return SC_ERROR_NO_READERS_FOUND;
}
*reader = sc_ctx_get_reader(*ctx, reader_id);
return SC_SUCCESS;
}
int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)
{
struct sc_path path;
struct sc_file *file;
unsigned char *p;
int ok = 0;
int r;
size_t len;
sc_format_path(str_path, &path);
if (SC_SUCCESS != sc_select_file(card, &path, &file)) {
goto err;
}
len = file && file->size > 0 ? file->size : 4096;
p = realloc(*data, len);
if (!p) {
goto err;
}
*data = p;
*data_len = len;
r = sc_read_binary(card, 0, p, len, 0);
if (r < 0)
goto err;
*data_len = r;
ok = 1;
err:
sc_file_free(file);
return ok;
}
void decode_version(unsigned char *bcd, unsigned int *major, unsigned int *minor, unsigned int *fix)
{
*major = 0;
*minor = 0;
*fix = 0;
/* decode BCD to decimal */
if ((bcd[0]>>4) < 10 && ((bcd[0]&0xF) < 10) && ((bcd[1]>>4) < 10)) {
*major = (bcd[0]>>4)*100 + (bcd[0]&0xF)*10 + (bcd[1]>>4);
}
if (((bcd[1]&0xF) < 10) && ((bcd[2]>>4) < 10) && ((bcd[2]&0xF) < 10)) {
*minor = (bcd[1]&0xF)*100 + (bcd[2]>>4)*10 + (bcd[2]&0xF);
}
if ((bcd[3]>>4) < 10 && ((bcd[3]&0xF) < 10)
&& (bcd[4]>>4) < 10 && ((bcd[4]&0xF) < 10)) {
*fix = (bcd[3]>>4)*1000 + (bcd[3]&0xF)*100
+ (bcd[4]>>4)*10 + (bcd[4]&0xF);
}
}
int
main (int argc, char **argv)
{
struct gengetopt_args_info cmdline;
struct sc_path path;
struct sc_context *ctx;
struct sc_reader *reader = NULL;
struct sc_card *card;
unsigned char *data = NULL;
size_t data_len = 0;
int r;
if (cmdline_parser(argc, argv, &cmdline) != 0)
exit(1);
r = initialize(cmdline.reader_arg, cmdline.verbose_given, &ctx, &reader);
if (r < 0) {
fprintf(stderr, "Can't initialize reader\n");
exit(1);
}
if (sc_connect_card(reader, &card) < 0) {
fprintf(stderr, "Could not connect to card\n");
sc_release_context(ctx);
exit(1);
}
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, aid_hca, sizeof aid_hca, 0, 0);
if (SC_SUCCESS != sc_select_file(card, &path, NULL))
goto err;
if (cmdline.pd_flag
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 2) {
size_t len_pd = (data[0] << 8) | data[1];
if (len_pd + 2 <= data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + 2, len_pd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + 2, len_pd);
}
}
}
if ((cmdline.vd_flag || cmdline.gvd_flag)
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 8) {
size_t off_vd = (data[0] << 8) | data[1];
size_t end_vd = (data[2] << 8) | data[3];
size_t off_gvd = (data[4] << 8) | data[5];
size_t end_gvd = (data[6] << 8) | data[7];
size_t len_vd = end_vd - off_vd + 1;
size_t len_gvd = end_gvd - off_gvd + 1;
if (off_vd <= end_vd && end_vd < data_len
&& off_gvd <= end_gvd && end_gvd < data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (cmdline.vd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_vd, len_vd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_vd, len_vd);
}
}
if (cmdline.gvd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_gvd, len_gvd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_gvd, len_gvd);
}
}
}
}
if (cmdline.vsd_status_flag
&& read_file(card, "D00C", &data, &data_len)
&& data_len >= 25) {
char *status;
unsigned int major, minor, fix;
switch (data[0]) {
case '0':
status = "Transactions pending";
break;
case '1':
status = "No transactions pending";
break;
default:
status = "Unknown";
break;
}
decode_version(data+15, &major, &minor, &fix);
printf(
"Status %s\n"
"Timestamp %c%c.%c%c.%c%c%c%c at %c%c:%c%c:%c%c\n"
"Version %u.%u.%u\n",
status,
PRINT(data[7]), PRINT(data[8]),
PRINT(data[5]), PRINT(data[6]),
PRINT(data[1]), PRINT(data[2]), PRINT(data[3]), PRINT(data[4]),
PRINT(data[9]), PRINT(data[10]),
PRINT(data[11]), PRINT(data[12]),
PRINT(data[13]), PRINT(data[14]),
major, minor, fix);
}
err:
sc_disconnect_card(card);
sc_release_context(ctx);
cmdline_parser_free (&cmdline);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_342_9 |
crossvul-cpp_data_bad_2945_0 | #ifndef IGNOREALL
/*
dcraw.c -- Dave Coffin's raw photo decoder
Copyright 1997-2015 by Dave Coffin, dcoffin a cybercom o net
This is a command-line ANSI C program to convert raw photos from
any digital camera on any computer running any operating system.
No license is required to download and use dcraw.c. However,
to lawfully redistribute dcraw, you must either (a) offer, at
no extra charge, full source code* for all executable files
containing RESTRICTED functions, (b) distribute this code under
the GPL Version 2 or later, (c) remove all RESTRICTED functions,
re-implement them, or copy them from an earlier, unrestricted
Revision of dcraw.c, or (d) purchase a license from the author.
The functions that process Foveon images have been RESTRICTED
since Revision 1.237. All other code remains free for all uses.
*If you have not modified dcraw.c in any way, a link to my
homepage qualifies as "full source code".
$Revision: 1.476 $
$Date: 2015/05/25 02:29:14 $
*/
/*@out DEFINES
#ifndef USE_JPEG
#define NO_JPEG
#endif
#ifndef USE_JASPER
#define NO_JASPER
#endif
@end DEFINES */
#define NO_LCMS
#define DCRAW_VERBOSE
//@out DEFINES
#define DCRAW_VERSION "9.26"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#define _USE_MATH_DEFINES
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
//@end DEFINES
#if defined(DJGPP) || defined(__MINGW32__)
#define fseeko fseek
#define ftello ftell
#else
#define fgetc getc_unlocked
#endif
//@out DEFINES
#ifdef __CYGWIN__
#include <io.h>
#endif
#if defined WIN32 || defined(__MINGW32__)
#include <sys/utime.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define snprintf _snprintf
#define strcasecmp stricmp
#define strncasecmp strnicmp
//@end DEFINES
typedef __int64 INT64;
typedef unsigned __int64 UINT64;
//@out DEFINES
#else
#include <unistd.h>
#include <utime.h>
#include <netinet/in.h>
typedef long long INT64;
typedef unsigned long long UINT64;
#endif
#ifdef NODEPS
#define NO_JASPER
#define NO_JPEG
#define NO_LCMS
#endif
#ifndef NO_JASPER
#include <jasper/jasper.h> /* Decode Red camera movies */
#endif
#ifndef NO_JPEG
#include <jpeglib.h> /* Decode compressed Kodak DC120 photos */
#endif /* and Adobe Lossy DNGs */
#ifndef NO_LCMS
#ifdef USE_LCMS
#include <lcms.h> /* Support color profiles */
#else
#include <lcms2.h> /* Support color profiles */
#endif
#endif
#ifdef LOCALEDIR
#include <libintl.h>
#define _(String) gettext(String)
#else
#define _(String) (String)
#endif
#ifdef LJPEG_DECODE
#error Please compile dcraw.c by itself.
#error Do not link it with ljpeg_decode.
#endif
#ifndef LONG_BIT
#define LONG_BIT (8 * sizeof(long))
#endif
//@end DEFINES
#if !defined(uchar)
#define uchar unsigned char
#endif
#if !defined(ushort)
#define ushort unsigned short
#endif
/*
All global variables are defined here, and all functions that
access them are prefixed with "CLASS". Note that a thread-safe
C++ class cannot have non-const static local variables.
*/
FILE *ifp, *ofp;
short order;
const char *ifname;
char *meta_data, xtrans[6][6], xtrans_abs[6][6];
char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64], software[64];
float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len;
time_t timestamp;
off_t strip_offset, data_offset;
off_t thumb_offset, meta_offset, profile_offset;
unsigned shot_order, kodak_cbpp, exif_cfa, unique_id;
unsigned thumb_length, meta_length, profile_length;
unsigned thumb_misc, *oprof, fuji_layout, shot_select = 0, multi_out = 0;
unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress;
unsigned black, maximum, mix_green, raw_color, zero_is_bad;
unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error;
unsigned tile_width, tile_length, gpsdata[32], load_flags;
unsigned flip, tiff_flip, filters, colors;
ushort raw_height, raw_width, height, width, top_margin, left_margin;
ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height;
ushort *raw_image, (*image)[4], cblack[4102];
ushort white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4];
double pixel_aspect, aber[4] = {1, 1, 1, 1}, gamm[6] = {0.45, 4.5, 0, 0, 0, 0};
float bright = 1, user_mul[4] = {0, 0, 0, 0}, threshold = 0;
int mask[8][4];
int half_size = 0, four_color_rgb = 0, document_mode = 0, highlight = 0;
int verbose = 0, use_auto_wb = 0, use_camera_wb = 0, use_camera_matrix = 1;
int output_color = 1, output_bps = 8, output_tiff = 0, med_passes = 0;
int no_auto_bright = 0;
unsigned greybox[4] = {0, 0, UINT_MAX, UINT_MAX};
float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4];
const double xyz_rgb[3][3] = {/* XYZ from RGB */
{0.412453, 0.357580, 0.180423},
{0.212671, 0.715160, 0.072169},
{0.019334, 0.119193, 0.950227}};
const float d65_white[3] = {0.950456, 1, 1.088754};
int histogram[4][0x2000];
void (*write_thumb)(), (*write_fun)();
void (*load_raw)(), (*thumb_load_raw)();
jmp_buf failure;
struct decode
{
struct decode *branch[2];
int leaf;
} first_decode[2048], *second_decode, *free_decode;
struct tiff_ifd
{
int t_width, t_height, bps, comp, phint, offset, t_flip, samples, bytes;
int t_tile_width, t_tile_length, sample_format, predictor;
float t_shutter;
} tiff_ifd[10];
struct ph1
{
int format, key_off, tag_21a;
int t_black, split_col, black_col, split_row, black_row;
float tag_210;
} ph1;
#define CLASS
//@out DEFINES
#define FORC(cnt) for (c = 0; c < cnt; c++)
#define FORC3 FORC(3)
#define FORC4 FORC(4)
#define FORCC for (c = 0; c < colors && c < 4; c++)
#define SQR(x) ((x) * (x))
#define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define LIM(x, min, max) MAX(min, MIN(x, max))
#define ULIM(x, y, z) ((y) < (z) ? LIM(x, y, z) : LIM(x, z, y))
#define CLIP(x) LIM((int)(x), 0, 65535)
#define CLIP15(x) LIM((int)(x), 0, 32767)
#define SWAP(a, b) \
{ \
a = a + b; \
b = a - b; \
a = a - b; \
}
#define my_swap(type, i, j) \
{ \
type t = i; \
i = j; \
j = t; \
}
static float fMAX(float a, float b) { return MAX(a, b); }
/*
In order to inline this calculation, I make the risky
assumption that all filter patterns can be described
by a repeating pattern of eight rows and two columns
Do not use the FC or BAYER macros with the Leaf CatchLight,
because its pattern is 16x16, not 2x8.
Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2
PowerShot 600 PowerShot A50 PowerShot Pro70 Pro90 & G1
0xe1e4e1e4: 0x1b4e4b1e: 0x1e4b4e1b: 0xb4b4b4b4:
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
0 G M G M G M 0 C Y C Y C Y 0 Y C Y C Y C 0 G M G M G M
1 C Y C Y C Y 1 M G M G M G 1 M G M G M G 1 Y C Y C Y C
2 M G M G M G 2 Y C Y C Y C 2 C Y C Y C Y
3 C Y C Y C Y 3 G M G M G M 3 G M G M G M
4 C Y C Y C Y 4 Y C Y C Y C
PowerShot A5 5 G M G M G M 5 G M G M G M
0x1e4e1e4e: 6 Y C Y C Y C 6 C Y C Y C Y
7 M G M G M G 7 M G M G M G
0 1 2 3 4 5
0 C Y C Y C Y
1 G M G M G M
2 C Y C Y C Y
3 M G M G M G
All RGB cameras use one of these Bayer grids:
0x16161616: 0x61616161: 0x49494949: 0x94949494:
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
0 B G B G B G 0 G R G R G R 0 G B G B G B 0 R G R G R G
1 G R G R G R 1 B G B G B G 1 R G R G R G 1 G B G B G B
2 B G B G B G 2 G R G R G R 2 G B G B G B 2 R G R G R G
3 G R G R G R 3 B G B G B G 3 R G R G R G 3 G B G B G B
*/
#define RAW(row, col) raw_image[(row)*raw_width + (col)]
//@end DEFINES
#define FC(row, col) (filters >> ((((row) << 1 & 14) + ((col)&1)) << 1) & 3)
//@out DEFINES
#define BAYER(row, col) image[((row) >> shrink) * iwidth + ((col) >> shrink)][FC(row, col)]
#define BAYER2(row, col) image[((row) >> shrink) * iwidth + ((col) >> shrink)][fcol(row, col)]
//@end DEFINES
/* @out COMMON
#include <math.h>
#define CLASS LibRaw::
#include "libraw/libraw_types.h"
#define LIBRAW_LIBRARY_BUILD
#define LIBRAW_IO_REDEFINED
#include "libraw/libraw.h"
#include "internal/defines.h"
#include "internal/var_defines.h"
@end COMMON */
//@out COMMON
int CLASS fcol(int row, int col)
{
static const char filter[16][16] = {
{2, 1, 1, 3, 2, 3, 2, 0, 3, 2, 3, 0, 1, 2, 1, 0}, {0, 3, 0, 2, 0, 1, 3, 1, 0, 1, 1, 2, 0, 3, 3, 2},
{2, 3, 3, 2, 3, 1, 1, 3, 3, 1, 2, 1, 2, 0, 0, 3}, {0, 1, 0, 1, 0, 2, 0, 2, 2, 0, 3, 0, 1, 3, 2, 1},
{3, 1, 1, 2, 0, 1, 0, 2, 1, 3, 1, 3, 0, 1, 3, 0}, {2, 0, 0, 3, 3, 2, 3, 1, 2, 0, 2, 0, 3, 2, 2, 1},
{2, 3, 3, 1, 2, 1, 2, 1, 2, 1, 1, 2, 3, 0, 0, 1}, {1, 0, 0, 2, 3, 0, 0, 3, 0, 3, 0, 3, 2, 1, 2, 3},
{2, 3, 3, 1, 1, 2, 1, 0, 3, 2, 3, 0, 2, 3, 1, 3}, {1, 0, 2, 0, 3, 0, 3, 2, 0, 1, 1, 2, 0, 1, 0, 2},
{0, 1, 1, 3, 3, 2, 2, 1, 1, 3, 3, 0, 2, 1, 3, 2}, {2, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 2, 3, 0, 1, 0},
{1, 3, 1, 2, 3, 2, 3, 2, 0, 2, 0, 1, 1, 0, 3, 0}, {0, 2, 0, 3, 1, 0, 0, 1, 1, 3, 3, 2, 3, 2, 2, 1},
{2, 1, 3, 2, 3, 1, 2, 1, 0, 3, 0, 2, 0, 2, 0, 2}, {0, 3, 1, 0, 0, 2, 0, 3, 2, 1, 3, 1, 1, 3, 1, 3}};
if (filters == 1)
return filter[(row + top_margin) & 15][(col + left_margin) & 15];
if (filters == 9)
return xtrans[(row + 6) % 6][(col + 6) % 6];
return FC(row, col);
}
#if !defined(__FreeBSD__)
static size_t local_strnlen(const char *s, size_t n)
{
const char *p = (const char *)memchr(s, 0, n);
return (p ? p - s : n);
}
/* add OS X version check here ?? */
#define strnlen(a, b) local_strnlen(a, b)
#endif
#ifdef LIBRAW_LIBRARY_BUILD
static int Fuji_wb_list1[] = {LIBRAW_WBI_FineWeather, LIBRAW_WBI_Shade, LIBRAW_WBI_FL_D,
LIBRAW_WBI_FL_L, LIBRAW_WBI_FL_W, LIBRAW_WBI_Tungsten};
static int nFuji_wb_list1 = sizeof(Fuji_wb_list1) / sizeof(int);
static int FujiCCT_K[31] = {2500, 2550, 2650, 2700, 2800, 2850, 2950, 3000, 3100, 3200, 3300,
3400, 3600, 3700, 3800, 4000, 4200, 4300, 4500, 4800, 5000, 5300,
5600, 5900, 6300, 6700, 7100, 7700, 8300, 9100, 10000};
static int Fuji_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Custom, 6, LIBRAW_WBI_FineWeather, 1,
LIBRAW_WBI_Shade, 8, LIBRAW_WBI_FL_D, 10, LIBRAW_WBI_FL_L, 11,
LIBRAW_WBI_FL_W, 12, LIBRAW_WBI_Tungsten, 2, LIBRAW_WBI_Underwater, 35,
LIBRAW_WBI_Ill_A, 82, LIBRAW_WBI_D65, 83};
static int nFuji_wb_list2 = sizeof(Fuji_wb_list2) / sizeof(int);
static int Oly_wb_list1[] = {LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_FineWeather,
LIBRAW_WBI_Tungsten, LIBRAW_WBI_Sunset, LIBRAW_WBI_FL_D,
LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_FL_WW};
static int Oly_wb_list2[] = {LIBRAW_WBI_Auto,
0,
LIBRAW_WBI_Tungsten,
3000,
0x100,
3300,
0x100,
3600,
0x100,
3900,
LIBRAW_WBI_FL_W,
4000,
0x100,
4300,
LIBRAW_WBI_FL_D,
4500,
0x100,
4800,
LIBRAW_WBI_FineWeather,
5300,
LIBRAW_WBI_Cloudy,
6000,
LIBRAW_WBI_FL_N,
6600,
LIBRAW_WBI_Shade,
7500,
LIBRAW_WBI_Custom1,
0,
LIBRAW_WBI_Custom2,
0,
LIBRAW_WBI_Custom3,
0,
LIBRAW_WBI_Custom4,
0};
static int Pentax_wb_list1[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten,
LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash};
static int Pentax_wb_list2[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy,
LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N,
LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash, LIBRAW_WBI_FL_L};
static int nPentax_wb_list2 = sizeof(Pentax_wb_list2) / sizeof(int);
static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp)
{
int r = fp->read(buf, len, 1);
buf[len - 1] = 0;
return r;
}
#define stmread(buf, maxlen, fp) stread(buf, MIN(maxlen, sizeof(buf)), fp)
#endif
#if !defined(__GLIBC__) && !defined(__FreeBSD__)
char *my_memmem(char *haystack, size_t haystacklen, char *needle, size_t needlelen)
{
char *c;
for (c = haystack; c <= haystack + haystacklen - needlelen; c++)
if (!memcmp(c, needle, needlelen))
return c;
return 0;
}
#define memmem my_memmem
char *my_strcasestr(char *haystack, const char *needle)
{
char *c;
for (c = haystack; *c; c++)
if (!strncasecmp(c, needle, strlen(needle)))
return c;
return 0;
}
#define strcasestr my_strcasestr
#endif
#define strbuflen(buf) strnlen(buf, sizeof(buf) - 1)
//@end COMMON
void CLASS merror(void *ptr, const char *where)
{
if (ptr)
return;
fprintf(stderr, _("%s: Out of memory in %s\n"), ifname, where);
longjmp(failure, 1);
}
void CLASS derror()
{
if (!data_error)
{
fprintf(stderr, "%s: ", ifname);
if (feof(ifp))
fprintf(stderr, _("Unexpected end of file\n"));
else
fprintf(stderr, _("Corrupt data near 0x%llx\n"), (INT64)ftello(ifp));
}
data_error++;
}
//@out COMMON
ushort CLASS sget2(uchar *s)
{
if (order == 0x4949) /* "II" means little-endian */
return s[0] | s[1] << 8;
else /* "MM" means big-endian */
return s[0] << 8 | s[1];
}
// DNG was written by:
#define nonDNG 0
#define CameraDNG 1
#define AdobeDNG 2
#ifdef LIBRAW_LIBRARY_BUILD
static int getwords(char *line, char *words[], int maxwords, int maxlen)
{
line[maxlen - 1] = 0;
char *p = line;
int nwords = 0;
while (1)
{
while (isspace(*p))
p++;
if (*p == '\0')
return nwords;
words[nwords++] = p;
while (!isspace(*p) && *p != '\0')
p++;
if (*p == '\0')
return nwords;
*p++ = '\0';
if (nwords >= maxwords)
return nwords;
}
}
static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f)
{
if ((a >> 4) > 9)
return 0;
else if ((a & 0x0f) > 9)
return 0;
else if ((b >> 4) > 9)
return 0;
else if ((b & 0x0f) > 9)
return 0;
else if ((c >> 4) > 9)
return 0;
else if ((c & 0x0f) > 9)
return 0;
else if ((d >> 4) > 9)
return 0;
else if ((d & 0x0f) > 9)
return 0;
else if ((e >> 4) > 9)
return 0;
else if ((e & 0x0f) > 9)
return 0;
else if ((f >> 4) > 9)
return 0;
else if ((f & 0x0f) > 9)
return 0;
return 1;
}
static ushort bcd2dec(uchar data)
{
if ((data >> 4) > 9)
return 0;
else if ((data & 0x0f) > 9)
return 0;
else
return (data >> 4) * 10 + (data & 0x0f);
}
static uchar SonySubstitution[257] =
"\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03"
"\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5"
"\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53"
"\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea"
"\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3"
"\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7"
"\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63"
"\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd"
"\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb"
"\xfc\xfd\xfe\xff";
ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse
{
if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */
return s[0] | s[1] << 8;
else /* "MM" means big-endian... */
return s[0] << 8 | s[1];
}
#endif
ushort CLASS get2()
{
uchar str[2] = {0xff, 0xff};
fread(str, 1, 2, ifp);
return sget2(str);
}
unsigned CLASS sget4(uchar *s)
{
if (order == 0x4949)
return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24;
else
return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3];
}
#define sget4(s) sget4((uchar *)s)
unsigned CLASS get4()
{
uchar str[4] = {0xff, 0xff, 0xff, 0xff};
fread(str, 1, 4, ifp);
return sget4(str);
}
unsigned CLASS getint(int type) { return type == 3 ? get2() : get4(); }
float CLASS int_to_float(int i)
{
union {
int i;
float f;
} u;
u.i = i;
return u.f;
}
double CLASS getreal(int type)
{
union {
char c[8];
double d;
} u, v;
int i, rev;
switch (type)
{
case 3:
return (unsigned short)get2();
case 4:
return (unsigned int)get4();
case 5:
u.d = (unsigned int)get4();
v.d = (unsigned int)get4();
return u.d / (v.d ? v.d : 1);
case 8:
return (signed short)get2();
case 9:
return (signed int)get4();
case 10:
u.d = (signed int)get4();
v.d = (signed int)get4();
return u.d / (v.d ? v.d : 1);
case 11:
return int_to_float(get4());
case 12:
rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234));
for (i = 0; i < 8; i++)
u.c[i ^ rev] = fgetc(ifp);
return u.d;
default:
return fgetc(ifp);
}
}
void CLASS read_shorts(ushort *pixel, int count)
{
if (fread(pixel, 2, count, ifp) < count)
derror();
if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
swab((char *)pixel, (char *)pixel, count * 2);
}
void CLASS cubic_spline(const int *x_, const int *y_, const int len)
{
float **A, *b, *c, *d, *x, *y;
int i, j;
A = (float **)calloc(((2 * len + 4) * sizeof **A + sizeof *A), 2 * len);
if (!A)
return;
A[0] = (float *)(A + 2 * len);
for (i = 1; i < 2 * len; i++)
A[i] = A[0] + 2 * len * i;
y = len + (x = i + (d = i + (c = i + (b = A[0] + i * i))));
for (i = 0; i < len; i++)
{
x[i] = x_[i] / 65535.0;
y[i] = y_[i] / 65535.0;
}
for (i = len - 1; i > 0; i--)
{
b[i] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]);
d[i - 1] = x[i] - x[i - 1];
}
for (i = 1; i < len - 1; i++)
{
A[i][i] = 2 * (d[i - 1] + d[i]);
if (i > 1)
{
A[i][i - 1] = d[i - 1];
A[i - 1][i] = d[i - 1];
}
A[i][len - 1] = 6 * (b[i + 1] - b[i]);
}
for (i = 1; i < len - 2; i++)
{
float v = A[i + 1][i] / A[i][i];
for (j = 1; j <= len - 1; j++)
A[i + 1][j] -= v * A[i][j];
}
for (i = len - 2; i > 0; i--)
{
float acc = 0;
for (j = i; j <= len - 2; j++)
acc += A[i][j] * c[j];
c[i] = (A[i][len - 1] - acc) / A[i][i];
}
for (i = 0; i < 0x10000; i++)
{
float x_out = (float)(i / 65535.0);
float y_out = 0;
for (j = 0; j < len - 1; j++)
{
if (x[j] <= x_out && x_out <= x[j + 1])
{
float v = x_out - x[j];
y_out = y[j] + ((y[j + 1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j + 1] * d[j]) / 6) * v + (c[j] * 0.5) * v * v +
((c[j + 1] - c[j]) / (6 * d[j])) * v * v * v;
}
}
curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5));
}
free(A);
}
void CLASS canon_600_fixed_wb(int temp)
{
static const short mul[4][5] = {
{667, 358, 397, 565, 452}, {731, 390, 367, 499, 517}, {1119, 396, 348, 448, 537}, {1399, 485, 431, 508, 688}};
int lo, hi, i;
float frac = 0;
for (lo = 4; --lo;)
if (*mul[lo] <= temp)
break;
for (hi = 0; hi < 3; hi++)
if (*mul[hi] >= temp)
break;
if (lo != hi)
frac = (float)(temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
for (i = 1; i < 5; i++)
pre_mul[i - 1] = 1 / (frac * mul[hi][i] + (1 - frac) * mul[lo][i]);
}
/* Return values: 0 = white 1 = near white 2 = not white */
int CLASS canon_600_color(int ratio[2], int mar)
{
int clipped = 0, target, miss;
if (flash_used)
{
if (ratio[1] < -104)
{
ratio[1] = -104;
clipped = 1;
}
if (ratio[1] > 12)
{
ratio[1] = 12;
clipped = 1;
}
}
else
{
if (ratio[1] < -264 || ratio[1] > 461)
return 2;
if (ratio[1] < -50)
{
ratio[1] = -50;
clipped = 1;
}
if (ratio[1] > 307)
{
ratio[1] = 307;
clipped = 1;
}
}
target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10);
if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped)
return 0;
miss = target - ratio[0];
if (abs(miss) >= mar * 4)
return 2;
if (miss < -20)
miss = -20;
if (miss > mar)
miss = mar;
ratio[0] = target - miss;
return 1;
}
void CLASS canon_600_auto_wb()
{
int mar, row, col, i, j, st, count[] = {0, 0};
int test[8], total[2][8], ratio[2][2], stat[2];
memset(&total, 0, sizeof total);
i = canon_ev + 0.5;
if (i < 10)
mar = 150;
else if (i > 12)
mar = 20;
else
mar = 280 - 20 * i;
if (flash_used)
mar = 80;
for (row = 14; row < height - 14; row += 4)
for (col = 10; col < width; col += 2)
{
for (i = 0; i < 8; i++)
test[(i & 4) + FC(row + (i >> 1), col + (i & 1))] = BAYER(row + (i >> 1), col + (i & 1));
for (i = 0; i < 8; i++)
if (test[i] < 150 || test[i] > 1500)
goto next;
for (i = 0; i < 4; i++)
if (abs(test[i] - test[i + 4]) > 50)
goto next;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 4; j += 2)
ratio[i][j >> 1] = ((test[i * 4 + j + 1] - test[i * 4 + j]) << 10) / test[i * 4 + j];
stat[i] = canon_600_color(ratio[i], mar);
}
if ((st = stat[0] | stat[1]) > 1)
goto next;
for (i = 0; i < 2; i++)
if (stat[i])
for (j = 0; j < 2; j++)
test[i * 4 + j * 2 + 1] = test[i * 4 + j * 2] * (0x400 + ratio[i][j]) >> 10;
for (i = 0; i < 8; i++)
total[st][i] += test[i];
count[st]++;
next:;
}
if (count[0] | count[1])
{
st = count[0] * 200 < count[1];
for (i = 0; i < 4; i++)
pre_mul[i] = 1.0 / (total[st][i] + total[st][i + 4]);
}
}
void CLASS canon_600_coeff()
{
static const short table[6][12] = {{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105},
{-1203, 1715, -1136, 1648, 1388, -876, 267, 245, -1641, 2153, 3921, -3409},
{-615, 1127, -1563, 2075, 1437, -925, 509, 3, -756, 1268, 2519, -2007},
{-190, 702, -1886, 2398, 2153, -1641, 763, -251, -452, 964, 3040, -2528},
{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105},
{-807, 1319, -1785, 2297, 1388, -876, 769, -257, -230, 742, 2067, -1555}};
int t = 0, i, c;
float mc, yc;
mc = pre_mul[1] / pre_mul[2];
yc = pre_mul[3] / pre_mul[2];
if (mc > 1 && mc <= 1.28 && yc < 0.8789)
t = 1;
if (mc > 1.28 && mc <= 2)
{
if (yc < 0.8789)
t = 3;
else if (yc <= 2)
t = 4;
}
if (flash_used)
t = 5;
for (raw_color = i = 0; i < 3; i++)
FORCC rgb_cam[i][c] = table[t][i * 4 + c] / 1024.0;
}
void CLASS canon_600_load_raw()
{
uchar data[1120], *dp;
ushort *pix;
int irow, row;
for (irow = row = 0; irow < height; irow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(data, 1, 1120, ifp) < 1120)
derror();
pix = raw_image + row * raw_width;
for (dp = data; dp < data + 1120; dp += 10, pix += 8)
{
pix[0] = (dp[0] << 2) + (dp[1] >> 6);
pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
pix[3] = (dp[4] << 2) + (dp[1] & 3);
pix[4] = (dp[5] << 2) + (dp[9] & 3);
pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
pix[7] = (dp[8] << 2) + (dp[9] >> 6);
}
if ((row += 2) > height)
row = 1;
}
}
void CLASS canon_600_correct()
{
int row, col, val;
static const short mul[4][2] = {{1141, 1145}, {1128, 1109}, {1178, 1149}, {1128, 1109}};
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col++)
{
if ((val = BAYER(row, col) - black) < 0)
val = 0;
val = val * mul[row & 3][col & 1] >> 9;
BAYER(row, col) = val;
}
}
canon_600_fixed_wb(1311);
canon_600_auto_wb();
canon_600_coeff();
maximum = (0x3ff - black) * 1109 >> 9;
black = 0;
}
int CLASS canon_s2is()
{
unsigned row;
for (row = 0; row < 100; row++)
{
fseek(ifp, row * 3340 + 3284, SEEK_SET);
if (getc(ifp) > 15)
return 1;
}
return 0;
}
unsigned CLASS getbithuff(int nbits, ushort *huff)
{
#ifdef LIBRAW_NOTHREADS
static unsigned bitbuf = 0;
static int vbits = 0, reset = 0;
#else
#define bitbuf tls->getbits.bitbuf
#define vbits tls->getbits.vbits
#define reset tls->getbits.reset
#endif
unsigned c;
if (nbits > 25)
return 0;
if (nbits < 0)
return bitbuf = vbits = reset = 0;
if (nbits == 0 || vbits < 0)
return 0;
while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp)))
{
bitbuf = (bitbuf << 8) + (uchar)c;
vbits += 8;
}
c = bitbuf << (32 - vbits) >> (32 - nbits);
if (huff)
{
vbits -= huff[c] >> 8;
c = (uchar)huff[c];
}
else
vbits -= nbits;
if (vbits < 0)
derror();
return c;
#ifndef LIBRAW_NOTHREADS
#undef bitbuf
#undef vbits
#undef reset
#endif
}
#define getbits(n) getbithuff(n, 0)
#define gethuff(h) getbithuff(*h, h + 1)
/*
Construct a decode tree according the specification in *source.
The first 16 bytes specify how many codes should be 1-bit, 2-bit
3-bit, etc. Bytes after that are the leaf values.
For example, if the source is
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
then the code is
00 0x04
010 0x03
011 0x05
100 0x06
101 0x02
1100 0x07
1101 0x01
11100 0x08
11101 0x09
11110 0x00
111110 0x0a
1111110 0x0b
1111111 0xff
*/
ushort *CLASS make_decoder_ref(const uchar **source)
{
int max, len, h, i, j;
const uchar *count;
ushort *huff;
count = (*source += 16) - 17;
for (max = 16; max && !count[max]; max--)
;
huff = (ushort *)calloc(1 + (1 << max), sizeof *huff);
merror(huff, "make_decoder()");
huff[0] = max;
for (h = len = 1; len <= max; len++)
for (i = 0; i < count[len]; i++, ++*source)
for (j = 0; j < 1 << (max - len); j++)
if (h <= 1 << max)
huff[h++] = len << 8 | **source;
return huff;
}
ushort *CLASS make_decoder(const uchar *source) { return make_decoder_ref(&source); }
void CLASS crw_init_tables(unsigned table, ushort *huff[2])
{
static const uchar first_tree[3][29] = {
{0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0x04, 0x03, 0x05, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x00, 0x0a, 0x0b, 0xff},
{0, 2, 2, 3, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0,
0, 0x03, 0x02, 0x04, 0x01, 0x05, 0x00, 0x06, 0x07, 0x09, 0x08, 0x0a, 0x0b, 0xff},
{0, 0, 6, 3, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0x06, 0x05, 0x07, 0x04, 0x08, 0x03, 0x09, 0x02, 0x00, 0x0a, 0x01, 0x0b, 0xff},
};
static const uchar second_tree[3][180] = {
{0, 2, 2, 2, 1, 4, 2, 1, 2, 5, 1, 1, 0, 0, 0, 139, 0x03, 0x04,
0x02, 0x05, 0x01, 0x06, 0x07, 0x08, 0x12, 0x13, 0x11, 0x14, 0x09, 0x15, 0x22, 0x00, 0x21, 0x16, 0x0a, 0xf0,
0x23, 0x17, 0x24, 0x31, 0x32, 0x18, 0x19, 0x33, 0x25, 0x41, 0x34, 0x42, 0x35, 0x51, 0x36, 0x37, 0x38, 0x29,
0x79, 0x26, 0x1a, 0x39, 0x56, 0x57, 0x28, 0x27, 0x52, 0x55, 0x58, 0x43, 0x76, 0x59, 0x77, 0x54, 0x61, 0xf9,
0x71, 0x78, 0x75, 0x96, 0x97, 0x49, 0xb7, 0x53, 0xd7, 0x74, 0xb6, 0x98, 0x47, 0x48, 0x95, 0x69, 0x99, 0x91,
0xfa, 0xb8, 0x68, 0xb5, 0xb9, 0xd6, 0xf7, 0xd8, 0x67, 0x46, 0x45, 0x94, 0x89, 0xf8, 0x81, 0xd5, 0xf6, 0xb4,
0x88, 0xb1, 0x2a, 0x44, 0x72, 0xd9, 0x87, 0x66, 0xd4, 0xf5, 0x3a, 0xa7, 0x73, 0xa9, 0xa8, 0x86, 0x62, 0xc7,
0x65, 0xc8, 0xc9, 0xa1, 0xf4, 0xd1, 0xe9, 0x5a, 0x92, 0x85, 0xa6, 0xe7, 0x93, 0xe8, 0xc1, 0xc6, 0x7a, 0x64,
0xe1, 0x4a, 0x6a, 0xe6, 0xb3, 0xf1, 0xd3, 0xa5, 0x8a, 0xb2, 0x9a, 0xba, 0x84, 0xa4, 0x63, 0xe5, 0xc5, 0xf3,
0xd2, 0xc4, 0x82, 0xaa, 0xda, 0xe4, 0xf2, 0xca, 0x83, 0xa3, 0xa2, 0xc3, 0xea, 0xc2, 0xe2, 0xe3, 0xff, 0xff},
{0, 2, 2, 1, 4, 1, 4, 1, 3, 3, 1, 0, 0, 0, 0, 140, 0x02, 0x03,
0x01, 0x04, 0x05, 0x12, 0x11, 0x06, 0x13, 0x07, 0x08, 0x14, 0x22, 0x09, 0x21, 0x00, 0x23, 0x15, 0x31, 0x32,
0x0a, 0x16, 0xf0, 0x24, 0x33, 0x41, 0x42, 0x19, 0x17, 0x25, 0x18, 0x51, 0x34, 0x43, 0x52, 0x29, 0x35, 0x61,
0x39, 0x71, 0x62, 0x36, 0x53, 0x26, 0x38, 0x1a, 0x37, 0x81, 0x27, 0x91, 0x79, 0x55, 0x45, 0x28, 0x72, 0x59,
0xa1, 0xb1, 0x44, 0x69, 0x54, 0x58, 0xd1, 0xfa, 0x57, 0xe1, 0xf1, 0xb9, 0x49, 0x47, 0x63, 0x6a, 0xf9, 0x56,
0x46, 0xa8, 0x2a, 0x4a, 0x78, 0x99, 0x3a, 0x75, 0x74, 0x86, 0x65, 0xc1, 0x76, 0xb6, 0x96, 0xd6, 0x89, 0x85,
0xc9, 0xf5, 0x95, 0xb4, 0xc7, 0xf7, 0x8a, 0x97, 0xb8, 0x73, 0xb7, 0xd8, 0xd9, 0x87, 0xa7, 0x7a, 0x48, 0x82,
0x84, 0xea, 0xf4, 0xa6, 0xc5, 0x5a, 0x94, 0xa4, 0xc6, 0x92, 0xc3, 0x68, 0xb5, 0xc8, 0xe4, 0xe5, 0xe6, 0xe9,
0xa2, 0xa3, 0xe3, 0xc2, 0x66, 0x67, 0x93, 0xaa, 0xd4, 0xd5, 0xe7, 0xf8, 0x88, 0x9a, 0xd7, 0x77, 0xc4, 0x64,
0xe2, 0x98, 0xa5, 0xca, 0xda, 0xe8, 0xf3, 0xf6, 0xa9, 0xb2, 0xb3, 0xf2, 0xd2, 0x83, 0xba, 0xd3, 0xff, 0xff},
{0, 0, 6, 2, 1, 3, 3, 2, 5, 1, 2, 2, 8, 10, 0, 117, 0x04, 0x05,
0x03, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x12, 0x13, 0x14, 0x11, 0x15, 0x0a, 0x16, 0x17, 0xf0, 0x00, 0x22,
0x21, 0x18, 0x23, 0x19, 0x24, 0x32, 0x31, 0x25, 0x33, 0x38, 0x37, 0x34, 0x35, 0x36, 0x39, 0x79, 0x57, 0x58,
0x59, 0x28, 0x56, 0x78, 0x27, 0x41, 0x29, 0x77, 0x26, 0x42, 0x76, 0x99, 0x1a, 0x55, 0x98, 0x97, 0xf9, 0x48,
0x54, 0x96, 0x89, 0x47, 0xb7, 0x49, 0xfa, 0x75, 0x68, 0xb6, 0x67, 0x69, 0xb9, 0xb8, 0xd8, 0x52, 0xd7, 0x88,
0xb5, 0x74, 0x51, 0x46, 0xd9, 0xf8, 0x3a, 0xd6, 0x87, 0x45, 0x7a, 0x95, 0xd5, 0xf6, 0x86, 0xb4, 0xa9, 0x94,
0x53, 0x2a, 0xa8, 0x43, 0xf5, 0xf7, 0xd4, 0x66, 0xa7, 0x5a, 0x44, 0x8a, 0xc9, 0xe8, 0xc8, 0xe7, 0x9a, 0x6a,
0x73, 0x4a, 0x61, 0xc7, 0xf4, 0xc6, 0x65, 0xe9, 0x72, 0xe6, 0x71, 0x91, 0x93, 0xa6, 0xda, 0x92, 0x85, 0x62,
0xf3, 0xc5, 0xb2, 0xa4, 0x84, 0xba, 0x64, 0xa5, 0xb3, 0xd2, 0x81, 0xe5, 0xd3, 0xaa, 0xc4, 0xca, 0xf2, 0xb1,
0xe4, 0xd1, 0x83, 0x63, 0xea, 0xc3, 0xe2, 0x82, 0xf1, 0xa3, 0xc2, 0xa1, 0xc1, 0xe3, 0xa2, 0xe1, 0xff, 0xff}};
if (table > 2)
table = 2;
huff[0] = make_decoder(first_tree[table]);
huff[1] = make_decoder(second_tree[table]);
}
/*
Return 0 if the image starts with compressed data,
1 if it starts with uncompressed low-order bits.
In Canon compressed data, 0xff is always followed by 0x00.
*/
int CLASS canon_has_lowbits()
{
uchar test[0x4000];
int ret = 1, i;
fseek(ifp, 0, SEEK_SET);
fread(test, 1, sizeof test, ifp);
for (i = 540; i < sizeof test - 1; i++)
if (test[i] == 0xff)
{
if (test[i + 1])
return 1;
ret = 0;
}
return ret;
}
void CLASS canon_load_raw()
{
ushort *pixel, *prow, *huff[2];
int nblocks, lowbits, i, c, row, r, save, val;
int block, diffbuf[64], leaf, len, diff, carry = 0, pnum = 0, base[2];
crw_init_tables(tiff_compress, huff);
lowbits = canon_has_lowbits();
if (!lowbits)
maximum = 0x3ff;
fseek(ifp, 540 + lowbits * raw_height * raw_width / 4, SEEK_SET);
zero_after_ff = 1;
getbits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row += 8)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pixel = raw_image + row * raw_width;
nblocks = MIN(8, raw_height - row) * raw_width >> 6;
for (block = 0; block < nblocks; block++)
{
memset(diffbuf, 0, sizeof diffbuf);
for (i = 0; i < 64; i++)
{
leaf = gethuff(huff[i > 0]);
if (leaf == 0 && i)
break;
if (leaf == 0xff)
continue;
i += leaf >> 4;
len = leaf & 15;
if (len == 0)
continue;
diff = getbits(len);
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
if (i < 64)
diffbuf[i] = diff;
}
diffbuf[0] += carry;
carry = diffbuf[0];
for (i = 0; i < 64; i++)
{
if (pnum++ % raw_width == 0)
base[0] = base[1] = 512;
if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10)
derror();
}
}
if (lowbits)
{
save = ftell(ifp);
fseek(ifp, 26 + row * raw_width / 4, SEEK_SET);
for (prow = pixel, i = 0; i < raw_width * 2; i++)
{
c = fgetc(ifp);
for (r = 0; r < 8; r += 2, prow++)
{
val = (*prow << 2) + ((c >> r) & 3);
if (raw_width == 2672 && val < 512)
val += 2;
*prow = val;
}
}
fseek(ifp, save, SEEK_SET);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
FORC(2) free(huff[c]);
throw;
}
#endif
FORC(2) free(huff[c]);
}
//@end COMMON
struct jhead
{
int algo, bits, high, wide, clrs, sraw, psv, restart, vpred[6];
ushort quant[64], idct[64], *huff[20], *free[20], *row;
};
//@out COMMON
int CLASS ljpeg_start(struct jhead *jh, int info_only)
{
ushort c, tag, len;
int cnt = 0;
uchar data[0x10000];
const uchar *dp;
memset(jh, 0, sizeof *jh);
jh->restart = INT_MAX;
if ((fgetc(ifp), fgetc(ifp)) != 0xd8)
return 0;
do
{
if (feof(ifp))
return 0;
if (cnt++ > 1024)
return 0; // 1024 tags limit
if (!fread(data, 2, 2, ifp))
return 0;
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
if (tag <= 0xff00)
return 0;
fread(data, 1, len, ifp);
switch (tag)
{
case 0xffc3: // start of frame; lossless, Huffman
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
case 0xffc1:
case 0xffc0:
jh->algo = tag & 0xff;
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (len == 9 && !dng_version)
getc(ifp);
break;
case 0xffc4: // define Huffman tables
if (info_only)
break;
for (dp = data; dp < data + len && !((c = *dp++) & -20);)
jh->free[c] = jh->huff[c] = make_decoder_ref(&dp);
break;
case 0xffda: // start of scan
jh->psv = data[1 + data[0] * 2];
jh->bits -= data[3 + data[0] * 2] & 15;
break;
case 0xffdb:
FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2];
break;
case 0xffdd:
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs)
return 0;
if (info_only)
return 1;
if (!jh->huff[0])
return 0;
FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c];
if (jh->sraw)
{
FORC(4) jh->huff[2 + c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0];
}
jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4);
merror(jh->row, "ljpeg_start()");
return zero_after_ff = 1;
}
void CLASS ljpeg_end(struct jhead *jh)
{
int c;
FORC4 if (jh->free[c]) free(jh->free[c]);
free(jh->row);
}
int CLASS ljpeg_diff(ushort *huff)
{
int len, diff;
if (!huff)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
len = gethuff(huff);
if (len == 16 && (!dng_version || dng_version >= 0x1010000))
return -32768;
diff = getbits(len);
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
return diff;
}
ushort *CLASS ljpeg_row(int jrow, struct jhead *jh)
{
int col, c, diff, pred, spred = 0;
ushort mark = 0, *row[3];
if (jrow * jh->wide % jh->restart == 0)
{
FORC(6) jh->vpred[c] = 1 << (jh->bits - 1);
if (jrow)
{
fseek(ifp, -2, SEEK_CUR);
do
mark = (mark << 8) + (c = fgetc(ifp));
while (c != EOF && mark >> 4 != 0xffd);
}
getbits(-1);
}
FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1);
for (col = 0; col < jh->wide; col++)
FORC(jh->clrs)
{
diff = ljpeg_diff(jh->huff[c]);
if (jh->sraw && c <= jh->sraw && (col | c))
pred = spred;
else if (col)
pred = row[0][-jh->clrs];
else
pred = (jh->vpred[c] += diff) - diff;
if (jrow && col)
switch (jh->psv)
{
case 1:
break;
case 2:
pred = row[1][0];
break;
case 3:
pred = row[1][-jh->clrs];
break;
case 4:
pred = pred + row[1][0] - row[1][-jh->clrs];
break;
case 5:
pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1);
break;
case 6:
pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1);
break;
case 7:
pred = (pred + row[1][0]) >> 1;
break;
default:
pred = 0;
}
if ((**row = pred + diff) >> jh->bits)
derror();
if (c <= jh->sraw)
spred = **row;
row[0]++;
row[1]++;
}
return row[2];
}
void CLASS lossless_jpeg_load_raw()
{
int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0;
struct jhead jh;
ushort *rp;
if (!ljpeg_start(&jh, 0))
return;
if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
jwide = jh.wide * jh.clrs;
jhigh = jh.high;
if (jh.clrs == 4 && jwide >= raw_width * 2)
jhigh *= 2;
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
if (load_flags & 1)
row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2;
for (jcol = 0; jcol < jwide; jcol++)
{
val = curve[*rp++];
if (cr2_slice[0])
{
jidx = jrow * jwide + jcol;
i = jidx / (cr2_slice[1] * raw_height);
if ((j = i >= cr2_slice[0]))
i = cr2_slice[0];
jidx -= i * (cr2_slice[1] * raw_height);
row = jidx / cr2_slice[1 + j];
col = jidx % cr2_slice[1 + j] + i * cr2_slice[1];
}
if (raw_width == 3984 && (col -= 2) < 0)
col += (row--, raw_width);
if (row > raw_height)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 3);
#endif
if ((unsigned)row < raw_height)
RAW(row, col) = val;
if (++col >= raw_width)
col = (row++, 0);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
ljpeg_end(&jh);
}
void CLASS canon_sraw_load_raw()
{
struct jhead jh;
short *rp = 0, (*ip)[4];
int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c;
int v[3] = {0, 0, 0}, ver, hue;
#ifdef LIBRAW_LIBRARY_BUILD
int saved_w = width, saved_h = height;
#endif
char *cp;
if (!ljpeg_start(&jh, 0) || jh.clrs < 4)
return;
jwide = (jh.wide >>= 1) * jh.clrs;
#ifdef LIBRAW_LIBRARY_BUILD
if (load_flags & 256)
{
width = raw_width;
height = raw_height;
}
try
{
#endif
for (ecol = slice = 0; slice <= cr2_slice[0]; slice++)
{
scol = ecol;
ecol += cr2_slice[1] * 2 / jh.clrs;
if (!cr2_slice[0] || ecol > raw_width - 1)
ecol = raw_width & -2;
for (row = 0; row < height; row += (jh.clrs >> 1) - 1)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
ip = (short(*)[4])image + row * width;
for (col = scol; col < ecol; col += 2, jcol += jh.clrs)
{
if ((jcol %= jwide) == 0)
rp = (short *)ljpeg_row(jrow++, &jh);
if (col >= width)
continue;
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
FORC(jh.clrs - 2)
{
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192;
}
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else
#endif
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 16384;
ip[col][2] = rp[jcol + jh.clrs - 1] - 16384;
}
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
ljpeg_end(&jh);
maximum = 0x3fff;
height = saved_h;
width = saved_w;
return;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (cp = model2; *cp && !isdigit(*cp); cp++)
;
sscanf(cp, "%d.%d.%d", v, v + 1, v + 2);
ver = (v[0] * 1000 + v[1]) * 1000 + v[2];
hue = (jh.sraw + 1) << 2;
if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006))
hue = jh.sraw << 1;
ip = (short(*)[4])image;
rp = ip[0];
for (row = 0; row < height; row++, ip += width)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (row & (jh.sraw >> 1))
{
for (col = 0; col < width; col += 2)
for (c = 1; c < 3; c++)
if (row == height - 1)
{
ip[col][c] = ip[col - width][c];
}
else
{
ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1;
}
}
for (col = 1; col < width; col += 2)
for (c = 1; c < 3; c++)
if (col == width - 1)
ip[col][c] = ip[col - 1][c];
else
ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB))
#endif
for (; rp < ip[0]; rp += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 ||
unique_id == 0x80000287)
{
rp[1] = (rp[1] << 2) + hue;
rp[2] = (rp[2] << 2) + hue;
pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14);
pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14);
pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14);
}
else
{
if (unique_id < 0x80000218)
rp[0] -= 512;
pix[0] = rp[0] + rp[2];
pix[2] = rp[0] + rp[1];
pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12);
}
FORC3 rp[c] = CLIP15(pix[c] * sraw_mul[c] >> 10);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
height = saved_h;
width = saved_w;
#endif
ljpeg_end(&jh);
maximum = 0x3fff;
}
void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp)
{
int c;
if (tiff_samples == 2 && shot_select)
(*rp)++;
if (raw_image)
{
if (row < raw_height && col < raw_width)
RAW(row, col) = curve[**rp];
*rp += tiff_samples;
}
else
{
#ifdef LIBRAW_LIBRARY_BUILD
if (row < raw_height && col < raw_width)
FORC(tiff_samples)
image[row * raw_width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#else
if (row < height && col < width)
FORC(tiff_samples)
image[row * width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#endif
}
if (tiff_samples == 2 && shot_select)
(*rp)--;
}
void CLASS ljpeg_idct(struct jhead *jh)
{
int c, i, j, len, skip, coef;
float work[3][8][8];
static float cs[106] = {0};
static const uchar zigzag[80] = {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, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63};
if (!cs[0])
FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2;
memset(work, 0, sizeof work);
work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0];
for (i = 1; i < 64; i++)
{
len = gethuff(jh->huff[16]);
i += skip = len >> 4;
if (!(len &= 15) && skip < 15)
break;
coef = getbits(len);
if ((coef & (1 << (len - 1))) == 0)
coef -= (1 << len) - 1;
((float *)work)[zigzag[i]] = coef * jh->quant[i];
}
FORC(8) work[0][0][c] *= M_SQRT1_2;
FORC(8) work[0][c][0] *= M_SQRT1_2;
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c];
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c];
FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5);
}
void CLASS lossless_dng_load_raw()
{
unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j;
struct jhead jh;
ushort *rp;
while (trow < raw_height)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
save = ftell(ifp);
if (tile_length < INT_MAX)
fseek(ifp, get4(), SEEK_SET);
if (!ljpeg_start(&jh, 0))
break;
jwide = jh.wide;
if (filters)
jwide *= jh.clrs;
jwide /= MIN(is_raw, tiff_samples);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
switch (jh.algo)
{
case 0xc1:
jh.vpred[0] = 16384;
getbits(-1);
for (jrow = 0; jrow + 7 < jh.high; jrow += 8)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (jcol = 0; jcol + 7 < jh.wide; jcol += 8)
{
ljpeg_idct(&jh);
rp = jh.idct;
row = trow + jcol / tile_width + jrow * 2;
col = tcol + jcol % tile_width;
for (i = 0; i < 16; i += 2)
for (j = 0; j < 8; j++)
adobe_copy_pixel(row + i, col + j, &rp);
}
}
break;
case 0xc3:
for (row = col = jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
for (jcol = 0; jcol < jwide; jcol++)
{
adobe_copy_pixel(trow + row, tcol + col, &rp);
if (++col >= tile_width || col >= raw_width)
row += 1 + (col = 0);
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
fseek(ifp, save + 4, SEEK_SET);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
ljpeg_end(&jh);
}
}
void CLASS packed_dng_load_raw()
{
ushort *pixel, *rp;
int row, col;
pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel);
merror(pixel, "packed_dng_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (tiff_bps == 16)
read_shorts(pixel, raw_width * tiff_samples);
else
{
getbits(-1);
for (col = 0; col < raw_width * tiff_samples; col++)
pixel[col] = getbits(tiff_bps);
}
for (rp = pixel, col = 0; col < raw_width; col++)
adobe_copy_pixel(row, col, &rp);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
}
void CLASS pentax_load_raw()
{
ushort bit[2][15], huff[4097];
int dep, row, col, diff, c, i;
ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2];
fseek(ifp, meta_offset, SEEK_SET);
dep = (get2() + 12) & 15;
fseek(ifp, 12, SEEK_CUR);
FORC(dep) bit[0][c] = get2();
FORC(dep) bit[1][c] = fgetc(ifp);
FORC(dep)
for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);)
huff[++i] = bit[1][c] << 8 | c;
huff[0] = 12;
fseek(ifp, data_offset, SEEK_SET);
getbits(-1);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
diff = ljpeg_diff(huff);
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
RAW(row, col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps)
derror();
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS nikon_coolscan_load_raw()
{
int bufsize = width * 3 * tiff_bps / 8;
if (tiff_bps <= 8)
gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255);
else
gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 65535);
fseek(ifp, data_offset, SEEK_SET);
unsigned char *buf = (unsigned char *)malloc(bufsize);
unsigned short *ubuf = (unsigned short *)buf;
for (int row = 0; row < raw_height; row++)
{
int red = fread(buf, 1, bufsize, ifp);
unsigned short(*ip)[4] = (unsigned short(*)[4])image + row * width;
if (tiff_bps <= 8)
for (int col = 0; col < width; col++)
{
ip[col][0] = curve[buf[col * 3]];
ip[col][1] = curve[buf[col * 3 + 1]];
ip[col][2] = curve[buf[col * 3 + 2]];
ip[col][3] = 0;
}
else
for (int col = 0; col < width; col++)
{
ip[col][0] = curve[ubuf[col * 3]];
ip[col][1] = curve[ubuf[col * 3 + 1]];
ip[col][2] = curve[ubuf[col * 3 + 2]];
ip[col][3] = 0;
}
}
free(buf);
}
#endif
void CLASS nikon_load_raw()
{
static const uchar nikon_tree[][32] = {
{0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy */
5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12},
{0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy after split */
0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12},
{0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 12-bit lossless */
5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12},
{0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 14-bit lossy */
5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14},
{0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, /* 14-bit lossy after split */
8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14},
{0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, /* 14-bit lossless */
7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}};
ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize;
int i, min, max, step = 0, tree = 0, split = 0, row, col, len, shl, diff;
fseek(ifp, meta_offset, SEEK_SET);
ver0 = fgetc(ifp);
ver1 = fgetc(ifp);
if (ver0 == 0x49 || ver1 == 0x58)
fseek(ifp, 2110, SEEK_CUR);
if (ver0 == 0x46)
tree = 2;
if (tiff_bps == 14)
tree += 3;
read_shorts(vpred[0], 4);
max = 1 << tiff_bps & 0x7fff;
if ((csize = get2()) > 1)
step = max / (csize - 1);
if (ver0 == 0x44 && ver1 == 0x20 && step > 0)
{
for (i = 0; i < csize; i++)
curve[i * step] = get2();
for (i = 0; i < max; i++)
curve[i] = (curve[i - i % step] * (step - i % step) + curve[i - i % step + step] * (i % step)) / step;
fseek(ifp, meta_offset + 562, SEEK_SET);
split = get2();
}
else if (ver0 != 0x46 && csize <= 0x4001)
read_shorts(curve, max = csize);
while (curve[max - 2] == curve[max - 1])
max--;
huff = make_decoder(nikon_tree[tree]);
fseek(ifp, data_offset, SEEK_SET);
getbits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (min = row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (split && row == split)
{
free(huff);
huff = make_decoder(nikon_tree[tree + 1]);
max += (min = 16) << 1;
}
for (col = 0; col < raw_width; col++)
{
i = gethuff(huff);
len = i & 15;
shl = i >> 4;
diff = ((getbits(len - shl) << 1) + 1) << shl >> 1;
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - !shl;
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
if ((ushort)(hpred[col & 1] + min) >= max)
derror();
RAW(row, col) = curve[LIM((short)hpred[col & 1], 0, 0x3fff)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(huff);
throw;
}
#endif
free(huff);
}
void CLASS nikon_yuv_load_raw()
{
int row, col, yuv[4], rgb[3], b, c;
UINT64 bitbuf = 0;
float cmul[4];
FORC4 { cmul[c] = cam_mul[c] > 0.001f ? cam_mul[c] : 1.f; }
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
if (!(b = col & 1))
{
bitbuf = 0;
FORC(6) bitbuf |= (UINT64)fgetc(ifp) << c * 8;
FORC(4) yuv[c] = (bitbuf >> c * 12 & 0xfff) - (c >> 1 << 11);
}
rgb[0] = yuv[b] + 1.370705 * yuv[3];
rgb[1] = yuv[b] - 0.337633 * yuv[2] - 0.698001 * yuv[3];
rgb[2] = yuv[b] + 1.732446 * yuv[2];
FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 0xfff)] / cmul[c];
}
}
}
/*
Returns 1 for a Coolpix 995, 0 for anything else.
*/
int CLASS nikon_e995()
{
int i, histo[256];
const uchar often[] = {0x00, 0x55, 0xaa, 0xff};
memset(histo, 0, sizeof histo);
fseek(ifp, -2000, SEEK_END);
for (i = 0; i < 2000; i++)
histo[fgetc(ifp)]++;
for (i = 0; i < 4; i++)
if (histo[often[i]] < 200)
return 0;
return 1;
}
/*
Returns 1 for a Coolpix 2100, 0 for anything else.
*/
int CLASS nikon_e2100()
{
uchar t[12];
int i;
fseek(ifp, 0, SEEK_SET);
for (i = 0; i < 1024; i++)
{
fread(t, 1, 12, ifp);
if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3)
return 0;
}
return 1;
}
void CLASS nikon_3700()
{
int bits, i;
uchar dp[24];
static const struct
{
int bits;
char t_make[12], t_model[15];
} table[] = {
{0x00, "Pentax", "Optio 33WR"}, {0x03, "Nikon", "E3200"}, {0x32, "Nikon", "E3700"}, {0x33, "Olympus", "C740UZ"}};
fseek(ifp, 3072, SEEK_SET);
fread(dp, 1, 24, ifp);
bits = (dp[8] & 3) << 4 | (dp[20] & 3);
for (i = 0; i < sizeof table / sizeof *table; i++)
if (bits == table[i].bits)
{
strcpy(make, table[i].t_make);
strcpy(model, table[i].t_model);
}
}
/*
Separates a Minolta DiMAGE Z2 from a Nikon E4300.
*/
int CLASS minolta_z2()
{
int i, nz;
char tail[424];
fseek(ifp, -sizeof tail, SEEK_END);
fread(tail, 1, sizeof tail, ifp);
for (nz = i = 0; i < sizeof tail; i++)
if (tail[i])
nz++;
return nz > 20;
}
//@end COMMON
void CLASS jpeg_thumb();
//@out COMMON
void CLASS ppm_thumb()
{
char *thumb;
thumb_length = thumb_width * thumb_height * 3;
thumb = (char *)malloc(thumb_length);
merror(thumb, "ppm_thumb()");
fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
fread(thumb, 1, thumb_length, ifp);
fwrite(thumb, 1, thumb_length, ofp);
free(thumb);
}
void CLASS ppm16_thumb()
{
int i;
char *thumb;
thumb_length = thumb_width * thumb_height * 3;
thumb = (char *)calloc(thumb_length, 2);
merror(thumb, "ppm16_thumb()");
read_shorts((ushort *)thumb, thumb_length);
for (i = 0; i < thumb_length; i++)
thumb[i] = ((ushort *)thumb)[i] >> 8;
fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
fwrite(thumb, 1, thumb_length, ofp);
free(thumb);
}
void CLASS layer_thumb()
{
int i, c;
char *thumb, map[][4] = {"012", "102"};
colors = thumb_misc >> 5 & 7;
thumb_length = thumb_width * thumb_height;
thumb = (char *)calloc(colors, thumb_length);
merror(thumb, "layer_thumb()");
fprintf(ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height);
fread(thumb, thumb_length, colors, ifp);
for (i = 0; i < thumb_length; i++)
FORCC putc(thumb[i + thumb_length * (map[thumb_misc >> 8][c] - '0')], ofp);
free(thumb);
}
void CLASS rollei_thumb()
{
unsigned i;
ushort *thumb;
thumb_length = thumb_width * thumb_height;
thumb = (ushort *)calloc(thumb_length, 2);
merror(thumb, "rollei_thumb()");
fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
read_shorts(thumb, thumb_length);
for (i = 0; i < thumb_length; i++)
{
putc(thumb[i] << 3, ofp);
putc(thumb[i] >> 5 << 2, ofp);
putc(thumb[i] >> 11 << 3, ofp);
}
free(thumb);
}
void CLASS rollei_load_raw()
{
uchar pixel[10];
unsigned iten = 0, isix, i, buffer = 0, todo[16];
isix = raw_width * raw_height * 5 / 8;
while (fread(pixel, 1, 10, ifp) == 10)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (i = 0; i < 10; i += 2)
{
todo[i] = iten++;
todo[i + 1] = pixel[i] << 8 | pixel[i + 1];
buffer = pixel[i] >> 2 | buffer << 6;
}
for (; i < 16; i += 2)
{
todo[i] = isix++;
todo[i + 1] = buffer >> (14 - i) * 5;
}
for (i = 0; i < 16; i += 2)
raw_image[todo[i]] = (todo[i + 1] & 0x3ff);
}
maximum = 0x3ff;
}
int CLASS raw(unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row, col) : 0; }
void CLASS phase_one_flat_field(int is_float, int nc)
{
ushort head[8];
unsigned wide, high, y, x, c, rend, cend, row, col;
float *mrow, num, mult[4];
read_shorts(head, 8);
if (head[2] * head[3] * head[4] * head[5] == 0)
return;
wide = head[2] / head[4] + (head[2] % head[4] != 0);
high = head[3] / head[5] + (head[3] % head[5] != 0);
mrow = (float *)calloc(nc * wide, sizeof *mrow);
merror(mrow, "phase_one_flat_field()");
for (y = 0; y < high; y++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (x = 0; x < wide; x++)
for (c = 0; c < nc; c += 2)
{
num = is_float ? getreal(11) : get2() / 32768.0;
if (y == 0)
mrow[c * wide + x] = num;
else
mrow[(c + 1) * wide + x] = (num - mrow[c * wide + x]) / head[5];
}
if (y == 0)
continue;
rend = head[1] + y * head[5];
for (row = rend - head[5]; row < raw_height && row < rend && row < head[1] + head[3] - head[5]; row++)
{
for (x = 1; x < wide; x++)
{
for (c = 0; c < nc; c += 2)
{
mult[c] = mrow[c * wide + x - 1];
mult[c + 1] = (mrow[c * wide + x] - mult[c]) / head[4];
}
cend = head[0] + x * head[4];
for (col = cend - head[4]; col < raw_width && col < cend && col < head[0] + head[2] - head[4]; col++)
{
c = nc > 2 ? FC(row - top_margin, col - left_margin) : 0;
if (!(c & 1))
{
c = RAW(row, col) * mult[c];
RAW(row, col) = LIM(c, 0, 65535);
}
for (c = 0; c < nc; c += 2)
mult[c] += mult[c + 1];
}
}
for (x = 0; x < wide; x++)
for (c = 0; c < nc; c += 2)
mrow[c * wide + x] += mrow[(c + 1) * wide + x];
}
}
free(mrow);
}
int CLASS phase_one_correct()
{
unsigned entries, tag, data, save, col, row, type;
int len, i, j, k, cip, val[4], dev[4], sum, max;
int head[9], diff, mindiff = INT_MAX, off_412 = 0;
/* static */ const signed char dir[12][2] = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}, {-2, 0}, {0, -2},
{0, 2}, {2, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}};
float poly[8], num, cfrac, frac, mult[2], *yval[2] = {NULL, NULL};
ushort *xval[2];
int qmult_applied = 0, qlin_applied = 0;
#ifdef LIBRAW_LIBRARY_BUILD
if (!meta_length)
#else
if (half_size || !meta_length)
#endif
return 0;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Phase One correction...\n"));
#endif
fseek(ifp, meta_offset, SEEK_SET);
order = get2();
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, meta_offset + get4(), SEEK_SET);
entries = get4();
get4();
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
while (entries--)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, meta_offset + data, SEEK_SET);
if (tag == 0x419)
{ /* Polynomial curve */
for (get4(), i = 0; i < 8; i++)
poly[i] = getreal(11);
poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1;
for (i = 0; i < 0x10000; i++)
{
num = (poly[5] * i + poly[3]) * i + poly[1];
curve[i] = LIM(num, 0, 65535);
}
goto apply; /* apply to right half */
}
else if (tag == 0x41a)
{ /* Polynomial curve */
for (i = 0; i < 4; i++)
poly[i] = getreal(11);
for (i = 0; i < 0x10000; i++)
{
for (num = 0, j = 4; j--;)
num = num * i + poly[j];
curve[i] = LIM(num + i, 0, 65535);
}
apply: /* apply to whole image */
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (tag & 1) * ph1.split_col; col < raw_width; col++)
RAW(row, col) = curve[RAW(row, col)];
}
}
else if (tag == 0x400)
{ /* Sensor defects */
while ((len -= 8) >= 0)
{
col = get2();
row = get2();
type = get2();
get2();
if (col >= raw_width)
continue;
if (type == 131 || type == 137) /* Bad column */
for (row = 0; row < raw_height; row++)
if (FC(row - top_margin, col - left_margin) == 1)
{
for (sum = i = 0; i < 4; i++)
sum += val[i] = raw(row + dir[i][0], col + dir[i][1]);
for (max = i = 0; i < 4; i++)
{
dev[i] = abs((val[i] << 2) - sum);
if (dev[max] < dev[i])
max = i;
}
RAW(row, col) = (sum - val[max]) / 3.0 + 0.5;
}
else
{
for (sum = 0, i = 8; i < 12; i++)
sum += raw(row + dir[i][0], col + dir[i][1]);
RAW(row, col) = 0.5 + sum * 0.0732233 + (raw(row, col - 2) + raw(row, col + 2)) * 0.3535534;
}
else if (type == 129)
{ /* Bad pixel */
if (row >= raw_height)
continue;
j = (FC(row - top_margin, col - left_margin) != 1) * 4;
for (sum = 0, i = j; i < j + 8; i++)
sum += raw(row + dir[i][0], col + dir[i][1]);
RAW(row, col) = (sum + 4) >> 3;
}
}
}
else if (tag == 0x401)
{ /* All-color flat fields */
phase_one_flat_field(1, 2);
}
else if (tag == 0x416 || tag == 0x410)
{
phase_one_flat_field(0, 2);
}
else if (tag == 0x40b)
{ /* Red+blue flat field */
phase_one_flat_field(0, 4);
}
else if (tag == 0x412)
{
fseek(ifp, 36, SEEK_CUR);
diff = abs(get2() - ph1.tag_21a);
if (mindiff > diff)
{
mindiff = diff;
off_412 = ftell(ifp) - 38;
}
}
else if (tag == 0x41f && !qlin_applied)
{ /* Quadrant linearization */
ushort lc[2][2][16], ref[16];
int qr, qc;
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
for (i = 0; i < 16; i++)
lc[qr][qc][i] = get4();
for (i = 0; i < 16; i++)
{
int v = 0;
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
v += lc[qr][qc][i];
ref[i] = (v + 2) >> 2;
}
for (qr = 0; qr < 2; qr++)
{
for (qc = 0; qc < 2; qc++)
{
int cx[19], cf[19];
for (i = 0; i < 16; i++)
{
cx[1 + i] = lc[qr][qc][i];
cf[1 + i] = ref[i];
}
cx[0] = cf[0] = 0;
cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15];
cf[18] = cx[18] = 65535;
cubic_spline(cx, cf, 19);
for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++)
RAW(row, col) = curve[RAW(row, col)];
}
}
}
qlin_applied = 1;
}
else if (tag == 0x41e && !qmult_applied)
{ /* Quadrant multipliers */
float qmult[2][2] = {{1, 1}, {1, 1}};
get4();
get4();
get4();
get4();
qmult[0][0] = 1.0 + getreal(11);
get4();
get4();
get4();
get4();
get4();
qmult[0][1] = 1.0 + getreal(11);
get4();
get4();
get4();
qmult[1][0] = 1.0 + getreal(11);
get4();
get4();
get4();
qmult[1][1] = 1.0 + getreal(11);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row, col);
RAW(row, col) = LIM(i, 0, 65535);
}
}
qmult_applied = 1;
}
else if (tag == 0x431 && !qmult_applied)
{ /* Quadrant combined */
ushort lc[2][2][7], ref[7];
int qr, qc;
for (i = 0; i < 7; i++)
ref[i] = get4();
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
for (i = 0; i < 7; i++)
lc[qr][qc][i] = get4();
for (qr = 0; qr < 2; qr++)
{
for (qc = 0; qc < 2; qc++)
{
int cx[9], cf[9];
for (i = 0; i < 7; i++)
{
cx[1 + i] = ref[i];
cf[1 + i] = ((unsigned)ref[i] * lc[qr][qc][i]) / 10000;
}
cx[0] = cf[0] = 0;
cx[8] = cf[8] = 65535;
cubic_spline(cx, cf, 9);
for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++)
RAW(row, col) = curve[RAW(row, col)];
}
}
}
qmult_applied = 1;
qlin_applied = 1;
}
fseek(ifp, save, SEEK_SET);
}
if (off_412)
{
fseek(ifp, off_412, SEEK_SET);
for (i = 0; i < 9; i++)
head[i] = get4() & 0x7fff;
yval[0] = (float *)calloc(head[1] * head[3] + head[2] * head[4], 6);
merror(yval[0], "phase_one_correct()");
yval[1] = (float *)(yval[0] + head[1] * head[3]);
xval[0] = (ushort *)(yval[1] + head[2] * head[4]);
xval[1] = (ushort *)(xval[0] + head[1] * head[3]);
get2();
for (i = 0; i < 2; i++)
for (j = 0; j < head[i + 1] * head[i + 3]; j++)
yval[i][j] = getreal(11);
for (i = 0; i < 2; i++)
for (j = 0; j < head[i + 1] * head[i + 3]; j++)
xval[i][j] = get2();
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
cfrac = (float)col * head[3] / raw_width;
cfrac -= cip = cfrac;
num = RAW(row, col) * 0.5;
for (i = cip; i < cip + 2; i++)
{
for (k = j = 0; j < head[1]; j++)
if (num < xval[0][k = head[1] * i + j])
break;
frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k - 1]);
mult[i - cip] = yval[0][k - 1] * frac + yval[0][k] * (1 - frac);
}
i = ((mult[0] * (1 - cfrac) + mult[1] * cfrac) * row + num) * 2;
RAW(row, col) = LIM(i, 0, 65535);
}
}
free(yval[0]);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
if (yval[0])
free(yval[0]);
return LIBRAW_CANCELLED_BY_CALLBACK;
}
#endif
return 0;
}
void CLASS phase_one_load_raw()
{
int a, b, i;
ushort akey, bkey, t_mask;
fseek(ifp, ph1.key_off, SEEK_SET);
akey = get2();
bkey = get2();
t_mask = ph1.format == 1 ? 0x5555 : 0x1354;
#ifdef LIBRAW_LIBRARY_BUILD
if (ph1.black_col || ph1.black_row)
{
imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort));
merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw()");
imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort));
merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw()");
if (ph1.black_col)
{
fseek(ifp, ph1.black_col, SEEK_SET);
read_shorts((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height * 2);
}
if (ph1.black_row)
{
fseek(ifp, ph1.black_row, SEEK_SET);
read_shorts((ushort *)imgdata.rawdata.ph1_rblack[0], raw_width * 2);
}
}
#endif
fseek(ifp, data_offset, SEEK_SET);
read_shorts(raw_image, raw_width * raw_height);
if (ph1.format)
for (i = 0; i < raw_width * raw_height; i += 2)
{
a = raw_image[i + 0] ^ akey;
b = raw_image[i + 1] ^ bkey;
raw_image[i + 0] = (a & t_mask) | (b & ~t_mask);
raw_image[i + 1] = (b & t_mask) | (a & ~t_mask);
}
}
unsigned CLASS ph1_bithuff(int nbits, ushort *huff)
{
#ifndef LIBRAW_NOTHREADS
#define bitbuf tls->ph1_bits.bitbuf
#define vbits tls->ph1_bits.vbits
#else
static UINT64 bitbuf = 0;
static int vbits = 0;
#endif
unsigned c;
if (nbits == -1)
return bitbuf = vbits = 0;
if (nbits == 0)
return 0;
if (vbits < nbits)
{
bitbuf = bitbuf << 32 | get4();
vbits += 32;
}
c = bitbuf << (64 - vbits) >> (64 - nbits);
if (huff)
{
vbits -= huff[c] >> 8;
return (uchar)huff[c];
}
vbits -= nbits;
return c;
#ifndef LIBRAW_NOTHREADS
#undef bitbuf
#undef vbits
#endif
}
#define ph1_bits(n) ph1_bithuff(n, 0)
#define ph1_huff(h) ph1_bithuff(*h, h + 1)
void CLASS phase_one_load_raw_c()
{
static const int length[] = {8, 7, 6, 9, 11, 10, 5, 12, 14, 13};
int *offset, len[2], pred[2], row, col, i, j;
ushort *pixel;
short(*c_black)[2], (*r_black)[2];
#ifdef LIBRAW_LIBRARY_BUILD
if (ph1.format == 6)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
pixel = (ushort *)calloc(raw_width * 3 + raw_height * 4, 2);
merror(pixel, "phase_one_load_raw_c()");
offset = (int *)(pixel + raw_width);
fseek(ifp, strip_offset, SEEK_SET);
for (row = 0; row < raw_height; row++)
offset[row] = get4();
c_black = (short(*)[2])(offset + raw_height);
fseek(ifp, ph1.black_col, SEEK_SET);
if (ph1.black_col)
read_shorts((ushort *)c_black[0], raw_height * 2);
r_black = c_black + raw_height;
fseek(ifp, ph1.black_row, SEEK_SET);
if (ph1.black_row)
read_shorts((ushort *)r_black[0], raw_width * 2);
#ifdef LIBRAW_LIBRARY_BUILD
// Copy data to internal copy (ever if not read)
if (ph1.black_col || ph1.black_row)
{
imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort));
merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw_c()");
memmove(imgdata.rawdata.ph1_cblack, (ushort *)c_black[0], raw_height * 2 * sizeof(ushort));
imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort));
merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw_c()");
memmove(imgdata.rawdata.ph1_rblack, (ushort *)r_black[0], raw_width * 2 * sizeof(ushort));
}
#endif
for (i = 0; i < 256; i++)
curve[i] = i * i / 3.969 + 0.5;
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek(ifp, data_offset + offset[row], SEEK_SET);
ph1_bits(-1);
pred[0] = pred[1] = 0;
for (col = 0; col < raw_width; col++)
{
if (col >= (raw_width & -8))
len[0] = len[1] = 14;
else if ((col & 7) == 0)
for (i = 0; i < 2; i++)
{
for (j = 0; j < 5 && !ph1_bits(1); j++)
;
if (j--)
len[i] = length[j * 2 + ph1_bits(1)];
}
if ((i = len[col & 1]) == 14)
pixel[col] = pred[col & 1] = ph1_bits(16);
else
pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1));
if (pred[col & 1] >> 16)
derror();
if (ph1.format == 5 && pixel[col] < 256)
pixel[col] = curve[pixel[col]];
}
#ifndef LIBRAW_LIBRARY_BUILD
for (col = 0; col < raw_width; col++)
{
int shift = ph1.format == 8 ? 0 : 2;
i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] +
r_black[col][row >= ph1.split_row];
if (i > 0)
RAW(row, col) = i;
}
#else
if (ph1.format == 8)
memmove(&RAW(row, 0), &pixel[0], raw_width * 2);
else
for (col = 0; col < raw_width; col++)
RAW(row, col) = pixel[col] << 2;
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = 0xfffc - ph1.t_black;
}
void CLASS hasselblad_load_raw()
{
struct jhead jh;
int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c;
unsigned upix, urow, ucol;
ushort *ip;
if (!ljpeg_start(&jh, 0))
return;
order = 0x4949;
ph1_bits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
back[4] = (int *)calloc(raw_width, 3 * sizeof **back);
merror(back[4], "hasselblad_load_raw()");
FORC3 back[c] = back[4] + c * raw_width;
cblack[6] >>= sh = tiff_samples > 1;
shot = LIM(shot_select, 1, tiff_samples) - 1;
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC4 back[(c + 3) & 3] = back[c];
for (col = 0; col < raw_width; col += 2)
{
for (s = 0; s < tiff_samples * 2; s += 2)
{
FORC(2) len[c] = ph1_huff(jh.huff[0]);
FORC(2)
{
diff[s + c] = ph1_bits(len[c]);
if ((diff[s + c] & (1 << (len[c] - 1))) == 0)
diff[s + c] -= (1 << len[c]) - 1;
if (diff[s + c] == 65535)
diff[s + c] = -32768;
}
}
for (s = col; s < col + 2; s++)
{
pred = 0x8000 + load_flags;
if (col)
pred = back[2][s - 2];
if (col && row > 1)
switch (jh.psv)
{
case 11:
pred += back[0][s] / 2 - back[0][s - 2] / 2;
break;
}
f = (row & 1) * 3 ^ ((col + s) & 1);
FORC(tiff_samples)
{
pred += diff[(s & 1) * tiff_samples + c];
upix = pred >> sh & 0xffff;
if (raw_image && c == shot)
RAW(row, s) = upix;
if (image)
{
urow = row - top_margin + (c & 1);
ucol = col - left_margin - ((c >> 1) & 1);
ip = &image[urow * width + ucol][f];
if (urow < height && ucol < width)
*ip = c < 4 ? upix : (*ip + upix) >> 1;
}
}
back[2][s] = pred;
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(back[4]);
ljpeg_end(&jh);
throw;
}
#endif
free(back[4]);
ljpeg_end(&jh);
if (image)
mix_green = 1;
}
void CLASS leaf_hdr_load_raw()
{
ushort *pixel = 0;
unsigned tile = 0, r, c, row, col;
if (!filters || !raw_image)
{
pixel = (ushort *)calloc(raw_width, sizeof *pixel);
merror(pixel, "leaf_hdr_load_raw()");
}
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
FORC(tiff_samples)
for (r = 0; r < raw_height; r++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (r % tile_length == 0)
{
fseek(ifp, data_offset + 4 * tile++, SEEK_SET);
fseek(ifp, get4(), SEEK_SET);
}
if (filters && c != shot_select)
continue;
if (filters && raw_image)
pixel = raw_image + r * raw_width;
read_shorts(pixel, raw_width);
if (!filters && image && (row = r - top_margin) < height)
for (col = 0; col < width; col++)
image[row * width + col][c] = pixel[col + left_margin];
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
if (!filters)
free(pixel);
throw;
}
#endif
if (!filters)
{
maximum = 0xffff;
raw_color = 1;
free(pixel);
}
}
void CLASS unpacked_load_raw()
{
int row, col, bits = 0;
while (1 << ++bits < maximum)
;
read_shorts(raw_image, raw_width * raw_height);
if (maximum < 0xffff || load_flags)
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height &&
(unsigned)(col - left_margin) < width)
derror();
}
}
void CLASS unpacked_load_raw_reversed()
{
int row, col, bits = 0;
while (1 << ++bits < maximum)
;
for (row = raw_height - 1; row >= 0; row--)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
read_shorts(&raw_image[row * raw_width], raw_width);
for (col = 0; col < raw_width; col++)
if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height &&
(unsigned)(col - left_margin) < width)
derror();
}
}
void CLASS sinar_4shot_load_raw()
{
ushort *pixel;
unsigned shot, row, col, r, c;
if (raw_image)
{
shot = LIM(shot_select, 1, 4) - 1;
fseek(ifp, data_offset + shot * 4, SEEK_SET);
fseek(ifp, get4(), SEEK_SET);
unpacked_load_raw();
return;
}
pixel = (ushort *)calloc(raw_width, sizeof *pixel);
merror(pixel, "sinar_4shot_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (shot = 0; shot < 4; shot++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek(ifp, data_offset + shot * 4, SEEK_SET);
fseek(ifp, get4(), SEEK_SET);
for (row = 0; row < raw_height; row++)
{
read_shorts(pixel, raw_width);
if ((r = row - top_margin - (shot >> 1 & 1)) >= height)
continue;
for (col = 0; col < raw_width; col++)
{
if ((c = col - left_margin - (shot & 1)) >= width)
continue;
image[r * width + c][(row & 1) * 3 ^ (~col & 1)] = pixel[col];
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
mix_green = 1;
}
void CLASS imacon_full_load_raw()
{
int row, col;
if (!image)
return;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned short *buf = (unsigned short *)malloc(width * 3 * sizeof(unsigned short));
merror(buf, "imacon_full_load_raw");
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
read_shorts(buf, width * 3);
unsigned short(*rowp)[4] = &image[row * width];
for (col = 0; col < width; col++)
{
rowp[col][0] = buf[col * 3];
rowp[col][1] = buf[col * 3 + 1];
rowp[col][2] = buf[col * 3 + 2];
rowp[col][3] = 0;
}
#else
for (col = 0; col < width; col++)
read_shorts(image[row * width + col], 3);
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
free(buf);
#endif
}
void CLASS packed_load_raw()
{
int vbits = 0, bwide, rbits, bite, half, irow, row, col, val, i;
UINT64 bitbuf = 0;
bwide = raw_width * tiff_bps / 8;
bwide += bwide & load_flags >> 7;
rbits = bwide * 8 - raw_width * tiff_bps;
if (load_flags & 1)
bwide = bwide * 16 / 15;
bite = 8 + (load_flags & 24);
half = (raw_height + 1) >> 1;
for (irow = 0; irow < raw_height; irow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
row = irow;
if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4)
{
if (vbits = 0, tiff_compress)
fseek(ifp, data_offset - (-half * bwide & -2048), SEEK_SET);
else
{
fseek(ifp, 0, SEEK_END);
fseek(ifp, ftell(ifp) >> 3 << 2, SEEK_SET);
}
}
for (col = 0; col < raw_width; col++)
{
for (vbits -= tiff_bps; vbits < 0; vbits += bite)
{
bitbuf <<= bite;
for (i = 0; i < bite; i += 8)
bitbuf |= (unsigned)(fgetc(ifp) << i);
}
val = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps);
RAW(row, col ^ (load_flags >> 6 & 1)) = val;
if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height + top_margin && col < width + left_margin)
derror();
}
vbits -= rbits;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
ushort raw_stride;
void CLASS parse_broadcom()
{
/* This structure is at offset 0xb0 from the 'BRCM' ident. */
struct
{
uint8_t umode[32];
uint16_t uwidth;
uint16_t uheight;
uint16_t padding_right;
uint16_t padding_down;
uint32_t unknown_block[6];
uint16_t transform;
uint16_t format;
uint8_t bayer_order;
uint8_t bayer_format;
} header;
header.bayer_order = 0;
fseek(ifp, 0xb0 - 0x20, SEEK_CUR);
fread(&header, 1, sizeof(header), ifp);
raw_stride = ((((((header.uwidth + header.padding_right) * 5) + 3) >> 2) + 0x1f) & (~0x1f));
raw_width = width = header.uwidth;
raw_height = height = header.uheight;
filters = 0x16161616; /* default Bayer order is 2, BGGR */
switch (header.bayer_order)
{
case 0: /* RGGB */
filters = 0x94949494;
break;
case 1: /* GBRG */
filters = 0x49494949;
break;
case 3: /* GRBG */
filters = 0x61616161;
break;
}
}
void CLASS broadcom_load_raw()
{
uchar *data, *dp;
int rev, row, col, c;
rev = 3 * (order == 0x4949);
data = (uchar *)malloc(raw_stride * 2);
merror(data, "broadcom_load_raw()");
for (row = 0; row < raw_height; row++)
{
if (fread(data + raw_stride, 1, raw_stride, ifp) < raw_stride)
derror();
FORC(raw_stride) data[c] = data[raw_stride + (c ^ rev)];
for (dp = data, col = 0; col < raw_width; dp += 5, col += 4)
FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
}
free(data);
}
#endif
void CLASS nokia_load_raw()
{
uchar *data, *dp;
int rev, dwide, row, col, c;
double sum[] = {0, 0};
rev = 3 * (order == 0x4949);
dwide = (raw_width * 5 + 1) / 4;
data = (uchar *)malloc(dwide * 2);
merror(data, "nokia_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(data + dwide, 1, dwide, ifp) < dwide)
derror();
FORC(dwide) data[c] = data[dwide + (c ^ rev)];
for (dp = data, col = 0; col < raw_width; dp += 5, col += 4)
FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(data);
throw;
}
#endif
free(data);
maximum = 0x3ff;
if (strncmp(make, "OmniVision", 10))
return;
row = raw_height / 2;
FORC(width - 1)
{
sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1));
sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1));
}
if (sum[1] > sum[0])
filters = 0x4b4b4b4b;
}
void CLASS android_tight_load_raw()
{
uchar *data, *dp;
int bwide, row, col, c;
bwide = -(-5 * raw_width >> 5) << 3;
data = (uchar *)malloc(bwide);
merror(data, "android_tight_load_raw()");
for (row = 0; row < raw_height; row++)
{
if (fread(data, 1, bwide, ifp) < bwide)
derror();
for (dp = data, col = 0; col < raw_width; dp += 5, col += 4)
FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
}
free(data);
}
void CLASS android_loose_load_raw()
{
uchar *data, *dp;
int bwide, row, col, c;
UINT64 bitbuf = 0;
bwide = (raw_width + 5) / 6 << 3;
data = (uchar *)malloc(bwide);
merror(data, "android_loose_load_raw()");
for (row = 0; row < raw_height; row++)
{
if (fread(data, 1, bwide, ifp) < bwide)
derror();
for (dp = data, col = 0; col < raw_width; dp += 8, col += 6)
{
FORC(8) bitbuf = (bitbuf << 8) | dp[c ^ 7];
FORC(6) RAW(row, col + c) = (bitbuf >> c * 10) & 0x3ff;
}
}
free(data);
}
void CLASS canon_rmf_load_raw()
{
int row, col, bits, orow, ocol, c;
#ifdef LIBRAW_LIBRARY_BUILD
int *words = (int *)malloc(sizeof(int) * (raw_width / 3 + 1));
merror(words, "canon_rmf_load_raw");
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
fread(words, sizeof(int), raw_width / 3, ifp);
for (col = 0; col < raw_width - 2; col += 3)
{
bits = words[col / 3];
FORC3
{
orow = row;
if ((ocol = col + c - 4) < 0)
{
ocol += raw_width;
if ((orow -= 2) < 0)
orow += raw_height;
}
RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff];
}
}
#else
for (col = 0; col < raw_width - 2; col += 3)
{
bits = get4();
FORC3
{
orow = row;
if ((ocol = col + c - 4) < 0)
{
ocol += raw_width;
if ((orow -= 2) < 0)
orow += raw_height;
}
RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff];
}
}
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
free(words);
#endif
maximum = curve[0x3ff];
}
unsigned CLASS pana_bits(int nbits)
{
#ifndef LIBRAW_NOTHREADS
#define buf tls->pana_bits.buf
#define vbits tls->pana_bits.vbits
#else
static uchar buf[0x4000];
static int vbits;
#endif
int byte;
if (!nbits)
return vbits = 0;
if (!vbits)
{
fread(buf + load_flags, 1, 0x4000 - load_flags, ifp);
fread(buf, 1, load_flags, ifp);
}
vbits = (vbits - nbits) & 0x1ffff;
byte = vbits >> 3 ^ 0x3ff0;
return (buf[byte] | buf[byte + 1] << 8) >> (vbits & 7) & ~((~0u) << nbits);
#ifndef LIBRAW_NOTHREADS
#undef buf
#undef vbits
#endif
}
void CLASS panasonic_load_raw()
{
int row, col, i, j, sh = 0, pred[2], nonz[2];
pana_bits(0);
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
if ((i = col % 14) == 0)
pred[0] = pred[1] = nonz[0] = nonz[1] = 0;
if (i % 3 == 2)
sh = 4 >> (3 - pana_bits(2));
if (nonz[i & 1])
{
if ((j = pana_bits(8)))
{
if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4)
pred[i & 1] &= ~((~0u) << sh);
pred[i & 1] += j << sh;
}
}
else if ((nonz[i & 1] = pana_bits(8)) || i > 11)
pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4);
if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width)
derror();
}
}
}
void CLASS panasonic_16x10_load_raw()
{
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_DECODE_RAW;
#endif
}
void CLASS olympus_load_raw()
{
ushort huff[4096];
int row, col, nbits, sign, low, high, i, c, w, n, nw;
int acarry[2][3], *carry, pred, diff;
huff[n = 0] = 0xc0c;
for (i = 12; i--;)
FORC(2048 >> i) huff[++n] = (i + 1) << 8 | i;
fseek(ifp, 7, SEEK_CUR);
getbits(-1);
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
memset(acarry, 0, sizeof acarry);
for (col = 0; col < raw_width; col++)
{
carry = acarry[col & 1];
i = 2 * (carry[2] < 3);
for (nbits = 2 + i; (ushort)carry[0] >> (nbits + i); nbits++)
;
low = (sign = getbits(3)) & 3;
sign = sign << 29 >> 31;
if ((high = getbithuff(12, huff)) == 12)
high = getbits(16 - nbits) >> 1;
carry[0] = (high << nbits) | getbits(nbits);
diff = (carry[0] ^ sign) + carry[1];
carry[1] = (diff * 3 + carry[1]) >> 5;
carry[2] = carry[0] > 16 ? 0 : carry[2] + 1;
if (col >= width)
continue;
if (row < 2 && col < 2)
pred = 0;
else if (row < 2)
pred = RAW(row, col - 2);
else if (col < 2)
pred = RAW(row - 2, col);
else
{
w = RAW(row, col - 2);
n = RAW(row - 2, col);
nw = RAW(row - 2, col - 2);
if ((w < nw && nw < n) || (n < nw && nw < w))
{
if (ABS(w - nw) > 32 || ABS(n - nw) > 32)
pred = w + n - nw;
else
pred = (w + n) >> 1;
}
else
pred = ABS(w - nw) > ABS(n - nw) ? w : n;
}
if ((RAW(row, col) = pred + ((diff << 2) | low)) >> 12)
derror();
}
}
}
void CLASS minolta_rd175_load_raw()
{
uchar pixel[768];
unsigned irow, box, row, col;
for (irow = 0; irow < 1481; irow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(pixel, 1, 768, ifp) < 768)
derror();
box = irow / 82;
row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box - 12) * 2);
switch (irow)
{
case 1477:
case 1479:
continue;
case 1476:
row = 984;
break;
case 1480:
row = 985;
break;
case 1478:
row = 985;
box = 1;
}
if ((box < 12) && (box & 1))
{
for (col = 0; col < 1533; col++, row ^= 1)
if (col != 1)
RAW(row, col) = (col + 1) & 2 ? pixel[col / 2 - 1] + pixel[col / 2 + 1] : pixel[col / 2] << 1;
RAW(row, 1) = pixel[1] << 1;
RAW(row, 1533) = pixel[765] << 1;
}
else
for (col = row & 1; col < 1534; col += 2)
RAW(row, col) = pixel[col / 2] << 1;
}
maximum = 0xff << 1;
}
void CLASS quicktake_100_load_raw()
{
uchar pixel[484][644];
static const short gstep[16] = {-89, -60, -44, -32, -22, -15, -8, -2, 2, 8, 15, 22, 32, 44, 60, 89};
static const short rstep[6][4] = {{-3, -1, 1, 3}, {-5, -1, 1, 5}, {-8, -2, 2, 8},
{-13, -3, 3, 13}, {-19, -4, 4, 19}, {-28, -6, 6, 28}};
static const short t_curve[256] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68,
69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 88, 90, 92, 94, 97, 99,
101, 103, 105, 107, 110, 112, 114, 116, 118, 120, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, 147,
149, 151, 153, 155, 158, 160, 162, 164, 166, 168, 171, 173, 175, 177, 179, 181, 184, 186, 188, 190, 192, 195,
197, 199, 201, 203, 205, 208, 210, 212, 214, 216, 218, 221, 223, 226, 230, 235, 239, 244, 248, 252, 257, 261,
265, 270, 274, 278, 283, 287, 291, 296, 300, 305, 309, 313, 318, 322, 326, 331, 335, 339, 344, 348, 352, 357,
361, 365, 370, 374, 379, 383, 387, 392, 396, 400, 405, 409, 413, 418, 422, 426, 431, 435, 440, 444, 448, 453,
457, 461, 466, 470, 474, 479, 483, 487, 492, 496, 500, 508, 519, 531, 542, 553, 564, 575, 587, 598, 609, 620,
631, 643, 654, 665, 676, 687, 698, 710, 721, 732, 743, 754, 766, 777, 788, 799, 810, 822, 833, 844, 855, 866,
878, 889, 900, 911, 922, 933, 945, 956, 967, 978, 989, 1001, 1012, 1023};
int rb, row, col, sharp, val = 0;
getbits(-1);
memset(pixel, 0x80, sizeof pixel);
for (row = 2; row < height + 2; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 2 + (row & 1); col < width + 2; col += 2)
{
val = ((pixel[row - 1][col - 1] + 2 * pixel[row - 1][col + 1] + pixel[row][col - 2]) >> 2) + gstep[getbits(4)];
pixel[row][col] = val = LIM(val, 0, 255);
if (col < 4)
pixel[row][col - 2] = pixel[row + 1][~row & 1] = val;
if (row == 2)
pixel[row - 1][col + 1] = pixel[row - 1][col + 3] = val;
}
pixel[row][col] = val;
}
for (rb = 0; rb < 2; rb++)
for (row = 2 + rb; row < height + 2; row += 2)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 3 - (row & 1); col < width + 2; col += 2)
{
if (row < 4 || col < 4)
sharp = 2;
else
{
val = ABS(pixel[row - 2][col] - pixel[row][col - 2]) + ABS(pixel[row - 2][col] - pixel[row - 2][col - 2]) +
ABS(pixel[row][col - 2] - pixel[row - 2][col - 2]);
sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5;
}
val = ((pixel[row - 2][col] + pixel[row][col - 2]) >> 1) + rstep[sharp][getbits(2)];
pixel[row][col] = val = LIM(val, 0, 255);
if (row < 4)
pixel[row - 2][col + 2] = val;
if (col < 4)
pixel[row + 2][col - 2] = val;
}
}
for (row = 2; row < height + 2; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 3 - (row & 1); col < width + 2; col += 2)
{
val = ((pixel[row][col - 1] + (pixel[row][col] << 2) + pixel[row][col + 1]) >> 1) - 0x100;
pixel[row][col] = LIM(val, 0, 255);
}
}
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col++)
RAW(row, col) = t_curve[pixel[row + 2][col + 2]];
}
maximum = 0x3ff;
}
#define radc_token(tree) ((signed char)getbithuff(8, huff[tree]))
#define FORYX \
for (y = 1; y < 3; y++) \
for (x = col + 1; x >= col; x--)
#define PREDICTOR \
(c ? (buf[c][y - 1][x] + buf[c][y][x + 1]) / 2 : (buf[c][y - 1][x + 1] + 2 * buf[c][y - 1][x] + buf[c][y][x + 1]) / 4)
#ifdef __GNUC__
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
#pragma GCC optimize("no-aggressive-loop-optimizations")
#endif
#endif
void CLASS kodak_radc_load_raw()
{
static const signed char src[] = {
1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6,
8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2,
4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3,
3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7,
5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5,
3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0,
2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2,
2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55,
6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37};
ushort huff[19][256];
int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
short last[3] = {16, 16, 16}, mul[3], buf[3][3][386];
static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383};
for (i = 2; i < 12; i += 2)
for (c = pt[i - 2]; c <= pt[i]; c++)
curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5;
for (s = i = 0; i < sizeof src; i += 2)
FORC(256 >> src[i])
((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1];
s = kodak_cbpp == 243 ? 2 : 3;
FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1);
getbits(-1);
for (i = 0; i < sizeof(buf) / sizeof(short); i++)
((short *)buf)[i] = 2048;
for (row = 0; row < height; row += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC3 mul[c] = getbits(6);
#ifdef LIBRAW_LIBRARY_BUILD
if(!mul[0] || !mul[1] || !mul[2])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
FORC3
{
val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c];
s = val > 65564 ? 10 : 12;
x = ~((~0u) << (s - 1));
val <<= 12 - s;
for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++)
((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s;
last[c] = mul[c];
for (r = 0; r <= !c; r++)
{
buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7;
for (tree = 1, col = width / 2; col > 0;)
{
if ((tree = radc_token(tree)))
{
col -= 2;
if (tree == 8)
FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c];
else
FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR;
}
else
do
{
nreps = (col > 2) ? radc_token(9) + 1 : 1;
for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++)
{
col -= 2;
FORYX buf[c][y][x] = PREDICTOR;
if (rep & 1)
{
step = radc_token(10) << 4;
FORYX buf[c][y][x] += step;
}
}
} while (nreps == 9);
}
for (y = 0; y < 2; y++)
for (x = 0; x < width / 2; x++)
{
val = (buf[c][y + 1][x] << 4) / mul[c];
if (val < 0)
val = 0;
if (c)
RAW(row + y * 2 + c - 1, x * 2 + 2 - c) = val;
else
RAW(row + r * 2 + y, x * 2 + y) = val;
}
memcpy(buf[c][0] + !c, buf[c][2], sizeof buf[c][0] - 2 * !c);
}
}
for (y = row; y < row + 4; y++)
for (x = 0; x < width; x++)
if ((x + y) & 1)
{
r = x ? x - 1 : x + 1;
s = x + 1 < width ? x + 1 : x - 1;
val = (RAW(y, x) - 2048) * 2 + (RAW(y, r) + RAW(y, s)) / 2;
if (val < 0)
val = 0;
RAW(y, x) = val;
}
}
for (i = 0; i < height * width; i++)
raw_image[i] = curve[raw_image[i]];
maximum = 0x3fff;
}
#undef FORYX
#undef PREDICTOR
#ifdef NO_JPEG
void CLASS kodak_jpeg_load_raw() {}
void CLASS lossy_dng_load_raw() {}
#else
#ifndef LIBRAW_LIBRARY_BUILD
METHODDEF(boolean)
fill_input_buffer(j_decompress_ptr cinfo)
{
static uchar jpeg_buffer[4096];
size_t nbytes;
nbytes = fread(jpeg_buffer, 1, 4096, ifp);
swab(jpeg_buffer, jpeg_buffer, nbytes);
cinfo->src->next_input_byte = jpeg_buffer;
cinfo->src->bytes_in_buffer = nbytes;
return TRUE;
}
void CLASS kodak_jpeg_load_raw()
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPARRAY buf;
JSAMPLE(*pixel)[3];
int row, col;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, ifp);
cinfo.src->fill_input_buffer = fill_input_buffer;
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3))
{
fprintf(stderr, _("%s: incorrect JPEG dimensions\n"), ifname);
jpeg_destroy_decompress(&cinfo);
longjmp(failure, 3);
}
buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, width * 3, 1);
while (cinfo.output_scanline < cinfo.output_height)
{
row = cinfo.output_scanline * 2;
jpeg_read_scanlines(&cinfo, buf, 1);
pixel = (JSAMPLE(*)[3])buf[0];
for (col = 0; col < width; col += 2)
{
RAW(row + 0, col + 0) = pixel[col + 0][1] << 1;
RAW(row + 1, col + 1) = pixel[col + 1][1] << 1;
RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0];
RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2];
}
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
maximum = 0xff << 1;
}
#else
struct jpegErrorManager
{
struct jpeg_error_mgr pub;
};
static void jpegErrorExit(j_common_ptr cinfo)
{
jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err;
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
// LibRaw's Kodak_jpeg_load_raw
void CLASS kodak_jpeg_load_raw()
{
if (data_size < 1)
throw LIBRAW_EXCEPTION_DECODE_JPEG;
int row, col;
jpegErrorManager jerr;
struct jpeg_decompress_struct cinfo;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = jpegErrorExit;
unsigned char *jpg_buf = (unsigned char *)malloc(data_size);
merror(jpg_buf, "kodak_jpeg_load_raw");
unsigned char *pixel_buf = (unsigned char *)malloc(width * 3);
jpeg_create_decompress(&cinfo);
merror(pixel_buf, "kodak_jpeg_load_raw");
fread(jpg_buf, data_size, 1, ifp);
swab((char *)jpg_buf, (char *)jpg_buf, data_size);
try
{
jpeg_mem_src(&cinfo, jpg_buf, data_size);
int rc = jpeg_read_header(&cinfo, TRUE);
if (rc != 1)
throw LIBRAW_EXCEPTION_DECODE_JPEG;
jpeg_start_decompress(&cinfo);
if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3))
{
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
unsigned char *buf[1];
buf[0] = pixel_buf;
while (cinfo.output_scanline < cinfo.output_height)
{
checkCancel();
row = cinfo.output_scanline * 2;
jpeg_read_scanlines(&cinfo, buf, 1);
unsigned char(*pixel)[3] = (unsigned char(*)[3])buf[0];
for (col = 0; col < width; col += 2)
{
RAW(row + 0, col + 0) = pixel[col + 0][1] << 1;
RAW(row + 1, col + 1) = pixel[col + 1][1] << 1;
RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0];
RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2];
}
}
}
catch (...)
{
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
free(jpg_buf);
free(pixel_buf);
throw;
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
free(jpg_buf);
free(pixel_buf);
maximum = 0xff << 1;
}
#endif
#ifndef LIBRAW_LIBRARY_BUILD
void CLASS gamma_curve(double pwr, double ts, int mode, int imax);
#endif
void CLASS lossy_dng_load_raw()
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPARRAY buf;
JSAMPLE(*pixel)[3];
unsigned sorder = order, ntags, opcode, deg, i, j, c;
unsigned save = data_offset - 4, trow = 0, tcol = 0, row, col;
ushort cur[3][256];
double coeff[9], tot;
if (meta_offset)
{
fseek(ifp, meta_offset, SEEK_SET);
order = 0x4d4d;
ntags = get4();
while (ntags--)
{
opcode = get4();
get4();
get4();
if (opcode != 8)
{
fseek(ifp, get4(), SEEK_CUR);
continue;
}
fseek(ifp, 20, SEEK_CUR);
if ((c = get4()) > 2)
break;
fseek(ifp, 12, SEEK_CUR);
if ((deg = get4()) > 8)
break;
for (i = 0; i <= deg && i < 9; i++)
coeff[i] = getreal(12);
for (i = 0; i < 256; i++)
{
for (tot = j = 0; j <= deg; j++)
tot += coeff[j] * pow(i / 255.0, (int)j);
cur[c][i] = tot * 0xffff;
}
}
order = sorder;
}
else
{
gamma_curve(1 / 2.4, 12.92, 1, 255);
FORC3 memcpy(cur[c], curve, sizeof cur[0]);
}
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
while (trow < raw_height)
{
fseek(ifp, save += 4, SEEK_SET);
if (tile_length < INT_MAX)
fseek(ifp, get4(), SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
if (libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1)
{
jpeg_destroy_decompress(&cinfo);
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
#else
jpeg_stdio_src(&cinfo, ifp);
#endif
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, cinfo.output_width * 3, 1);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
jpeg_read_scanlines(&cinfo, buf, 1);
pixel = (JSAMPLE(*)[3])buf[0];
for (col = 0; col < cinfo.output_width && tcol + col < width; col++)
{
FORC3 image[row * width + tcol + col][c] = cur[c][pixel[col][c]];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
jpeg_destroy_decompress(&cinfo);
throw;
}
#endif
jpeg_abort_decompress(&cinfo);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
}
jpeg_destroy_decompress(&cinfo);
maximum = 0xffff;
}
#endif
void CLASS kodak_dc120_load_raw()
{
static const int mul[4] = {162, 192, 187, 92};
static const int add[4] = {0, 636, 424, 212};
uchar pixel[848];
int row, shift, col;
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(pixel, 1, 848, ifp) < 848)
derror();
shift = row * mul[row & 3] + add[row & 3];
for (col = 0; col < width; col++)
RAW(row, col) = (ushort)pixel[(col + shift) % 848];
}
maximum = 0xff;
}
void CLASS eight_bit_load_raw()
{
uchar *pixel;
unsigned row, col;
pixel = (uchar *)calloc(raw_width, sizeof *pixel);
merror(pixel, "eight_bit_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(pixel, 1, raw_width, ifp) < raw_width)
derror();
for (col = 0; col < raw_width; col++)
RAW(row, col) = curve[pixel[col]];
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = curve[0xff];
}
void CLASS kodak_c330_load_raw()
{
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *)calloc(raw_width, 2 * sizeof *pixel);
merror(pixel, "kodak_c330_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(pixel, raw_width, 2, ifp) < 2)
derror();
if (load_flags && (row & 31) == 31)
fseek(ifp, raw_width * 32, SEEK_CUR);
for (col = 0; col < width; col++)
{
y = pixel[col * 2];
cb = pixel[(col * 2 & -4) | 1] - 128;
cr = pixel[(col * 2 & -4) | 3] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = curve[0xff];
}
void CLASS kodak_c603_load_raw()
{
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel);
merror(pixel, "kodak_c603_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (~row & 1)
if (fread(pixel, raw_width, 3, ifp) < 3)
derror();
for (col = 0; col < width; col++)
{
y = pixel[width * 2 * (row & 1) + col];
cb = pixel[width + (col & -2)] - 128;
cr = pixel[width + (col & -2) + 1] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = curve[0xff];
}
void CLASS kodak_262_load_raw()
{
static const uchar kodak_tree[2][26] = {
{0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
ushort *huff[2];
uchar *pixel;
int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val;
FORC(2) huff[c] = make_decoder(kodak_tree[c]);
ns = (raw_height + 63) >> 5;
pixel = (uchar *)malloc(raw_width * 32 + ns * 4);
merror(pixel, "kodak_262_load_raw()");
strip = (int *)(pixel + raw_width * 32);
order = 0x4d4d;
FORC(ns) strip[c] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if ((row & 31) == 0)
{
fseek(ifp, strip[row >> 5], SEEK_SET);
getbits(-1);
pi = 0;
}
for (col = 0; col < raw_width; col++)
{
chess = (row + col) & 1;
pi1 = chess ? pi - 2 : pi - raw_width - 1;
pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1;
if (col <= chess)
pi1 = -1;
if (pi1 < 0)
pi1 = pi2;
if (pi2 < 0)
pi2 = pi1;
if (pi1 < 0 && col > 1)
pi1 = pi2 = pi - 2;
pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
pixel[pi] = val = pred + ljpeg_diff(huff[chess]);
if (val >> 8)
derror();
val = curve[pixel[pi++]];
RAW(row, col) = val;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
FORC(2) free(huff[c]);
}
int CLASS kodak_65000_decode(short *out, int bsize)
{
uchar c, blen[768];
ushort raw[6];
INT64 bitbuf = 0;
int save, bits = 0, i, j, len, diff;
save = ftell(ifp);
bsize = (bsize + 3) & -4;
for (i = 0; i < bsize; i += 2)
{
c = fgetc(ifp);
if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12)
{
fseek(ifp, save, SEEK_SET);
for (i = 0; i < bsize; i += 8)
{
read_shorts(raw, 6);
out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
for (j = 0; j < 6; j++)
out[i + 2 + j] = raw[j] & 0xfff;
}
return 1;
}
}
if ((bsize & 7) == 4)
{
bitbuf = fgetc(ifp) << 8;
bitbuf += fgetc(ifp);
bits = 16;
}
for (i = 0; i < bsize; i++)
{
len = blen[i];
if (bits < len)
{
for (j = 0; j < 32; j += 8)
bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8));
bits += 32;
}
diff = bitbuf & (0xffff >> (16 - len));
bitbuf >>= len;
bits -= len;
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
out[i] = diff;
}
return 0;
}
void CLASS kodak_65000_load_raw()
{
short buf[272]; /* 264 looks enough */
int row, col, len, pred[2], ret, i;
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col += 256)
{
pred[0] = pred[1] = 0;
len = MIN(256, width - col);
ret = kodak_65000_decode(buf, len);
for (i = 0; i < len; i++)
{
int idx = ret ? buf[i] : (pred[i & 1] += buf[i]);
if(idx >=0 && idx < 0xffff)
{
if ((RAW(row, col + i) = curve[idx]) >> 12)
derror();
}
else
derror();
}
}
}
}
void CLASS kodak_ycbcr_load_raw()
{
short buf[384], *bp;
int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
ushort *ip;
if (!image)
return;
unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17) ? load_flags : 10;
for (row = 0; row < height; row += 2)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col += 128)
{
len = MIN(128, width - col);
kodak_65000_decode(buf, len * 3);
y[0][1] = y[1][1] = cb = cr = 0;
for (bp = buf, i = 0; i < len; i += 2, bp += 2)
{
cb += bp[4];
cr += bp[5];
rgb[1] = -((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
for (j = 0; j < 2; j++)
for (k = 0; k < 2; k++)
{
if ((y[j][k] = y[j][k ^ 1] + *bp++) >> bits)
derror();
ip = image[(row + j) * width + col + i + k];
FORC3 ip[c] = curve[LIM(y[j][k] + rgb[c], 0, 0xfff)];
}
}
}
}
}
void CLASS kodak_rgb_load_raw()
{
short buf[768], *bp;
int row, col, len, c, i, rgb[3], ret;
ushort *ip = image[0];
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col += 256)
{
len = MIN(256, width - col);
ret = kodak_65000_decode(buf, len * 3);
memset(rgb, 0, sizeof rgb);
for (bp = buf, i = 0; i < len; i++, ip += 4)
#ifdef LIBRAW_LIBRARY_BUILD
if (load_flags == 12)
{
FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++);
}
else
#endif
FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror();
}
}
}
void CLASS kodak_thumb_load_raw()
{
int row, col;
colors = thumb_misc >> 5;
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
read_shorts(image[row * width + col], colors);
maximum = (1 << (thumb_misc & 31)) - 1;
}
void CLASS sony_decrypt(unsigned *data, int len, int start, int key)
{
#ifndef LIBRAW_NOTHREADS
#define pad tls->sony_decrypt.pad
#define p tls->sony_decrypt.p
#else
static unsigned pad[128], p;
#endif
if (start)
{
for (p = 0; p < 4; p++)
pad[p] = key = key * 48828125 + 1;
pad[3] = pad[3] << 1 | (pad[0] ^ pad[2]) >> 31;
for (p = 4; p < 127; p++)
pad[p] = (pad[p - 4] ^ pad[p - 2]) << 1 | (pad[p - 3] ^ pad[p - 1]) >> 31;
for (p = 0; p < 127; p++)
pad[p] = htonl(pad[p]);
}
while (len--)
{
*data++ ^= pad[p & 127] = pad[(p + 1) & 127] ^ pad[(p + 65) & 127];
p++;
}
#ifndef LIBRAW_NOTHREADS
#undef pad
#undef p
#endif
}
void CLASS sony_load_raw()
{
uchar head[40];
ushort *pixel;
unsigned i, key, row, col;
fseek(ifp, 200896, SEEK_SET);
fseek(ifp, (unsigned)fgetc(ifp) * 4 - 1, SEEK_CUR);
order = 0x4d4d;
key = get4();
fseek(ifp, 164600, SEEK_SET);
fread(head, 1, 40, ifp);
sony_decrypt((unsigned *)head, 10, 1, key);
for (i = 26; i-- > 22;)
key = key << 8 | head[i];
fseek(ifp, data_offset, SEEK_SET);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pixel = raw_image + row * raw_width;
if (fread(pixel, 2, raw_width, ifp) < raw_width)
derror();
sony_decrypt((unsigned *)pixel, raw_width / 2, !row, key);
for (col = 0; col < raw_width; col++)
if ((pixel[col] = ntohs(pixel[col])) >> 14)
derror();
}
maximum = 0x3ff0;
}
void CLASS sony_arw_load_raw()
{
ushort huff[32770];
static const ushort tab[18] = {0xf11, 0xf10, 0xe0f, 0xd0e, 0xc0d, 0xb0c, 0xa0b, 0x90a, 0x809,
0x708, 0x607, 0x506, 0x405, 0x304, 0x303, 0x300, 0x202, 0x201};
int i, c, n, col, row, sum = 0;
huff[0] = 15;
for (n = i = 0; i < 18; i++)
FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i];
getbits(-1);
for (col = raw_width; col--;)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (row = 0; row < raw_height + 1; row += 2)
{
if (row == raw_height)
row = 1;
if ((sum += ljpeg_diff(huff)) >> 12)
derror();
if (row < height)
RAW(row, col) = sum;
}
}
}
void CLASS sony_arw2_load_raw()
{
uchar *data, *dp;
ushort pix[16];
int row, col, val, max, min, imax, imin, sh, bit, i;
data = (uchar *)malloc(raw_width + 1);
merror(data, "sony_arw2_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fread(data, 1, raw_width, ifp);
for (dp = data, col = 0; col < raw_width - 30; dp += 16)
{
max = 0x7ff & (val = sget4(dp));
min = 0x7ff & val >> 11;
imax = 0x0f & val >> 22;
imin = 0x0f & val >> 26;
for (sh = 0; sh < 4 && 0x80 << sh <= max - min; sh++)
;
#ifdef LIBRAW_LIBRARY_BUILD
/* flag checks if outside of loop */
if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set
|| (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE))
{
for (bit = 30, i = 0; i < 16; i++)
if (i == imax)
pix[i] = max;
else if (i == imin)
pix[i] = min;
else
{
pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff)
pix[i] = 0x7ff;
bit += 7;
}
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY)
{
for (bit = 30, i = 0; i < 16; i++)
if (i == imax)
pix[i] = max;
else if (i == imin)
pix[i] = min;
else
pix[i] = 0;
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY)
{
for (bit = 30, i = 0; i < 16; i++)
if (i == imax)
pix[i] = 0;
else if (i == imin)
pix[i] = 0;
else
{
pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff)
pix[i] = 0x7ff;
bit += 7;
}
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE)
{
for (bit = 30, i = 0; i < 16; i++)
if (i == imax)
pix[i] = 0;
else if (i == imin)
pix[i] = 0;
else
{
pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh);
if (pix[i] > 0x7ff)
pix[i] = 0x7ff;
bit += 7;
}
}
#else
/* unaltered dcraw processing */
for (bit = 30, i = 0; i < 16; i++)
if (i == imax)
pix[i] = max;
else if (i == imin)
pix[i] = min;
else
{
pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff)
pix[i] = 0x7ff;
bit += 7;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)
{
for (i = 0; i < 16; i++, col += 2)
{
unsigned slope = pix[i] < 1001 ? 2 : curve[pix[i] << 1] - curve[(pix[i] << 1) - 2];
unsigned step = 1 << sh;
RAW(row, col) = curve[pix[i] << 1] > black + imgdata.params.sony_arw2_posterization_thr
? LIM(((slope * step * 1000) / (curve[pix[i] << 1] - black)), 0, 10000)
: 0;
}
}
else
{
for (i = 0; i < 16; i++, col += 2)
RAW(row, col) = curve[pix[i] << 1];
}
#else
for (i = 0; i < 16; i++, col += 2)
RAW(row, col) = curve[pix[i] << 1] >> 2;
#endif
col -= col & 1 ? 1 : 31;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(data);
throw;
}
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)
maximum = 10000;
#endif
free(data);
}
void CLASS samsung_load_raw()
{
int row, col, c, i, dir, op[4], len[4];
order = 0x4949;
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek(ifp, strip_offset + row * 4, SEEK_SET);
fseek(ifp, data_offset + get4(), SEEK_SET);
ph1_bits(-1);
FORC4 len[c] = row < 2 ? 7 : 4;
for (col = 0; col < raw_width; col += 16)
{
dir = ph1_bits(1);
FORC4 op[c] = ph1_bits(2);
FORC4 switch (op[c])
{
case 3:
len[c] = ph1_bits(4);
break;
case 2:
len[c]--;
break;
case 1:
len[c]++;
}
for (c = 0; c < 16; c += 2)
{
i = len[((c & 1) << 1) | (c >> 3)];
RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) +
(dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128);
if (c == 14)
c = -1;
}
}
}
for (row = 0; row < raw_height - 1; row += 2)
for (col = 0; col < raw_width - 1; col += 2)
SWAP(RAW(row, col + 1), RAW(row + 1, col));
}
void CLASS samsung2_load_raw()
{
static const ushort tab[14] = {0x304, 0x307, 0x206, 0x205, 0x403, 0x600, 0x709,
0x80a, 0x90b, 0xa0c, 0xa0d, 0x501, 0x408, 0x402};
ushort huff[1026], vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2];
int i, c, n, row, col, diff;
huff[0] = 10;
for (n = i = 0; i < 14; i++)
FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i];
getbits(-1);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
diff = ljpeg_diff(huff);
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
RAW(row, col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps)
derror();
}
}
}
void CLASS samsung3_load_raw()
{
int opt, init, mag, pmode, row, tab, col, pred, diff, i, c;
ushort lent[3][2], len[4], *prow[2];
order = 0x4949;
fseek(ifp, 9, SEEK_CUR);
opt = fgetc(ifp);
init = (get2(), get2());
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek(ifp, (data_offset - ftell(ifp)) & 15, SEEK_CUR);
ph1_bits(-1);
mag = 0;
pmode = 7;
FORC(6)((ushort *)lent)[c] = row < 2 ? 7 : 4;
prow[row & 1] = &RAW(row - 1, 1 - ((row & 1) << 1)); // green
prow[~row & 1] = &RAW(row - 2, 0); // red and blue
for (tab = 0; tab + 15 < raw_width; tab += 16)
{
if (~opt & 4 && !(tab & 63))
{
i = ph1_bits(2);
mag = i < 3 ? mag - '2' + "204"[i] : ph1_bits(12);
}
if (opt & 2)
pmode = 7 - 4 * ph1_bits(1);
else if (!ph1_bits(1))
pmode = ph1_bits(3);
if (opt & 1 || !ph1_bits(1))
{
FORC4 len[c] = ph1_bits(2);
FORC4
{
i = ((row & 1) << 1 | (c & 1)) % 3;
len[c] = len[c] < 3 ? lent[i][0] - '1' + "120"[len[c]] : ph1_bits(4);
lent[i][0] = lent[i][1];
lent[i][1] = len[c];
}
}
FORC(16)
{
col = tab + (((c & 7) << 1) ^ (c >> 3) ^ (row & 1));
pred =
(pmode == 7 || row < 2)
? (tab ? RAW(row, tab - 2 + (col & 1)) : init)
: (prow[col & 1][col - '4' + "0224468"[pmode]] + prow[col & 1][col - '4' + "0244668"[pmode]] + 1) >> 1;
diff = ph1_bits(i = len[c >> 2]);
if (diff >> (i - 1))
diff -= 1 << i;
diff = diff * (mag * 2 + 1) + mag;
RAW(row, col) = pred + diff;
}
}
}
}
#define HOLE(row) ((holes >> (((row)-raw_height) & 7)) & 1)
/* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */
void CLASS smal_decode_segment(unsigned seg[2][2], int holes)
{
uchar hist[3][13] = {{7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0},
{7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0},
{3, 3, 0, 0, 63, 47, 31, 15, 0}};
int low, high = 0xff, carry = 0, nbits = 8;
int pix, s, count, bin, next, i, sym[3];
uchar diff, pred[] = {0, 0};
ushort data = 0, range = 0;
fseek(ifp, seg[0][1] + 1, SEEK_SET);
getbits(-1);
if (seg[1][0] > raw_width * raw_height)
seg[1][0] = raw_width * raw_height;
for (pix = seg[0][0]; pix < seg[1][0]; pix++)
{
for (s = 0; s < 3; s++)
{
data = data << nbits | getbits(nbits);
if (carry < 0)
carry = (nbits += carry + 1) < 1 ? nbits - 1 : 0;
while (--nbits >= 0)
if ((data >> nbits & 0xff) == 0xff)
break;
if (nbits > 0)
data = ((data & ((1 << (nbits - 1)) - 1)) << 1) |
((data + (((data & (1 << (nbits - 1)))) << 1)) & ((~0u) << nbits));
if (nbits >= 0)
{
data += getbits(1);
carry = nbits - 8;
}
count = ((((data - range + 1) & 0xffff) << 2) - 1) / (high >> 4);
for (bin = 0; hist[s][bin + 5] > count; bin++)
;
low = hist[s][bin + 5] * (high >> 4) >> 2;
if (bin)
high = hist[s][bin + 4] * (high >> 4) >> 2;
high -= low;
for (nbits = 0; high << nbits < 128; nbits++)
;
range = (range + low) << nbits;
high <<= nbits;
next = hist[s][1];
if (++hist[s][2] > hist[s][3])
{
next = (next + 1) & hist[s][0];
hist[s][3] = (hist[s][next + 4] - hist[s][next + 5]) >> 2;
hist[s][2] = 1;
}
if (hist[s][hist[s][1] + 4] - hist[s][hist[s][1] + 5] > 1)
{
if (bin < hist[s][1])
for (i = bin; i < hist[s][1]; i++)
hist[s][i + 5]--;
else if (next <= bin)
for (i = hist[s][1]; i < bin; i++)
hist[s][i + 5]++;
}
hist[s][1] = next;
sym[s] = bin;
}
diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3);
if (sym[0] & 4)
diff = diff ? -diff : 0x80;
if (ftell(ifp) + 12 >= seg[1][1])
diff = 0;
#ifdef LIBRAW_LIBRARY_BUILD
if (pix >= raw_width * raw_height)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
raw_image[pix] = pred[pix & 1] += diff;
if (!(pix & 1) && HOLE(pix / raw_width))
pix += 2;
}
maximum = 0xff;
}
void CLASS smal_v6_load_raw()
{
unsigned seg[2][2];
fseek(ifp, 16, SEEK_SET);
seg[0][0] = 0;
seg[0][1] = get2();
seg[1][0] = raw_width * raw_height;
seg[1][1] = INT_MAX;
smal_decode_segment(seg, 0);
}
int CLASS median4(int *p)
{
int min, max, sum, i;
min = max = sum = p[0];
for (i = 1; i < 4; i++)
{
sum += p[i];
if (min > p[i])
min = p[i];
if (max < p[i])
max = p[i];
}
return (sum - min - max) >> 1;
}
void CLASS fill_holes(int holes)
{
int row, col, val[4];
for (row = 2; row < height - 2; row++)
{
if (!HOLE(row))
continue;
for (col = 1; col < width - 1; col += 4)
{
val[0] = RAW(row - 1, col - 1);
val[1] = RAW(row - 1, col + 1);
val[2] = RAW(row + 1, col - 1);
val[3] = RAW(row + 1, col + 1);
RAW(row, col) = median4(val);
}
for (col = 2; col < width - 2; col += 4)
if (HOLE(row - 2) || HOLE(row + 2))
RAW(row, col) = (RAW(row, col - 2) + RAW(row, col + 2)) >> 1;
else
{
val[0] = RAW(row, col - 2);
val[1] = RAW(row, col + 2);
val[2] = RAW(row - 2, col);
val[3] = RAW(row + 2, col);
RAW(row, col) = median4(val);
}
}
}
void CLASS smal_v9_load_raw()
{
unsigned seg[256][2], offset, nseg, holes, i;
fseek(ifp, 67, SEEK_SET);
offset = get4();
nseg = (uchar)fgetc(ifp);
fseek(ifp, offset, SEEK_SET);
for (i = 0; i < nseg * 2; i++)
((unsigned *)seg)[i] = get4() + data_offset * (i & 1);
fseek(ifp, 78, SEEK_SET);
holes = fgetc(ifp);
fseek(ifp, 88, SEEK_SET);
seg[nseg][0] = raw_height * raw_width;
seg[nseg][1] = get4() + data_offset;
for (i = 0; i < nseg; i++)
smal_decode_segment(seg + i, holes);
if (holes)
fill_holes(holes);
}
void CLASS redcine_load_raw()
{
#ifndef NO_JASPER
int c, row, col;
jas_stream_t *in;
jas_image_t *jimg;
jas_matrix_t *jmat;
jas_seqent_t *data;
ushort *img, *pix;
jas_init();
#ifndef LIBRAW_LIBRARY_BUILD
in = jas_stream_fopen(ifname, "rb");
#else
in = (jas_stream_t *)ifp->make_jas_stream();
if (!in)
throw LIBRAW_EXCEPTION_DECODE_JPEG2000;
#endif
jas_stream_seek(in, data_offset + 20, SEEK_SET);
jimg = jas_image_decode(in, -1, 0);
#ifndef LIBRAW_LIBRARY_BUILD
if (!jimg)
longjmp(failure, 3);
#else
if (!jimg)
{
jas_stream_close(in);
throw LIBRAW_EXCEPTION_DECODE_JPEG2000;
}
#endif
jmat = jas_matrix_create(height / 2, width / 2);
merror(jmat, "redcine_load_raw()");
img = (ushort *)calloc((height + 2), (width + 2) * 2);
merror(img, "redcine_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
bool fastexitflag = false;
try
{
#endif
FORC4
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
jas_image_readcmpt(jimg, c, 0, 0, width / 2, height / 2, jmat);
data = jas_matrix_getref(jmat, 0, 0);
for (row = c >> 1; row < height; row += 2)
for (col = c & 1; col < width; col += 2)
img[(row + 1) * (width + 2) + col + 1] = data[(row / 2) * (width / 2) + col / 2];
}
for (col = 1; col <= width; col++)
{
img[col] = img[2 * (width + 2) + col];
img[(height + 1) * (width + 2) + col] = img[(height - 1) * (width + 2) + col];
}
for (row = 0; row < height + 2; row++)
{
img[row * (width + 2)] = img[row * (width + 2) + 2];
img[(row + 1) * (width + 2) - 1] = img[(row + 1) * (width + 2) - 3];
}
for (row = 1; row <= height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pix = img + row * (width + 2) + (col = 1 + (FC(row, 1) & 1));
for (; col <= width; col += 2, pix += 2)
{
c = (((pix[0] - 0x800) << 3) + pix[-(width + 2)] + pix[width + 2] + pix[-1] + pix[1]) >> 2;
pix[0] = LIM(c, 0, 4095);
}
}
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col++)
RAW(row, col) = curve[img[(row + 1) * (width + 2) + col + 1]];
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
fastexitflag = true;
}
#endif
free(img);
jas_matrix_destroy(jmat);
jas_image_destroy(jimg);
jas_stream_close(in);
#ifdef LIBRAW_LIBRARY_BUILD
if (fastexitflag)
throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK;
#endif
#endif
}
//@end COMMON
/* RESTRICTED code starts here */
void CLASS foveon_decoder(unsigned size, unsigned code)
{
static unsigned huff[1024];
struct decode *cur;
int i, len;
if (!code)
{
for (i = 0; i < size; i++)
huff[i] = get4();
memset(first_decode, 0, sizeof first_decode);
free_decode = first_decode;
}
cur = free_decode++;
if (free_decode > first_decode + 2048)
{
fprintf(stderr, _("%s: decoder table overflow\n"), ifname);
longjmp(failure, 2);
}
if (code)
for (i = 0; i < size; i++)
if (huff[i] == code)
{
cur->leaf = i;
return;
}
if ((len = code >> 27) > 26)
return;
code = (len + 1) << 27 | (code & 0x3ffffff) << 1;
cur->branch[0] = free_decode;
foveon_decoder(size, code);
cur->branch[1] = free_decode;
foveon_decoder(size, code + 1);
}
void CLASS foveon_thumb()
{
unsigned bwide, row, col, bitbuf = 0, bit = 1, c, i;
char *buf;
struct decode *dindex;
short pred[3];
bwide = get4();
fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
if (bwide > 0)
{
if (bwide < thumb_width * 3)
return;
buf = (char *)malloc(bwide);
merror(buf, "foveon_thumb()");
for (row = 0; row < thumb_height; row++)
{
fread(buf, 1, bwide, ifp);
fwrite(buf, 3, thumb_width, ofp);
}
free(buf);
return;
}
foveon_decoder(256, 0);
for (row = 0; row < thumb_height; row++)
{
memset(pred, 0, sizeof pred);
if (!bit)
get4();
for (bit = col = 0; col < thumb_width; col++)
FORC3
{
for (dindex = first_decode; dindex->branch[0];)
{
if ((bit = (bit - 1) & 31) == 31)
for (i = 0; i < 4; i++)
bitbuf = (bitbuf << 8) + fgetc(ifp);
dindex = dindex->branch[bitbuf >> bit & 1];
}
pred[c] += dindex->leaf;
fputc(pred[c], ofp);
}
}
}
void CLASS foveon_sd_load_raw()
{
struct decode *dindex;
short diff[1024];
unsigned bitbuf = 0;
int pred[3], row, col, bit = -1, c, i;
read_shorts((ushort *)diff, 1024);
if (!load_flags)
foveon_decoder(1024, 0);
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
memset(pred, 0, sizeof pred);
if (!bit && !load_flags && atoi(model + 2) < 14)
get4();
for (col = bit = 0; col < width; col++)
{
if (load_flags)
{
bitbuf = get4();
FORC3 pred[2 - c] += diff[bitbuf >> c * 10 & 0x3ff];
}
else
FORC3
{
for (dindex = first_decode; dindex->branch[0];)
{
if ((bit = (bit - 1) & 31) == 31)
for (i = 0; i < 4; i++)
bitbuf = (bitbuf << 8) + fgetc(ifp);
dindex = dindex->branch[bitbuf >> bit & 1];
}
pred[c] += diff[dindex->leaf];
if (pred[c] >> 16 && ~pred[c] >> 16)
derror();
}
FORC3 image[row * width + col][c] = pred[c];
}
}
}
void CLASS foveon_huff(ushort *huff)
{
int i, j, clen, code;
huff[0] = 8;
for (i = 0; i < 13; i++)
{
clen = getc(ifp);
code = getc(ifp);
for (j = 0; j<256>> clen;)
huff[code + ++j] = clen << 8 | i;
}
get2();
}
void CLASS foveon_dp_load_raw()
{
unsigned c, roff[4], row, col, diff;
ushort huff[512], vpred[2][2], hpred[2];
fseek(ifp, 8, SEEK_CUR);
foveon_huff(huff);
roff[0] = 48;
FORC3 roff[c + 1] = -(-(roff[c] + get4()) & -16);
FORC3
{
fseek(ifp, data_offset + roff[c], SEEK_SET);
getbits(-1);
vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col++)
{
diff = ljpeg_diff(huff);
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
image[row * width + col][c] = hpred[col & 1];
}
}
}
}
void CLASS foveon_load_camf()
{
unsigned type, wide, high, i, j, row, col, diff;
ushort huff[258], vpred[2][2] = {{512, 512}, {512, 512}}, hpred[2];
fseek(ifp, meta_offset, SEEK_SET);
type = get4();
get4();
get4();
wide = get4();
high = get4();
if (type == 2)
{
fread(meta_data, 1, meta_length, ifp);
for (i = 0; i < meta_length; i++)
{
high = (high * 1597 + 51749) % 244944;
wide = high * (INT64)301593171 >> 24;
meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17;
}
}
else if (type == 4)
{
free(meta_data);
meta_data = (char *)malloc(meta_length = wide * high * 3 / 2);
merror(meta_data, "foveon_load_camf()");
foveon_huff(huff);
get4();
getbits(-1);
for (j = row = 0; row < high; row++)
{
for (col = 0; col < wide; col++)
{
diff = ljpeg_diff(huff);
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
if (col & 1)
{
meta_data[j++] = hpred[0] >> 4;
meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8;
meta_data[j++] = hpred[1];
}
}
}
}
#ifdef DCRAW_VERBOSE
else
fprintf(stderr, _("%s has unknown CAMF type %d.\n"), ifname, type);
#endif
}
const char *CLASS foveon_camf_param(const char *block, const char *param)
{
unsigned idx, num;
char *pos, *cp, *dp;
for (idx = 0; idx < meta_length; idx += sget4(pos + 8))
{
pos = meta_data + idx;
if (strncmp(pos, "CMb", 3))
break;
if (pos[3] != 'P')
continue;
if (strcmp(block, pos + sget4(pos + 12)))
continue;
cp = pos + sget4(pos + 16);
num = sget4(cp);
dp = pos + sget4(cp + 4);
while (num--)
{
cp += 8;
if (!strcmp(param, dp + sget4(cp)))
return dp + sget4(cp + 4);
}
}
return 0;
}
void *CLASS foveon_camf_matrix(unsigned dim[3], const char *name)
{
unsigned i, idx, type, ndim, size, *mat;
char *pos, *cp, *dp;
double dsize;
for (idx = 0; idx < meta_length; idx += sget4(pos + 8))
{
pos = meta_data + idx;
if (strncmp(pos, "CMb", 3))
break;
if (pos[3] != 'M')
continue;
if (strcmp(name, pos + sget4(pos + 12)))
continue;
dim[0] = dim[1] = dim[2] = 1;
cp = pos + sget4(pos + 16);
type = sget4(cp);
if ((ndim = sget4(cp + 4)) > 3)
break;
dp = pos + sget4(cp + 8);
for (i = ndim; i--;)
{
cp += 12;
dim[i] = sget4(cp);
}
if ((dsize = (double)dim[0] * dim[1] * dim[2]) > meta_length / 4)
break;
mat = (unsigned *)malloc((size = dsize) * 4);
merror(mat, "foveon_camf_matrix()");
for (i = 0; i < size; i++)
if (type && type != 6)
mat[i] = sget4(dp + i * 4);
else
mat[i] = sget4(dp + i * 2) & 0xffff;
return mat;
}
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: \"%s\" matrix not found!\n"), ifname, name);
#endif
return 0;
}
int CLASS foveon_fixed(void *ptr, int size, const char *name)
{
void *dp;
unsigned dim[3];
if (!name)
return 0;
dp = foveon_camf_matrix(dim, name);
if (!dp)
return 0;
memcpy(ptr, dp, size * 4);
free(dp);
return 1;
}
float CLASS foveon_avg(short *pix, int range[2], float cfilt)
{
int i;
float val, min = FLT_MAX, max = -FLT_MAX, sum = 0;
for (i = range[0]; i <= range[1]; i++)
{
sum += val = pix[i * 4] + (pix[i * 4] - pix[(i - 1) * 4]) * cfilt;
if (min > val)
min = val;
if (max < val)
max = val;
}
if (range[1] - range[0] == 1)
return sum / 2;
return (sum - min - max) / (range[1] - range[0] - 1);
}
short *CLASS foveon_make_curve(double max, double mul, double filt)
{
short *curve;
unsigned i, size;
double x;
if (!filt)
filt = 0.8;
size = 4 * M_PI * max / filt;
if (size == UINT_MAX)
size--;
curve = (short *)calloc(size + 1, sizeof *curve);
merror(curve, "foveon_make_curve()");
curve[0] = size;
for (i = 0; i < size; i++)
{
x = i * filt / max / 4;
curve[i + 1] = (cos(x) + 1) / 2 * tanh(i * filt / mul) * mul + 0.5;
}
return curve;
}
void CLASS foveon_make_curves(short **curvep, float dq[3], float div[3], float filt)
{
double mul[3], max = 0;
int c;
FORC3 mul[c] = dq[c] / div[c];
FORC3 if (max < mul[c]) max = mul[c];
FORC3 curvep[c] = foveon_make_curve(max, mul[c], filt);
}
int CLASS foveon_apply_curve(short *curve, int i)
{
if (abs(i) >= curve[0])
return 0;
return i < 0 ? -curve[1 - i] : curve[1 + i];
}
#define image ((short(*)[4])image)
void CLASS foveon_interpolate()
{
static const short hood[] = {-1, -1, -1, 0, -1, 1, 0, -1, 0, 1, 1, -1, 1, 0, 1, 1};
short *pix, prev[3], *curve[8], (*shrink)[3];
float cfilt = 0, ddft[3][3][2], ppm[3][3][3];
float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3];
float chroma_dq[3], color_dq[3], diag[3][3], div[3];
float(*black)[3], (*sgain)[3], (*sgrow)[3];
float fsum[3], val, frow, num;
int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit;
int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3];
int work[3][3], smlast, smred, smred_p = 0, dev[3];
int satlev[3], keep[4], active[4];
unsigned dim[3], *badpix;
double dsum = 0, trsum[3];
char str[128];
const char *cp;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Foveon interpolation...\n"));
#endif
foveon_load_camf();
foveon_fixed(dscr, 4, "DarkShieldColRange");
foveon_fixed(ppm[0][0], 27, "PostPolyMatrix");
foveon_fixed(satlev, 3, "SaturationLevel");
foveon_fixed(keep, 4, "KeepImageArea");
foveon_fixed(active, 4, "ActiveImageArea");
foveon_fixed(chroma_dq, 3, "ChromaDQ");
foveon_fixed(color_dq, 3, foveon_camf_param("IncludeBlocks", "ColorDQ") ? "ColorDQ" : "ColorDQCamRGB");
if (foveon_camf_param("IncludeBlocks", "ColumnFilter"))
foveon_fixed(&cfilt, 1, "ColumnFilter");
memset(ddft, 0, sizeof ddft);
if (!foveon_camf_param("IncludeBlocks", "DarkDrift") || !foveon_fixed(ddft[1][0], 12, "DarkDrift"))
for (i = 0; i < 2; i++)
{
foveon_fixed(dstb, 4, i ? "DarkShieldBottom" : "DarkShieldTop");
for (row = dstb[1]; row <= dstb[3]; row++)
for (col = dstb[0]; col <= dstb[2]; col++)
FORC3 ddft[i + 1][c][1] += (short)image[row * width + col][c];
FORC3 ddft[i + 1][c][1] /= (dstb[3] - dstb[1] + 1) * (dstb[2] - dstb[0] + 1);
}
if (!(cp = foveon_camf_param("WhiteBalanceIlluminants", model2)))
{
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: Invalid white balance \"%s\"\n"), ifname, model2);
#endif
return;
}
foveon_fixed(cam_xyz, 9, cp);
foveon_fixed(correct, 9, foveon_camf_param("WhiteBalanceCorrections", model2));
memset(last, 0, sizeof last);
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j];
#define LAST(x, y) last[(i + x) % 3][(c + y) % 3]
for (i = 0; i < 3; i++)
FORC3 diag[c][i] = LAST(1, 1) * LAST(2, 2) - LAST(1, 2) * LAST(2, 1);
#undef LAST
FORC3 div[c] = diag[c][0] * 0.3127 + diag[c][1] * 0.329 + diag[c][2] * 0.3583;
sprintf(str, "%sRGBNeutral", model2);
if (foveon_camf_param("IncludeBlocks", str))
foveon_fixed(div, 3, str);
num = 0;
FORC3 if (num < div[c]) num = div[c];
FORC3 div[c] /= num;
memset(trans, 0, sizeof trans);
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j];
FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2];
dsum = (6 * trsum[0] + 11 * trsum[1] + 3 * trsum[2]) / 20;
for (i = 0; i < 3; i++)
FORC3 last[i][c] = trans[i][c] * dsum / trsum[i];
memset(trans, 0, sizeof trans);
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
FORC3 trans[i][j] += (i == c ? 32 : -1) * last[c][j] / 30;
foveon_make_curves(curve, color_dq, div, cfilt);
FORC3 chroma_dq[c] /= 3;
foveon_make_curves(curve + 3, chroma_dq, div, cfilt);
FORC3 dsum += chroma_dq[c] / div[c];
curve[6] = foveon_make_curve(dsum, dsum, cfilt);
curve[7] = foveon_make_curve(dsum * 2, dsum * 2, cfilt);
sgain = (float(*)[3])foveon_camf_matrix(dim, "SpatialGain");
if (!sgain)
return;
sgrow = (float(*)[3])calloc(dim[1], sizeof *sgrow);
sgx = (width + dim[1] - 2) / (dim[1] - 1);
black = (float(*)[3])calloc(height, sizeof *black);
for (row = 0; row < height; row++)
{
for (i = 0; i < 6; i++)
((float *)ddft[0])[i] =
((float *)ddft[1])[i] + row / (height - 1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]);
FORC3 black[row][c] = (foveon_avg(image[row * width] + c, dscr[0], cfilt) +
foveon_avg(image[row * width] + c, dscr[1], cfilt) * 3 - ddft[0][c][0]) /
4 -
ddft[0][c][1];
}
memcpy(black, black + 8, sizeof *black * 8);
memcpy(black + height - 11, black + height - 22, 11 * sizeof *black);
memcpy(last, black, sizeof last);
for (row = 1; row < height - 1; row++)
{
FORC3 if (last[1][c] > last[0][c])
{
if (last[1][c] > last[2][c])
black[row][c] = (last[0][c] > last[2][c]) ? last[0][c] : last[2][c];
}
else if (last[1][c] < last[2][c]) black[row][c] = (last[0][c] < last[2][c]) ? last[0][c] : last[2][c];
memmove(last, last + 1, 2 * sizeof last[0]);
memcpy(last[2], black[row + 1], sizeof last[2]);
}
FORC3 black[row][c] = (last[0][c] + last[1][c]) / 2;
FORC3 black[0][c] = (black[1][c] + black[3][c]) / 2;
val = 1 - exp(-1 / 24.0);
memcpy(fsum, black, sizeof fsum);
for (row = 1; row < height; row++)
FORC3 fsum[c] += black[row][c] = (black[row][c] - black[row - 1][c]) * val + black[row - 1][c];
memcpy(last[0], black[height - 1], sizeof last[0]);
FORC3 fsum[c] /= height;
for (row = height; row--;)
FORC3 last[0][c] = black[row][c] = (black[row][c] - fsum[c] - last[0][c]) * val + last[0][c];
memset(total, 0, sizeof total);
for (row = 2; row < height; row += 4)
for (col = 2; col < width; col += 4)
{
FORC3 total[c] += (short)image[row * width + col][c];
total[3]++;
}
for (row = 0; row < height; row++)
FORC3 black[row][c] += fsum[c] / 2 + total[c] / (total[3] * 100.0);
for (row = 0; row < height; row++)
{
for (i = 0; i < 6; i++)
((float *)ddft[0])[i] =
((float *)ddft[1])[i] + row / (height - 1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]);
pix = image[row * width];
memcpy(prev, pix, sizeof prev);
frow = row / (height - 1.0) * (dim[2] - 1);
if ((irow = frow) == dim[2] - 1)
irow--;
frow -= irow;
for (i = 0; i < dim[1]; i++)
FORC3 sgrow[i][c] = sgain[irow * dim[1] + i][c] * (1 - frow) + sgain[(irow + 1) * dim[1] + i][c] * frow;
for (col = 0; col < width; col++)
{
FORC3
{
diff = pix[c] - prev[c];
prev[c] = pix[c];
ipix[c] = pix[c] + floor((diff + (diff * diff >> 14)) * cfilt - ddft[0][c][1] -
ddft[0][c][0] * ((float)col / width - 0.5) - black[row][c]);
}
FORC3
{
work[0][c] = ipix[c] * ipix[c] >> 14;
work[2][c] = ipix[c] * work[0][c] >> 14;
work[1][2 - c] = ipix[(c + 1) % 3] * ipix[(c + 2) % 3] >> 14;
}
FORC3
{
for (val = i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
val += ppm[c][i][j] * work[i][j];
ipix[c] =
floor((ipix[c] + floor(val)) *
(sgrow[col / sgx][c] * (sgx - col % sgx) + sgrow[col / sgx + 1][c] * (col % sgx)) / sgx / div[c]);
if (ipix[c] > 32000)
ipix[c] = 32000;
pix[c] = ipix[c];
}
pix += 4;
}
}
free(black);
free(sgrow);
free(sgain);
if ((badpix = (unsigned *)foveon_camf_matrix(dim, "BadPixels")))
{
for (i = 0; i < dim[0]; i++)
{
col = (badpix[i] >> 8 & 0xfff) - keep[0];
row = (badpix[i] >> 20) - keep[1];
if ((unsigned)(row - 1) > height - 3 || (unsigned)(col - 1) > width - 3)
continue;
memset(fsum, 0, sizeof fsum);
for (sum = j = 0; j < 8; j++)
if (badpix[i] & (1 << j))
{
FORC3 fsum[c] += (short)image[(row + hood[j * 2]) * width + col + hood[j * 2 + 1]][c];
sum++;
}
if (sum)
FORC3 image[row * width + col][c] = fsum[c] / sum;
}
free(badpix);
}
/* Array for 5x5 Gaussian averaging of red values */
smrow[6] = (int(*)[3])calloc(width * 5, sizeof **smrow);
merror(smrow[6], "foveon_interpolate()");
for (i = 0; i < 5; i++)
smrow[i] = smrow[6] + i * width;
/* Sharpen the reds against these Gaussian averages */
for (smlast = -1, row = 2; row < height - 2; row++)
{
while (smlast < row + 2)
{
for (i = 0; i < 6; i++)
smrow[(i + 5) % 6] = smrow[i];
pix = image[++smlast * width + 2];
for (col = 2; col < width - 2; col++)
{
smrow[4][col][0] = (pix[0] * 6 + (pix[-4] + pix[4]) * 4 + pix[-8] + pix[8] + 8) >> 4;
pix += 4;
}
}
pix = image[row * width + 2];
for (col = 2; col < width - 2; col++)
{
smred = (6 * smrow[2][col][0] + 4 * (smrow[1][col][0] + smrow[3][col][0]) + smrow[0][col][0] + smrow[4][col][0] +
8) >>
4;
if (col == 2)
smred_p = smred;
i = pix[0] + ((pix[0] - ((smred * 7 + smred_p) >> 3)) >> 3);
if (i > 32000)
i = 32000;
pix[0] = i;
smred_p = smred;
pix += 4;
}
}
/* Adjust the brighter pixels for better linearity */
min = 0xffff;
FORC3
{
i = satlev[c] / div[c];
if (min > i)
min = i;
}
limit = min * 9 >> 4;
for (pix = image[0]; pix < image[height * width]; pix += 4)
{
if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit)
continue;
min = max = pix[0];
for (c = 1; c < 3; c++)
{
if (min > pix[c])
min = pix[c];
if (max < pix[c])
max = pix[c];
}
if (min >= limit * 2)
{
pix[0] = pix[1] = pix[2] = max;
}
else
{
i = 0x4000 - ((min - limit) << 14) / limit;
i = 0x4000 - (i * i >> 14);
i = i * i >> 14;
FORC3 pix[c] += (max - pix[c]) * i >> 14;
}
}
/*
Because photons that miss one detector often hit another,
the sum R+G+B is much less noisy than the individual colors.
So smooth the hues without smoothing the total.
*/
for (smlast = -1, row = 2; row < height - 2; row++)
{
while (smlast < row + 2)
{
for (i = 0; i < 6; i++)
smrow[(i + 5) % 6] = smrow[i];
pix = image[++smlast * width + 2];
for (col = 2; col < width - 2; col++)
{
FORC3 smrow[4][col][c] = (pix[c - 4] + 2 * pix[c] + pix[c + 4] + 2) >> 2;
pix += 4;
}
}
pix = image[row * width + 2];
for (col = 2; col < width - 2; col++)
{
FORC3 dev[c] =
-foveon_apply_curve(curve[7], pix[c] - ((smrow[1][col][c] + 2 * smrow[2][col][c] + smrow[3][col][c]) >> 2));
sum = (dev[0] + dev[1] + dev[2]) >> 3;
FORC3 pix[c] += dev[c] - sum;
pix += 4;
}
}
for (smlast = -1, row = 2; row < height - 2; row++)
{
while (smlast < row + 2)
{
for (i = 0; i < 6; i++)
smrow[(i + 5) % 6] = smrow[i];
pix = image[++smlast * width + 2];
for (col = 2; col < width - 2; col++)
{
FORC3 smrow[4][col][c] = (pix[c - 8] + pix[c - 4] + pix[c] + pix[c + 4] + pix[c + 8] + 2) >> 2;
pix += 4;
}
}
pix = image[row * width + 2];
for (col = 2; col < width - 2; col++)
{
for (total[3] = 375, sum = 60, c = 0; c < 3; c++)
{
for (total[c] = i = 0; i < 5; i++)
total[c] += smrow[i][col][c];
total[3] += total[c];
sum += pix[c];
}
if (sum < 0)
sum = 0;
j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174;
FORC3 pix[c] += foveon_apply_curve(curve[6], ((j * total[c] + 0x8000) >> 16) - pix[c]);
pix += 4;
}
}
/* Transform the image to a different colorspace */
for (pix = image[0]; pix < image[height * width]; pix += 4)
{
FORC3 pix[c] -= foveon_apply_curve(curve[c], pix[c]);
sum = (pix[0] + pix[1] + pix[1] + pix[2]) >> 2;
FORC3 pix[c] -= foveon_apply_curve(curve[c], pix[c] - sum);
FORC3
{
for (dsum = i = 0; i < 3; i++)
dsum += trans[c][i] * pix[i];
if (dsum < 0)
dsum = 0;
if (dsum > 24000)
dsum = 24000;
ipix[c] = dsum + 0.5;
}
FORC3 pix[c] = ipix[c];
}
/* Smooth the image bottom-to-top and save at 1/4 scale */
shrink = (short(*)[3])calloc((height / 4), (width / 4) * sizeof *shrink);
merror(shrink, "foveon_interpolate()");
for (row = height / 4; row--;)
for (col = 0; col < width / 4; col++)
{
ipix[0] = ipix[1] = ipix[2] = 0;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
FORC3 ipix[c] += image[(row * 4 + i) * width + col * 4 + j][c];
FORC3
if (row + 2 > height / 4)
shrink[row * (width / 4) + col][c] = ipix[c] >> 4;
else
shrink[row * (width / 4) + col][c] =
(shrink[(row + 1) * (width / 4) + col][c] * 1840 + ipix[c] * 141 + 2048) >> 12;
}
/* From the 1/4-scale image, smooth right-to-left */
for (row = 0; row < (height & ~3); row++)
{
ipix[0] = ipix[1] = ipix[2] = 0;
if ((row & 3) == 0)
for (col = width & ~3; col--;)
FORC3 smrow[0][col][c] = ipix[c] =
(shrink[(row / 4) * (width / 4) + col / 4][c] * 1485 + ipix[c] * 6707 + 4096) >> 13;
/* Then smooth left-to-right */
ipix[0] = ipix[1] = ipix[2] = 0;
for (col = 0; col < (width & ~3); col++)
FORC3 smrow[1][col][c] = ipix[c] = (smrow[0][col][c] * 1485 + ipix[c] * 6707 + 4096) >> 13;
/* Smooth top-to-bottom */
if (row == 0)
memcpy(smrow[2], smrow[1], sizeof **smrow * width);
else
for (col = 0; col < (width & ~3); col++)
FORC3 smrow[2][col][c] = (smrow[2][col][c] * 6707 + smrow[1][col][c] * 1485 + 4096) >> 13;
/* Adjust the chroma toward the smooth values */
for (col = 0; col < (width & ~3); col++)
{
for (i = j = 30, c = 0; c < 3; c++)
{
i += smrow[2][col][c];
j += image[row * width + col][c];
}
j = (j << 16) / i;
for (sum = c = 0; c < 3; c++)
{
ipix[c] =
foveon_apply_curve(curve[c + 3], ((smrow[2][col][c] * j + 0x8000) >> 16) - image[row * width + col][c]);
sum += ipix[c];
}
sum >>= 3;
FORC3
{
i = image[row * width + col][c] + ipix[c] - sum;
if (i < 0)
i = 0;
image[row * width + col][c] = i;
}
}
}
free(shrink);
free(smrow[6]);
for (i = 0; i < 8; i++)
free(curve[i]);
/* Trim off the black border */
active[1] -= keep[1];
active[3] -= 2;
i = active[2] - active[0];
for (row = 0; row < active[3] - active[1]; row++)
memcpy(image[row * i], image[(row + active[1]) * width + active[0]], i * sizeof *image);
width = i;
height = row;
}
#undef image
/* RESTRICTED code ends here */
//@out COMMON
void CLASS crop_masked_pixels()
{
int row, col;
unsigned
#ifndef LIBRAW_LIBRARY_BUILD
r,
raw_pitch = raw_width * 2, c, m, mblack[8], zero, val;
#else
c,
m, zero, val;
#define mblack imgdata.color.black_stat
#endif
#ifndef LIBRAW_LIBRARY_BUILD
if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c)
phase_one_correct();
if (fuji_width)
{
for (row = 0; row < raw_height - top_margin * 2; row++)
{
for (col = 0; col < fuji_width << !fuji_layout; col++)
{
if (fuji_layout)
{
r = fuji_width - 1 - col + (row >> 1);
c = col + ((row + 1) >> 1);
}
else
{
r = fuji_width - 1 + row - (col >> 1);
c = row + ((col + 1) >> 1);
}
if (r < height && c < width)
BAYER(r, c) = RAW(row + top_margin, col + left_margin);
}
}
}
else
{
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
BAYER2(row, col) = RAW(row + top_margin, col + left_margin);
}
#endif
if (mask[0][3] > 0)
goto mask_set;
if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw)
{
mask[0][1] = mask[1][1] += 2;
mask[0][3] -= 2;
goto sides;
}
if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw ||
(load_raw == &CLASS eight_bit_load_raw && strncmp(model, "DC2", 3)) || load_raw == &CLASS kodak_262_load_raw ||
(load_raw == &CLASS packed_load_raw && (load_flags & 32)))
{
sides:
mask[0][0] = mask[1][0] = top_margin;
mask[0][2] = mask[1][2] = top_margin + height;
mask[0][3] += left_margin;
mask[1][1] += left_margin + width;
mask[1][3] += raw_width;
}
if (load_raw == &CLASS nokia_load_raw)
{
mask[0][2] = top_margin;
mask[0][3] = width;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (load_raw == &CLASS broadcom_load_raw)
{
mask[0][2] = top_margin;
mask[0][3] = width;
}
#endif
mask_set:
memset(mblack, 0, sizeof mblack);
for (zero = m = 0; m < 8; m++)
for (row = MAX(mask[m][0], 0); row < MIN(mask[m][2], raw_height); row++)
for (col = MAX(mask[m][1], 0); col < MIN(mask[m][3], raw_width); col++)
{
c = FC(row - top_margin, col - left_margin);
mblack[c] += val = raw_image[(row)*raw_pitch / 2 + (col)];
mblack[4 + c]++;
zero += !val;
}
if (load_raw == &CLASS canon_600_load_raw && width < raw_width)
{
black = (mblack[0] + mblack[1] + mblack[2] + mblack[3]) / (mblack[4] + mblack[5] + mblack[6] + mblack[7]) - 4;
#ifndef LIBRAW_LIBRARY_BUILD
canon_600_correct();
#endif
}
else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7])
{
FORC4 cblack[c] = mblack[c] / mblack[4 + c];
black = cblack[4] = cblack[5] = cblack[6] = 0;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
#undef mblack
#endif
void CLASS remove_zeroes()
{
unsigned row, col, tot, n, r, c;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 0, 2);
#endif
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
if (BAYER(row, col) == 0)
{
tot = n = 0;
for (r = row - 2; r <= row + 2; r++)
for (c = col - 2; c <= col + 2; c++)
if (r < height && c < width && FC(r, c) == FC(row, col) && BAYER(r, c))
tot += (n++, BAYER(r, c));
if (n)
BAYER(row, col) = tot / n;
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 1, 2);
#endif
}
//@end COMMON
/* @out FILEIO
#include <math.h>
#define CLASS LibRaw::
#include "libraw/libraw_types.h"
#define LIBRAW_LIBRARY_BUILD
#include "libraw/libraw.h"
#include "internal/defines.h"
#include "internal/var_defines.h"
@end FILEIO */
// @out FILEIO
/*
Seach from the current directory up to the root looking for
a ".badpixels" file, and fix those pixels now.
*/
void CLASS bad_pixels(const char *cfname)
{
FILE *fp = NULL;
#ifndef LIBRAW_LIBRARY_BUILD
char *fname, *cp, line[128];
int len, time, row, col, r, c, rad, tot, n, fixed = 0;
#else
char *cp, line[128];
int time, row, col, r, c, rad, tot, n;
#ifdef DCRAW_VERBOSE
int fixed = 0;
#endif
#endif
if (!filters)
return;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS, 0, 2);
#endif
if (cfname)
fp = fopen(cfname, "r");
// @end FILEIO
else
{
for (len = 32;; len *= 2)
{
fname = (char *)malloc(len);
if (!fname)
return;
if (getcwd(fname, len - 16))
break;
free(fname);
if (errno != ERANGE)
return;
}
#if defined(WIN32) || defined(DJGPP)
if (fname[1] == ':')
memmove(fname, fname + 2, len - 2);
for (cp = fname; *cp; cp++)
if (*cp == '\\')
*cp = '/';
#endif
cp = fname + strlen(fname);
if (cp[-1] == '/')
cp--;
while (*fname == '/')
{
strcpy(cp, "/.badpixels");
if ((fp = fopen(fname, "r")))
break;
if (cp == fname)
break;
while (*--cp != '/')
;
}
free(fname);
}
// @out FILEIO
if (!fp)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_BADPIXELMAP;
#endif
return;
}
while (fgets(line, 128, fp))
{
cp = strchr(line, '#');
if (cp)
*cp = 0;
if (sscanf(line, "%d %d %d", &col, &row, &time) != 3)
continue;
if ((unsigned)col >= width || (unsigned)row >= height)
continue;
if (time > timestamp)
continue;
for (tot = n = 0, rad = 1; rad < 3 && n == 0; rad++)
for (r = row - rad; r <= row + rad; r++)
for (c = col - rad; c <= col + rad; c++)
if ((unsigned)r < height && (unsigned)c < width && (r != row || c != col) && fcol(r, c) == fcol(row, col))
{
tot += BAYER2(r, c);
n++;
}
BAYER2(row, col) = tot / n;
#ifdef DCRAW_VERBOSE
if (verbose)
{
if (!fixed++)
fprintf(stderr, _("Fixed dead pixels at:"));
fprintf(stderr, " %d,%d", col, row);
}
#endif
}
#ifdef DCRAW_VERBOSE
if (fixed)
fputc('\n', stderr);
#endif
fclose(fp);
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS, 1, 2);
#endif
}
void CLASS subtract(const char *fname)
{
FILE *fp;
int dim[3] = {0, 0, 0}, comment = 0, number = 0, error = 0, nd = 0, c, row, col;
ushort *pixel;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME, 0, 2);
#endif
if (!(fp = fopen(fname, "rb")))
{
#ifdef DCRAW_VERBOSE
perror(fname);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_FILE;
#endif
return;
}
if (fgetc(fp) != 'P' || fgetc(fp) != '5')
error = 1;
while (!error && nd < 3 && (c = fgetc(fp)) != EOF)
{
if (c == '#')
comment = 1;
if (c == '\n')
comment = 0;
if (comment)
continue;
if (isdigit(c))
number = 1;
if (number)
{
if (isdigit(c))
dim[nd] = dim[nd] * 10 + c - '0';
else if (isspace(c))
{
number = 0;
nd++;
}
else
error = 1;
}
}
if (error || nd < 3)
{
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s is not a valid PGM file!\n"), fname);
#endif
fclose(fp);
return;
}
else if (dim[0] != width || dim[1] != height || dim[2] != 65535)
{
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s has the wrong dimensions!\n"), fname);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_DIM;
#endif
fclose(fp);
return;
}
pixel = (ushort *)calloc(width, sizeof *pixel);
merror(pixel, "subtract()");
for (row = 0; row < height; row++)
{
fread(pixel, 2, width, fp);
for (col = 0; col < width; col++)
BAYER(row, col) = MAX(BAYER(row, col) - ntohs(pixel[col]), 0);
}
free(pixel);
fclose(fp);
memset(cblack, 0, sizeof cblack);
black = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME, 1, 2);
#endif
}
//@end FILEIO
//@out COMMON
static const uchar xlat[2][256] = {
{0xc1, 0xbf, 0x6d, 0x0d, 0x59, 0xc5, 0x13, 0x9d, 0x83, 0x61, 0x6b, 0x4f, 0xc7, 0x7f, 0x3d, 0x3d, 0x53, 0x59, 0xe3,
0xc7, 0xe9, 0x2f, 0x95, 0xa7, 0x95, 0x1f, 0xdf, 0x7f, 0x2b, 0x29, 0xc7, 0x0d, 0xdf, 0x07, 0xef, 0x71, 0x89, 0x3d,
0x13, 0x3d, 0x3b, 0x13, 0xfb, 0x0d, 0x89, 0xc1, 0x65, 0x1f, 0xb3, 0x0d, 0x6b, 0x29, 0xe3, 0xfb, 0xef, 0xa3, 0x6b,
0x47, 0x7f, 0x95, 0x35, 0xa7, 0x47, 0x4f, 0xc7, 0xf1, 0x59, 0x95, 0x35, 0x11, 0x29, 0x61, 0xf1, 0x3d, 0xb3, 0x2b,
0x0d, 0x43, 0x89, 0xc1, 0x9d, 0x9d, 0x89, 0x65, 0xf1, 0xe9, 0xdf, 0xbf, 0x3d, 0x7f, 0x53, 0x97, 0xe5, 0xe9, 0x95,
0x17, 0x1d, 0x3d, 0x8b, 0xfb, 0xc7, 0xe3, 0x67, 0xa7, 0x07, 0xf1, 0x71, 0xa7, 0x53, 0xb5, 0x29, 0x89, 0xe5, 0x2b,
0xa7, 0x17, 0x29, 0xe9, 0x4f, 0xc5, 0x65, 0x6d, 0x6b, 0xef, 0x0d, 0x89, 0x49, 0x2f, 0xb3, 0x43, 0x53, 0x65, 0x1d,
0x49, 0xa3, 0x13, 0x89, 0x59, 0xef, 0x6b, 0xef, 0x65, 0x1d, 0x0b, 0x59, 0x13, 0xe3, 0x4f, 0x9d, 0xb3, 0x29, 0x43,
0x2b, 0x07, 0x1d, 0x95, 0x59, 0x59, 0x47, 0xfb, 0xe5, 0xe9, 0x61, 0x47, 0x2f, 0x35, 0x7f, 0x17, 0x7f, 0xef, 0x7f,
0x95, 0x95, 0x71, 0xd3, 0xa3, 0x0b, 0x71, 0xa3, 0xad, 0x0b, 0x3b, 0xb5, 0xfb, 0xa3, 0xbf, 0x4f, 0x83, 0x1d, 0xad,
0xe9, 0x2f, 0x71, 0x65, 0xa3, 0xe5, 0x07, 0x35, 0x3d, 0x0d, 0xb5, 0xe9, 0xe5, 0x47, 0x3b, 0x9d, 0xef, 0x35, 0xa3,
0xbf, 0xb3, 0xdf, 0x53, 0xd3, 0x97, 0x53, 0x49, 0x71, 0x07, 0x35, 0x61, 0x71, 0x2f, 0x43, 0x2f, 0x11, 0xdf, 0x17,
0x97, 0xfb, 0x95, 0x3b, 0x7f, 0x6b, 0xd3, 0x25, 0xbf, 0xad, 0xc7, 0xc5, 0xc5, 0xb5, 0x8b, 0xef, 0x2f, 0xd3, 0x07,
0x6b, 0x25, 0x49, 0x95, 0x25, 0x49, 0x6d, 0x71, 0xc7},
{0xa7, 0xbc, 0xc9, 0xad, 0x91, 0xdf, 0x85, 0xe5, 0xd4, 0x78, 0xd5, 0x17, 0x46, 0x7c, 0x29, 0x4c, 0x4d, 0x03, 0xe9,
0x25, 0x68, 0x11, 0x86, 0xb3, 0xbd, 0xf7, 0x6f, 0x61, 0x22, 0xa2, 0x26, 0x34, 0x2a, 0xbe, 0x1e, 0x46, 0x14, 0x68,
0x9d, 0x44, 0x18, 0xc2, 0x40, 0xf4, 0x7e, 0x5f, 0x1b, 0xad, 0x0b, 0x94, 0xb6, 0x67, 0xb4, 0x0b, 0xe1, 0xea, 0x95,
0x9c, 0x66, 0xdc, 0xe7, 0x5d, 0x6c, 0x05, 0xda, 0xd5, 0xdf, 0x7a, 0xef, 0xf6, 0xdb, 0x1f, 0x82, 0x4c, 0xc0, 0x68,
0x47, 0xa1, 0xbd, 0xee, 0x39, 0x50, 0x56, 0x4a, 0xdd, 0xdf, 0xa5, 0xf8, 0xc6, 0xda, 0xca, 0x90, 0xca, 0x01, 0x42,
0x9d, 0x8b, 0x0c, 0x73, 0x43, 0x75, 0x05, 0x94, 0xde, 0x24, 0xb3, 0x80, 0x34, 0xe5, 0x2c, 0xdc, 0x9b, 0x3f, 0xca,
0x33, 0x45, 0xd0, 0xdb, 0x5f, 0xf5, 0x52, 0xc3, 0x21, 0xda, 0xe2, 0x22, 0x72, 0x6b, 0x3e, 0xd0, 0x5b, 0xa8, 0x87,
0x8c, 0x06, 0x5d, 0x0f, 0xdd, 0x09, 0x19, 0x93, 0xd0, 0xb9, 0xfc, 0x8b, 0x0f, 0x84, 0x60, 0x33, 0x1c, 0x9b, 0x45,
0xf1, 0xf0, 0xa3, 0x94, 0x3a, 0x12, 0x77, 0x33, 0x4d, 0x44, 0x78, 0x28, 0x3c, 0x9e, 0xfd, 0x65, 0x57, 0x16, 0x94,
0x6b, 0xfb, 0x59, 0xd0, 0xc8, 0x22, 0x36, 0xdb, 0xd2, 0x63, 0x98, 0x43, 0xa1, 0x04, 0x87, 0x86, 0xf7, 0xa6, 0x26,
0xbb, 0xd6, 0x59, 0x4d, 0xbf, 0x6a, 0x2e, 0xaa, 0x2b, 0xef, 0xe6, 0x78, 0xb6, 0x4e, 0xe0, 0x2f, 0xdc, 0x7c, 0xbe,
0x57, 0x19, 0x32, 0x7e, 0x2a, 0xd0, 0xb8, 0xba, 0x29, 0x00, 0x3c, 0x52, 0x7d, 0xa8, 0x49, 0x3b, 0x2d, 0xeb, 0x25,
0x49, 0xfa, 0xa3, 0xaa, 0x39, 0xa7, 0xc5, 0xa7, 0x50, 0x11, 0x36, 0xfb, 0xc6, 0x67, 0x4a, 0xf5, 0xa5, 0x12, 0x65,
0x7e, 0xb0, 0xdf, 0xaf, 0x4e, 0xb3, 0x61, 0x7f, 0x2f}};
void CLASS gamma_curve(double pwr, double ts, int mode, int imax)
{
int i;
double g[6], bnd[2] = {0, 0}, r;
g[0] = pwr;
g[1] = ts;
g[2] = g[3] = g[4] = 0;
bnd[g[1] >= 1] = 1;
if (g[1] && (g[1] - 1) * (g[0] - 1) <= 0)
{
for (i = 0; i < 48; i++)
{
g[2] = (bnd[0] + bnd[1]) / 2;
if (g[0])
bnd[(pow(g[2] / g[1], -g[0]) - 1) / g[0] - 1 / g[2] > -1] = g[2];
else
bnd[g[2] / exp(1 - 1 / g[2]) < g[1]] = g[2];
}
g[3] = g[2] / g[1];
if (g[0])
g[4] = g[2] * (1 / g[0] - 1);
}
if (g[0])
g[5] = 1 / (g[1] * SQR(g[3]) / 2 - g[4] * (1 - g[3]) + (1 - pow(g[3], 1 + g[0])) * (1 + g[4]) / (1 + g[0])) - 1;
else
g[5] = 1 / (g[1] * SQR(g[3]) / 2 + 1 - g[2] - g[3] - g[2] * g[3] * (log(g[3]) - 1)) - 1;
if (!mode--)
{
memcpy(gamm, g, sizeof gamm);
return;
}
for (i = 0; i < 0x10000; i++)
{
curve[i] = 0xffff;
if ((r = (double)i / imax) < 1)
curve[i] = 0x10000 *
(mode ? (r < g[3] ? r * g[1] : (g[0] ? pow(r, g[0]) * (1 + g[4]) - g[4] : log(r) * g[2] + 1))
: (r < g[2] ? r / g[1] : (g[0] ? pow((r + g[4]) / (1 + g[4]), 1 / g[0]) : exp((r - 1) / g[2]))));
}
}
void CLASS pseudoinverse(double (*in)[3], double (*out)[3], int size)
{
double work[3][6], num;
int i, j, k;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 6; j++)
work[i][j] = j == i + 3;
for (j = 0; j < 3; j++)
for (k = 0; k < size; k++)
work[i][j] += in[k][i] * in[k][j];
}
for (i = 0; i < 3; i++)
{
num = work[i][i];
for (j = 0; j < 6; j++)
work[i][j] /= num;
for (k = 0; k < 3; k++)
{
if (k == i)
continue;
num = work[k][i];
for (j = 0; j < 6; j++)
work[k][j] -= work[i][j] * num;
}
}
for (i = 0; i < size; i++)
for (j = 0; j < 3; j++)
for (out[i][j] = k = 0; k < 3; k++)
out[i][j] += work[j][k + 3] * in[i][k];
}
void CLASS cam_xyz_coeff(float _rgb_cam[3][4], double cam_xyz[4][3])
{
double cam_rgb[4][3], inverse[4][3], num;
int i, j, k;
for (i = 0; i < colors; i++) /* Multiply out XYZ colorspace */
for (j = 0; j < 3; j++)
for (cam_rgb[i][j] = k = 0; k < 3; k++)
cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j];
for (i = 0; i < colors; i++)
{ /* Normalize cam_rgb so that */
for (num = j = 0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */
num += cam_rgb[i][j];
if (num > 0.00001)
{
for (j = 0; j < 3; j++)
cam_rgb[i][j] /= num;
pre_mul[i] = 1 / num;
}
else
{
for (j = 0; j < 3; j++)
cam_rgb[i][j] = 0.0;
pre_mul[i] = 1.0;
}
}
pseudoinverse(cam_rgb, inverse, colors);
for (i = 0; i < 3; i++)
for (j = 0; j < colors; j++)
_rgb_cam[i][j] = inverse[j][i];
}
#ifdef COLORCHECK
void CLASS colorcheck()
{
#define NSQ 24
// Coordinates of the GretagMacbeth ColorChecker squares
// width, height, 1st_column, 1st_row
int cut[NSQ][4]; // you must set these
// ColorChecker Chart under 6500-kelvin illumination
static const double gmb_xyY[NSQ][3] = {{0.400, 0.350, 10.1}, // Dark Skin
{0.377, 0.345, 35.8}, // Light Skin
{0.247, 0.251, 19.3}, // Blue Sky
{0.337, 0.422, 13.3}, // Foliage
{0.265, 0.240, 24.3}, // Blue Flower
{0.261, 0.343, 43.1}, // Bluish Green
{0.506, 0.407, 30.1}, // Orange
{0.211, 0.175, 12.0}, // Purplish Blue
{0.453, 0.306, 19.8}, // Moderate Red
{0.285, 0.202, 6.6}, // Purple
{0.380, 0.489, 44.3}, // Yellow Green
{0.473, 0.438, 43.1}, // Orange Yellow
{0.187, 0.129, 6.1}, // Blue
{0.305, 0.478, 23.4}, // Green
{0.539, 0.313, 12.0}, // Red
{0.448, 0.470, 59.1}, // Yellow
{0.364, 0.233, 19.8}, // Magenta
{0.196, 0.252, 19.8}, // Cyan
{0.310, 0.316, 90.0}, // White
{0.310, 0.316, 59.1}, // Neutral 8
{0.310, 0.316, 36.2}, // Neutral 6.5
{0.310, 0.316, 19.8}, // Neutral 5
{0.310, 0.316, 9.0}, // Neutral 3.5
{0.310, 0.316, 3.1}}; // Black
double gmb_cam[NSQ][4], gmb_xyz[NSQ][3];
double inverse[NSQ][3], cam_xyz[4][3], balance[4], num;
int c, i, j, k, sq, row, col, pass, count[4];
memset(gmb_cam, 0, sizeof gmb_cam);
for (sq = 0; sq < NSQ; sq++)
{
FORCC count[c] = 0;
for (row = cut[sq][3]; row < cut[sq][3] + cut[sq][1]; row++)
for (col = cut[sq][2]; col < cut[sq][2] + cut[sq][0]; col++)
{
c = FC(row, col);
if (c >= colors)
c -= 2;
gmb_cam[sq][c] += BAYER2(row, col);
BAYER2(row, col) = black + (BAYER2(row, col) - black) / 2;
count[c]++;
}
FORCC gmb_cam[sq][c] = gmb_cam[sq][c] / count[c] - black;
gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1];
gmb_xyz[sq][1] = gmb_xyY[sq][2];
gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1];
}
pseudoinverse(gmb_xyz, inverse, NSQ);
for (pass = 0; pass < 2; pass++)
{
for (raw_color = i = 0; i < colors; i++)
for (j = 0; j < 3; j++)
for (cam_xyz[i][j] = k = 0; k < NSQ; k++)
cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j];
cam_xyz_coeff(rgb_cam, cam_xyz);
FORCC balance[c] = pre_mul[c] * gmb_cam[20][c];
for (sq = 0; sq < NSQ; sq++)
FORCC gmb_cam[sq][c] *= balance[c];
}
if (verbose)
{
printf(" { \"%s %s\", %d,\n\t{", make, model, black);
num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]);
FORCC for (j = 0; j < 3; j++) printf("%c%d", (c | j) ? ',' : ' ', (int)(cam_xyz[c][j] * num + 0.5));
puts(" } },");
}
#undef NSQ
}
#endif
void CLASS hat_transform(float *temp, float *base, int st, int size, int sc)
{
int i;
for (i = 0; i < sc; i++)
temp[i] = 2 * base[st * i] + base[st * (sc - i)] + base[st * (i + sc)];
for (; i + sc < size; i++)
temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (i + sc)];
for (; i < size; i++)
temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (2 * size - 2 - (i + sc))];
}
#if !defined(LIBRAW_USE_OPENMP)
void CLASS wavelet_denoise()
{
float *fimg = 0, *temp, thold, mul[2], avg, diff;
int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
ushort *window[4];
static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044};
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Wavelet denoising...\n"));
#endif
while (maximum << scale < 0x10000)
scale++;
maximum <<= --scale;
black <<= scale;
FORC4 cblack[c] <<= scale;
if ((size = iheight * iwidth) < 0x15550000)
fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg);
merror(fimg, "wavelet_denoise()");
temp = fimg + size * 3;
if ((nc = colors) == 3 && filters)
nc++;
FORC(nc)
{ /* denoise R,G1,B,G3 individually */
for (i = 0; i < size; i++)
fimg[i] = 256 * sqrt((double)(image[i][c] << scale));
for (hpass = lev = 0; lev < 5; lev++)
{
lpass = size * ((lev & 1) + 1);
for (row = 0; row < iheight; row++)
{
hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev);
for (col = 0; col < iwidth; col++)
fimg[lpass + row * iwidth + col] = temp[col] * 0.25;
}
for (col = 0; col < iwidth; col++)
{
hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev);
for (row = 0; row < iheight; row++)
fimg[lpass + row * iwidth + col] = temp[row] * 0.25;
}
thold = threshold * noise[lev];
for (i = 0; i < size; i++)
{
fimg[hpass + i] -= fimg[lpass + i];
if (fimg[hpass + i] < -thold)
fimg[hpass + i] += thold;
else if (fimg[hpass + i] > thold)
fimg[hpass + i] -= thold;
else
fimg[hpass + i] = 0;
if (hpass)
fimg[i] += fimg[hpass + i];
}
hpass = lpass;
}
for (i = 0; i < size; i++)
image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000);
}
if (filters && colors == 3)
{ /* pull G1 and G3 closer together */
for (row = 0; row < 2; row++)
{
mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1];
blk[row] = cblack[FC(row, 0) | 1];
}
for (i = 0; i < 4; i++)
window[i] = (ushort *)fimg + width * i;
for (wlast = -1, row = 1; row < height - 1; row++)
{
while (wlast < row + 1)
{
for (wlast++, i = 0; i < 4; i++)
window[(i + 3) & 3] = window[i];
for (col = FC(wlast, 1) & 1; col < width; col += 2)
window[2][col] = BAYER(wlast, col);
}
thold = threshold / 512;
for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2)
{
avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) *
mul[row & 1] +
(window[1][col] + blk[row & 1]) * 0.5;
avg = avg < 0 ? 0 : sqrt(avg);
diff = sqrt((double)BAYER(row, col)) - avg;
if (diff < -thold)
diff += thold;
else if (diff > thold)
diff -= thold;
else
diff = 0;
BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5);
}
}
}
free(fimg);
}
#else /* LIBRAW_USE_OPENMP */
void CLASS wavelet_denoise()
{
float *fimg = 0, *temp, thold, mul[2], avg, diff;
int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
ushort *window[4];
static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044};
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Wavelet denoising...\n"));
#endif
while (maximum << scale < 0x10000)
scale++;
maximum <<= --scale;
black <<= scale;
FORC4 cblack[c] <<= scale;
if ((size = iheight * iwidth) < 0x15550000)
fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg);
merror(fimg, "wavelet_denoise()");
temp = fimg + size * 3;
if ((nc = colors) == 3 && filters)
nc++;
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp parallel default(shared) private(i, col, row, thold, lev, lpass, hpass, temp, c) firstprivate(scale, size)
#endif
{
temp = (float *)malloc((iheight + iwidth) * sizeof *fimg);
FORC(nc)
{ /* denoise R,G1,B,G3 individually */
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i = 0; i < size; i++)
fimg[i] = 256 * sqrt((double)(image[i][c] << scale));
for (hpass = lev = 0; lev < 5; lev++)
{
lpass = size * ((lev & 1) + 1);
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (row = 0; row < iheight; row++)
{
hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev);
for (col = 0; col < iwidth; col++)
fimg[lpass + row * iwidth + col] = temp[col] * 0.25;
}
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (col = 0; col < iwidth; col++)
{
hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev);
for (row = 0; row < iheight; row++)
fimg[lpass + row * iwidth + col] = temp[row] * 0.25;
}
thold = threshold * noise[lev];
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i = 0; i < size; i++)
{
fimg[hpass + i] -= fimg[lpass + i];
if (fimg[hpass + i] < -thold)
fimg[hpass + i] += thold;
else if (fimg[hpass + i] > thold)
fimg[hpass + i] -= thold;
else
fimg[hpass + i] = 0;
if (hpass)
fimg[i] += fimg[hpass + i];
}
hpass = lpass;
}
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i = 0; i < size; i++)
image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000);
}
free(temp);
} /* end omp parallel */
/* the following loops are hard to parallize, no idea yes,
* problem is wlast which is carrying dependency
* second part should be easyer, but did not yet get it right.
*/
if (filters && colors == 3)
{ /* pull G1 and G3 closer together */
for (row = 0; row < 2; row++)
{
mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1];
blk[row] = cblack[FC(row, 0) | 1];
}
for (i = 0; i < 4; i++)
window[i] = (ushort *)fimg + width * i;
for (wlast = -1, row = 1; row < height - 1; row++)
{
while (wlast < row + 1)
{
for (wlast++, i = 0; i < 4; i++)
window[(i + 3) & 3] = window[i];
for (col = FC(wlast, 1) & 1; col < width; col += 2)
window[2][col] = BAYER(wlast, col);
}
thold = threshold / 512;
for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2)
{
avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) *
mul[row & 1] +
(window[1][col] + blk[row & 1]) * 0.5;
avg = avg < 0 ? 0 : sqrt(avg);
diff = sqrt((double)BAYER(row, col)) - avg;
if (diff < -thold)
diff += thold;
else if (diff > thold)
diff -= thold;
else
diff = 0;
BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5);
}
}
}
free(fimg);
}
#endif
// green equilibration
void CLASS green_matching()
{
int i, j;
double m1, m2, c1, c2;
int o1_1, o1_2, o1_3, o1_4;
int o2_1, o2_2, o2_3, o2_4;
ushort(*img)[4];
const int margin = 3;
int oj = 2, oi = 2;
float f;
const float thr = 0.01f;
if (half_size || shrink)
return;
if (FC(oj, oi) != 3)
oj++;
if (FC(oj, oi) != 3)
oi++;
if (FC(oj, oi) != 3)
oj--;
img = (ushort(*)[4])calloc(height * width, sizeof *image);
merror(img, "green_matching()");
memcpy(img, image, height * width * sizeof *image);
for (j = oj; j < height - margin; j += 2)
for (i = oi; i < width - margin; i += 2)
{
o1_1 = img[(j - 1) * width + i - 1][1];
o1_2 = img[(j - 1) * width + i + 1][1];
o1_3 = img[(j + 1) * width + i - 1][1];
o1_4 = img[(j + 1) * width + i + 1][1];
o2_1 = img[(j - 2) * width + i][3];
o2_2 = img[(j + 2) * width + i][3];
o2_3 = img[j * width + i - 2][3];
o2_4 = img[j * width + i + 2][3];
m1 = (o1_1 + o1_2 + o1_3 + o1_4) / 4.0;
m2 = (o2_1 + o2_2 + o2_3 + o2_4) / 4.0;
c1 = (abs(o1_1 - o1_2) + abs(o1_1 - o1_3) + abs(o1_1 - o1_4) + abs(o1_2 - o1_3) + abs(o1_3 - o1_4) +
abs(o1_2 - o1_4)) /
6.0;
c2 = (abs(o2_1 - o2_2) + abs(o2_1 - o2_3) + abs(o2_1 - o2_4) + abs(o2_2 - o2_3) + abs(o2_3 - o2_4) +
abs(o2_2 - o2_4)) /
6.0;
if ((img[j * width + i][3] < maximum * 0.95) && (c1 < maximum * thr) && (c2 < maximum * thr))
{
f = image[j * width + i][3] * m1 / m2;
image[j * width + i][3] = f > 0xffff ? 0xffff : f;
}
}
free(img);
}
void CLASS scale_colors()
{
unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8];
int val, dark, sat;
double dsum[8], dmin, dmax;
float scale_mul[4], fr, fc;
ushort *img = 0, *pix;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 0, 2);
#endif
if (user_mul[0])
memcpy(pre_mul, user_mul, sizeof pre_mul);
if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1))
{
memset(dsum, 0, sizeof dsum);
bottom = MIN(greybox[1] + greybox[3], height);
right = MIN(greybox[0] + greybox[2], width);
for (row = greybox[1]; row < bottom; row += 8)
for (col = greybox[0]; col < right; col += 8)
{
memset(sum, 0, sizeof sum);
for (y = row; y < row + 8 && y < bottom; y++)
for (x = col; x < col + 8 && x < right; x++)
FORC4
{
if (filters)
{
c = fcol(y, x);
val = BAYER2(y, x);
}
else
val = image[y * width + x][c];
if (val > maximum - 25)
goto skip_block;
if ((val -= cblack[c]) < 0)
val = 0;
sum[c] += val;
sum[c + 4]++;
if (filters)
break;
}
FORC(8) dsum[c] += sum[c];
skip_block:;
}
FORC4 if (dsum[c]) pre_mul[c] = dsum[c + 4] / dsum[c];
}
if (use_camera_wb && cam_mul[0] != -1)
{
memset(sum, 0, sizeof sum);
for (row = 0; row < 8; row++)
for (col = 0; col < 8; col++)
{
c = FC(row, col);
if ((val = white[row][col] - cblack[c]) > 0)
sum[c] += val;
sum[c + 4]++;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (load_raw == &LibRaw::nikon_load_sraw)
{
// Nikon sRAW: camera WB already applied:
pre_mul[0] = pre_mul[1] = pre_mul[2] = pre_mul[3] = 1.0;
}
else
#endif
if (sum[0] && sum[1] && sum[2] && sum[3])
FORC4 pre_mul[c] = (float)sum[c + 4] / sum[c];
else if (cam_mul[0] && cam_mul[2])
memcpy(pre_mul, cam_mul, sizeof pre_mul);
else
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB;
#endif
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: Cannot use camera white balance.\n"), ifname);
#endif
}
}
#ifdef LIBRAW_LIBRARY_BUILD
// Nikon sRAW, daylight
if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f &&
cam_mul[1] > 0.001f && cam_mul[2] > 0.001f)
{
for (c = 0; c < 3; c++)
pre_mul[c] /= cam_mul[c];
}
#endif
if (pre_mul[1] == 0)
pre_mul[1] = 1;
if (pre_mul[3] == 0)
pre_mul[3] = colors < 4 ? pre_mul[1] : 1;
dark = black;
sat = maximum;
if (threshold)
wavelet_denoise();
maximum -= black;
for (dmin = DBL_MAX, dmax = c = 0; c < 4; c++)
{
if (dmin > pre_mul[c])
dmin = pre_mul[c];
if (dmax < pre_mul[c])
dmax = pre_mul[c];
}
if (!highlight)
dmax = dmin;
FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum;
#ifdef DCRAW_VERBOSE
if (verbose)
{
fprintf(stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat);
FORC4 fprintf(stderr, " %f", pre_mul[c]);
fputc('\n', stderr);
}
#endif
if (filters > 1000 && (cblack[4] + 1) / 2 == 1 && (cblack[5] + 1) / 2 == 1)
{
FORC4 cblack[FC(c / 2, c % 2)] += cblack[6 + c / 2 % cblack[4] * cblack[5] + c % 2 % cblack[5]];
cblack[4] = cblack[5] = 0;
}
size = iheight * iwidth;
#ifdef LIBRAW_LIBRARY_BUILD
scale_colors_loop(scale_mul);
#else
for (i = 0; i < size * 4; i++)
{
if (!(val = ((ushort *)image)[i]))
continue;
if (cblack[4] && cblack[5])
val -= cblack[6 + i / 4 / iwidth % cblack[4] * cblack[5] + i / 4 % iwidth % cblack[5]];
val -= cblack[i & 3];
val *= scale_mul[i & 3];
((ushort *)image)[i] = CLIP(val);
}
#endif
if ((aber[0] != 1 || aber[2] != 1) && colors == 3)
{
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Correcting chromatic aberration...\n"));
#endif
for (c = 0; c < 4; c += 2)
{
if (aber[c] == 1)
continue;
img = (ushort *)malloc(size * sizeof *img);
merror(img, "scale_colors()");
for (i = 0; i < size; i++)
img[i] = image[i][c];
for (row = 0; row < iheight; row++)
{
ur = fr = (row - iheight * 0.5) * aber[c] + iheight * 0.5;
if (ur > iheight - 2)
continue;
fr -= ur;
for (col = 0; col < iwidth; col++)
{
uc = fc = (col - iwidth * 0.5) * aber[c] + iwidth * 0.5;
if (uc > iwidth - 2)
continue;
fc -= uc;
pix = img + ur * iwidth + uc;
image[row * iwidth + col][c] =
(pix[0] * (1 - fc) + pix[1] * fc) * (1 - fr) + (pix[iwidth] * (1 - fc) + pix[iwidth + 1] * fc) * fr;
}
}
free(img);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 1, 2);
#endif
}
void CLASS pre_interpolate()
{
ushort(*img)[4];
int row, col, c;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 0, 2);
#endif
if (shrink)
{
if (half_size)
{
height = iheight;
width = iwidth;
if (filters == 9)
{
for (row = 0; row < 3; row++)
for (col = 1; col < 4; col++)
if (!(image[row * width + col][0] | image[row * width + col][2]))
goto break2;
break2:
for (; row < height; row += 3)
for (col = (col - 1) % 3 + 1; col < width - 1; col += 3)
{
img = image + row * width + col;
for (c = 0; c < 3; c += 2)
img[0][c] = (img[-1][c] + img[1][c]) >> 1;
}
}
}
else
{
img = (ushort(*)[4])calloc(height, width * sizeof *img);
merror(img, "pre_interpolate()");
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
{
c = fcol(row, col);
img[row * width + col][c] = image[(row >> 1) * iwidth + (col >> 1)][c];
}
free(image);
image = img;
shrink = 0;
}
}
if (filters > 1000 && colors == 3)
{
mix_green = four_color_rgb ^ half_size;
if (four_color_rgb | half_size)
colors++;
else
{
for (row = FC(1, 0) >> 1; row < height; row += 2)
for (col = FC(row, 1) & 1; col < width; col += 2)
image[row * width + col][1] = image[row * width + col][3];
filters &= ~((filters & 0x55555555) << 1);
}
}
if (half_size)
filters = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 1, 2);
#endif
}
void CLASS border_interpolate(int border)
{
unsigned row, col, y, x, f, c, sum[8];
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
{
if (col == border && row >= border && row < height - border)
col = width - border;
memset(sum, 0, sizeof sum);
for (y = row - 1; y != row + 2; y++)
for (x = col - 1; x != col + 2; x++)
if (y < height && x < width)
{
f = fcol(y, x);
sum[f] += image[y * width + x][f];
sum[f + 4]++;
}
f = fcol(row, col);
FORCC if (c != f && sum[c + 4]) image[row * width + col][c] = sum[c] / sum[c + 4];
}
}
void CLASS lin_interpolate_loop(int code[16][16][32], int size)
{
int row;
for (row = 1; row < height - 1; row++)
{
int col, *ip;
ushort *pix;
for (col = 1; col < width - 1; col++)
{
int i;
int sum[4];
pix = image[row * width + col];
ip = code[row % size][col % size];
memset(sum, 0, sizeof sum);
for (i = *ip++; i--; ip += 3)
sum[ip[2]] += pix[ip[0]] << ip[1];
for (i = colors; --i; ip += 2)
pix[ip[0]] = sum[ip[0]] * ip[1] >> 8;
}
}
}
void CLASS lin_interpolate()
{
int code[16][16][32], size = 16, *ip, sum[4];
int f, c, x, y, row, col, shift, color;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Bilinear interpolation...\n"));
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3);
#endif
if (filters == 9)
size = 6;
border_interpolate(1);
for (row = 0; row < size; row++)
for (col = 0; col < size; col++)
{
ip = code[row][col] + 1;
f = fcol(row, col);
memset(sum, 0, sizeof sum);
for (y = -1; y <= 1; y++)
for (x = -1; x <= 1; x++)
{
shift = (y == 0) + (x == 0);
color = fcol(row + y, col + x);
if (color == f)
continue;
*ip++ = (width * y + x) * 4 + color;
*ip++ = shift;
*ip++ = color;
sum[color] += 1 << shift;
}
code[row][col][0] = (ip - code[row][col]) / 3;
FORCC
if (c != f)
{
*ip++ = c;
*ip++ = sum[c] > 0 ? 256 / sum[c] : 0;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3);
#endif
lin_interpolate_loop(code, size);
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3);
#endif
}
/*
This algorithm is officially called:
"Interpolation using a Threshold-based variable number of gradients"
described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html
I've extended the basic idea to work with non-Bayer filter arrays.
Gradients are numbered clockwise from NW=0 to W=7.
*/
void CLASS vng_interpolate()
{
static const signed char *cp,
terms[] = {-2, -2, +0, -1, 0, 0x01, -2, -2, +0, +0, 1, 0x01, -2, -1, -1, +0, 0, 0x01, -2, -1, +0, -1, 0, 0x02,
-2, -1, +0, +0, 0, 0x03, -2, -1, +0, +1, 1, 0x01, -2, +0, +0, -1, 0, 0x06, -2, +0, +0, +0, 1, 0x02,
-2, +0, +0, +1, 0, 0x03, -2, +1, -1, +0, 0, 0x04, -2, +1, +0, -1, 1, 0x04, -2, +1, +0, +0, 0, 0x06,
-2, +1, +0, +1, 0, 0x02, -2, +2, +0, +0, 1, 0x04, -2, +2, +0, +1, 0, 0x04, -1, -2, -1, +0, 0, -128,
-1, -2, +0, -1, 0, 0x01, -1, -2, +1, -1, 0, 0x01, -1, -2, +1, +0, 1, 0x01, -1, -1, -1, +1, 0, -120,
-1, -1, +1, -2, 0, 0x40, -1, -1, +1, -1, 0, 0x22, -1, -1, +1, +0, 0, 0x33, -1, -1, +1, +1, 1, 0x11,
-1, +0, -1, +2, 0, 0x08, -1, +0, +0, -1, 0, 0x44, -1, +0, +0, +1, 0, 0x11, -1, +0, +1, -2, 1, 0x40,
-1, +0, +1, -1, 0, 0x66, -1, +0, +1, +0, 1, 0x22, -1, +0, +1, +1, 0, 0x33, -1, +0, +1, +2, 1, 0x10,
-1, +1, +1, -1, 1, 0x44, -1, +1, +1, +0, 0, 0x66, -1, +1, +1, +1, 0, 0x22, -1, +1, +1, +2, 0, 0x10,
-1, +2, +0, +1, 0, 0x04, -1, +2, +1, +0, 1, 0x04, -1, +2, +1, +1, 0, 0x04, +0, -2, +0, +0, 1, -128,
+0, -1, +0, +1, 1, -120, +0, -1, +1, -2, 0, 0x40, +0, -1, +1, +0, 0, 0x11, +0, -1, +2, -2, 0, 0x40,
+0, -1, +2, -1, 0, 0x20, +0, -1, +2, +0, 0, 0x30, +0, -1, +2, +1, 1, 0x10, +0, +0, +0, +2, 1, 0x08,
+0, +0, +2, -2, 1, 0x40, +0, +0, +2, -1, 0, 0x60, +0, +0, +2, +0, 1, 0x20, +0, +0, +2, +1, 0, 0x30,
+0, +0, +2, +2, 1, 0x10, +0, +1, +1, +0, 0, 0x44, +0, +1, +1, +2, 0, 0x10, +0, +1, +2, -1, 1, 0x40,
+0, +1, +2, +0, 0, 0x60, +0, +1, +2, +1, 0, 0x20, +0, +1, +2, +2, 0, 0x10, +1, -2, +1, +0, 0, -128,
+1, -1, +1, +1, 0, -120, +1, +0, +1, +2, 0, 0x08, +1, +0, +2, -1, 0, 0x40, +1, +0, +2, +1, 0, 0x10},
chood[] = {-1, -1, -1, 0, -1, +1, 0, +1, +1, +1, +1, 0, +1, -1, 0, -1};
ushort(*brow[5])[4], *pix;
int prow = 8, pcol = 2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4];
int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag;
int g, diff, thold, num, c;
lin_interpolate();
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("VNG interpolation...\n"));
#endif
if (filters == 1)
prow = pcol = 16;
if (filters == 9)
prow = pcol = 6;
ip = (int *)calloc(prow * pcol, 1280);
merror(ip, "vng_interpolate()");
for (row = 0; row < prow; row++) /* Precalculate for VNG */
for (col = 0; col < pcol; col++)
{
code[row][col] = ip;
for (cp = terms, t = 0; t < 64; t++)
{
y1 = *cp++;
x1 = *cp++;
y2 = *cp++;
x2 = *cp++;
weight = *cp++;
grads = *cp++;
color = fcol(row + y1, col + x1);
if (fcol(row + y2, col + x2) != color)
continue;
diag = (fcol(row, col + 1) == color && fcol(row + 1, col) == color) ? 2 : 1;
if (abs(y1 - y2) == diag && abs(x1 - x2) == diag)
continue;
*ip++ = (y1 * width + x1) * 4 + color;
*ip++ = (y2 * width + x2) * 4 + color;
*ip++ = weight;
for (g = 0; g < 8; g++)
if (grads & 1 << g)
*ip++ = g;
*ip++ = -1;
}
*ip++ = INT_MAX;
for (cp = chood, g = 0; g < 8; g++)
{
y = *cp++;
x = *cp++;
*ip++ = (y * width + x) * 4;
color = fcol(row, col);
if (fcol(row + y, col + x) != color && fcol(row + y * 2, col + x * 2) == color)
*ip++ = (y * width + x) * 8 + color;
else
*ip++ = 0;
}
}
brow[4] = (ushort(*)[4])calloc(width * 3, sizeof **brow);
merror(brow[4], "vng_interpolate()");
for (row = 0; row < 3; row++)
brow[row] = brow[4] + row * width;
for (row = 2; row < height - 2; row++)
{ /* Do VNG interpolation */
#ifdef LIBRAW_LIBRARY_BUILD
if (!((row - 2) % 256))
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, (row - 2) / 256 + 1, ((height - 3) / 256) + 1);
#endif
for (col = 2; col < width - 2; col++)
{
pix = image[row * width + col];
ip = code[row % prow][col % pcol];
memset(gval, 0, sizeof gval);
while ((g = ip[0]) != INT_MAX)
{ /* Calculate gradients */
diff = ABS(pix[g] - pix[ip[1]]) << ip[2];
gval[ip[3]] += diff;
ip += 5;
if ((g = ip[-1]) == -1)
continue;
gval[g] += diff;
while ((g = *ip++) != -1)
gval[g] += diff;
}
ip++;
gmin = gmax = gval[0]; /* Choose a threshold */
for (g = 1; g < 8; g++)
{
if (gmin > gval[g])
gmin = gval[g];
if (gmax < gval[g])
gmax = gval[g];
}
if (gmax == 0)
{
memcpy(brow[2][col], pix, sizeof *image);
continue;
}
thold = gmin + (gmax >> 1);
memset(sum, 0, sizeof sum);
color = fcol(row, col);
for (num = g = 0; g < 8; g++, ip += 2)
{ /* Average the neighbors */
if (gval[g] <= thold)
{
FORCC
if (c == color && ip[1])
sum[c] += (pix[c] + pix[ip[1]]) >> 1;
else
sum[c] += pix[ip[0] + c];
num++;
}
}
FORCC
{ /* Save to buffer */
t = pix[color];
if (c != color)
t += (sum[c] - sum[color]) / num;
brow[2][col][c] = CLIP(t);
}
}
if (row > 3) /* Write buffer to image */
memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image);
for (g = 0; g < 4; g++)
brow[(g - 1) & 3] = brow[g];
}
memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image);
memcpy(image[(row - 1) * width + 2], brow[1] + 2, (width - 4) * sizeof *image);
free(brow[4]);
free(code[0][0]);
}
/*
Patterned Pixel Grouping Interpolation by Alain Desbiolles
*/
void CLASS ppg_interpolate()
{
int dir[5] = {1, width, -1, -width, 1};
int row, col, diff[2], guess[2], c, d, i;
ushort(*pix)[4];
border_interpolate(3);
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("PPG interpolation...\n"));
#endif
/* Fill in the green layer with gradients and pattern recognition: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row = 3; row < height - 3; row++)
for (col = 3 + (FC(row, 3) & 1), c = FC(row, col); col < width - 3; col += 2)
{
pix = image + row * width + col;
for (i = 0; (d = dir[i]) > 0; i++)
{
guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2 * d][c] - pix[2 * d][c];
diff[i] = (ABS(pix[-2 * d][c] - pix[0][c]) + ABS(pix[2 * d][c] - pix[0][c]) + ABS(pix[-d][1] - pix[d][1])) * 3 +
(ABS(pix[3 * d][1] - pix[d][1]) + ABS(pix[-3 * d][1] - pix[-d][1])) * 2;
}
d = dir[i = diff[0] > diff[1]];
pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]);
}
/* Calculate red and blue for each green pixel: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row = 1; row < height - 1; row++)
for (col = 1 + (FC(row, 2) & 1), c = FC(row, col + 1); col < width - 1; col += 2)
{
pix = image + row * width + col;
for (i = 0; (d = dir[i]) > 0; c = 2 - c, i++)
pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]) >> 1);
}
/* Calculate blue for red pixels and vice versa: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row = 1; row < height - 1; row++)
for (col = 1 + (FC(row, 1) & 1), c = 2 - FC(row, col); col < width - 1; col += 2)
{
pix = image + row * width + col;
for (i = 0; (d = dir[i] + dir[i + 1]) > 0; i++)
{
diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[d][1] - pix[0][1]);
guess[i] = pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1];
}
if (diff[0] != diff[1])
pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1);
else
pix[0][c] = CLIP((guess[0] + guess[1]) >> 2);
}
}
void CLASS cielab(ushort rgb[3], short lab[3])
{
int c, i, j, k;
float r, xyz[3];
#ifdef LIBRAW_NOTHREADS
static float cbrt[0x10000], xyz_cam[3][4];
#else
#define cbrt tls->ahd_data.cbrt
#define xyz_cam tls->ahd_data.xyz_cam
#endif
if (!rgb)
{
#ifndef LIBRAW_NOTHREADS
if (cbrt[0] < -1.0f)
#endif
for (i = 0; i < 0x10000; i++)
{
r = i / 65535.0;
cbrt[i] = r > 0.008856 ? pow(r, 1.f / 3.0f) : 7.787f * r + 16.f / 116.0f;
}
for (i = 0; i < 3; i++)
for (j = 0; j < colors; j++)
for (xyz_cam[i][j] = k = 0; k < 3; k++)
xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i];
return;
}
xyz[0] = xyz[1] = xyz[2] = 0.5;
FORCC
{
xyz[0] += xyz_cam[0][c] * rgb[c];
xyz[1] += xyz_cam[1][c] * rgb[c];
xyz[2] += xyz_cam[2][c] * rgb[c];
}
xyz[0] = cbrt[CLIP((int)xyz[0])];
xyz[1] = cbrt[CLIP((int)xyz[1])];
xyz[2] = cbrt[CLIP((int)xyz[2])];
lab[0] = 64 * (116 * xyz[1] - 16);
lab[1] = 64 * 500 * (xyz[0] - xyz[1]);
lab[2] = 64 * 200 * (xyz[1] - xyz[2]);
#ifndef LIBRAW_NOTHREADS
#undef cbrt
#undef xyz_cam
#endif
}
#define TS 512 /* Tile Size */
#define fcol(row, col) xtrans[(row + 6) % 6][(col + 6) % 6]
/*
Frank Markesteijn's algorithm for Fuji X-Trans sensors
*/
void CLASS xtrans_interpolate(int passes)
{
int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol;
#ifdef LIBRAW_LIBRARY_BUILD
int cstat[4]={0,0,0,0};
#endif
int val, ndir, pass, hm[8], avg[4], color[3][8];
static const short orth[12] = {1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1},
patt[2][16] = {{0, 1, 0, -1, 2, 0, -1, 0, 1, 1, 1, -1, 0, 0, 0, 0},
{0, 1, 0, -2, 1, 0, -2, 0, 1, 1, -2, -2, 1, -1, -1, 1}},
dir[4] = {1, TS, TS + 1, TS - 1};
short allhex[3][3][2][8], *hex;
ushort min, max, sgrow, sgcol;
ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4];
short(*lab)[TS][3], (*lix)[3];
float(*drv)[TS][TS], diff[6], tr;
char(*homo)[TS][TS], *buffer;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("%d-pass X-Trans interpolation...\n"), passes);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
/* Check against right pattern */
for (row = 0; row < 6; row++)
for (col = 0; col < 6; col++)
cstat[fcol(row,col)]++;
if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16
|| cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
cielab(0, 0);
ndir = 4 << (passes > 1);
buffer = (char *)malloc(TS * TS * (ndir * 11 + 6));
merror(buffer, "xtrans_interpolate()");
rgb = (ushort(*)[TS][TS][3])buffer;
lab = (short(*)[TS][3])(buffer + TS * TS * (ndir * 6));
drv = (float(*)[TS][TS])(buffer + TS * TS * (ndir * 6 + 6));
homo = (char(*)[TS][TS])(buffer + TS * TS * (ndir * 10 + 6));
/* Map a green hexagon around each non-green pixel and vice versa: */
for (row = 0; row < 3; row++)
for (col = 0; col < 3; col++)
for (ng = d = 0; d < 10; d += 2)
{
g = fcol(row, col) == 1;
if (fcol(row + orth[d], col + orth[d + 2]) == 1)
ng = 0;
else
ng++;
if (ng == 4)
{
sgrow = row;
sgcol = col;
}
if (ng == g + 1)
FORC(8)
{
v = orth[d] * patt[g][c * 2] + orth[d + 1] * patt[g][c * 2 + 1];
h = orth[d + 2] * patt[g][c * 2] + orth[d + 3] * patt[g][c * 2 + 1];
allhex[row][col][0][c ^ (g * 2 & d)] = h + v * width;
allhex[row][col][1][c ^ (g * 2 & d)] = h + v * TS;
}
}
/* Set green1 and green3 to the minimum and maximum allowed values: */
for (row = 2; row < height - 2; row++)
for (min = ~(max = 0), col = 2; col < width - 2; col++)
{
if (fcol(row, col) == 1 && (min = ~(max = 0)))
continue;
pix = image + row * width + col;
hex = allhex[row % 3][col % 3][0];
if (!max)
FORC(6)
{
val = pix[hex[c]][1];
if (min > val)
min = val;
if (max < val)
max = val;
}
pix[0][1] = min;
pix[0][3] = max;
switch ((row - sgrow) % 3)
{
case 1:
if (row < height - 3)
{
row++;
col--;
}
break;
case 2:
if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2)
row--;
}
}
for (top = 3; top < height - 19; top += TS - 16)
for (left = 3; left < width - 19; left += TS - 16)
{
mrow = MIN(top + TS, height - 3);
mcol = MIN(left + TS, width - 3);
for (row = top; row < mrow; row++)
for (col = left; col < mcol; col++)
memcpy(rgb[0][row - top][col - left], image[row * width + col], 6);
FORC3 memcpy(rgb[c + 1], rgb[0], sizeof *rgb);
/* Interpolate green horizontally, vertically, and along both diagonals: */
for (row = top; row < mrow; row++)
for (col = left; col < mcol; col++)
{
if ((f = fcol(row, col)) == 1)
continue;
pix = image + row * width + col;
hex = allhex[row % 3][col % 3][0];
color[1][0] = 174 * (pix[hex[1]][1] + pix[hex[0]][1]) - 46 * (pix[2 * hex[1]][1] + pix[2 * hex[0]][1]);
color[1][1] = 223 * pix[hex[3]][1] + pix[hex[2]][1] * 33 + 92 * (pix[0][f] - pix[-hex[2]][f]);
FORC(2)
color[1][2 + c] = 164 * pix[hex[4 + c]][1] + 92 * pix[-2 * hex[4 + c]][1] +
33 * (2 * pix[0][f] - pix[3 * hex[4 + c]][f] - pix[-3 * hex[4 + c]][f]);
FORC4 rgb[c ^ !((row - sgrow) % 3)][row - top][col - left][1] = LIM(color[1][c] >> 8, pix[0][1], pix[0][3]);
}
for (pass = 0; pass < passes; pass++)
{
if (pass == 1)
memcpy(rgb += 4, buffer, 4 * sizeof *rgb);
/* Recalculate green from interpolated values of closer pixels: */
if (pass)
{
for (row = top + 2; row < mrow - 2; row++)
for (col = left + 2; col < mcol - 2; col++)
{
if ((f = fcol(row, col)) == 1)
continue;
pix = image + row * width + col;
hex = allhex[row % 3][col % 3][1];
for (d = 3; d < 6; d++)
{
rix = &rgb[(d - 2) ^ !((row - sgrow) % 3)][row - top][col - left];
val =
rix[-2 * hex[d]][1] + 2 * rix[hex[d]][1] - rix[-2 * hex[d]][f] - 2 * rix[hex[d]][f] + 3 * rix[0][f];
rix[0][1] = LIM(val / 3, pix[0][1], pix[0][3]);
}
}
}
/* Interpolate red and blue values for solitary green pixels: */
for (row = (top - sgrow + 4) / 3 * 3 + sgrow; row < mrow - 2; row += 3)
for (col = (left - sgcol + 4) / 3 * 3 + sgcol; col < mcol - 2; col += 3)
{
rix = &rgb[0][row - top][col - left];
h = fcol(row, col + 1);
memset(diff, 0, sizeof diff);
for (i = 1, d = 0; d < 6; d++, i ^= TS ^ 1, h ^= 2)
{
for (c = 0; c < 2; c++, h ^= 2)
{
g = 2 * rix[0][1] - rix[i << c][1] - rix[-i << c][1];
color[h][d] = g + rix[i << c][h] + rix[-i << c][h];
if (d > 1)
diff[d] += SQR(rix[i << c][1] - rix[-i << c][1] - rix[i << c][h] + rix[-i << c][h]) + SQR(g);
}
if (d > 1 && (d & 1))
if (diff[d - 1] < diff[d])
FORC(2) color[c * 2][d] = color[c * 2][d - 1];
if (d < 2 || (d & 1))
{
FORC(2) rix[0][c * 2] = CLIP(color[c * 2][d] / 2);
rix += TS * TS;
}
}
}
/* Interpolate red for blue pixels and vice versa: */
for (row = top + 3; row < mrow - 3; row++)
for (col = left + 3; col < mcol - 3; col++)
{
if ((f = 2 - fcol(row, col)) == 1)
continue;
rix = &rgb[0][row - top][col - left];
c = (row - sgrow) % 3 ? TS : 1;
h = 3 * (c ^ TS ^ 1);
for (d = 0; d < 4; d++, rix += TS * TS)
{
i = d > 1 || ((d ^ c) & 1) ||
((ABS(rix[0][1] - rix[c][1]) + ABS(rix[0][1] - rix[-c][1])) <
2 * (ABS(rix[0][1] - rix[h][1]) + ABS(rix[0][1] - rix[-h][1])))
? c
: h;
rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2 * rix[0][1] - rix[i][1] - rix[-i][1]) / 2);
}
}
/* Fill in red and blue for 2x2 blocks of green: */
for (row = top + 2; row < mrow - 2; row++)
if ((row - sgrow) % 3)
for (col = left + 2; col < mcol - 2; col++)
if ((col - sgcol) % 3)
{
rix = &rgb[0][row - top][col - left];
hex = allhex[row % 3][col % 3][1];
for (d = 0; d < ndir; d += 2, rix += TS * TS)
if (hex[d] + hex[d + 1])
{
g = 3 * rix[0][1] - 2 * rix[hex[d]][1] - rix[hex[d + 1]][1];
for (c = 0; c < 4; c += 2)
rix[0][c] = CLIP((g + 2 * rix[hex[d]][c] + rix[hex[d + 1]][c]) / 3);
}
else
{
g = 2 * rix[0][1] - rix[hex[d]][1] - rix[hex[d + 1]][1];
for (c = 0; c < 4; c += 2)
rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d + 1]][c]) / 2);
}
}
}
rgb = (ushort(*)[TS][TS][3])buffer;
mrow -= top;
mcol -= left;
/* Convert to CIELab and differentiate in all directions: */
for (d = 0; d < ndir; d++)
{
for (row = 2; row < mrow - 2; row++)
for (col = 2; col < mcol - 2; col++)
cielab(rgb[d][row][col], lab[row][col]);
for (f = dir[d & 3], row = 3; row < mrow - 3; row++)
for (col = 3; col < mcol - 3; col++)
{
lix = &lab[row][col];
g = 2 * lix[0][0] - lix[f][0] - lix[-f][0];
drv[d][row][col] = SQR(g) + SQR((2 * lix[0][1] - lix[f][1] - lix[-f][1] + g * 500 / 232)) +
SQR((2 * lix[0][2] - lix[f][2] - lix[-f][2] - g * 500 / 580));
}
}
/* Build homogeneity maps from the derivatives: */
memset(homo, 0, ndir * TS * TS);
for (row = 4; row < mrow - 4; row++)
for (col = 4; col < mcol - 4; col++)
{
for (tr = FLT_MAX, d = 0; d < ndir; d++)
if (tr > drv[d][row][col])
tr = drv[d][row][col];
tr *= 8;
for (d = 0; d < ndir; d++)
for (v = -1; v <= 1; v++)
for (h = -1; h <= 1; h++)
if (drv[d][row + v][col + h] <= tr)
homo[d][row][col]++;
}
/* Average the most homogenous pixels for the final result: */
if (height - top < TS + 4)
mrow = height - top + 2;
if (width - left < TS + 4)
mcol = width - left + 2;
for (row = MIN(top, 8); row < mrow - 8; row++)
for (col = MIN(left, 8); col < mcol - 8; col++)
{
for (d = 0; d < ndir; d++)
for (hm[d] = 0, v = -2; v <= 2; v++)
for (h = -2; h <= 2; h++)
hm[d] += homo[d][row + v][col + h];
for (d = 0; d < ndir - 4; d++)
if (hm[d] < hm[d + 4])
hm[d] = 0;
else if (hm[d] > hm[d + 4])
hm[d + 4] = 0;
for (max = hm[0], d = 1; d < ndir; d++)
if (max < hm[d])
max = hm[d];
max -= max >> 3;
memset(avg, 0, sizeof avg);
for (d = 0; d < ndir; d++)
if (hm[d] >= max)
{
FORC3 avg[c] += rgb[d][row][col][c];
avg[3]++;
}
FORC3 image[(row + top) * width + col + left][c] = avg[c] / avg[3];
}
}
free(buffer);
border_interpolate(8);
}
#undef fcol
/*
Adaptive Homogeneity-Directed interpolation is based on
the work of Keigo Hirakawa, Thomas Parks, and Paul Lee.
*/
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3])
{
int row, col;
int c, val;
ushort(*pix)[4];
const int rowlimit = MIN(top + TS, height - 2);
const int collimit = MIN(left + TS, width - 2);
for (row = top; row < rowlimit; row++)
{
col = left + (FC(row, left) & 1);
for (c = FC(row, col); col < collimit; col += 2)
{
pix = image + row * width + col;
val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2;
out_rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]);
val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2;
out_rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]);
}
}
}
void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3],
short (*out_lab)[TS][3])
{
unsigned row, col;
int c, val;
ushort(*pix)[4];
ushort(*rix)[3];
short(*lix)[3];
float xyz[3];
const unsigned num_pix_per_row = 4 * width;
const unsigned rowlimit = MIN(top + TS - 1, height - 3);
const unsigned collimit = MIN(left + TS - 1, width - 3);
ushort *pix_above;
ushort *pix_below;
int t1, t2;
for (row = top + 1; row < rowlimit; row++)
{
pix = image + row * width + left;
rix = &inout_rgb[row - top][0];
lix = &out_lab[row - top][0];
for (col = left + 1; col < collimit; col++)
{
pix++;
pix_above = &pix[0][0] - num_pix_per_row;
pix_below = &pix[0][0] + num_pix_per_row;
rix++;
lix++;
c = 2 - FC(row, col);
if (c == 1)
{
c = FC(row + 1, col);
t1 = 2 - c;
val = pix[0][1] + ((pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1]) >> 1);
rix[0][t1] = CLIP(val);
val = pix[0][1] + ((pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1]) >> 1);
}
else
{
t1 = -4 + c; /* -4+c: pixel of color c to the left */
t2 = 4 + c; /* 4+c: pixel of color c to the right */
val = rix[0][1] + ((pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS - 1][1] -
rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >>
2);
}
rix[0][c] = CLIP(val);
c = FC(row, col);
rix[0][c] = pix[0][c];
cielab(rix[0], lix[0]);
}
}
}
void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3],
short (*out_lab)[TS][TS][3])
{
int direction;
for (direction = 0; direction < 2; direction++)
{
ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]);
}
}
void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3],
char (*out_homogeneity_map)[TS][2])
{
int row, col;
int tr, tc;
int direction;
int i;
short(*lix)[3];
short(*lixs[2])[3];
short *adjacent_lix;
unsigned ldiff[2][4], abdiff[2][4], leps, abeps;
static const int dir[4] = {-1, 1, -TS, TS};
const int rowlimit = MIN(top + TS - 2, height - 4);
const int collimit = MIN(left + TS - 2, width - 4);
int homogeneity;
char(*homogeneity_map_p)[2];
memset(out_homogeneity_map, 0, 2 * TS * TS);
for (row = top + 2; row < rowlimit; row++)
{
tr = row - top;
homogeneity_map_p = &out_homogeneity_map[tr][1];
for (direction = 0; direction < 2; direction++)
{
lixs[direction] = &lab[direction][tr][1];
}
for (col = left + 2; col < collimit; col++)
{
tc = col - left;
homogeneity_map_p++;
for (direction = 0; direction < 2; direction++)
{
lix = ++lixs[direction];
for (i = 0; i < 4; i++)
{
adjacent_lix = lix[dir[i]];
ldiff[direction][i] = ABS(lix[0][0] - adjacent_lix[0]);
abdiff[direction][i] = SQR(lix[0][1] - adjacent_lix[1]) + SQR(lix[0][2] - adjacent_lix[2]);
}
}
leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3]));
abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3]));
for (direction = 0; direction < 2; direction++)
{
homogeneity = 0;
for (i = 0; i < 4; i++)
{
if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps)
{
homogeneity++;
}
}
homogeneity_map_p[0][direction] = homogeneity;
}
}
}
}
void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3],
char (*homogeneity_map)[TS][2])
{
int row, col;
int tr, tc;
int i, j;
int direction;
int hm[2];
int c;
const int rowlimit = MIN(top + TS - 3, height - 5);
const int collimit = MIN(left + TS - 3, width - 5);
ushort(*pix)[4];
ushort(*rix[2])[3];
for (row = top + 3; row < rowlimit; row++)
{
tr = row - top;
pix = &image[row * width + left + 2];
for (direction = 0; direction < 2; direction++)
{
rix[direction] = &rgb[direction][tr][2];
}
for (col = left + 3; col < collimit; col++)
{
tc = col - left;
pix++;
for (direction = 0; direction < 2; direction++)
{
rix[direction]++;
}
for (direction = 0; direction < 2; direction++)
{
hm[direction] = 0;
for (i = tr - 1; i <= tr + 1; i++)
{
for (j = tc - 1; j <= tc + 1; j++)
{
hm[direction] += homogeneity_map[i][j][direction];
}
}
}
if (hm[0] != hm[1])
{
memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort));
}
else
{
FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; }
}
}
}
}
void CLASS ahd_interpolate()
{
int i, j, k, top, left;
float xyz_cam[3][4], r;
char *buffer;
ushort(*rgb)[TS][TS][3];
short(*lab)[TS][TS][3];
char(*homo)[TS][2];
int terminate_flag = 0;
cielab(0, 0);
border_interpolate(5);
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel private(buffer, rgb, lab, homo, top, left, i, j, k) shared(xyz_cam, terminate_flag)
#endif
#endif
{
buffer = (char *)malloc(26 * TS * TS); /* 1664 kB */
merror(buffer, "ahd_interpolate()");
rgb = (ushort(*)[TS][TS][3])buffer;
lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS);
homo = (char(*)[TS][2])(buffer + 24 * TS * TS);
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
#pragma omp for schedule(dynamic)
#endif
#endif
for (top = 2; top < height - 5; top += TS - 6)
{
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
if (0 == omp_get_thread_num())
#endif
if (callbacks.progress_cb)
{
int rr =
(*callbacks.progress_cb)(callbacks.progresscb_data, LIBRAW_PROGRESS_INTERPOLATE, top - 2, height - 7);
if (rr)
terminate_flag = 1;
}
#endif
for (left = 2; !terminate_flag && (left < width - 5); left += TS - 6)
{
ahd_interpolate_green_h_and_v(top, left, rgb);
ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab);
ahd_interpolate_build_homogeneity_map(top, left, lab, homo);
ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo);
}
}
free(buffer);
}
#ifdef LIBRAW_LIBRARY_BUILD
if (terminate_flag)
throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK;
#endif
}
#else
void CLASS ahd_interpolate()
{
int i, j, top, left, row, col, tr, tc, c, d, val, hm[2];
static const int dir[4] = {-1, 1, -TS, TS};
unsigned ldiff[2][4], abdiff[2][4], leps, abeps;
ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4];
short(*lab)[TS][TS][3], (*lix)[3];
char(*homo)[TS][TS], *buffer;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("AHD interpolation...\n"));
#endif
cielab(0, 0);
border_interpolate(5);
buffer = (char *)malloc(26 * TS * TS);
merror(buffer, "ahd_interpolate()");
rgb = (ushort(*)[TS][TS][3])buffer;
lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS);
homo = (char(*)[TS][TS])(buffer + 24 * TS * TS);
for (top = 2; top < height - 5; top += TS - 6)
for (left = 2; left < width - 5; left += TS - 6)
{
/* Interpolate green horizontally and vertically: */
for (row = top; row < top + TS && row < height - 2; row++)
{
col = left + (FC(row, left) & 1);
for (c = FC(row, col); col < left + TS && col < width - 2; col += 2)
{
pix = image + row * width + col;
val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2;
rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]);
val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2;
rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]);
}
}
/* Interpolate red and blue, and convert to CIELab: */
for (d = 0; d < 2; d++)
for (row = top + 1; row < top + TS - 1 && row < height - 3; row++)
for (col = left + 1; col < left + TS - 1 && col < width - 3; col++)
{
pix = image + row * width + col;
rix = &rgb[d][row - top][col - left];
lix = &lab[d][row - top][col - left];
if ((c = 2 - FC(row, col)) == 1)
{
c = FC(row + 1, col);
val = pix[0][1] + ((pix[-1][2 - c] + pix[1][2 - c] - rix[-1][1] - rix[1][1]) >> 1);
rix[0][2 - c] = CLIP(val);
val = pix[0][1] + ((pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1]) >> 1);
}
else
val = rix[0][1] + ((pix[-width - 1][c] + pix[-width + 1][c] + pix[+width - 1][c] + pix[+width + 1][c] -
rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >>
2);
rix[0][c] = CLIP(val);
c = FC(row, col);
rix[0][c] = pix[0][c];
cielab(rix[0], lix[0]);
}
/* Build homogeneity maps from the CIELab images: */
memset(homo, 0, 2 * TS * TS);
for (row = top + 2; row < top + TS - 2 && row < height - 4; row++)
{
tr = row - top;
for (col = left + 2; col < left + TS - 2 && col < width - 4; col++)
{
tc = col - left;
for (d = 0; d < 2; d++)
{
lix = &lab[d][tr][tc];
for (i = 0; i < 4; i++)
{
ldiff[d][i] = ABS(lix[0][0] - lix[dir[i]][0]);
abdiff[d][i] = SQR(lix[0][1] - lix[dir[i]][1]) + SQR(lix[0][2] - lix[dir[i]][2]);
}
}
leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3]));
abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3]));
for (d = 0; d < 2; d++)
for (i = 0; i < 4; i++)
if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps)
homo[d][tr][tc]++;
}
}
/* Combine the most homogenous pixels for the final result: */
for (row = top + 3; row < top + TS - 3 && row < height - 5; row++)
{
tr = row - top;
for (col = left + 3; col < left + TS - 3 && col < width - 5; col++)
{
tc = col - left;
for (d = 0; d < 2; d++)
for (hm[d] = 0, i = tr - 1; i <= tr + 1; i++)
for (j = tc - 1; j <= tc + 1; j++)
hm[d] += homo[d][i][j];
if (hm[0] != hm[1])
FORC3 image[row * width + col][c] = rgb[hm[1] > hm[0]][tr][tc][c];
else
FORC3 image[row * width + col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1;
}
}
}
free(buffer);
}
#endif
#undef TS
void CLASS median_filter()
{
ushort(*pix)[4];
int pass, c, i, j, k, med[9];
static const uchar opt[] = /* Optimal 9-element median search */
{1, 2, 4, 5, 7, 8, 0, 1, 3, 4, 6, 7, 1, 2, 4, 5, 7, 8, 0,
3, 5, 8, 4, 7, 3, 6, 1, 4, 2, 5, 4, 7, 4, 2, 6, 4, 4, 2};
for (pass = 1; pass <= med_passes; pass++)
{
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER, pass - 1, med_passes);
#endif
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Median filter pass %d...\n"), pass);
#endif
for (c = 0; c < 3; c += 2)
{
for (pix = image; pix < image + width * height; pix++)
pix[0][3] = pix[0][c];
for (pix = image + width; pix < image + width * (height - 1); pix++)
{
if ((pix - image + 1) % width < 2)
continue;
for (k = 0, i = -width; i <= width; i += width)
for (j = i - 1; j <= i + 1; j++)
med[k++] = pix[j][3] - pix[j][1];
for (i = 0; i < sizeof opt; i += 2)
if (med[opt[i]] > med[opt[i + 1]])
SWAP(med[opt[i]], med[opt[i + 1]]);
pix[0][c] = CLIP(med[4] + pix[0][1]);
}
}
}
}
void CLASS blend_highlights()
{
int clip = INT_MAX, row, col, c, i, j;
static const float trans[2][4][4] = {{{1, 1, 1}, {1.7320508, -1.7320508, 0}, {-1, -1, 2}},
{{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}};
static const float itrans[2][4][4] = {{{1, 0.8660254, -0.5}, {1, -0.8660254, -0.5}, {1, 0, 1}},
{{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}};
float cam[2][4], lab[2][4], sum[2], chratio;
if ((unsigned)(colors - 3) > 1)
return;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Blending highlights...\n"));
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 0, 2);
#endif
FORCC if (clip > (i = 65535 * pre_mul[c])) clip = i;
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
{
FORCC if (image[row * width + col][c] > clip) break;
if (c == colors)
continue;
FORCC
{
cam[0][c] = image[row * width + col][c];
cam[1][c] = MIN(cam[0][c], clip);
}
for (i = 0; i < 2; i++)
{
FORCC for (lab[i][c] = j = 0; j < colors; j++) lab[i][c] += trans[colors - 3][c][j] * cam[i][j];
for (sum[i] = 0, c = 1; c < colors; c++)
sum[i] += SQR(lab[i][c]);
}
chratio = sqrt(sum[1] / sum[0]);
for (c = 1; c < colors; c++)
lab[0][c] *= chratio;
FORCC for (cam[0][c] = j = 0; j < colors; j++) cam[0][c] += itrans[colors - 3][c][j] * lab[0][j];
FORCC image[row * width + col][c] = cam[0][c] / colors;
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 1, 2);
#endif
}
#define SCALE (4 >> shrink)
void CLASS recover_highlights()
{
float *map, sum, wgt, grow;
int hsat[4], count, spread, change, val, i;
unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x;
ushort *pixel;
static const signed char dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}};
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Rebuilding highlights...\n"));
#endif
grow = pow(2.0, 4 - highlight);
FORCC hsat[c] = 32000 * pre_mul[c];
for (kc = 0, c = 1; c < colors; c++)
if (pre_mul[kc] < pre_mul[c])
kc = c;
high = height / SCALE;
wide = width / SCALE;
map = (float *)calloc(high, wide * sizeof *map);
merror(map, "recover_highlights()");
FORCC if (c != kc)
{
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, c - 1, colors - 1);
#endif
memset(map, 0, high * wide * sizeof *map);
for (mrow = 0; mrow < high; mrow++)
for (mcol = 0; mcol < wide; mcol++)
{
sum = wgt = count = 0;
for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++)
for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++)
{
pixel = image[row * width + col];
if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000)
{
sum += pixel[c];
wgt += pixel[kc];
count++;
}
}
if (count == SCALE * SCALE)
map[mrow * wide + mcol] = sum / wgt;
}
for (spread = 32 / grow; spread--;)
{
for (mrow = 0; mrow < high; mrow++)
for (mcol = 0; mcol < wide; mcol++)
{
if (map[mrow * wide + mcol])
continue;
sum = count = 0;
for (d = 0; d < 8; d++)
{
y = mrow + dir[d][0];
x = mcol + dir[d][1];
if (y < high && x < wide && map[y * wide + x] > 0)
{
sum += (1 + (d & 1)) * map[y * wide + x];
count += 1 + (d & 1);
}
}
if (count > 3)
map[mrow * wide + mcol] = -(sum + grow) / (count + grow);
}
for (change = i = 0; i < high * wide; i++)
if (map[i] < 0)
{
map[i] = -map[i];
change = 1;
}
if (!change)
break;
}
for (i = 0; i < high * wide; i++)
if (map[i] == 0)
map[i] = 1;
for (mrow = 0; mrow < high; mrow++)
for (mcol = 0; mcol < wide; mcol++)
{
for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++)
for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++)
{
pixel = image[row * width + col];
if (pixel[c] / hsat[c] > 1)
{
val = pixel[kc] * map[mrow * wide + mcol];
if (pixel[c] < val)
pixel[c] = CLIP(val);
}
}
}
}
free(map);
}
#undef SCALE
void CLASS tiff_get(unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save)
{
*tag = get2();
*type = get2();
*len = get4();
*save = ftell(ifp) + 4;
if (*len * ("11124811248484"[*type < 14 ? *type : 0] - '0') > 4)
fseek(ifp, get4() + base, SEEK_SET);
}
void CLASS parse_thumb_note(int base, unsigned toff, unsigned tlen)
{
unsigned entries, tag, type, len, save;
entries = get2();
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (tag == toff)
thumb_offset = get4() + base;
if (tag == tlen)
thumb_length = get4();
fseek(ifp, save, SEEK_SET);
}
}
//@end COMMON
int CLASS parse_tiff_ifd(int base);
//@out COMMON
static float powf_lim(float a, float b, float limup) { return (b > limup || b < -limup) ? 0.f : powf(a, b); }
static float powf64(float a, float b) { return powf_lim(a, b, 64.f); }
#ifdef LIBRAW_LIBRARY_BUILD
static float my_roundf(float x)
{
float t;
if (x >= 0.0)
{
t = ceilf(x);
if (t - x > 0.5)
t -= 1.0;
return t;
}
else
{
t = ceilf(-x);
if (t + x > 0.5)
t -= 1.0;
return -t;
}
}
static float _CanonConvertAperture(ushort in)
{
if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff))
return 0.0f;
return powf64(2.0, in / 64.0);
}
static float _CanonConvertEV(short in)
{
short EV, Sign, Frac;
float Frac_f;
EV = in;
if (EV < 0)
{
EV = -EV;
Sign = -1;
}
else
{
Sign = 1;
}
Frac = EV & 0x1f;
EV -= Frac; // remove fraction
if (Frac == 0x0c)
{ // convert 1/3 and 2/3 codes
Frac_f = 32.0f / 3.0f;
}
else if (Frac == 0x14)
{
Frac_f = 64.0f / 3.0f;
}
else
Frac_f = (float)Frac;
return ((float)Sign * ((float)EV + Frac_f)) / 32.0f;
}
unsigned CLASS setCanonBodyFeatures(unsigned id)
{
if (id == 0x03740000) // EOS M3
id = 0x80000374;
else if (id == 0x03840000) // EOS M10
id = 0x80000384;
else if (id == 0x03940000) // EOS M5
id = 0x80000394;
else if (id == 0x04070000) // EOS M6
id = 0x80000407;
else if (id == 0x03980000) // EOS M100
id = 0x80000398;
imgdata.lens.makernotes.CamID = id;
if ((id == 0x80000001) || // 1D
(id == 0x80000174) || // 1D2
(id == 0x80000232) || // 1D2N
(id == 0x80000169) || // 1D3
(id == 0x80000281) // 1D4
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000167) || // 1Ds
(id == 0x80000188) || // 1Ds2
(id == 0x80000215) || // 1Ds3
(id == 0x80000269) || // 1DX
(id == 0x80000328) || // 1DX2
(id == 0x80000324) || // 1DC
(id == 0x80000213) || // 5D
(id == 0x80000218) || // 5D2
(id == 0x80000285) || // 5D3
(id == 0x80000349) || // 5D4
(id == 0x80000382) || // 5DS
(id == 0x80000401) || // 5DS R
(id == 0x80000302) // 6D
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000331) || // M
(id == 0x80000355) || // M2
(id == 0x80000374) || // M3
(id == 0x80000384) || // M10
(id == 0x80000394) || // M5
(id == 0x80000407) || // M6
(id == 0x80000398) // M100
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M;
}
else if ((id == 0x01140000) || // D30
(id == 0x01668000) || // D60
(id > 0x80000000))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
return id;
}
void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen, unsigned type)
{
ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0,
iCanonFocalType = 0;
if(maxlen<16) return; // too short
CameraInfo[0] = 0;
CameraInfo[1] = 0;
if (type == 4) {
if ((maxlen == 94) ||
(maxlen == 138) ||
(maxlen == 148) ||
(maxlen == 156) ||
(maxlen == 162) ||
(maxlen == 167) ||
(maxlen == 171) ||
(maxlen == 264) ||
(maxlen > 400))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-3)<<2));
else if (maxlen == 72) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-1)<<2));
else if ((maxlen == 85) || (maxlen == 93)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-2)<<2));
else if ((maxlen == 96) || (maxlen == 104)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-4)<<2));
}
switch (id)
{
case 0x80000001: // 1D
case 0x80000167: // 1DS
iCanonCurFocal = 10;
iCanonLensID = 13;
iCanonMinFocal = 14;
iCanonMaxFocal = 16;
if (!imgdata.lens.makernotes.CurFocal)
imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal);
if (!imgdata.lens.makernotes.MinFocal)
imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal);
if (!imgdata.lens.makernotes.MaxFocal)
imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal);
imgdata.other.CameraTemperature = 0.0f;
break;
case 0x80000174: // 1DMkII
case 0x80000188: // 1DsMkII
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
iCanonFocalType = 45;
break;
case 0x80000232: // 1DMkII N
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
break;
case 0x80000169: // 1DMkIII
case 0x80000215: // 1DsMkIII
iCanonCurFocal = 29;
iCanonLensID = 273;
iCanonMinFocal = 275;
iCanonMaxFocal = 277;
break;
case 0x80000281: // 1DMkIV
iCanonCurFocal = 30;
iCanonLensID = 335;
iCanonMinFocal = 337;
iCanonMaxFocal = 339;
break;
case 0x80000269: // 1D X
iCanonCurFocal = 35;
iCanonLensID = 423;
iCanonMinFocal = 425;
iCanonMaxFocal = 427;
break;
case 0x80000213: // 5D
iCanonCurFocal = 40;
if (!sget2Rev(CameraInfo + 12))
iCanonLensID = 151;
else
iCanonLensID = 12;
iCanonMinFocal = 147;
iCanonMaxFocal = 149;
break;
case 0x80000218: // 5DMkII
iCanonCurFocal = 30;
iCanonLensID = 230;
iCanonMinFocal = 232;
iCanonMaxFocal = 234;
break;
case 0x80000285: // 5DMkIII
iCanonCurFocal = 35;
iCanonLensID = 339;
iCanonMinFocal = 341;
iCanonMaxFocal = 343;
break;
case 0x80000302: // 6D
iCanonCurFocal = 35;
iCanonLensID = 353;
iCanonMinFocal = 355;
iCanonMaxFocal = 357;
break;
case 0x80000250: // 7D
iCanonCurFocal = 30;
iCanonLensID = 274;
iCanonMinFocal = 276;
iCanonMaxFocal = 278;
break;
case 0x80000190: // 40D
iCanonCurFocal = 29;
iCanonLensID = 214;
iCanonMinFocal = 216;
iCanonMaxFocal = 218;
iCanonLens = 2347;
break;
case 0x80000261: // 50D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000287: // 60D
iCanonCurFocal = 30;
iCanonLensID = 232;
iCanonMinFocal = 234;
iCanonMaxFocal = 236;
break;
case 0x80000325: // 70D
iCanonCurFocal = 35;
iCanonLensID = 358;
iCanonMinFocal = 360;
iCanonMaxFocal = 362;
break;
case 0x80000176: // 450D
iCanonCurFocal = 29;
iCanonLensID = 222;
iCanonLens = 2355;
break;
case 0x80000252: // 500D
iCanonCurFocal = 30;
iCanonLensID = 246;
iCanonMinFocal = 248;
iCanonMaxFocal = 250;
break;
case 0x80000270: // 550D
iCanonCurFocal = 30;
iCanonLensID = 255;
iCanonMinFocal = 257;
iCanonMaxFocal = 259;
break;
case 0x80000286: // 600D
case 0x80000288: // 1100D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000301: // 650D
case 0x80000326: // 700D
iCanonCurFocal = 35;
iCanonLensID = 295;
iCanonMinFocal = 297;
iCanonMaxFocal = 299;
break;
case 0x80000254: // 1000D
iCanonCurFocal = 29;
iCanonLensID = 226;
iCanonMinFocal = 228;
iCanonMaxFocal = 230;
iCanonLens = 2359;
break;
}
if (iCanonFocalType)
{
if (iCanonFocalType >= maxlen)
return; // broken;
imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType];
if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1'
imgdata.lens.makernotes.FocalType = 1;
}
if (!imgdata.lens.makernotes.CurFocal)
{
if (iCanonCurFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal);
}
if (!imgdata.lens.makernotes.LensID)
{
if (iCanonLensID >= maxlen)
return; // broken;
imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID);
}
if (!imgdata.lens.makernotes.MinFocal)
{
if (iCanonMinFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal);
}
if (!imgdata.lens.makernotes.MaxFocal)
{
if (iCanonMaxFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal);
}
if (!imgdata.lens.makernotes.Lens[0] && iCanonLens)
{
if (iCanonLens + 64 >= maxlen)
return; // broken;
if (CameraInfo[iCanonLens] < 65) // non-Canon lens
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.Lens[2] = 32;
memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62);
}
}
return;
}
void CLASS Canon_CameraSettings()
{
fseek(ifp, 10, SEEK_CUR);
imgdata.shootinginfo.DriveMode = get2();
get2();
imgdata.shootinginfo.FocusMode = get2();
fseek(ifp, 18, SEEK_CUR);
imgdata.shootinginfo.MeteringMode = get2();
get2();
imgdata.shootinginfo.AFPoint = get2();
imgdata.shootinginfo.ExposureMode = get2();
get2();
imgdata.lens.makernotes.LensID = get2();
imgdata.lens.makernotes.MaxFocal = get2();
imgdata.lens.makernotes.MinFocal = get2();
imgdata.lens.makernotes.CanonFocalUnits = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2());
imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2());
fseek(ifp, 12, SEEK_CUR);
imgdata.shootinginfo.ImageStabilization = get2();
}
void CLASS Canon_WBpresets(int skip1, int skip2)
{
int c;
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();
if (skip2)
fseek(ifp, skip2, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();
return;
}
void CLASS Canon_WBCTpresets(short WBCTversion)
{
if (WBCTversion == 0)
for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if (WBCTversion == 1)
for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3
(unique_id == 0x80000384) || // M10
(unique_id == 0x80000394) || // M5
(unique_id == 0x80000407) || // M6
(unique_id == 0x80000398) || // M100
(unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000) || // G9 X Mark II
(unique_id == 0x04180000))) // G1 X Mark III
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
return;
}
void CLASS processNikonLensData(uchar *LensData, unsigned len)
{
ushort i;
if (!(imgdata.lens.nikon.NikonLensType & 0x01))
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'A';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
else
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'M';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
if (imgdata.lens.nikon.NikonLensType & 0x02)
{
if (imgdata.lens.nikon.NikonLensType & 0x04)
imgdata.lens.makernotes.LensFeatures_suf[0] = 'G';
else
imgdata.lens.makernotes.LensFeatures_suf[0] = 'D';
imgdata.lens.makernotes.LensFeatures_suf[1] = ' ';
}
if (imgdata.lens.nikon.NikonLensType & 0x08)
{
imgdata.lens.makernotes.LensFeatures_suf[2] = 'V';
imgdata.lens.makernotes.LensFeatures_suf[3] = 'R';
}
if (imgdata.lens.nikon.NikonLensType & 0x10)
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH;
}
else
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F;
if (imgdata.lens.nikon.NikonLensType & 0x20)
{
strcpy(imgdata.lens.makernotes.Adapter, "FT-1");
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH;
}
imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf;
if (len < 20)
{
switch (len)
{
case 9:
i = 2;
break;
case 15:
i = 7;
break;
case 16:
i = 8;
break;
}
imgdata.lens.nikon.NikonLensIDNumber = LensData[i];
imgdata.lens.nikon.NikonLensFStops = LensData[i + 1];
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f)
{
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2])
imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3])
imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4])
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5])
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f);
}
imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6];
if (i != 2)
{
if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f))
imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f);
if (LensData[i + 7])
imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f);
}
imgdata.lens.makernotes.LensID =
(unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 |
(unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 |
(unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 |
(unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType;
}
else if ((len == 459) || (len == 590))
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64);
}
else if (len == 509)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64);
}
else if (len == 879)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64);
}
return;
}
void CLASS setOlympusBodyFeatures(unsigned long long id)
{
imgdata.lens.makernotes.CamID = id;
if (id == 0x5330303638ULL) {
strcpy (model, "E-M10MarkIII");
}
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-300
((id & 0x00ffff0000ULL) == 0x0030300000ULL))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT;
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-330
((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520
(id == 0x5330303233ULL) || // E-620
(id == 0x5330303239ULL) || // E-450
(id == 0x5330303330ULL) || // E-600
(id == 0x5330303333ULL)) // E-5
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT;
}
}
else
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len)
{
if (tag == 0x0001)
Canon_CameraSettings();
else if (tag == 0x0002) // focal length
{
imgdata.lens.makernotes.FocalType = get2();
imgdata.lens.makernotes.CurFocal = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
}
else if (tag == 0x0004) // shot info
{
short tempAp;
fseek(ifp, 24, SEEK_CUR);
tempAp = get2();
if (tempAp != 0) imgdata.other.CameraTemperature = (float)(tempAp-128);
tempAp = get2();
if (tempAp != -1) imgdata.other.FlashGN = ((float)tempAp) / 32;
get2();
// fseek(ifp, 30, SEEK_CUR);
imgdata.other.FlashEC = _CanonConvertEV((signed short)get2());
fseek(ifp, 8 - 32, SEEK_CUR);
if ((tempAp = get2()) != 0x7fff)
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp);
if (imgdata.lens.makernotes.CurAp < 0.7f)
{
fseek(ifp, 32, SEEK_CUR);
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2());
}
if (!aperture)
aperture = imgdata.lens.makernotes.CurAp;
}
else if (tag == 0x0095 && // lens model tag
!imgdata.lens.makernotes.Lens[0])
{
fread(imgdata.lens.makernotes.Lens, 2, 1, ifp);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens
fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp);
else
{
char efs[2];
imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0];
imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1];
fread(efs, 2, 1, ifp);
if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77))
{ // "EF-S, TS-E, MP-E, EF-M" lenses
imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0];
imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1];
imgdata.lens.makernotes.Lens[4] = 32;
if (efs[1] == 83)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
else if (efs[1] == 77)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
}
}
else
{ // "EF" lenses
imgdata.lens.makernotes.Lens[2] = 32;
imgdata.lens.makernotes.Lens[3] = efs[0];
imgdata.lens.makernotes.Lens[4] = efs[1];
}
fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp);
}
}
else if (tag == 0x00a9)
{
long int save1 = ftell(ifp);
int c;
fseek(ifp, (0x1 << 1), SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
Canon_WBpresets(0, 0);
fseek(ifp, save1, SEEK_SET);
}
else if (tag == 0x00e0) // sensor info
{
imgdata.makernotes.canon.SensorWidth = (get2(), get2());
imgdata.makernotes.canon.SensorHeight = get2();
imgdata.makernotes.canon.SensorLeftBorder = (get2(), get2(), get2());
imgdata.makernotes.canon.SensorTopBorder = get2();
imgdata.makernotes.canon.SensorRightBorder = get2();
imgdata.makernotes.canon.SensorBottomBorder = get2();
imgdata.makernotes.canon.BlackMaskLeftBorder = get2();
imgdata.makernotes.canon.BlackMaskTopBorder = get2();
imgdata.makernotes.canon.BlackMaskRightBorder = get2();
imgdata.makernotes.canon.BlackMaskBottomBorder = get2();
}
else if (tag == 0x4001 && len > 500)
{
int c;
long int save1 = ftell(ifp);
switch (len)
{
case 582:
imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D
{
fseek(ifp, save1 + (0x1e << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x41 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x46 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x23 << 1), SEEK_SET);
Canon_WBpresets(2, 2);
fseek(ifp, save1 + (0x4b << 1), SEEK_SET);
Canon_WBCTpresets(1); // ABCT
}
break;
case 653:
imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2
{
fseek(ifp, save1 + (0x18 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x90 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x95 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x9a << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x27 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xa4 << 1), SEEK_SET);
Canon_WBCTpresets(1); // ABCT
}
break;
case 796:
imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x71 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x76 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x7b << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x80 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x4e << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0x85 << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x0c4 << 1), SEEK_SET); // offset 196 short
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
break;
// 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII
// 7D / 40D / 50D / 60D / 450D / 500D
// 550D / 1000D / 1100D
case 674:
case 692:
case 702:
case 1227:
case 1250:
case 1251:
case 1337:
case 1338:
case 1346:
imgdata.makernotes.canon.CanonColorDataVer = 4;
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x53 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xa8 << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x0e7 << 1), SEEK_SET); // offset 231 short
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5))
{
fseek(ifp, save1 + (0x2b9 << 1), SEEK_SET); // offset 697 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) ||
(imgdata.makernotes.canon.CanonColorDataSubVer == 7))
{
fseek(ifp, save1 + (0x2d0 << 1), SEEK_SET); // offset 720 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9)
{
fseek(ifp, save1 + (0x2d4 << 1), SEEK_SET); // offset 724 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
case 5120:
imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6
{
if ((unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000) || // G9 X Mark II
(unique_id == 0x04180000) || // G1 X Mark III
(unique_id == 0x80000394) || // EOS M5
(unique_id == 0x80000398) || // EOS M100
(unique_id == 0x80000407)) // EOS M6
{
fseek(ifp, save1 + (0x4f << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
Canon_WBpresets(8, 24);
fseek(ifp, 168, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2();
fseek(ifp, 24, SEEK_CUR);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, 6, SEEK_CUR);
}
else
{
fseek(ifp, save1 + (0x4c << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
get2();
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xba << 1), SEEK_SET);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short
}
int bls = 0;
FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
break;
case 1273:
case 1275:
imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x67 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xbc << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
fseek(ifp, save1 + (0x1e4 << 1), SEEK_SET); // offset 484 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
break;
// 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D
case 1312:
case 1313:
case 1316:
case 1506:
imgdata.makernotes.canon.CanonColorDataVer = 7;
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x80 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xd5 << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x114 << 1), SEEK_SET); // offset 276 shorts
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
if (imgdata.makernotes.canon.CanonColorDataSubVer == 10)
{
fseek(ifp, save1 + (0x1fd << 1), SEEK_SET); // offset 509 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11)
{
fseek(ifp, save1 + (0x2dd << 1), SEEK_SET); // offset 733 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
// 5DS / 5DS R / 80D / 1300D / 5D4 / 800D / 77D / 6D II / 200D
case 1560:
case 1592:
case 1353:
case 1602:
imgdata.makernotes.canon.CanonColorDataVer = 8;
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x85 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0x107 << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x146 << 1), SEEK_SET); // offset 326 shorts
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D
{
fseek(ifp, save1 + (0x231 << 1), SEEK_SET);
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else
{
fseek(ifp, save1 + (0x30f << 1), SEEK_SET); // offset 783 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
}
fseek(ifp, save1, SEEK_SET);
}
}
void CLASS setPentaxBodyFeatures(unsigned id)
{
imgdata.lens.makernotes.CamID = id;
switch (id)
{
case 0x12994:
case 0x12aa2:
case 0x12b1a:
case 0x12b60:
case 0x12b62:
case 0x12b7e:
case 0x12b80:
case 0x12b9c:
case 0x12b9d:
case 0x12ba2:
case 0x12c1e:
case 0x12c20:
case 0x12cd2:
case 0x12cd4:
case 0x12cfa:
case 0x12d72:
case 0x12d73:
case 0x12db8:
case 0x12dfe:
case 0x12e6c:
case 0x12e76:
case 0x12ef8:
case 0x12f52:
case 0x12f70:
case 0x12f71:
case 0x12fb6:
case 0x12fc0:
case 0x12fca:
case 0x1301a:
case 0x13024:
case 0x1309c:
case 0x13222:
case 0x1322c:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
break;
case 0x13092:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
break;
case 0x12e08:
case 0x13010:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF;
break;
case 0x12ee4:
case 0x12f66:
case 0x12f7a:
case 0x1302e:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q;
break;
default:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS PentaxISO(ushort c)
{
int code[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261,
262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278};
double value[] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640,
800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000,
12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000,
204800, 258000, 325000, 409600, 516000, 650000, 819200, 50, 100, 200, 400, 800,
1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100,
1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200};
#define numel (sizeof(code) / sizeof(code[0]))
int i;
for (i = 0; i < numel; i++)
{
if (code[i] == c)
{
iso_speed = value[i];
return;
}
}
if (i == numel)
iso_speed = 65535.0f;
}
#undef numel
void CLASS PentaxLensInfo(unsigned id, unsigned len) // tag 0x0207
{
ushort iLensData = 0;
uchar *table_buf;
table_buf = (uchar *)malloc(MAX(len, 128));
fread(table_buf, len, 1, ifp);
if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D
(id == 0x12b9d) || // K110D
(id == 0x12ba2)) && // K100D Super
((!table_buf[20] || (table_buf[20] == 0xff)))))
{
iLensData = 3;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1];
}
else
switch (len)
{
case 90: // LensInfo3
iLensData = 13;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4];
break;
case 91: // LensInfo4
iLensData = 12;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4];
break;
case 80: // LensInfo5
case 128:
iLensData = 15;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) << 8) + table_buf[5];
break;
default:
if (id >= 0x12b9c) // LensInfo2
{
iLensData = 4;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) << 8) + table_buf[3];
}
}
if (iLensData)
{
if (table_buf[iLensData + 9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f))
imgdata.lens.makernotes.CurFocal =
10 * (table_buf[iLensData + 9] >> 2) * powf64(4, (table_buf[iLensData + 9] & 0x03) - 2);
if (table_buf[iLensData + 10] & 0xf0)
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f);
if (table_buf[iLensData + 10] & 0x0f)
imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0x0f) + 10) / 4.0f);
if (iLensData != 12)
{
switch (table_buf[iLensData] & 0x06)
{
case 0:
imgdata.lens.makernotes.MinAp4MinFocal = 22.0f;
break;
case 2:
imgdata.lens.makernotes.MinAp4MinFocal = 32.0f;
break;
case 4:
imgdata.lens.makernotes.MinAp4MinFocal = 45.0f;
break;
case 6:
imgdata.lens.makernotes.MinAp4MinFocal = 16.0f;
break;
}
if (table_buf[iLensData] & 0x70)
imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f;
imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData + 3] & 0xf8);
imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData + 3] & 0x07);
if ((table_buf[iLensData + 14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f))
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 14] & 0x7f) - 1) / 32.0f);
}
else if ((id != 0x12e76) && // K-5
(table_buf[iLensData + 15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f))
{
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 15] & 0x7f) - 1) / 32.0f);
}
}
free(table_buf);
return;
}
void CLASS setPhaseOneFeatures(unsigned id)
{
ushort i;
static const struct
{
ushort id;
char t_model[32];
} p1_unique[] = {
// Phase One section:
{1, "Hasselblad V"},
{10, "PhaseOne/Mamiya"},
{12, "Contax 645"},
{16, "Hasselblad V"},
{17, "Hasselblad V"},
{18, "Contax 645"},
{19, "PhaseOne/Mamiya"},
{20, "Hasselblad V"},
{21, "Contax 645"},
{22, "PhaseOne/Mamiya"},
{23, "Hasselblad V"},
{24, "Hasselblad H"},
{25, "PhaseOne/Mamiya"},
{32, "Contax 645"},
{34, "Hasselblad V"},
{35, "Hasselblad V"},
{36, "Hasselblad H"},
{37, "Contax 645"},
{38, "PhaseOne/Mamiya"},
{39, "Hasselblad V"},
{40, "Hasselblad H"},
{41, "Contax 645"},
{42, "PhaseOne/Mamiya"},
{44, "Hasselblad V"},
{45, "Hasselblad H"},
{46, "Contax 645"},
{47, "PhaseOne/Mamiya"},
{48, "Hasselblad V"},
{49, "Hasselblad H"},
{50, "Contax 645"},
{51, "PhaseOne/Mamiya"},
{52, "Hasselblad V"},
{53, "Hasselblad H"},
{54, "Contax 645"},
{55, "PhaseOne/Mamiya"},
{67, "Hasselblad V"},
{68, "Hasselblad H"},
{69, "Contax 645"},
{70, "PhaseOne/Mamiya"},
{71, "Hasselblad V"},
{72, "Hasselblad H"},
{73, "Contax 645"},
{74, "PhaseOne/Mamiya"},
{76, "Hasselblad V"},
{77, "Hasselblad H"},
{78, "Contax 645"},
{79, "PhaseOne/Mamiya"},
{80, "Hasselblad V"},
{81, "Hasselblad H"},
{82, "Contax 645"},
{83, "PhaseOne/Mamiya"},
{84, "Hasselblad V"},
{85, "Hasselblad H"},
{86, "Contax 645"},
{87, "PhaseOne/Mamiya"},
{99, "Hasselblad V"},
{100, "Hasselblad H"},
{101, "Contax 645"},
{102, "PhaseOne/Mamiya"},
{103, "Hasselblad V"},
{104, "Hasselblad H"},
{105, "PhaseOne/Mamiya"},
{106, "Contax 645"},
{112, "Hasselblad V"},
{113, "Hasselblad H"},
{114, "Contax 645"},
{115, "PhaseOne/Mamiya"},
{131, "Hasselblad V"},
{132, "Hasselblad H"},
{133, "Contax 645"},
{134, "PhaseOne/Mamiya"},
{135, "Hasselblad V"},
{136, "Hasselblad H"},
{137, "Contax 645"},
{138, "PhaseOne/Mamiya"},
{140, "Hasselblad V"},
{141, "Hasselblad H"},
{142, "Contax 645"},
{143, "PhaseOne/Mamiya"},
{148, "Hasselblad V"},
{149, "Hasselblad H"},
{150, "Contax 645"},
{151, "PhaseOne/Mamiya"},
{160, "A-250"},
{161, "A-260"},
{162, "A-280"},
{167, "Hasselblad V"},
{168, "Hasselblad H"},
{169, "Contax 645"},
{170, "PhaseOne/Mamiya"},
{172, "Hasselblad V"},
{173, "Hasselblad H"},
{174, "Contax 645"},
{175, "PhaseOne/Mamiya"},
{176, "Hasselblad V"},
{177, "Hasselblad H"},
{178, "Contax 645"},
{179, "PhaseOne/Mamiya"},
{180, "Hasselblad V"},
{181, "Hasselblad H"},
{182, "Contax 645"},
{183, "PhaseOne/Mamiya"},
{208, "Hasselblad V"},
{211, "PhaseOne/Mamiya"},
{448, "Phase One 645AF"},
{457, "Phase One 645DF"},
{471, "Phase One 645DF+"},
{704, "Phase One iXA"},
{705, "Phase One iXA - R"},
{706, "Phase One iXU 150"},
{707, "Phase One iXU 150 - NIR"},
{708, "Phase One iXU 180"},
{721, "Phase One iXR"},
// Leaf section:
{333, "Mamiya"},
{329, "Universal"},
{330, "Hasselblad H1/H2"},
{332, "Contax"},
{336, "AFi"},
{327, "Mamiya"},
{324, "Universal"},
{325, "Hasselblad H1/H2"},
{326, "Contax"},
{335, "AFi"},
{340, "Mamiya"},
{337, "Universal"},
{338, "Hasselblad H1/H2"},
{339, "Contax"},
{323, "Mamiya"},
{320, "Universal"},
{322, "Hasselblad H1/H2"},
{321, "Contax"},
{334, "AFi"},
{369, "Universal"},
{370, "Mamiya"},
{371, "Hasselblad H1/H2"},
{372, "Contax"},
{373, "Afi"},
};
imgdata.lens.makernotes.CamID = id;
if (id && !imgdata.lens.makernotes.body[0])
{
for (i = 0; i < sizeof p1_unique / sizeof *p1_unique; i++)
if (id == p1_unique[i].id)
{
strcpy(imgdata.lens.makernotes.body, p1_unique[i].t_model);
}
}
return;
}
void CLASS parseFujiMakernotes(unsigned tag, unsigned type)
{
switch (tag)
{
case 0x1002:
imgdata.makernotes.fuji.WB_Preset = get2();
break;
case 0x1011:
imgdata.other.FlashEC = getreal(type);
break;
case 0x1020:
imgdata.makernotes.fuji.Macro = get2();
break;
case 0x1021:
imgdata.makernotes.fuji.FocusMode = get2();
break;
case 0x1022:
imgdata.makernotes.fuji.AFMode = get2();
break;
case 0x1023:
imgdata.makernotes.fuji.FocusPixel[0] = get2();
imgdata.makernotes.fuji.FocusPixel[1] = get2();
break;
case 0x1034:
imgdata.makernotes.fuji.ExrMode = get2();
break;
case 0x1050:
imgdata.makernotes.fuji.ShutterType = get2();
break;
case 0x1400:
imgdata.makernotes.fuji.FujiDynamicRange = get2();
break;
case 0x1401:
imgdata.makernotes.fuji.FujiFilmMode = get2();
break;
case 0x1402:
imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2();
break;
case 0x1403:
imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2();
break;
case 0x140b:
imgdata.makernotes.fuji.FujiAutoDynamicRange = get2();
break;
case 0x1404:
imgdata.lens.makernotes.MinFocal = getreal(type);
break;
case 0x1405:
imgdata.lens.makernotes.MaxFocal = getreal(type);
break;
case 0x1406:
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
break;
case 0x1407:
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
break;
case 0x1422:
imgdata.makernotes.fuji.ImageStabilization[0] = get2();
imgdata.makernotes.fuji.ImageStabilization[1] = get2();
imgdata.makernotes.fuji.ImageStabilization[2] = get2();
imgdata.shootinginfo.ImageStabilization =
(imgdata.makernotes.fuji.ImageStabilization[0] << 9) + imgdata.makernotes.fuji.ImageStabilization[1];
break;
case 0x1431:
imgdata.makernotes.fuji.Rating = get4();
break;
case 0x3820:
imgdata.makernotes.fuji.FrameRate = get2();
break;
case 0x3821:
imgdata.makernotes.fuji.FrameWidth = get2();
break;
case 0x3822:
imgdata.makernotes.fuji.FrameHeight = get2();
break;
}
return;
}
void CLASS setSonyBodyFeatures(unsigned id)
{
imgdata.lens.makernotes.CamID = id;
if ( // FF cameras
(id == 257) || // a900
(id == 269) || // a850
(id == 340) || // ILCE-7M2
(id == 318) || // ILCE-7S
(id == 350) || // ILCE-7SM2
(id == 311) || // ILCE-7R
(id == 347) || // ILCE-7RM2
(id == 306) || // ILCE-7
(id == 298) || // DSC-RX1
(id == 299) || // NEX-VG900
(id == 310) || // DSC-RX1R
(id == 344) || // DSC-RX1RM2
(id == 354) || // ILCA-99M2
(id == 358) || // ILCE-9
(id == 362) || // ILCE-7RM3
(id == 294) // SLT-99, Hasselblad HV
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
else if ((id == 297) || // DSC-RX100
(id == 308) || // DSC-RX100M2
(id == 309) || // DSC-RX10
(id == 317) || // DSC-RX100M3
(id == 341) || // DSC-RX100M4
(id == 342) || // DSC-RX10M2
(id == 355) || // DSC-RX10M3
(id == 356) || // DSC-RX100M5
(id == 364) || // DSC-RX0
(id == 365) // DSC-RX10M4
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH;
}
else if (id != 002) // DSC-R1
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
}
if ( // E-mount cameras, ILCE series
(id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) ||
(id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 358) || (id == 360) || (id == 362))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE;
}
else if ( // E-mount cameras, NEX series
(id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) ||
(id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX;
}
else if ( // A-mount cameras, DSLR series
(id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) ||
(id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) ||
(id == 274) || (id == 275) || (id == 282) || (id == 283))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR;
}
else if ( // A-mount cameras, SLT series
(id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) ||
(id == 294) || (id == 303))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT;
}
else if ( // A-mount cameras, ILCA series
(id == 319) || (id == 353) || (id == 354))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA;
}
else if ( // DSC
(id == 002) || // DSC-R1
(id == 297) || // DSC-RX100
(id == 298) || // DSC-RX1
(id == 308) || // DSC-RX100M2
(id == 309) || // DSC-RX10
(id == 310) || // DSC-RX1R
(id == 344) || // DSC-RX1RM2
(id == 317) || // DSC-RX100M3
(id == 341) || // DSC-RX100M4
(id == 342) || // DSC-RX10M2
(id == 355) || // DSC-RX10M3
(id == 356) || // DSC-RX100M5
(id == 364) || // DSC-RX0
(id == 365) // DSC-RX10M4
)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC;
}
return;
}
void CLASS parseSonyLensType2(uchar a, uchar b)
{
ushort lid2;
lid2 = (((ushort)a) << 8) | ((ushort)b);
if (!lid2)
return;
if (lid2 < 0x100)
{
if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00))
{
imgdata.lens.makernotes.AdapterID = lid2;
switch (lid2)
{
case 1:
case 2:
case 3:
case 6:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 44:
case 78:
case 239:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
break;
}
}
}
else
imgdata.lens.makernotes.LensID = lid2;
if ((lid2 >= 50481) && (lid2 < 50500))
{
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
imgdata.lens.makernotes.AdapterID = 0x4900;
}
return;
}
#define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf)))
void CLASS parseSonyLensFeatures(uchar a, uchar b)
{
ushort features;
features = (((ushort)a) << 8) | ((ushort)b);
if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) ||
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features)
return;
imgdata.lens.makernotes.LensFeatures_pre[0] = 0;
imgdata.lens.makernotes.LensFeatures_suf[0] = 0;
if ((features & 0x0200) && (features & 0x0100))
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E");
else if (features & 0x0200)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE");
else if (features & 0x0100)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT");
if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
if ((features & 0x0200) && (features & 0x0100))
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0200)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0100)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
}
if (features & 0x4000)
strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ");
if (features & 0x0008)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G");
else if (features & 0x0004)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA");
if ((features & 0x0020) && (features & 0x0040))
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro");
else if (features & 0x0020)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF");
else if (features & 0x0040)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex");
else if (features & 0x0080)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye");
if (features & 0x0001)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM");
else if (features & 0x0002)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM");
if (features & 0x8000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS");
if (features & 0x2000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE");
if (features & 0x0800)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II");
if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ')
memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1,
strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1);
return;
}
#undef strnXcat
void CLASS process_Sony_0x0116(uchar *buf, unsigned id) {
if ((id == 257) ||
(id == 262) ||
(id == 269) ||
(id == 270))
imgdata.other.BatteryTemperature = (float) (buf[1]-32) / 1.8f;
else if ((id != 263) &&
(id != 264) &&
(id != 265) &&
(id != 266))
imgdata.other.BatteryTemperature = (float) (buf[2]-32) / 1.8f;
return;
}
void CLASS process_Sony_0x9402(uchar *buf) {
if (buf[2] != 0xff) return;
short bufx = SonySubstitution[buf[0]];
if ((bufx < 0x0f) ||
(bufx > 0x1a) ||
(bufx == 0x16) ||
(bufx == 0x18)) return;
imgdata.other.AmbientTemperature = (float) ((short) SonySubstitution[buf[4]]);
return;
}
void CLASS process_Sony_0x9403(uchar *buf) {
short bufx = SonySubstitution[buf[4]];
if ((bufx == 0x00) ||
(bufx == 0x94)) return;
imgdata.other.SensorTemperature = (float) ((short) SonySubstitution[buf[5]]);
return;
}
void CLASS process_Sony_0x9406(uchar *buf) {
short bufx = SonySubstitution[buf[0]];
if ((bufx != 0x00) &&
(bufx == 0x01) &&
(bufx == 0x03)) return;
bufx = SonySubstitution[buf[2]];
if ((bufx != 0x02) &&
(bufx == 0x03)) return;
imgdata.other.BatteryTemperature = (float) (SonySubstitution[buf[5]]-32) / 1.8f;
return;
}
void CLASS process_Sony_0x940c(uchar *buf)
{
ushort lid2;
if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) &&
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F))
{
switch (SonySubstitution[buf[0x0008]])
{
case 1:
case 5:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 4:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
break;
}
}
lid2 = (((ushort)SonySubstitution[buf[0x000a]]) << 8) | ((ushort)SonySubstitution[buf[0x0009]]);
if ((lid2 > 0) && (lid2 < 32784))
parseSonyLensType2(SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0009]]);
return;
}
void CLASS process_Sony_0x9050(uchar *buf, unsigned id)
{
ushort lid;
if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) &&
(imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens))
{
if (buf[0])
imgdata.lens.makernotes.MaxAp4CurFocal =
my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f;
if (buf[1])
imgdata.lens.makernotes.MinAp4CurFocal =
my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f;
}
if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)
{
if (buf[0x3d] | buf[0x3c])
{
lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]];
imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 256.0f - 16.0f) / 2.0f);
}
if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) &&
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F))
imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]];
if (buf[0x106])
imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]];
}
if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)
{
parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0107]]);
}
if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) &&
(buf[0x010a] | buf[0x0109]))
{
imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids
SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]];
if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900))
{
imgdata.lens.makernotes.AdapterID = 0x4900;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F;
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
}
else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) &&
(imgdata.lens.makernotes.LensID != 0xFF00))
{
imgdata.lens.makernotes.AdapterID = 0xEF00;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
}
}
if ((id >= 286) && (id <= 293))
// "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E",
// "SLT-A37", "SLT-A57", "NEX-F3", "Lunar"
parseSonyLensFeatures(SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]);
else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)
parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]);
if ((id == 347) || (id == 350) || (id == 357))
{
unsigned long long b88 = SonySubstitution[buf[0x88]];
unsigned long long b89 = SonySubstitution[buf[0x89]];
unsigned long long b8a = SonySubstitution[buf[0x8a]];
unsigned long long b8b = SonySubstitution[buf[0x8b]];
unsigned long long b8c = SonySubstitution[buf[0x8c]];
unsigned long long b8d = SonySubstitution[buf[0x8d]];
sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx",
(b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d);
}
else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283))
{
unsigned long long bf0 = SonySubstitution[buf[0xf0]];
unsigned long long bf1 = SonySubstitution[buf[0xf1]];
unsigned long long bf2 = SonySubstitution[buf[0xf2]];
unsigned long long bf3 = SonySubstitution[buf[0xf3]];
unsigned long long bf4 = SonySubstitution[buf[0xf4]];
sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx",
(bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4);
}
else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290))
{
unsigned b7c = SonySubstitution[buf[0x7c]];
unsigned b7d = SonySubstitution[buf[0x7d]];
unsigned b7e = SonySubstitution[buf[0x7e]];
unsigned b7f = SonySubstitution[buf[0x7f]];
sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f);
}
return;
}
void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer,
uchar *&table_buf_0x9050, ushort &table_buf_0x9050_present,
uchar *&table_buf_0x940c, ushort &table_buf_0x940c_present,
uchar *&table_buf_0x0116, ushort &table_buf_0x0116_present,
uchar *&table_buf_0x9402, ushort &table_buf_0x9402_present,
uchar *&table_buf_0x9403, ushort &table_buf_0x9403_present,
uchar *&table_buf_0x9406, ushort &table_buf_0x9406_present)
{
ushort lid;
uchar *table_buf;
if (tag == 0xb001) // Sony ModelID
{
unique_id = get2();
setSonyBodyFeatures(unique_id);
if (table_buf_0x0116_present) {
process_Sony_0x0116(table_buf_0x0116, unique_id);
free(table_buf_0x0116);
table_buf_0x0116_present = 0;
}
if (table_buf_0x9050_present) {
process_Sony_0x9050(table_buf_0x9050, unique_id);
free(table_buf_0x9050);
table_buf_0x9050_present = 0;
}
if (table_buf_0x9402_present) {
process_Sony_0x9402(table_buf_0x9402);
free(table_buf_0x9402);
table_buf_0x9402_present = 0;
}
if (table_buf_0x9403_present) {
process_Sony_0x9403(table_buf_0x9403);
free(table_buf_0x9403);
table_buf_0x9403_present = 0;
}
if (table_buf_0x9406_present) {
process_Sony_0x9406(table_buf_0x9406);
free(table_buf_0x9406);
table_buf_0x9406_present = 0;
}
if (table_buf_0x940c_present) {
if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) {
process_Sony_0x940c(table_buf_0x940c);
}
free(table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if ((tag == 0x0010) && // CameraInfo
strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) &&
((len == 368) || // a700
(len == 5478) || // a850, a900
(len == 5506) || // a200, a300, a350
(len == 6118) || // a230, a290, a330, a380, a390
// a450, a500, a550, a560, a580
// a33, a35, a55
// NEX3, NEX5, NEX5C, NEXC3, VG10E
(len == 15360)))
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) &&
memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8))
{
switch (len)
{
case 368:
case 5478:
// a700, a850, a900: CameraInfo
if ((!dng_writer) ||
(saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7])))
{
if (table_buf[0] | table_buf[3])
imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]);
if (table_buf[2] | table_buf[5])
imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]);
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f;
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f;
parseSonyLensFeatures(table_buf[1], table_buf[6]);
}
break;
default:
// CameraInfo2 & 3
if ((!dng_writer) ||
(saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])))
{
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
}
}
free(table_buf);
}
else if ((!dng_writer) && (tag == 0x0020) && // WBInfoA100, needs 0xb028 processing
!strncasecmp(model, "DSLR-A100", 9))
{
fseek(ifp, 0x49dc, SEEK_CUR);
stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp);
}
else if (tag == 0x0104)
{
imgdata.other.FlashEC = getreal(type);
}
else if (tag == 0x0105) // Teleconverter
{
imgdata.lens.makernotes.TeleconverterID = get2();
}
else if (tag == 0x0114 && len < 256000) // CameraSettings
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
switch (len)
{
case 280:
case 364:
case 332:
// CameraSettings and CameraSettings2 are big endian
if (table_buf[2] | table_buf[3])
{
lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]);
imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 8.0f - 1.0f) / 2.0f);
}
break;
case 1536:
case 2048:
// CameraSettings3 are little endian
parseSonyLensType2(table_buf[1016], table_buf[1015]);
if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF)
{
switch (table_buf[153])
{
case 16:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 17:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
break;
}
}
break;
}
free(table_buf);
}
else if (tag == 0x0116 && len < 256000) {
table_buf_0x0116 = (uchar *)malloc(len);
table_buf_0x0116_present = 1;
fread(table_buf_0x0116, len, 1, ifp);
if (imgdata.lens.makernotes.CamID) {
process_Sony_0x0116 (table_buf_0x0116, unique_id);
free(table_buf_0x0116);
table_buf_0x0116_present = 0;
}
}
else if (tag == 0x9050 && len < 256000) // little endian
{
table_buf_0x9050 = (uchar *)malloc(len);
table_buf_0x9050_present = 1;
fread(table_buf_0x9050, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID);
free(table_buf_0x9050);
table_buf_0x9050_present = 0;
}
}
else if (tag == 0x9402 && len < 256000) {
table_buf_0x9402 = (uchar *)malloc(len);
table_buf_0x9402_present = 1;
fread(table_buf_0x9402, len, 1, ifp);
if (imgdata.lens.makernotes.CamID) {
process_Sony_0x9402(table_buf_0x9402);
free(table_buf_0x9402);
table_buf_0x9402_present = 0;
}
}
else if (tag == 0x9403 && len < 256000) {
table_buf_0x9403 = (uchar *)malloc(len);
table_buf_0x9403_present = 1;
fread(table_buf_0x9403, len, 1, ifp);
if (imgdata.lens.makernotes.CamID) {
process_Sony_0x9403(table_buf_0x9403);
free(table_buf_0x9403);
table_buf_0x9403_present = 0;
}
}
else if (tag == 0x9406 && len < 256000) {
table_buf_0x9406 = (uchar *)malloc(len);
table_buf_0x9406_present = 1;
fread(table_buf_0x9406, len, 1, ifp);
if (imgdata.lens.makernotes.CamID) {
process_Sony_0x9406(table_buf_0x9406);
free(table_buf_0x9406);
table_buf_0x9406_present = 0;
}
}
else if (tag == 0x940c && len < 256000)
{
table_buf_0x940c = (uchar *)malloc(len);
table_buf_0x940c_present = 1;
fread(table_buf_0x940c, len, 1, ifp);
if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E))
{
process_Sony_0x940c(table_buf_0x940c);
free(table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1))
{
imgdata.lens.makernotes.LensID = get4();
if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900))
{
imgdata.lens.makernotes.AdapterID = 0x4900;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F;
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
}
else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) &&
(imgdata.lens.makernotes.LensID != 0xFF00))
{
imgdata.lens.makernotes.AdapterID = 0xEF00;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
}
if (tag == 0x010c)
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
}
else if (tag == 0xb02a && len < 256000) // Sony LensSpec
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
if ((!dng_writer) ||
(saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])))
{
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
free(table_buf);
}
}
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{
unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c;
unsigned i;
uchar NikonKey, ci, cj, ck;
unsigned serial = 0;
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
unsigned typeCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_present = 0;
uchar *table_buf_0x9402;
ushort table_buf_0x9402_present = 0;
uchar *table_buf_0x9403;
ushort table_buf_0x9403_present = 0;
uchar *table_buf_0x9406;
ushort table_buf_0x9406_present = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_present = 0;
uchar *table_buf_0x0116;
ushort table_buf_0x0116_present = 0;
short morder, sorder = order;
char buf[10];
INT64 fsize = ifp->size();
fread(buf, 1, 10, ifp);
/*
printf("===>>buf: 0x");
for (int i = 0; i < sizeof buf; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
*/
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)))
base = ftell(ifp);
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
INT64 pos = ifp->tell();
if (len > 8 && pos + len > 2 * fsize)
continue;
tag |= uptag << 16;
if (len > 100 * 1024 * 1024)
goto next; // 100Mb tag? No!
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
if (type != 4) {
CanonCameraInfo = (uchar *)malloc(MAX(16,len));
fread(CanonCameraInfo, len, 1, ifp);
} else {
CanonCameraInfo = (uchar *)malloc(MAX(16,len*4));
fread(CanonCameraInfo, len, 4, ifp);
}
lenCanonCameraInfo = len;
typeCanonCameraInfo = type;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
unique_id = setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
parseFujiMakernotes(tag, type);
else if (!strncasecmp(make, "LEICA", 5))
{
if ((tag == 0x0320) && (type == 9) && (len == 1) &&
!strncasecmp (make, "Leica Camera AG", 15) &&
!strncmp (buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0)
) imgdata.other.CameraTemperature = getreal(type);
if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type);
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x1d) // serial number
while ((c = fgetc(ifp)) && c != EOF)
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
}
else if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093)
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0097)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0xa7) // shutter count
{
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 37 && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc, 1, 1, ifp);
iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0));
break;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
int SubDirOffsetValid = strncmp(model, "E-300", 5) && strncmp(model, "E-330", 5) && strncmp(model, "E-400", 5) &&
strncmp(model, "E-500", 5) && strncmp(model, "E-1", 3);
if ((tag == 0x2010) || (tag == 0x2020))
{
fseek(ifp, save - 4, SEEK_SET);
fseek(ifp, base + get4(), SEEK_SET);
parse_makernote_0xc634(base, tag, dng_writer);
}
if (!SubDirOffsetValid && ((len > 4) || (((type == 3) || (type == 8)) && (len > 2)) ||
(((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9)))
goto skip_Oly_broken_tags;
switch (tag)
{
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2);
break;
case 0x20100102:
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
break;
case 0x20100201:
imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp) << 16 |
(unsigned long long)(fgetc(ifp), fgetc(ifp)) << 8 |
(unsigned long long)fgetc(ifp);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT;
if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) &&
(imgdata.lens.makernotes.LensID & 0x10))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT;
}
break;
case 0x20100202:
if ((!imgdata.lens.LensSerial[0]))
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0x20100203:
stmread(imgdata.lens.makernotes.Lens, len, ifp);
break;
case 0x20100205:
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100207:
imgdata.lens.makernotes.MinFocal = (float)get2();
break;
case 0x20100208:
imgdata.lens.makernotes.MaxFocal = (float)get2();
if (imgdata.lens.makernotes.MaxFocal > 1000.0f)
imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal;
break;
case 0x2010020a:
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);
break;
case 0x20100403:
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
break;
case 0x20200401:
imgdata.other.FlashEC = getreal(type);
break;
case 0x1007:
imgdata.other.SensorTemperature = (float)get2();
break;
case 0x1008:
imgdata.other.LensTemperature = (float)get2();
break;
case 0x20401306:
{
int temp = get2();
if ((temp != 0) && (temp != 100)) {
if (temp < 61) imgdata.other.CameraTemperature = (float) temp;
else imgdata.other.CameraTemperature = (float) (temp-32) / 1.8f;
if ((OlyID == 0x4434353933ULL) && // TG-5
(imgdata.other.exifAmbientTemperature > -273.15f))
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
}
}
break;
case 0x20501500:
if (OlyID != 0x0ULL) {
short temp = get2();
if ((OlyID == 0x4434303430ULL) || // E-1
(OlyID == 0x5330303336ULL) || // E-M5
(len != 1))
imgdata.other.SensorTemperature = (float)temp;
else if ((temp != -32768) && (temp != 0)) {
if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f*(float)temp;
else imgdata.other.SensorTemperature = (float)temp;
}
}
break;
}
skip_Oly_broken_tags:;
}
else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x0013)
{
imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f;
}
else if (tag == 0x0014)
{
PentaxISO(get2());
}
else if (tag == 0x001d)
{
imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f;
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0047)
{
imgdata.other.CameraTemperature = (float)fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 12, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
imgdata.lens.makernotes.CamID = unique_id = get4();
}
else if (tag == 0x0043)
{
int temp = get4();
if (temp) {
imgdata.other.CameraTemperature = (float) temp;
if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f;
}
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) ||
!strncasecmp(make, "Konica", 6) ||
!strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) ||
!strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) ||
!strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, AdobeDNG,
table_buf_0x9050, table_buf_0x9050_present,
table_buf_0x940c, table_buf_0x940c_present,
table_buf_0x0116, table_buf_0x0116_present,
table_buf_0x9402, table_buf_0x9402_present,
table_buf_0x9403, table_buf_0x9403_present,
table_buf_0x9406, table_buf_0x9406_present);
}
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
#else
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */}
#endif
void CLASS parse_makernote(int base, int uptag)
{
unsigned offset = 0, entries, tag, type, len, save, c;
unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0};
uchar buf97[324], ci, cj, ck;
short morder, sorder = order;
char buf[10];
unsigned SamsungKey[11];
uchar NikonKey;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
unsigned typeCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_present = 0;
uchar *table_buf_0x9402;
ushort table_buf_0x9402_present = 0;
uchar *table_buf_0x9403;
ushort table_buf_0x9403_present = 0;
uchar *table_buf_0x9406;
ushort table_buf_0x9406_present = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_present = 0;
uchar *table_buf_0x0116;
ushort table_buf_0x0116_present = 0;
INT64 fsize = ifp->size();
#endif
/*
The MakerNote might have its own TIFF header (possibly with
its own byte-order!), or it might just be a table.
*/
if (!strncmp(make, "Nokia", 5))
return;
fread(buf, 1, 10, ifp);
/*
printf("===>>buf: 0x");
for (int i = 0; i < sizeof buf; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
*/
if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */
!strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4))
return;
if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */
!strncmp(buf, "MLY", 3))
{ /* Minolta DiMAGE G series */
order = 0x4d4d;
while ((i = ftell(ifp)) < data_offset && i < 16384)
{
wb[0] = wb[2];
wb[2] = wb[1];
wb[1] = wb[3];
wb[3] = get2();
if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
FORC4 cam_mul[c] = wb[c];
}
goto quit;
}
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX "))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if (!strncmp(make, "SAMSUNG", 7))
base = ftell(ifp);
}
// adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400
if (!strncasecmp(make, "LEICA", 5))
{
if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7))
{
base = ftell(ifp) - 8;
}
else if (!strncasecmp(model, "LEICA M (Typ 240)", 17))
{
base = 0;
}
else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) ||
!strncasecmp(model, "Leica M Monochrom", 11))
{
if (!uptag)
{
base = ftell(ifp) - 10;
fseek(ifp, 8, SEEK_CUR);
}
else if (uptag == 0x3400)
{
fseek(ifp, 10, SEEK_CUR);
base += 10;
}
}
else if (!strncasecmp(model, "LEICA T", 7))
{
base = ftell(ifp) - 8;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T;
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (!strncasecmp(model, "LEICA SL", 8))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
#endif
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
tag |= uptag << 16;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos = ftell(ifp);
if (len > 8 && _pos + len > 2 * fsize)
continue;
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
if (type != 4) {
CanonCameraInfo = (uchar *)malloc(MAX(16,len));
fread(CanonCameraInfo, len, 1, ifp);
} else {
CanonCameraInfo = (uchar *)malloc(MAX(16,len*4));
fread(CanonCameraInfo, len, 4, ifp);
}
lenCanonCameraInfo = len;
typeCanonCameraInfo = type;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
unique_id = setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
{
if (tag == 0x0010)
{
char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)];
char *words[4];
char yy[2], mm[3], dd[3], ystr[16], ynum[16];
int year, nwords, ynum_len;
unsigned c;
stmread(FujiSerial, len, ifp);
nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial));
for (int i = 0; i < nwords; i++)
{
mm[2] = dd[2] = 0;
if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18)
if (i == 0)
strncpy(imgdata.shootinginfo.InternalBodySerial, words[0],
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2);
strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2);
strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2);
year = (yy[0] - '0') * 10 + (yy[1] - '0');
if (year < 70)
year += 2000;
else
year += 1900;
ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18;
strncpy(ynum, words[i], ynum_len);
ynum[ynum_len] = 0;
for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2)
ystr[j / 2] = c;
ystr[ynum_len / 2 + 1] = 0;
strcpy(model2, ystr);
if (i == 0)
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
if (nwords == 1)
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s",
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr,
year, mm, dd);
else
snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd,
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm,
dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
}
}
}
else
parseFujiMakernotes(tag, type);
}
else if (!strncasecmp(model, "Hasselblad X1D", 14)
|| !strncasecmp(model, "Hasselblad H6D", 14)
|| !strncasecmp(model, "Hasselblad A6D", 14))
{
if (tag == 0x0045)
{
imgdata.makernotes.hasselblad.BaseISO = get4();
}
else if (tag == 0x0046)
{
imgdata.makernotes.hasselblad.Gain = getreal(type);
}
}
else if (!strncasecmp(make, "LEICA", 5))
{
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0320) && (type == 9) && (len == 1) &&
!strncasecmp (make, "Leica Camera AG", 15) &&
!strncmp (buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0)
) imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0012)
{
char a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
imgdata.other.FlashEC = (float)(a * b) / (float)c;
}
else if (tag == 0x003b) // all 1s for regular exposures
{
imgdata.makernotes.nikon.ME_WB[0] = getreal(type);
imgdata.makernotes.nikon.ME_WB[2] = getreal(type);
imgdata.makernotes.nikon.ME_WB[1] = getreal(type);
imgdata.makernotes.nikon.ME_WB[3] = getreal(type);
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093) // Nikon compression
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData > 0)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0x00a0)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 0x00b0)
{
get4(); // ME tag version, 4 symbols
imgdata.makernotes.nikon.ExposureMode = get4();
imgdata.makernotes.nikon.nMEshots = get4();
imgdata.makernotes.nikon.MEgainOn = get4();
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
switch (tag)
{
case 0x0404:
case 0x101a:
case 0x20100101:
if (!imgdata.shootinginfo.BodySerial[0])
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0x20100102:
if (!imgdata.shootinginfo.InternalBodySerial[0])
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
break;
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2);
break;
case 0x20401112:
imgdata.makernotes.olympus.OlympusCropID = get2();
break;
case 0x20401113:
FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2();
break;
case 0x20100201:
{
unsigned long long oly_lensid[3];
oly_lensid[0] = fgetc(ifp);
fgetc(ifp);
oly_lensid[1] = fgetc(ifp);
oly_lensid[2] = fgetc(ifp);
imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2];
}
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT;
if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) &&
(imgdata.lens.makernotes.LensID & 0x10))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT;
}
break;
case 0x20100202:
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0x20100203:
stmread(imgdata.lens.makernotes.Lens, len, ifp);
break;
case 0x20100205:
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100207:
imgdata.lens.makernotes.MinFocal = (float)get2();
break;
case 0x20100208:
imgdata.lens.makernotes.MaxFocal = (float)get2();
if (imgdata.lens.makernotes.MaxFocal > 1000.0f)
imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal;
break;
case 0x2010020a:
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);
break;
case 0x20100403:
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
break;
case 0x1007:
imgdata.other.SensorTemperature = (float)get2();
break;
case 0x1008:
imgdata.other.LensTemperature = (float)get2();
break;
case 0x20401306:
{
int temp = get2();
if ((temp != 0) && (temp != 100)) {
if (temp < 61) imgdata.other.CameraTemperature = (float) temp;
else imgdata.other.CameraTemperature = (float) (temp-32) / 1.8f;
if ((OlyID == 0x4434353933ULL) && // TG-5
(imgdata.other.exifAmbientTemperature > -273.15f))
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
}
}
break;
case 0x20501500:
if (OlyID != 0x0ULL) {
short temp = get2();
if ((OlyID == 0x4434303430ULL) || // E-1
(OlyID == 0x5330303336ULL) || // E-M5
(len != 1))
imgdata.other.SensorTemperature = (float)temp;
else if ((temp != -32768) && (temp != 0)) {
if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f*(float)temp;
else imgdata.other.SensorTemperature = (float)temp;
}
}
break;
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
char buffer[17];
int count = 0;
fread(buffer, 16, 1, ifp);
buffer[16] = 0;
for (int i = 0; i < 16; i++)
{
// sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]);
if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i])))
count++;
}
if (count == 16)
{
sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8);
buffer[8] = 0;
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else
{
sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10],
buffer[11]);
}
}
else if ((tag == 0x1001) && (type == 3))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
imgdata.lens.makernotes.FocalType = 1;
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
}
else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6))
{
if ((tag == 0x0005) && !strncmp(model, "GXR", 3))
{
char buffer[9];
buffer[8] = 0;
fread(buffer, 8, 1, ifp);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
else if ((tag == 0x2001) && !strncmp(model, "GXR", 3))
{
short ntags, cur_tag;
fseek(ifp, 20, SEEK_CUR);
ntags = get2();
cur_tag = get2();
while (cur_tag != 0x002c)
{
fseek(ifp, 10, SEEK_CUR);
cur_tag = get2();
}
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, get4() + 20, SEEK_SET);
stread(imgdata.shootinginfo.BodySerial, 12, ifp);
get2();
imgdata.lens.makernotes.LensID = getc(ifp) - '0';
switch (imgdata.lens.makernotes.LensID)
{
case 1:
case 2:
case 3:
case 5:
case 6:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule;
break;
case 8:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
break;
default:
imgdata.lens.makernotes.LensID = -1;
}
fseek(ifp, 17, SEEK_CUR);
stread(imgdata.lens.LensSerial, 12, ifp);
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && dng_version)) &&
strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x0013)
{
imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f;
}
else if (tag == 0x0014)
{
PentaxISO(get2());
}
else if (tag == 0x001d)
{
imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f;
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0047)
{
imgdata.other.CameraTemperature = (float)fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 2, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
unique_id = imgdata.lens.makernotes.CamID = get4();
}
else if (tag == 0x0043)
{
int temp = get4();
if (temp) {
imgdata.other.CameraTemperature = (float) temp;
if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f;
}
}
else if (tag == 0xa002)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) ||
!strncasecmp(make, "Konica", 6) ||
!strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) ||
!strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) ||
!strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, nonDNG,
table_buf_0x9050, table_buf_0x9050_present,
table_buf_0x940c, table_buf_0x940c_present,
table_buf_0x0116, table_buf_0x0116_present,
table_buf_0x9402, table_buf_0x9402_present,
table_buf_0x9403, table_buf_0x9403_present,
table_buf_0x9406, table_buf_0x9406_present);
}
fseek(ifp, _pos, SEEK_SET);
#endif
if (tag == 2 && strstr(make, "NIKON") && !iso_speed)
iso_speed = (get2(), get2());
if (tag == 37 && strstr(make, "NIKON") && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc, 1, 1, ifp);
iso_speed = int(100.0 * powf64(2.0f, float(cc) / 12.0 - 5.0));
}
if (tag == 4 && len > 26 && len < 35)
{
if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535))
iso_speed = 50 * powf64(2.0, i / 32.0 - 4);
#ifdef LIBRAW_LIBRARY_BUILD
get4();
#else
if ((i = (get2(), get2())) != 0x7fff && !aperture)
aperture = powf64(2.0, i / 64.0);
#endif
if ((i = get2()) != 0xffff && !shutter)
shutter = powf64(2.0, (short)i / -32.0);
wbi = (get2(), get2());
shot_order = (get2(), get2());
}
if ((tag == 4 || tag == 0x114) && !strncmp(make, "KONICA", 6))
{
fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR);
switch (get2())
{
case 72:
flip = 0;
break;
case 76:
flip = 6;
break;
case 82:
flip = 5;
break;
}
}
if (tag == 7 && type == 2 && len > 20)
fgets(model2, 64, ifp);
if (tag == 8 && type == 4)
shot_order = get4();
if (tag == 9 && !strncmp(make, "Canon", 5))
fread(artist, 64, 1, ifp);
if (tag == 0xc && len == 4)
FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type);
if (tag == 0xd && type == 7 && get2() == 0xaaaa)
{
#if 0 /* Canon rotation data is handled by EXIF.Orientation */
for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++)
c = c << 8 | fgetc(ifp);
while ((i += 4) < len - 5)
if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3)
flip = "065"[c] - '0';
#endif
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x10 && type == 4)
unique_id = get4();
#endif
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos2 = ftell(ifp);
if (!strncasecmp(make, "Olympus", 7))
{
short nWB, tWB;
if ((tag == 0x20300108) || (tag == 0x20310109))
imgdata.makernotes.olympus.ColorSpace = get2();
if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5)))
{
int i;
for (i = 0; i < 64; i++)
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] =
imgdata.color.WB_Coeffs[i][3] = 0x100;
for (i = 64; i < 256; i++)
imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100;
}
if ((tag >= 0x20400101) && (tag <= 0x20400111))
{
nWB = tag - 0x20400101;
tWB = Oly_wb_list2[nWB << 1];
ushort CT = Oly_wb_list2[(nWB << 1) | 1];
int wb[4];
wb[0] = get2();
wb[2] = get2();
if (tWB != 0x100)
{
imgdata.color.WB_Coeffs[tWB][0] = wb[0];
imgdata.color.WB_Coeffs[tWB][2] = wb[2];
}
if (CT)
{
imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT;
imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0];
imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2];
}
if (len == 4)
{
wb[1] = get2();
wb[3] = get2();
if (tWB != 0x100)
{
imgdata.color.WB_Coeffs[tWB][1] = wb[1];
imgdata.color.WB_Coeffs[tWB][3] = wb[3];
}
if (CT)
{
imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1];
imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3];
}
}
}
if ((tag >= 0x20400112) && (tag <= 0x2040011e))
{
nWB = tag - 0x20400112;
int wbG = get2();
tWB = Oly_wb_list2[nWB << 1];
if (nWB)
imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG;
if (tWB != 0x100)
imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG;
}
if (tag == 0x20400121)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2();
if (len == 4)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2();
}
}
if (tag == 0x2040011f)
{
int wbG = get2();
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0])
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG;
FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0])
imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] =
wbG;
}
if ((tag == 0x30000110) && strcmp(software, "v757-71"))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2();
if (len == 2)
{
for (int i = 0; i < 256; i++)
imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100;
}
}
if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) &&
strcmp(software, "v757-71"))
{
int wb_ind;
if (tag <= 0x30000124)
wb_ind = tag - 0x30000120;
else
wb_ind = tag - 0x30000130 + 5;
imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2();
imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2();
}
if ((tag == 0x20400805) && (len == 2))
{
imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type);
imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type);
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0];
}
if (tag == 0x20200401)
{
imgdata.other.FlashEC = getreal(type);
}
}
fseek(ifp, _pos2, SEEK_SET);
#endif
if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5))
{
fseek(ifp, get4() + base, SEEK_SET);
parse_tiff_ifd(base);
}
if (tag == 0x14 && type == 7)
{
if (len == 2560)
{
fseek(ifp, 1248, SEEK_CUR);
goto get2_256;
}
fread(buf, 1, 10, ifp);
if (!strncmp(buf, "NRW ", 4))
{
fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR);
cam_mul[0] = get4() << 2;
cam_mul[1] = get4() + get4();
cam_mul[2] = get4() << 2;
}
}
if (tag == 0x15 && type == 2 && is_raw)
fread(model, 64, 1, ifp);
if (strstr(make, "PENTAX"))
{
if (tag == 0x1b)
tag = 0x1018;
if (tag == 0x1c)
tag = 0x1017;
}
if (tag == 0x1d)
{
while ((c = fgetc(ifp)) && c != EOF)
#ifdef LIBRAW_LIBRARY_BUILD
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
#endif
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
#ifdef LIBRAW_LIBRARY_BUILD
}
if (!imgdata.shootinginfo.BodySerial[0])
sprintf(imgdata.shootinginfo.BodySerial, "%d", serial);
#endif
}
if (tag == 0x29 && type == 1)
{ // Canon PowerShot G9
c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0;
fseek(ifp, 8 + c * 32, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x3d && type == 3 && len == 4)
FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps);
#endif
if (tag == 0x81 && type == 4)
{
data_offset = get4();
fseek(ifp, data_offset + 41, SEEK_SET);
raw_height = get2() * 2;
raw_width = get2();
filters = 0x61616161;
}
if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1))
{
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
thumb_offset += base;
if (tag == 0x89 && type == 4)
thumb_length = get4();
if (tag == 0x8c || tag == 0x96)
meta_offset = ftell(ifp);
if (tag == 0x97)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
switch (ver97)
{
case 100:
fseek(ifp, 68, SEEK_CUR);
FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
break;
case 102:
fseek(ifp, 6, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
break;
case 103:
fseek(ifp, 16, SEEK_CUR);
FORC4 cam_mul[c] = get2();
}
if (ver97 >= 200)
{
if (ver97 != 205)
fseek(ifp, 280, SEEK_CUR);
fread(buf97, 324, 1, ifp);
}
}
if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7))
{
order = 0x4949;
fseek(ifp, 140, SEEK_CUR);
FORC3 cam_mul[c] = get4();
}
if (tag == 0xa4 && type == 3)
{
fseek(ifp, wbi * 48, SEEK_CUR);
FORC3 cam_mul[c] = get2();
}
if (tag == 0xa7)
{ // shutter count
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((unsigned)(ver97 - 200) < 17)
{
ci = xlat[0][serial & 0xff];
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < 324; i++)
buf97[i] ^= (cj += ci * ck++);
i = "66666>666;6A;:;55"[ver97 - 200] - '0';
FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2);
}
#ifdef LIBRAW_LIBRARY_BUILD
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
#endif
}
if (tag == 0xb001 && type == 3) // Sony ModelID
{
unique_id = get2();
}
if (tag == 0x200 && len == 3)
shot_order = (get4(), get4());
if (tag == 0x200 && len == 4) // Pentax black level
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x201 && len == 4) // Pentax As Shot WB
FORC4 cam_mul[c ^ (c >> 1)] = get2();
if (tag == 0x220 && type == 7)
meta_offset = ftell(ifp);
if (tag == 0x401 && type == 4 && len == 4)
FORC4 cblack[c ^ c >> 1] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
// not corrected for file bitcount, to be patched in open_datastream
if (tag == 0x03d && strstr(make, "NIKON") && len == 4)
{
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black += i;
}
#endif
if (tag == 0xe01)
{ /* Nikon Capture Note */
#ifdef LIBRAW_LIBRARY_BUILD
int loopc = 0;
#endif
order = 0x4949;
fseek(ifp, 22, SEEK_CUR);
for (offset = 22; offset + 22 < len; offset += 22 + i)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (loopc++ > 1024)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
tag = get4();
fseek(ifp, 14, SEEK_CUR);
i = get4() - 4;
if (tag == 0x76a43207)
flip = get2();
else
fseek(ifp, i, SEEK_CUR);
}
}
if (tag == 0xe80 && len == 256 && type == 7)
{
fseek(ifp, 48, SEEK_CUR);
cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
}
if (tag == 0xf00 && type == 7)
{
if (len == 614)
fseek(ifp, 176, SEEK_CUR);
else if (len == 734 || len == 1502)
fseek(ifp, 148, SEEK_CUR);
else
goto next;
goto get2_256;
}
if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71"))
for (i = 0; i < 3; i++)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.makernotes.olympus.ColorSpace)
{
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
}
else
{
FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0;
}
#else
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
#endif
}
if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x1017 || tag == 0x20400100)
cam_mul[0] = get2() / 256.0;
if (tag == 0x1018 || tag == 0x20400100)
cam_mul[2] = get2() / 256.0;
if (tag == 0x2011 && len == 2)
{
get2_256:
order = 0x4d4d;
cam_mul[0] = get2() / 256.0;
cam_mul[2] = get2() / 256.0;
}
if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13))
fseek(ifp, get4() + base, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
if (tag == 0x2010)
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, 0x2010);
fseek(ifp, _pos3, SEEK_SET);
}
if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) &&
((type == 7) || (type == 13)) &&
!strncasecmp(make, "Olympus", 7))
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, tag);
fseek(ifp, _pos3, SEEK_SET);
}
// IB end
#endif
if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5))
parse_thumb_note(base, 257, 258);
if (tag == 0x2040)
parse_makernote(base, 0x2040);
if (tag == 0xb028)
{
fseek(ifp, get4() + base, SEEK_SET);
parse_thumb_note(base, 136, 137);
}
if (tag == 0x4001 && len > 500 && len < 100000)
{
i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
fseek(ifp, i, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
for (i += 18; i <= len; i += 10)
{
get2();
FORC4 sraw_mul[c ^ (c >> 1)] = get2();
if (sraw_mul[1] == 1170)
break;
}
}
if (!strncasecmp(make, "Samsung", 7))
{
if (tag == 0xa020) // get the full Samsung encryption key
for (i = 0; i < 11; i++)
SamsungKey[i] = get4();
if (tag == 0xa021) // get and decode Samsung cam_mul array
FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c];
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0xa022)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4;
}
}
if (tag == 0xa023)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4;
}
}
if (tag == 0xa024)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4;
}
}
/*
if (tag == 0xa025) {
i = get4();
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); }
*/
if (tag == 0xa030 && len == 9)
for (i = 0; i < 3; i++)
FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
#endif
if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix
for (i = 0; i < 3; i++)
FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
if (tag == 0xa028)
FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c];
}
else
{
// Somebody else use 0xa021 and 0xa028?
if (tag == 0xa021)
FORC4 cam_mul[c ^ (c >> 1)] = get4();
if (tag == 0xa028)
FORC4 cam_mul[c ^ (c >> 1)] -= get4();
}
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) &&
(imgdata.makernotes.canon.multishot[1] = get4()))
{
if (len >= 4)
{
imgdata.makernotes.canon.multishot[2] = get4();
imgdata.makernotes.canon.multishot[3] = get4();
}
FORC4 cam_mul[c] = 1024;
}
#else
if (tag == 0x4021 && get4() && get4())
FORC4 cam_mul[c] = 1024;
#endif
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
/*
Since the TIFF DateTime string has no timezone information,
assume that the camera's clock was set to Universal Time.
*/
void CLASS get_timestamp(int reversed)
{
struct tm t;
char str[20];
int i;
str[19] = 0;
if (reversed)
for (i = 19; i--;)
str[i] = fgetc(ifp);
else
fread(str, 19, 1, ifp);
memset(&t, 0, sizeof t);
if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
return;
t.tm_year -= 1900;
t.tm_mon -= 1;
t.tm_isdst = -1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
void CLASS parse_exif(int base)
{
unsigned kodak, entries, tag, type, len, save, c;
double expo, ape;
kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3;
entries = get2();
if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512))
return;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 fsize = ifp->size();
#endif
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
#ifdef LIBRAW_LIBRARY_BUILD
INT64 savepos = ftell(ifp);
if (len > 8 && savepos + len > fsize * 2)
continue;
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
#endif
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0x9400:
imgdata.other.exifAmbientTemperature = getreal(type);
if ((imgdata.other.CameraTemperature > -273.15f) &&
(OlyID == 0x4434353933ULL)) // TG-5
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
break;
case 0x9401:
imgdata.other.exifHumidity = getreal(type);
break;
case 0x9402:
imgdata.other.exifPressure = getreal(type);
break;
case 0x9403:
imgdata.other.exifWaterDepth = getreal(type);
break;
case 0x9404:
imgdata.other.exifAcceleration = getreal(type);
break;
case 0x9405:
imgdata.other.exifCameraElevationAngle = getreal(type);
break;
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.dng.MinFocal = getreal(type);
imgdata.lens.dng.MaxFocal = getreal(type);
imgdata.lens.dng.MaxAp4MinFocal = getreal(type);
imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f));
break;
#endif
case 33434:
tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type);
break;
case 33437:
aperture = getreal(type);
break; // 0x829d FNumber
case 34855:
iso_speed = get2();
break;
case 34865:
if (iso_speed == 0xffff && !strncasecmp(make, "FUJI", 4))
iso_speed = getreal(type);
break;
case 34866:
if (iso_speed == 0xffff && (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "CANON", 5)))
iso_speed = getreal(type);
break;
case 36867:
case 36868:
get_timestamp(0);
break;
case 37377:
if ((expo = -getreal(type)) < 128 && shutter == 0.)
tiff_ifd[tiff_nifds - 1].t_shutter = shutter = powf64(2.0, expo);
break;
case 37378: // 0x9202 ApertureValue
if ((fabs(ape = getreal(type)) < 256.0) && (!aperture))
aperture = powf64(2.0, ape / 2);
break;
case 37385:
flash_used = getreal(type);
break;
case 37386:
focal_len = getreal(type);
break;
case 37500: // tag 0x927c
#ifdef LIBRAW_LIBRARY_BUILD
if (((make[0] == '\0') && (!strncmp(model, "ov5647", 6))) ||
((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_OV5647", 9))) ||
((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_imx219", 9))))
{
char mn_text[512];
char *pos;
char ccms[512];
ushort l;
float num;
fgets(mn_text, len, ifp);
pos = strstr(mn_text, "gain_r=");
if (pos)
cam_mul[0] = atof(pos + 7);
pos = strstr(mn_text, "gain_b=");
if (pos)
cam_mul[2] = atof(pos + 7);
if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f))
cam_mul[1] = cam_mul[3] = 1.0f;
else
cam_mul[0] = cam_mul[2] = 0.0f;
pos = strstr(mn_text, "ccm=") + 4;
l = strstr(pos, " ") - pos;
memcpy(ccms, pos, l);
ccms[l] = '\0';
pos = strtok(ccms, ",");
for (l = 0; l < 4; l++)
{
num = 0.0;
for (c = 0; c < 3; c++)
{
imgdata.color.ccm[l][c] = (float)atoi(pos);
num += imgdata.color.ccm[l][c];
pos = strtok(NULL, ",");
}
if (num > 0.01)
FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;
}
}
else
#endif
parse_makernote(base, 0);
break;
case 40962:
if (kodak)
raw_width = get4();
break;
case 40963:
if (kodak)
raw_height = get4();
break;
case 41730:
if (get4() == 0x20002)
for (exif_cfa = c = 0; c < 8; c += 2)
exif_cfa |= fgetc(ifp) * 0x01010101 << c;
}
fseek(ifp, save, SEEK_SET);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS parse_gps_libraw(int base)
{
unsigned entries, tag, type, len, save, c;
entries = get2();
if (entries > 200)
return;
if (entries > 0)
imgdata.other.parsed_gps.gpsparsed = 1;
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (len > 1024)
continue; // no GPS tags are 1k or larger
switch (tag)
{
case 1:
imgdata.other.parsed_gps.latref = getc(ifp);
break;
case 3:
imgdata.other.parsed_gps.longref = getc(ifp);
break;
case 5:
imgdata.other.parsed_gps.altref = getc(ifp);
break;
case 2:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type);
break;
case 4:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type);
break;
case 7:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type);
break;
case 6:
imgdata.other.parsed_gps.altitude = getreal(type);
break;
case 9:
imgdata.other.parsed_gps.gpsstatus = getc(ifp);
break;
}
fseek(ifp, save, SEEK_SET);
}
}
#endif
void CLASS parse_gps(int base)
{
unsigned entries, tag, type, len, save, c;
entries = get2();
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (len > 1024)
continue; // no GPS tags are 1k or larger
switch (tag)
{
case 1:
case 3:
case 5:
gpsdata[29 + tag / 2] = getc(ifp);
break;
case 2:
case 4:
case 7:
FORC(6) gpsdata[tag / 3 * 6 + c] = get4();
break;
case 6:
FORC(2) gpsdata[18 + c] = get4();
break;
case 18:
case 29:
fgets((char *)(gpsdata + 14 + tag / 3), MIN(len, 12), ifp);
}
fseek(ifp, save, SEEK_SET);
}
}
void CLASS romm_coeff(float romm_cam[3][3])
{
static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */
{{2.034193, -0.727420, -0.306766}, {-0.228811, 1.231729, -0.002922}, {-0.008565, -0.153273, 1.161839}};
int i, j, k;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
for (cmatrix[i][j] = k = 0; k < 3; k++)
cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j];
}
void CLASS parse_mos(int offset)
{
char data[40];
int skip, from, i, c, neut[4], planes = 0, frot = 0;
static const char *mod[] = {"",
"DCB2",
"Volare",
"Cantare",
"CMost",
"Valeo 6",
"Valeo 11",
"Valeo 22",
"Valeo 11p",
"Valeo 17",
"",
"Aptus 17",
"Aptus 22",
"Aptus 75",
"Aptus 65",
"Aptus 54S",
"Aptus 65S",
"Aptus 75S",
"AFi 5",
"AFi 6",
"AFi 7",
"AFi-II 7",
"Aptus-II 7",
"",
"Aptus-II 6",
"",
"",
"Aptus-II 10",
"Aptus-II 5",
"",
"",
"",
"",
"Aptus-II 10R",
"Aptus-II 8",
"",
"Aptus-II 12",
"",
"AFi-II 12"};
float romm_cam[3][3];
fseek(ifp, offset, SEEK_SET);
while (1)
{
if (get4() != 0x504b5453)
break;
get4();
fread(data, 1, 40, ifp);
skip = get4();
from = ftell(ifp);
// IB start
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(data, "CameraObj_camera_type"))
{
stmread(imgdata.lens.makernotes.body, skip, ifp);
}
if (!strcmp(data, "back_serial_number"))
{
char buffer[sizeof(imgdata.shootinginfo.BodySerial)];
char *words[4];
int nwords;
stmread(buffer, skip, ifp);
nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.BodySerial));
strcpy(imgdata.shootinginfo.BodySerial, words[0]);
}
if (!strcmp(data, "CaptProf_serial_number"))
{
char buffer[sizeof(imgdata.shootinginfo.InternalBodySerial)];
char *words[4];
int nwords;
stmread(buffer, skip, ifp);
nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial));
strcpy(imgdata.shootinginfo.InternalBodySerial, words[0]);
}
#endif
// IB end
if (!strcmp(data, "JPEG_preview_data"))
{
thumb_offset = from;
thumb_length = skip;
}
if (!strcmp(data, "icc_camera_profile"))
{
profile_offset = from;
profile_length = skip;
}
if (!strcmp(data, "ShootObj_back_type"))
{
fscanf(ifp, "%d", &i);
if ((unsigned)i < sizeof mod / sizeof(*mod))
strcpy(model, mod[i]);
}
if (!strcmp(data, "icc_camera_to_tone_matrix"))
{
for (i = 0; i < 9; i++)
((float *)romm_cam)[i] = int_to_float(get4());
romm_coeff(romm_cam);
}
if (!strcmp(data, "CaptProf_color_matrix"))
{
for (i = 0; i < 9; i++)
fscanf(ifp, "%f", (float *)romm_cam + i);
romm_coeff(romm_cam);
}
if (!strcmp(data, "CaptProf_number_of_planes"))
fscanf(ifp, "%d", &planes);
if (!strcmp(data, "CaptProf_raw_data_rotation"))
fscanf(ifp, "%d", &flip);
if (!strcmp(data, "CaptProf_mosaic_pattern"))
FORC4
{
fscanf(ifp, "%d", &i);
if (i == 1)
frot = c ^ (c >> 1);
}
if (!strcmp(data, "ImgProf_rotation_angle"))
{
fscanf(ifp, "%d", &i);
flip = i - flip;
}
if (!strcmp(data, "NeutObj_neutrals") && !cam_mul[0])
{
FORC4 fscanf(ifp, "%d", neut + c);
FORC3 cam_mul[c] = (float)neut[0] / neut[c + 1];
}
if (!strcmp(data, "Rows_data"))
load_flags = get4();
parse_mos(from);
fseek(ifp, skip + from, SEEK_SET);
}
if (planes)
filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3];
}
void CLASS linear_table(unsigned len)
{
int i;
if (len > 0x10000)
len = 0x10000;
read_shorts(curve, len);
for (i = len; i < 0x10000; i++)
curve[i] = curve[i - 1];
maximum = curve[len < 0x1000 ? 0xfff : len - 1];
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS Kodak_WB_0x08tags(int wb, unsigned type)
{
float mul[3] = {1, 1, 1}, num, mul2;
int c;
FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num;
imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1];
mul2 = mul[1] * mul[1];
imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0];
imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2];
return;
}
/* Thanks to Alexey Danilchenko for wb as-shot parsing code */
void CLASS parse_kodak_ifd(int base)
{
unsigned entries, tag, type, len, save;
int i, c, wbi = -2;
float mul[3] = {1, 1, 1}, num;
static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042};
// int a_blck = 0;
entries = get2();
if (entries > 1024)
return;
INT64 fsize = ifp->size();
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
INT64 savepos = ftell(ifp);
if (len > 8 && len + savepos > 2 * fsize)
continue;
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
if (tag == 1011)
imgdata.other.FlashEC = getreal(type);
if (tag == 1020)
wbi = getint(type);
if (tag == 1021 && len == 72)
{ /* WB set in software */
fseek(ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2());
wbi = -2;
}
if ((tag == 1030) && (len == 1))
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 1043) && (len == 1))
imgdata.other.SensorTemperature = getreal(type);
if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C")))
black = get2();
if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C")))
{
if (black) // already set by tag 0x03ef
black = (black + get2()) / 2;
else
black = get2();
}
INT64 _pos2 = ftell(ifp);
if (tag == 0x0848)
Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type);
if (tag == 0x0849)
Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type);
if (tag == 0x084a)
Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type);
if (tag == 0x084b)
Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type);
if (tag == 0x084c)
Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type);
if (tag == 0x084d)
Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type);
if (tag == 0x0e93)
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = get2();
if (tag == 0x09ce)
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
if (tag == 0xfa00)
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if (tag == 0xfa27)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];
}
if (tag == 0xfa28)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];
}
if (tag == 0xfa29)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];
}
if (tag == 0xfa2a)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];
}
fseek(ifp, _pos2, SEEK_SET);
if (tag == 2120 + wbi || (wbi < 0 && tag == 2125)) /* use Auto WB if illuminant index is not set */
{
FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num;
FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */
}
if (tag == 2317)
linear_table(len);
if (tag == 0x903)
iso_speed = getreal(type);
// if (tag == 6020) iso_speed = getint(type);
if (tag == 64013)
wbi = fgetc(ifp);
if ((unsigned)wbi < 7 && tag == wbtag[wbi])
FORC3 cam_mul[c] = get4();
if (tag == 64019)
width = getint(type);
if (tag == 64020)
height = (getint(type) + 1) & -2;
fseek(ifp, save, SEEK_SET);
}
}
#else
void CLASS parse_kodak_ifd(int base)
{
unsigned entries, tag, type, len, save;
int i, c, wbi = -2, wbtemp = 6500;
float mul[3] = {1, 1, 1}, num;
static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042};
entries = get2();
if (entries > 1024)
return;
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (tag == 1020)
wbi = getint(type);
if (tag == 1021 && len == 72)
{ /* WB set in software */
fseek(ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, get2());
wbi = -2;
}
if (tag == 2118)
wbtemp = getint(type);
if (tag == 2120 + wbi && wbi >= 0)
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, getreal(type));
if (tag == 2130 + wbi)
FORC3 mul[c] = getreal(type);
if (tag == 2140 + wbi && wbi >= 0)
FORC3
{
for (num = i = 0; i < 4; i++)
num += getreal(type) * pow(wbtemp / 100.0, i);
cam_mul[c] = 2048 / fMAX(1.0, (num * mul[c]));
}
if (tag == 2317)
linear_table(len);
if (tag == 6020)
iso_speed = getint(type);
if (tag == 64013)
wbi = fgetc(ifp);
if ((unsigned)wbi < 7 && tag == wbtag[wbi])
FORC3 cam_mul[c] = get4();
if (tag == 64019)
width = getint(type);
if (tag == 64020)
height = (getint(type) + 1) & -2;
fseek(ifp, save, SEEK_SET);
}
}
#endif
//@end COMMON
void CLASS parse_minolta(int base);
int CLASS parse_tiff(int base);
//@out COMMON
int CLASS parse_tiff_ifd(int base)
{
unsigned entries, tag, type, len, plen = 16, save;
int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0;
char *cbuf, *cp;
uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256];
double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num;
double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1};
unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095};
unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0;
struct jhead jh;
int pana_raw = 0;
#ifndef LIBRAW_LIBRARY_BUILD
FILE *sfp;
#endif
if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0])
return 1;
ifd = tiff_nifds++;
for (j = 0; j < 4; j++)
for (i = 0; i < 4; i++)
cc[j][i] = i == j;
entries = get2();
if (entries > 512)
return 1;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 fsize = ifp->size();
#endif
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
#ifdef LIBRAW_LIBRARY_BUILD
INT64 savepos = ftell(ifp);
if (len > 8 && len + savepos > fsize * 2)
continue; // skip tag pointing out of 2xfile
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : 0), type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncasecmp(make, "SONY", 4) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) ||
!strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "HV", 2))))
{
switch (tag)
{
case 0x7300: // SR2 black level
for (int i = 0; i < 4 && i < len; i++)
cblack[i] = get2();
break;
case 0x7302:
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = get2();
break;
case 0x7312:
{
int i, lc[4];
FORC4 lc[c] = get2();
i = (lc[1] == 1024 && lc[2] == 1024) << 1;
SWAP(lc[i], lc[i + 1]);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c] = lc[c];
}
break;
case 0x7480:
case 0x7820:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];
break;
case 0x7481:
case 0x7821:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1];
break;
case 0x7482:
case 0x7822:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];
break;
case 0x7483:
case 0x7823:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1];
break;
case 0x7484:
case 0x7824:
imgdata.color.WBCT_Coeffs[0][0] = 4500;
FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = get2();
imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2];
break;
case 0x7486:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];
break;
case 0x7825:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];
break;
case 0x7826:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1];
break;
case 0x7827:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1];
break;
case 0x7828:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1];
break;
case 0x7829:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1];
break;
case 0x782a:
imgdata.color.WBCT_Coeffs[1][0] = 8500;
FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = get2();
imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2];
break;
case 0x782b:
imgdata.color.WBCT_Coeffs[2][0] = 6000;
FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = get2();
imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2];
break;
case 0x782c:
imgdata.color.WBCT_Coeffs[3][0] = 3200;
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1];
break;
case 0x782d:
imgdata.color.WBCT_Coeffs[4][0] = 2500;
FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = get2();
imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2];
break;
case 0x787f:
FORC3 imgdata.color.linear_max[c] = get2();
imgdata.color.linear_max[3] = imgdata.color.linear_max[1];
break;
}
}
#endif
switch (tag)
{
case 1:
if (len == 4)
pana_raw = get4();
break;
case 5:
width = get2();
break;
case 6:
height = get2();
break;
case 7:
width += get2();
break;
case 9:
if ((i = get2()))
filters = i;
#ifdef LIBRAW_LIBRARY_BUILD
if (pana_raw && len == 1 && type == 3)
pana_black[3] += i;
#endif
break;
case 8:
case 10:
#ifdef LIBRAW_LIBRARY_BUILD
if (pana_raw && len == 1 && type == 3)
pana_black[3] += get2();
#endif
break;
case 14:
case 15:
case 16:
#ifdef LIBRAW_LIBRARY_BUILD
if (pana_raw)
{
imgdata.color.linear_max[tag - 14] = get2();
if (tag == 15)
imgdata.color.linear_max[3] = imgdata.color.linear_max[1];
}
#endif
break;
case 17:
case 18:
if (type == 3 && len == 1)
cam_mul[(tag - 17) * 2] = get2() / 256.0;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 19:
if (pana_raw)
{
ushort nWB, cnt, tWB;
nWB = get2();
if (nWB > 0x100)
break;
for (cnt = 0; cnt < nWB; cnt++)
{
tWB = get2();
if (tWB < 0x100)
{
imgdata.color.WB_Coeffs[tWB][0] = get2();
imgdata.color.WB_Coeffs[tWB][2] = get2();
imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100;
}
else
get4();
}
}
break;
#endif
case 23:
if (type == 3)
iso_speed = get2();
break;
case 28:
case 29:
case 30:
#ifdef LIBRAW_LIBRARY_BUILD
if (pana_raw && len == 1 && type == 3)
{
pana_black[tag - 28] = get2();
}
else
#endif
{
cblack[tag - 28] = get2();
cblack[3] = cblack[1];
}
break;
case 36:
case 37:
case 38:
cam_mul[tag - 36] = get2();
break;
case 39:
#ifdef LIBRAW_LIBRARY_BUILD
if (pana_raw)
{
ushort nWB, cnt, tWB;
nWB = get2();
if (nWB > 0x100)
break;
for (cnt = 0; cnt < nWB; cnt++)
{
tWB = get2();
if (tWB < 0x100)
{
imgdata.color.WB_Coeffs[tWB][0] = get2();
imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2();
imgdata.color.WB_Coeffs[tWB][2] = get2();
}
else
fseek(ifp, 6, SEEK_CUR);
}
}
break;
#endif
if (len < 50 || cam_mul[0])
break;
fseek(ifp, 12, SEEK_CUR);
FORC3 cam_mul[c] = get2();
break;
case 46:
if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)
break;
thumb_offset = ftell(ifp) - 2;
thumb_length = len;
break;
case 61440: /* Fuji HS10 table */
fseek(ifp, get4() + base, SEEK_SET);
parse_tiff_ifd(base);
break;
case 2:
case 256:
case 61441: /* ImageWidth */
tiff_ifd[ifd].t_width = getint(type);
break;
case 3:
case 257:
case 61442: /* ImageHeight */
tiff_ifd[ifd].t_height = getint(type);
break;
case 258: /* BitsPerSample */
case 61443:
tiff_ifd[ifd].samples = len & 7;
tiff_ifd[ifd].bps = getint(type);
if (tiff_bps < tiff_ifd[ifd].bps)
tiff_bps = tiff_ifd[ifd].bps;
break;
case 61446:
raw_height = 0;
if (tiff_ifd[ifd].bps > 12)
break;
load_raw = &CLASS packed_load_raw;
load_flags = get4() ? 24 : 80;
break;
case 259: /* Compression */
tiff_ifd[ifd].comp = getint(type);
break;
case 262: /* PhotometricInterpretation */
tiff_ifd[ifd].phint = get2();
break;
case 270: /* ImageDescription */
fread(desc, 512, 1, ifp);
break;
case 271: /* Make */
fgets(make, 64, ifp);
break;
case 272: /* Model */
fgets(model, 64, ifp);
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 278:
tiff_ifd[ifd].rows_per_strip = getint(type);
break;
#endif
case 280: /* Panasonic RW2 offset */
if (type != 4)
break;
load_raw = &CLASS panasonic_load_raw;
load_flags = 0x2008;
case 273: /* StripOffset */
#ifdef LIBRAW_LIBRARY_BUILD
if (len > 1 && len < 16384)
{
off_t sav = ftell(ifp);
tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int));
tiff_ifd[ifd].strip_offsets_count = len;
for (int i = 0; i < len; i++)
tiff_ifd[ifd].strip_offsets[i] = get4() + base;
fseek(ifp, sav, SEEK_SET); // restore position
}
/* fallback */
#endif
case 513: /* JpegIFOffset */
case 61447:
tiff_ifd[ifd].offset = get4() + base;
if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0)
{
fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET);
if (ljpeg_start(&jh, 1))
{
tiff_ifd[ifd].comp = 6;
tiff_ifd[ifd].t_width = jh.wide;
tiff_ifd[ifd].t_height = jh.high;
tiff_ifd[ifd].bps = jh.bits;
tiff_ifd[ifd].samples = jh.clrs;
if (!(jh.sraw || (jh.clrs & 1)))
tiff_ifd[ifd].t_width *= jh.clrs;
if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs)
{
tiff_ifd[ifd].t_width /= 2;
tiff_ifd[ifd].t_height *= 2;
}
i = order;
parse_tiff(tiff_ifd[ifd].offset + 12);
order = i;
}
}
break;
case 274: /* Orientation */
tiff_ifd[ifd].t_flip = "50132467"[get2() & 7] - '0';
break;
case 277: /* SamplesPerPixel */
tiff_ifd[ifd].samples = getint(type) & 7;
break;
case 279: /* StripByteCounts */
#ifdef LIBRAW_LIBRARY_BUILD
if (len > 1 && len < 16384)
{
off_t sav = ftell(ifp);
tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int));
tiff_ifd[ifd].strip_byte_counts_count = len;
for (int i = 0; i < len; i++)
tiff_ifd[ifd].strip_byte_counts[i] = get4();
fseek(ifp, sav, SEEK_SET); // restore position
}
/* fallback */
#endif
case 514:
case 61448:
tiff_ifd[ifd].bytes = get4();
break;
case 61454: // FujiFilm "As Shot"
FORC3 cam_mul[(4 - c) % 3] = getint(type);
break;
case 305:
case 11: /* Software */
fgets(software, 64, ifp);
if (!strncmp(software, "Adobe", 5) || !strncmp(software, "dcraw", 5) || !strncmp(software, "UFRaw", 5) ||
!strncmp(software, "Bibble", 6) || !strcmp(software, "Digital Photo Professional"))
is_raw = 0;
break;
case 306: /* DateTime */
get_timestamp(0);
break;
case 315: /* Artist */
fread(artist, 64, 1, ifp);
break;
case 317:
tiff_ifd[ifd].predictor = getint(type);
break;
case 322: /* TileWidth */
tiff_ifd[ifd].t_tile_width = getint(type);
break;
case 323: /* TileLength */
tiff_ifd[ifd].t_tile_length = getint(type);
break;
case 324: /* TileOffsets */
tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4();
if (len == 1)
tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0;
if (len == 4)
{
load_raw = &CLASS sinar_4shot_load_raw;
is_raw = 5;
}
break;
case 325:
tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4();
break;
case 330: /* SubIFDs */
if (!strcmp(model, "DSLR-A100") && tiff_ifd[ifd].t_width == 3872)
{
load_raw = &CLASS sony_arw_load_raw;
data_offset = get4() + base;
ifd++;
#ifdef LIBRAW_LIBRARY_BUILD
if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "Hasselblad", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag)
{
fseek(ifp, ftell(ifp) + 4, SEEK_SET);
fseek(ifp, get4() + base, SEEK_SET);
parse_tiff_ifd(base);
break;
}
#endif
if (len > 1000)
len = 1000; /* 1000 SubIFDs is enough */
while (len--)
{
i = ftell(ifp);
fseek(ifp, get4() + base, SEEK_SET);
if (parse_tiff_ifd(base))
break;
fseek(ifp, i + 4, SEEK_SET);
}
break;
case 339:
tiff_ifd[ifd].sample_format = getint(type);
break;
case 400:
strcpy(make, "Sarnoff");
maximum = 0xfff;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 700:
if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000)
{
xmpdata = (char *)malloc(xmplen = len + 1);
fread(xmpdata, len, 1, ifp);
xmpdata[len] = 0;
}
break;
#endif
case 28688:
FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff;
for (i = 0; i < 5; i++)
for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++)
curve[j] = curve[j - 1] + (1 << i);
break;
case 29184:
sony_offset = get4();
break;
case 29185:
sony_length = get4();
break;
case 29217:
sony_key = get4();
break;
case 29264:
parse_minolta(ftell(ifp));
raw_width = 0;
break;
case 29443:
FORC4 cam_mul[c ^ (c < 2)] = get2();
break;
case 29459:
FORC4 cam_mul[c] = get2();
i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1;
SWAP(cam_mul[i], cam_mul[i + 1])
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800
for (i = 0; i < 3; i++)
{
float num = 0.0;
for (c = 0; c < 3; c++)
{
imgdata.color.ccm[i][c] = (float)((short)get2());
num += imgdata.color.ccm[i][c];
}
if (num > 0.01)
FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num;
}
break;
#endif
case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black = i;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("...Sony black: %u cblack: %u %u %u %u\n"), black, cblack[0], cblack[1], cblack[2],
cblack[3]);
#endif
break;
case 33405: /* Model2 */
fgets(model2, 64, ifp);
break;
case 33421: /* CFARepeatPatternDim */
if (get2() == 6 && get2() == 6)
filters = 9;
break;
case 33422: /* CFAPattern */
if (filters == 9)
{
FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3;
break;
}
case 64777: /* Kodak P-series */
if (len == 36)
{
filters = 9;
colors = 3;
FORC(36) xtrans[0][c] = fgetc(ifp) & 3;
}
else if (len > 0)
{
if ((plen = len) > 16)
plen = 16;
fread(cfa_pat, 1, plen, ifp);
for (colors = cfa = i = 0; i < plen && colors < 4; i++)
{
colors += !(cfa & (1 << cfa_pat[i]));
cfa |= 1 << cfa_pat[i];
}
if (cfa == 070)
memcpy(cfa_pc, "\003\004\005", 3); /* CMY */
if (cfa == 072)
memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */
goto guess_cfa_pc;
}
break;
case 33424:
case 65024:
fseek(ifp, get4() + base, SEEK_SET);
parse_kodak_ifd(base);
break;
case 33434: /* ExposureTime */
tiff_ifd[ifd].t_shutter = shutter = getreal(type);
break;
case 33437: /* FNumber */
aperture = getreal(type);
break;
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
case 0x9400:
imgdata.other.exifAmbientTemperature = getreal(type);
if ((imgdata.other.CameraTemperature > -273.15f) &&
(OlyID == 0x4434353933ULL)) // TG-5
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
break;
case 0x9401:
imgdata.other.exifHumidity = getreal(type);
break;
case 0x9402:
imgdata.other.exifPressure = getreal(type);
break;
case 0x9403:
imgdata.other.exifWaterDepth = getreal(type);
break;
case 0x9404:
imgdata.other.exifAcceleration = getreal(type);
break;
case 0x9405:
imgdata.other.exifCameraElevationAngle = getreal(type);
break;
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
case 0xc62f:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f));
break;
// IB end
#endif
case 34306: /* Leaf white balance */
FORC4 cam_mul[c ^ 1] = 4096.0 / get2();
break;
case 34307: /* Leaf CatchLight color matrix */
fread(software, 1, 7, ifp);
if (strncmp(software, "MATRIX", 6))
break;
colors = 4;
for (raw_color = i = 0; i < 3; i++)
{
FORC4 fscanf(ifp, "%f", &rgb_cam[i][c ^ 1]);
if (!use_camera_wb)
continue;
num = 0;
FORC4 num += rgb_cam[i][c];
FORC4 rgb_cam[i][c] /= MAX(1, num);
}
break;
case 34310: /* Leaf metadata */
parse_mos(ftell(ifp));
case 34303:
strcpy(make, "Leaf");
break;
case 34665: /* EXIF tag */
fseek(ifp, get4() + base, SEEK_SET);
parse_exif(base);
break;
case 34853: /* GPSInfo tag */
{
unsigned pos;
fseek(ifp, pos = (get4() + base), SEEK_SET);
parse_gps(base);
#ifdef LIBRAW_LIBRARY_BUILD
fseek(ifp, pos, SEEK_SET);
parse_gps_libraw(base);
#endif
}
break;
case 34675: /* InterColorProfile */
case 50831: /* AsShotICCProfile */
profile_offset = ftell(ifp);
profile_length = len;
break;
case 37122: /* CompressedBitsPerPixel */
kodak_cbpp = get4();
break;
case 37386: /* FocalLength */
focal_len = getreal(type);
break;
case 37393: /* ImageNumber */
shot_order = getint(type);
break;
case 37400: /* old Kodak KDC tag */
for (raw_color = i = 0; i < 3; i++)
{
getreal(type);
FORC3 rgb_cam[i][c] = getreal(type);
}
break;
case 40976:
strip_offset = get4();
switch (tiff_ifd[ifd].comp)
{
case 32770:
load_raw = &CLASS samsung_load_raw;
break;
case 32772:
load_raw = &CLASS samsung2_load_raw;
break;
case 32773:
load_raw = &CLASS samsung3_load_raw;
break;
}
break;
case 46275: /* Imacon tags */
strcpy(make, "Imacon");
data_offset = ftell(ifp);
ima_len = len;
break;
case 46279:
if (!ima_len)
break;
fseek(ifp, 38, SEEK_CUR);
case 46274:
fseek(ifp, 40, SEEK_CUR);
raw_width = get4();
raw_height = get4();
left_margin = get4() & 7;
width = raw_width - left_margin - (get4() & 7);
top_margin = get4() & 7;
height = raw_height - top_margin - (get4() & 7);
if (raw_width == 7262 && ima_len == 234317952)
{
height = 5412;
width = 7216;
left_margin = 7;
filters = 0;
}
else if (raw_width == 7262)
{
height = 5444;
width = 7244;
left_margin = 7;
}
fseek(ifp, 52, SEEK_CUR);
FORC3 cam_mul[c] = getreal(11);
fseek(ifp, 114, SEEK_CUR);
flip = (get2() >> 7) * 90;
if (width * height * 6 == ima_len)
{
if (flip % 180 == 90)
SWAP(width, height);
raw_width = width;
raw_height = height;
left_margin = top_margin = filters = flip = 0;
}
sprintf(model, "Ixpress %d-Mp", height * width / 1000000);
load_raw = &CLASS imacon_full_load_raw;
if (filters)
{
if (left_margin & 1)
filters = 0x61616161;
load_raw = &CLASS unpacked_load_raw;
}
maximum = 0xffff;
break;
case 50454: /* Sinar tag */
case 50455:
if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len)))
break;
#ifndef LIBRAW_LIBRARY_BUILD
fread(cbuf, 1, len, ifp);
#else
if (fread(cbuf, 1, len, ifp) != len)
throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle
#endif
cbuf[len - 1] = 0;
for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\n'))
if (!strncmp(++cp, "Neutral ", 8))
sscanf(cp + 8, "%f %f %f", cam_mul, cam_mul + 1, cam_mul + 2);
free(cbuf);
break;
case 50458:
if (!make[0])
strcpy(make, "Hasselblad");
break;
case 50459: /* Hasselblad tag */
#ifdef LIBRAW_LIBRARY_BUILD
libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1;
#endif
i = order;
j = ftell(ifp);
c = tiff_nifds;
order = get2();
fseek(ifp, j + (get2(), get4()), SEEK_SET);
parse_tiff_ifd(j);
maximum = 0xffff;
tiff_nifds = c;
order = i;
break;
case 50706: /* DNGVersion */
FORC4 dng_version = (dng_version << 8) + fgetc(ifp);
if (!make[0])
strcpy(make, "DNG");
is_raw = 1;
break;
case 50708: /* UniqueCameraModel */
#ifdef LIBRAW_LIBRARY_BUILD
stmread(imgdata.color.UniqueCameraModel, len, ifp);
imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel) - 1] = 0;
#endif
if (model[0])
break;
#ifndef LIBRAW_LIBRARY_BUILD
fgets(make, 64, ifp);
#else
strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel)));
#endif
if ((cp = strchr(make, ' ')))
{
strcpy(model, cp + 1);
*cp = 0;
}
break;
case 50710: /* CFAPlaneColor */
if (filters == 9)
break;
if (len > 4)
len = 4;
colors = len;
fread(cfa_pc, 1, colors, ifp);
guess_cfa_pc:
FORCC tab[cfa_pc[c]] = c;
cdesc[c] = 0;
for (i = 16; i--;)
filters = filters << 2 | tab[cfa_pat[i % plen]];
filters -= !filters;
break;
case 50711: /* CFALayout */
if (get2() == 2)
fuji_width = 1;
break;
case 291:
case 50712: /* LinearizationTable */
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINTABLE;
tiff_ifd[ifd].lineartable_offset = ftell(ifp);
tiff_ifd[ifd].lineartable_len = len;
#endif
linear_table(len);
break;
case 50713: /* BlackLevelRepeatDim */
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK;
tiff_ifd[ifd].dng_levels.dng_cblack[4] =
#endif
cblack[4] = get2();
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.dng_cblack[5] =
#endif
cblack[5] = get2();
if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof(cblack[0]) - 6))
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] =
#endif
cblack[4] = cblack[5] = 1;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0xf00d:
if (strcmp(model, "X-A3") && strcmp(model, "X-A10"))
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][(4 - c) % 3] = getint(type);
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1];
}
break;
case 0xf00c:
if (strcmp(model, "X-A3") && strcmp(model, "X-A10"))
{
unsigned fwb[4];
FORC4 fwb[c] = get4();
if (fwb[3] < 0x100)
{
imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1];
imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0];
imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2];
if ((fwb[3] == 17) && (libraw_internal_data.unpacker_data.lenRAFData > 3) &&
(libraw_internal_data.unpacker_data.lenRAFData < 10240000))
{
INT64 f_save = ftell(ifp);
ushort *rafdata = (ushort *)malloc(sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData);
fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET);
fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp);
fseek(ifp, f_save, SEEK_SET);
int fj, found = 0;
for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++)
{
if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2]))
{
if (rafdata[fi - 15] != fwb[0])
continue;
for (int wb_ind = 0, ofst = fi - 15; wb_ind < nFuji_wb_list1; wb_ind++, ofst += 3)
{
imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][1] =
imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][3] = rafdata[ofst];
imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][0] = rafdata[ofst + 1];
imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][2] = rafdata[ofst + 2];
}
fi += 0x60;
for (fj = fi; fj < (fi + 15); fj += 3)
if (rafdata[fj] != rafdata[fi])
{
found = 1;
break;
}
if (found)
{
fj = fj - 93;
for (int iCCT = 0; iCCT < 31; iCCT++)
{
imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT];
imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT * 3 + 1 + fj];
imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT * 3 + fj];
imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT * 3 + 2 + fj];
}
}
free(rafdata);
break;
}
}
}
}
FORC4 fwb[c] = get4();
if (fwb[3] < 0x100)
{
imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1];
imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0];
imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2];
}
}
break;
#endif
#ifdef LIBRAW_LIBRARY_BUILD
case 50709:
stmread(imgdata.color.LocalizedCameraModel, len, ifp);
break;
#endif
case 61450:
cblack[4] = cblack[5] = MIN(sqrt((double)len), 64);
case 50714: /* BlackLevel */
#ifdef LIBRAW_LIBRARY_BUILD
if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black
{
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK;
for (i = 0; i < colors && i < 4 && i < len; i++)
tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = getreal(type) + 0.5;
tiff_ifd[ifd].dng_levels.dng_black = black = 0;
}
else
#endif
if ((cblack[4] * cblack[5] < 2) && len == 1)
{
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK;
tiff_ifd[ifd].dng_levels.dng_black =
#endif
black = getreal(type);
}
else if (cblack[4] * cblack[5] <= len)
{
FORC(cblack[4] * cblack[5])
cblack[6 + c] = getreal(type);
black = 0;
FORC4
cblack[c] = 0;
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 50714)
{
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK;
FORC(cblack[4] * cblack[5])
tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c];
tiff_ifd[ifd].dng_levels.dng_black = 0;
FORC4
tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0;
}
#endif
}
break;
case 50715: /* BlackLevelDeltaH */
case 50716: /* BlackLevelDeltaV */
for (num = i = 0; i < len && i < 65536; i++)
num += getreal(type);
black += num / len + 0.5;
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.dng_black += num / len + 0.5;
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK;
#endif
break;
case 50717: /* WhiteLevel */
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_WHITE;
tiff_ifd[ifd].dng_levels.dng_whitelevel[0] =
#endif
maximum = getint(type);
#ifdef LIBRAW_LIBRARY_BUILD
if (tiff_ifd[ifd].samples > 1) // Linear DNG case
for (i = 1; i < colors && i < 4 && i < len; i++)
tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type);
#endif
break;
case 50718: /* DefaultScale */
pixel_aspect = getreal(type);
pixel_aspect /= getreal(type);
if (pixel_aspect > 0.995 && pixel_aspect < 1.005)
pixel_aspect = 1.0;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 50719: /* DefaultCropOrigin */
if (len == 2)
{
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPORIGIN;
tiff_ifd[ifd].dng_levels.default_crop[0] = getreal(type);
tiff_ifd[ifd].dng_levels.default_crop[1] = getreal(type);
}
break;
case 50720: /* DefaultCropSize */
if (len == 2)
{
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPSIZE;
tiff_ifd[ifd].dng_levels.default_crop[2] = getreal(type);
tiff_ifd[ifd].dng_levels.default_crop[3] = getreal(type);
}
break;
#endif
#ifdef LIBRAW_LIBRARY_BUILD
case 50778:
tiff_ifd[ifd].dng_color[0].illuminant = get2();
tiff_ifd[ifd].dng_color[0].parsedfields |= LIBRAW_DNGFM_ILLUMINANT;
break;
case 50779:
tiff_ifd[ifd].dng_color[1].illuminant = get2();
tiff_ifd[ifd].dng_color[1].parsedfields |= LIBRAW_DNGFM_ILLUMINANT;
break;
#endif
case 50721: /* ColorMatrix1 */
case 50722: /* ColorMatrix2 */
#ifdef LIBRAW_LIBRARY_BUILD
i = tag == 50721 ? 0 : 1;
tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_COLORMATRIX;
#endif
FORCC for (j = 0; j < 3; j++)
{
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_color[i].colormatrix[c][j] =
#endif
cm[c][j] = getreal(type);
}
use_cm = 1;
break;
case 0xc714: /* ForwardMatrix1 */
case 0xc715: /* ForwardMatrix2 */
#ifdef LIBRAW_LIBRARY_BUILD
i = tag == 0xc714 ? 0 : 1;
tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
#endif
for (j = 0; j < 3; j++)
FORCC
{
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] =
#endif
fm[j][c] = getreal(type);
}
break;
case 50723: /* CameraCalibration1 */
case 50724: /* CameraCalibration2 */
#ifdef LIBRAW_LIBRARY_BUILD
j = tag == 50723 ? 0 : 1;
tiff_ifd[ifd].dng_color[j].parsedfields |= LIBRAW_DNGFM_CALIBRATION;
#endif
for (i = 0; i < colors; i++)
FORCC
{
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_color[j].calibration[i][c] =
#endif
cc[i][c] = getreal(type);
}
break;
case 50727: /* AnalogBalance */
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ANALOGBALANCE;
#endif
FORCC
{
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.analogbalance[c] =
#endif
ab[c] = getreal(type);
}
break;
case 50728: /* AsShotNeutral */
FORCC asn[c] = getreal(type);
break;
case 50729: /* AsShotWhiteXY */
xyz[0] = getreal(type);
xyz[1] = getreal(type);
xyz[2] = 1 - xyz[0] - xyz[1];
FORC3 xyz[c] /= d65_white[c];
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 50730: /* DNG: Baseline Exposure */
baseline_exposure = getreal(type);
break;
#endif
// IB start
case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */
#ifdef LIBRAW_LIBRARY_BUILD
{
char mbuf[64];
unsigned short makernote_found = 0;
INT64 curr_pos, start_pos = ftell(ifp);
unsigned MakN_order, m_sorder = order;
unsigned MakN_length;
unsigned pos_in_original_raw;
fread(mbuf, 1, 6, ifp);
if (!strcmp(mbuf, "Adobe"))
{
order = 0x4d4d; // Adobe header is always in "MM" / big endian
curr_pos = start_pos + 6;
while (curr_pos + 8 - start_pos <= len)
{
fread(mbuf, 1, 4, ifp);
curr_pos += 8;
if (!strncmp(mbuf, "MakN", 4))
{
makernote_found = 1;
MakN_length = get4();
MakN_order = get2();
pos_in_original_raw = get4();
order = MakN_order;
parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG);
break;
}
}
}
else
{
fread(mbuf + 6, 1, 2, ifp);
if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG"))
{
makernote_found = 1;
fseek(ifp, start_pos, SEEK_SET);
parse_makernote_0xc634(base, 0, CameraDNG);
}
}
fseek(ifp, start_pos, SEEK_SET);
order = m_sorder;
}
// IB end
#endif
if (dng_version)
break;
parse_minolta(j = get4() + base);
fseek(ifp, j, SEEK_SET);
parse_tiff_ifd(base);
break;
case 50752:
read_shorts(cr2_slice, 3);
break;
case 50829: /* ActiveArea */
top_margin = getint(type);
left_margin = getint(type);
height = getint(type) - top_margin;
width = getint(type) - left_margin;
break;
case 50830: /* MaskedAreas */
for (i = 0; i < len && i < 32; i++)
((int *)mask)[i] = getint(type);
black = 0;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 50970: /* PreviewColorSpace */
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_PREVIEWCS;
tiff_ifd[ifd].dng_levels.preview_colorspace = getint(type);
break;
#endif
case 51009: /* OpcodeList2 */
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_OPCODE2;
tiff_ifd[ifd].opcode2_offset =
#endif
meta_offset = ftell(ifp);
break;
case 64772: /* Kodak P-series */
if (len < 13)
break;
fseek(ifp, 16, SEEK_CUR);
data_offset = get4();
fseek(ifp, 28, SEEK_CUR);
data_offset += get4();
load_raw = &CLASS packed_load_raw;
break;
case 65026:
if (type == 2)
fgets(model2, 64, ifp);
}
fseek(ifp, save, SEEK_SET);
}
if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length)))
{
fseek(ifp, sony_offset, SEEK_SET);
fread(buf, sony_length, 1, ifp);
sony_decrypt(buf, sony_length / 4, 1, sony_key);
#ifndef LIBRAW_LIBRARY_BUILD
sfp = ifp;
if ((ifp = tmpfile()))
{
fwrite(buf, sony_length, 1, ifp);
fseek(ifp, 0, SEEK_SET);
parse_tiff_ifd(-sony_offset);
fclose(ifp);
}
ifp = sfp;
#else
if (!ifp->tempbuffer_open(buf, sony_length))
{
parse_tiff_ifd(-sony_offset);
ifp->tempbuffer_close();
}
#endif
free(buf);
}
for (i = 0; i < colors; i++)
FORCC cc[i][c] *= ab[i];
if (use_cm)
{
FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] +=
cc[c][j] * cm[j][i] * xyz[i];
cam_xyz_coeff(cmatrix, cam_xyz);
}
if (asn[0])
{
cam_mul[3] = 0;
FORCC cam_mul[c] = 1 / asn[c];
}
if (!use_cm)
FORCC pre_mul[c] /= cc[c][c];
return 0;
}
int CLASS parse_tiff(int base)
{
int doff;
fseek(ifp, base, SEEK_SET);
order = get2();
if (order != 0x4949 && order != 0x4d4d)
return 0;
get2();
while ((doff = get4()))
{
fseek(ifp, doff + base, SEEK_SET);
if (parse_tiff_ifd(base))
break;
}
return 1;
}
void CLASS apply_tiff()
{
int max_samp = 0, ties = 0, raw = -1, thm = -1, i;
unsigned long long ns, os;
struct jhead jh;
thumb_misc = 16;
if (thumb_offset)
{
fseek(ifp, thumb_offset, SEEK_SET);
if (ljpeg_start(&jh, 1))
{
if ((unsigned)jh.bits < 17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000)
{
thumb_misc = jh.bits;
thumb_width = jh.wide;
thumb_height = jh.high;
}
}
}
for (i = tiff_nifds; i--;)
{
if (tiff_ifd[i].t_shutter)
shutter = tiff_ifd[i].t_shutter;
tiff_ifd[i].t_shutter = shutter;
}
for (i = 0; i < tiff_nifds; i++)
{
if (max_samp < tiff_ifd[i].samples)
max_samp = tiff_ifd[i].samples;
if (max_samp > 3)
max_samp = 3;
os = raw_width * raw_height;
ns = tiff_ifd[i].t_width * tiff_ifd[i].t_height;
if (tiff_bps)
{
os *= tiff_bps;
ns *= tiff_ifd[i].bps;
}
if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) &&
unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 &&
(unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++)))
{
raw_width = tiff_ifd[i].t_width;
raw_height = tiff_ifd[i].t_height;
tiff_bps = tiff_ifd[i].bps;
tiff_compress = tiff_ifd[i].comp;
data_offset = tiff_ifd[i].offset;
#ifdef LIBRAW_LIBRARY_BUILD
data_size = tiff_ifd[i].bytes;
#endif
tiff_flip = tiff_ifd[i].t_flip;
tiff_samples = tiff_ifd[i].samples;
tile_width = tiff_ifd[i].t_tile_width;
tile_length = tiff_ifd[i].t_tile_length;
shutter = tiff_ifd[i].t_shutter;
raw = i;
}
}
if (is_raw == 1 && ties)
is_raw = ties;
if (!tile_width)
tile_width = INT_MAX;
if (!tile_length)
tile_length = INT_MAX;
for (i = tiff_nifds; i--;)
if (tiff_ifd[i].t_flip)
tiff_flip = tiff_ifd[i].t_flip;
if (raw >= 0 && !load_raw)
switch (tiff_compress)
{
case 32767:
if (tiff_ifd[raw].bytes == raw_width * raw_height)
{
tiff_bps = 12;
load_raw = &CLASS sony_arw2_load_raw;
break;
}
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2)
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps)
{
raw_height += 8;
load_raw = &CLASS sony_arw_load_raw;
break;
}
load_flags = 79;
case 32769:
load_flags++;
case 32770:
case 32773:
goto slr;
case 0:
case 1:
#ifdef LIBRAW_LIBRARY_BUILD
// Sony 14-bit uncompressed
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2)
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10))
{
load_raw = &CLASS nikon_coolscan_load_raw;
raw_color = 1;
filters = 0;
break;
}
#endif
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3)
load_flags = 24;
if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8)
{
load_flags = 81;
tiff_bps = 12;
}
slr:
switch (tiff_bps)
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 12:
if (tiff_ifd[raw].phint == 2)
load_flags = 6;
load_raw = &CLASS packed_load_raw;
break;
case 14:
load_flags = 0;
case 16:
load_raw = &CLASS unpacked_load_raw;
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height)
load_raw = &CLASS olympus_load_raw;
}
break;
case 6:
case 7:
case 99:
load_raw = &CLASS lossless_jpeg_load_raw;
break;
case 262:
load_raw = &CLASS kodak_262_load_raw;
break;
case 34713:
if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes)
{
load_raw = &CLASS packed_load_raw;
load_flags = 1;
}
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2)
{
load_raw = &CLASS packed_load_raw;
if (model[0] == 'N')
load_flags = 80;
}
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes)
{
load_raw = &CLASS nikon_yuv_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
memset(cblack, 0, sizeof cblack);
filters = 0;
}
else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes)
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
order = 0x4d4d;
}
else
#ifdef LIBRAW_LIBRARY_BUILD
if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2)
{
load_raw = &CLASS packed_load_raw;
load_flags = 80;
}
else if (tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count &&
tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count)
{
int fit = 1;
for (int i = 0; i < tiff_ifd[raw].strip_byte_counts_count - 1; i++) // all but last
if (tiff_ifd[raw].strip_byte_counts[i] * 2 != tiff_ifd[raw].rows_per_strip * raw_width * 3)
{
fit = 0;
break;
}
if (fit)
load_raw = &CLASS nikon_load_striped_packed_raw;
else
load_raw = &CLASS nikon_load_raw; // fallback
}
else
#endif
load_raw = &CLASS nikon_load_raw;
break;
case 65535:
load_raw = &CLASS pentax_load_raw;
break;
case 65000:
switch (tiff_ifd[raw].phint)
{
case 2:
load_raw = &CLASS kodak_rgb_load_raw;
filters = 0;
break;
case 6:
load_raw = &CLASS kodak_ycbcr_load_raw;
filters = 0;
break;
case 32803:
load_raw = &CLASS kodak_65000_load_raw;
}
case 32867:
case 34892:
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 8:
break;
#endif
default:
is_raw = 0;
}
if (!dng_version)
if (((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) ||
(tiff_bps == 8 && strncmp(make, "Phase", 5) && strncmp(make, "Leaf", 4) && !strcasestr(make, "Kodak") &&
!strstr(model2, "DEBUG RAW"))) &&
strncmp(software, "Nikon Scan", 10))
is_raw = 0;
for (i = 0; i < tiff_nifds; i++)
if (i != raw &&
(tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */
&& tiff_ifd[i].bps > 0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 &&
unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 &&
tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps) + 1) >
thumb_width * thumb_height / (SQR(thumb_misc) + 1) &&
tiff_ifd[i].comp != 34892)
{
thumb_width = tiff_ifd[i].t_width;
thumb_height = tiff_ifd[i].t_height;
thumb_offset = tiff_ifd[i].offset;
thumb_length = tiff_ifd[i].bytes;
thumb_misc = tiff_ifd[i].bps;
thm = i;
}
if (thm >= 0)
{
thumb_misc |= tiff_ifd[thm].samples << 5;
switch (tiff_ifd[thm].comp)
{
case 0:
write_thumb = &CLASS layer_thumb;
break;
case 1:
if (tiff_ifd[thm].bps <= 8)
write_thumb = &CLASS ppm_thumb;
else if (!strncmp(make, "Imacon", 6))
write_thumb = &CLASS ppm16_thumb;
else
thumb_load_raw = &CLASS kodak_thumb_load_raw;
break;
case 65000:
thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw;
}
}
}
void CLASS parse_minolta(int base)
{
int save, tag, len, offset, high = 0, wide = 0, i, c;
short sorder = order;
fseek(ifp, base, SEEK_SET);
if (fgetc(ifp) || fgetc(ifp) - 'M' || fgetc(ifp) - 'R')
return;
order = fgetc(ifp) * 0x101;
offset = base + get4() + 8;
while ((save = ftell(ifp)) < offset)
{
for (tag = i = 0; i < 4; i++)
tag = tag << 8 | fgetc(ifp);
len = get4();
switch (tag)
{
case 0x505244: /* PRD */
fseek(ifp, 8, SEEK_CUR);
high = get2();
wide = get2();
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0x524946: /* RIF */
if (!strncasecmp(model, "DSLR-A100", 9))
{
fseek(ifp, 8, SEEK_CUR);
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2();
get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100;
}
break;
#endif
case 0x574247: /* WBG */
get4();
i = strcmp(model, "DiMAGE A200") ? 0 : 3;
FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2();
break;
case 0x545457: /* TTW */
parse_tiff(ftell(ifp));
data_offset = offset;
}
fseek(ifp, save + len + 8, SEEK_SET);
}
raw_height = high;
raw_width = wide;
order = sorder;
}
/*
Many cameras have a "debug mode" that writes JPEG and raw
at the same time. The raw file has no header, so try to
to open the matching JPEG file and read its metadata.
*/
void CLASS parse_external_jpeg()
{
const char *file, *ext;
char *jname, *jfile, *jext;
#ifndef LIBRAW_LIBRARY_BUILD
FILE *save = ifp;
#else
#if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310)
if (ifp->wfname())
{
std::wstring rawfile(ifp->wfname());
rawfile.replace(rawfile.length() - 3, 3, L"JPG");
if (!ifp->subfile_open(rawfile.c_str()))
{
parse_tiff(12);
thumb_offset = 0;
is_raw = 1;
ifp->subfile_close();
}
else
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA;
return;
}
#endif
if (!ifp->fname())
{
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA;
return;
}
#endif
ext = strrchr(ifname, '.');
file = strrchr(ifname, '/');
if (!file)
file = strrchr(ifname, '\\');
#ifndef LIBRAW_LIBRARY_BUILD
if (!file)
file = ifname - 1;
#else
if (!file)
file = (char *)ifname - 1;
#endif
file++;
if (!ext || strlen(ext) != 4 || ext - file != 8)
return;
jname = (char *)malloc(strlen(ifname) + 1);
merror(jname, "parse_external_jpeg()");
strcpy(jname, ifname);
jfile = file - ifname + jname;
jext = ext - ifname + jname;
if (strcasecmp(ext, ".jpg"))
{
strcpy(jext, isupper(ext[1]) ? ".JPG" : ".jpg");
if (isdigit(*file))
{
memcpy(jfile, file + 4, 4);
memcpy(jfile + 4, file, 4);
}
}
else
while (isdigit(*--jext))
{
if (*jext != '9')
{
(*jext)++;
break;
}
*jext = '0';
}
#ifndef LIBRAW_LIBRARY_BUILD
if (strcmp(jname, ifname))
{
if ((ifp = fopen(jname, "rb")))
{
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Reading metadata from %s ...\n"), jname);
#endif
parse_tiff(12);
thumb_offset = 0;
is_raw = 1;
fclose(ifp);
}
}
#else
if (strcmp(jname, ifname))
{
if (!ifp->subfile_open(jname))
{
parse_tiff(12);
thumb_offset = 0;
is_raw = 1;
ifp->subfile_close();
}
else
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA;
}
#endif
if (!timestamp)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA;
#endif
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("Failed to read metadata from %s\n"), jname);
#endif
}
free(jname);
#ifndef LIBRAW_LIBRARY_BUILD
ifp = save;
#endif
}
/*
CIFF block 0x1030 contains an 8x8 white sample.
Load this into white[][] for use in scale_colors().
*/
void CLASS ciff_block_1030()
{
static const ushort key[] = {0x410, 0x45f3};
int i, bpp, row, col, vbits = 0;
unsigned long bitbuf = 0;
if ((get2(), get4()) != 0x80008 || !get4())
return;
bpp = get2();
if (bpp != 10 && bpp != 12)
return;
for (i = row = 0; row < 8; row++)
for (col = 0; col < 8; col++)
{
if (vbits < bpp)
{
bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]);
vbits += 16;
}
white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp);
}
}
/*
Parse a CIFF file, better known as Canon CRW format.
*/
void CLASS parse_ciff(int offset, int length, int depth)
{
int tboff, nrecs, c, type, len, save, wbi = -1;
ushort key[] = {0x410, 0x45f3};
fseek(ifp, offset + length - 4, SEEK_SET);
tboff = get4() + offset;
fseek(ifp, tboff, SEEK_SET);
nrecs = get2();
if ((nrecs | depth) > 127)
return;
while (nrecs--)
{
type = get2();
len = get4();
save = ftell(ifp) + 4;
fseek(ifp, offset + get4(), SEEK_SET);
if ((((type >> 8) + 8) | 8) == 0x38)
{
parse_ciff(ftell(ifp), len, depth + 1); /* Parse a sub-table */
}
#ifdef LIBRAW_LIBRARY_BUILD
if (type == 0x3004)
parse_ciff(ftell(ifp), len, depth + 1);
#endif
if (type == 0x0810)
fread(artist, 64, 1, ifp);
if (type == 0x080a)
{
fread(make, 64, 1, ifp);
fseek(ifp, strbuflen(make) - 63, SEEK_CUR);
fread(model, 64, 1, ifp);
}
if (type == 0x1810)
{
width = get4();
height = get4();
pixel_aspect = int_to_float(get4());
flip = get4();
}
if (type == 0x1835) /* Get the decoder table */
tiff_compress = get4();
if (type == 0x2007)
{
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (type == 0x1818)
{
shutter = powf64(2.0f, -int_to_float((get4(), get4())));
aperture = powf64(2.0f, int_to_float(get4()) / 2);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurAp = aperture;
#endif
}
if (type == 0x102a)
{
// iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50;
iso_speed = powf64(2.0f, ((get2(), get2()) + get2()) / 32.0f - 5.0f) * 100.0f;
#ifdef LIBRAW_LIBRARY_BUILD
aperture = _CanonConvertAperture((get2(), get2()));
imgdata.lens.makernotes.CurAp = aperture;
#else
aperture = powf64(2.0, (get2(), (short)get2()) / 64.0);
#endif
shutter = powf64(2.0, -((short)get2()) / 32.0);
wbi = (get2(), get2());
if (wbi > 17)
wbi = 0;
fseek(ifp, 32, SEEK_CUR);
if (shutter > 1e6)
shutter = get2() / 10.0;
}
if (type == 0x102c)
{
if (get2() > 512)
{ /* Pro90, G1 */
fseek(ifp, 118, SEEK_CUR);
FORC4 cam_mul[c ^ 2] = get2();
}
else
{ /* G2, S30, S40 */
fseek(ifp, 98, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2();
}
}
#ifdef LIBRAW_LIBRARY_BUILD
if (type == 0x10a9)
{
INT64 o = ftell(ifp);
fseek(ifp, (0x1 << 1), SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
Canon_WBpresets(0, 0);
fseek(ifp, o, SEEK_SET);
}
if (type == 0x102d)
{
INT64 o = ftell(ifp);
Canon_CameraSettings();
fseek(ifp, o, SEEK_SET);
}
if (type == 0x580b)
{
if (strcmp(model, "Canon EOS D30"))
sprintf(imgdata.shootinginfo.BodySerial, "%d", len);
else
sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len >> 16, len & 0xffff);
}
#endif
if (type == 0x0032)
{
if (len == 768)
{ /* EOS D30 */
fseek(ifp, 72, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2();
if (!wbi)
cam_mul[0] = -1; /* use my auto white balance */
}
else if (!cam_mul[0])
{
if (get2() == key[0]) /* Pro1, G6, S60, S70 */
c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2;
else
{ /* G3, G5, S45, S50 */
c = "023457000000006000"[LIM(0, wbi, 17)] - '0';
key[0] = key[1] = 0;
}
fseek(ifp, 78 + c * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
if (!wbi)
cam_mul[0] = -1;
}
}
if (type == 0x10a9)
{ /* D60, 10D, 300D, and clones */
if (len > 66)
wbi = "0134567028"[LIM(0, wbi, 9)] - '0';
fseek(ifp, 2 + wbi * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
}
if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1))
ciff_block_1030(); /* all that don't have 0x10a9 */
if (type == 0x1031)
{
raw_width = (get2(), get2());
raw_height = get2();
}
if (type == 0x501c)
{
iso_speed = len & 0xffff;
}
if (type == 0x5029)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurFocal = len >> 16;
imgdata.lens.makernotes.FocalType = len & 0xffff;
if (imgdata.lens.makernotes.FocalType == 2)
{
imgdata.lens.makernotes.CanonFocalUnits = 32;
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
focal_len = imgdata.lens.makernotes.CurFocal;
#else
focal_len = len >> 16;
if ((len & 0xffff) == 2)
focal_len /= 32;
#endif
}
if (type == 0x5813)
flash_used = int_to_float(len);
if (type == 0x5814)
canon_ev = int_to_float(len);
if (type == 0x5817)
shot_order = len;
if (type == 0x5834)
{
unique_id = len;
#ifdef LIBRAW_LIBRARY_BUILD
unique_id = setCanonBodyFeatures(unique_id);
#endif
}
if (type == 0x580e)
timestamp = len;
if (type == 0x180e)
timestamp = get4();
#ifdef LOCALTIME
if ((type | 0x4000) == 0x580e)
timestamp = mktime(gmtime(×tamp));
#endif
fseek(ifp, save, SEEK_SET);
}
}
void CLASS parse_rollei()
{
char line[128], *val;
struct tm t;
fseek(ifp, 0, SEEK_SET);
memset(&t, 0, sizeof t);
do
{
fgets(line, 128, ifp);
if ((val = strchr(line, '=')))
*val++ = 0;
else
val = line + strbuflen(line);
if (!strcmp(line, "DAT"))
sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
if (!strcmp(line, "TIM"))
sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
if (!strcmp(line, "HDR"))
thumb_offset = atoi(val);
if (!strcmp(line, "X "))
raw_width = atoi(val);
if (!strcmp(line, "Y "))
raw_height = atoi(val);
if (!strcmp(line, "TX "))
thumb_width = atoi(val);
if (!strcmp(line, "TY "))
thumb_height = atoi(val);
} while (strncmp(line, "EOHD", 4));
data_offset = thumb_offset + thumb_width * thumb_height * 2;
t.tm_year -= 1900;
t.tm_mon -= 1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
strcpy(make, "Rollei");
strcpy(model, "d530flex");
write_thumb = &CLASS rollei_thumb;
}
void CLASS parse_sinar_ia()
{
int entries, off;
char str[8], *cp;
order = 0x4949;
fseek(ifp, 4, SEEK_SET);
entries = get4();
fseek(ifp, get4(), SEEK_SET);
while (entries--)
{
off = get4();
get4();
fread(str, 8, 1, ifp);
if (!strcmp(str, "META"))
meta_offset = off;
if (!strcmp(str, "THUMB"))
thumb_offset = off;
if (!strcmp(str, "RAW0"))
data_offset = off;
}
fseek(ifp, meta_offset + 20, SEEK_SET);
fread(make, 64, 1, ifp);
make[63] = 0;
if ((cp = strchr(make, ' ')))
{
strcpy(model, cp + 1);
*cp = 0;
}
raw_width = get2();
raw_height = get2();
load_raw = &CLASS unpacked_load_raw;
thumb_width = (get4(), get2());
thumb_height = get2();
write_thumb = &CLASS ppm_thumb;
maximum = 0x3fff;
}
void CLASS parse_phase_one(int base)
{
unsigned entries, tag, type, len, data, save, i, c;
float romm_cam[3][3];
char *cp;
memset(&ph1, 0, sizeof ph1);
fseek(ifp, base, SEEK_SET);
order = get4() & 0xffff;
if (get4() >> 8 != 0x526177)
return; /* "Raw" */
fseek(ifp, get4() + base, SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
type = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, base + data, SEEK_SET);
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0x0102:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
break;
case 0x0211:
imgdata.other.SensorTemperature2 = int_to_float(data);
break;
case 0x0401:
if (type == 4)
imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data) / 2.0f));
else
imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type) / 2.0f));
break;
case 0x0403:
if (type == 4)
imgdata.lens.makernotes.CurFocal = int_to_float(data);
else
imgdata.lens.makernotes.CurFocal = getreal(type);
break;
case 0x0410:
stmread(imgdata.lens.makernotes.body, len, ifp);
break;
case 0x0412:
stmread(imgdata.lens.makernotes.Lens, len, ifp);
break;
case 0x0414:
if (type == 4)
{
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0415:
if (type == 4)
{
imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0416:
if (type == 4)
{
imgdata.lens.makernotes.MinFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MinFocal = getreal(type);
}
if (imgdata.lens.makernotes.MinFocal > 1000.0f)
{
imgdata.lens.makernotes.MinFocal = 0.0f;
}
break;
case 0x0417:
if (type == 4)
{
imgdata.lens.makernotes.MaxFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MaxFocal = getreal(type);
}
break;
#endif
case 0x100:
flip = "0653"[data & 3] - '0';
break;
case 0x106:
for (i = 0; i < 9; i++)
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.P1_color[0].romm_cam[i] =
#endif
((float *)romm_cam)[i] = getreal(11);
romm_coeff(romm_cam);
break;
case 0x107:
FORC3 cam_mul[c] = getreal(11);
break;
case 0x108:
raw_width = data;
break;
case 0x109:
raw_height = data;
break;
case 0x10a:
left_margin = data;
break;
case 0x10b:
top_margin = data;
break;
case 0x10c:
width = data;
break;
case 0x10d:
height = data;
break;
case 0x10e:
ph1.format = data;
break;
case 0x10f:
data_offset = data + base;
break;
case 0x110:
meta_offset = data + base;
meta_length = len;
break;
case 0x112:
ph1.key_off = save - 4;
break;
case 0x210:
ph1.tag_210 = int_to_float(data);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.other.SensorTemperature = ph1.tag_210;
#endif
break;
case 0x21a:
ph1.tag_21a = data;
break;
case 0x21c:
strip_offset = data + base;
break;
case 0x21d:
ph1.t_black = data;
break;
case 0x222:
ph1.split_col = data;
break;
case 0x223:
ph1.black_col = data + base;
break;
case 0x224:
ph1.split_row = data;
break;
case 0x225:
ph1.black_row = data + base;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0x226:
for (i = 0; i < 9; i++)
imgdata.color.P1_color[1].romm_cam[i] = getreal(11);
break;
#endif
case 0x301:
model[63] = 0;
fread(model, 1, 63, ifp);
if ((cp = strstr(model, " camera")))
*cp = 0;
}
fseek(ifp, save, SEEK_SET);
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0])
{
fseek(ifp, meta_offset, SEEK_SET);
order = get2();
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, meta_offset + get4(), SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, meta_offset + data, SEEK_SET);
if (tag == 0x0407)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
}
fseek(ifp, save, SEEK_SET);
}
}
#endif
load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
maximum = 0xffff;
strcpy(make, "Phase One");
if (model[0])
return;
switch (raw_height)
{
case 2060:
strcpy(model, "LightPhase");
break;
case 2682:
strcpy(model, "H 10");
break;
case 4128:
strcpy(model, "H 20");
break;
case 5488:
strcpy(model, "H 25");
break;
}
}
void CLASS parse_fuji(int offset)
{
unsigned entries, tag, len, save, c;
fseek(ifp, offset, SEEK_SET);
entries = get4();
if (entries > 255)
return;
while (entries--)
{
tag = get2();
len = get2();
save = ftell(ifp);
if (tag == 0x100)
{
raw_height = get2();
raw_width = get2();
}
else if (tag == 0x121)
{
height = get2();
if ((width = get2()) == 4284)
width += 3;
}
else if (tag == 0x130)
{
fuji_layout = fgetc(ifp) >> 7;
fuji_width = !(fgetc(ifp) & 8);
}
else if (tag == 0x131)
{
filters = 9;
FORC(36)
{
int q = fgetc(ifp);
xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/
}
}
else if (tag == 0x2ff0)
{
FORC4 cam_mul[c ^ 1] = get2();
// IB start
#ifdef LIBRAW_LIBRARY_BUILD
}
else if (tag == 0x9650)
{
short a = (short)get2();
float b = fMAX(1.0f, get2());
imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b;
}
else if (tag == 0x2f00)
{
int nWBs = get4();
nWBs = MIN(nWBs, 6);
for (int wb_ind = 0; wb_ind < nWBs; wb_ind++)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + wb_ind][c ^ 1] = get2();
fseek(ifp, 8, SEEK_CUR);
}
}
else if (tag == 0x2000)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ 1] = get2();
}
else if (tag == 0x2100)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][c ^ 1] = get2();
}
else if (tag == 0x2200)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ 1] = get2();
}
else if (tag == 0x2300)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2();
}
else if (tag == 0x2301)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2();
}
else if (tag == 0x2302)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2();
}
else if (tag == 0x2310)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2();
}
else if (tag == 0x2400)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2();
}
else if (tag == 0x2410)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ 1] = get2();
#endif
// IB end
}
else if (tag == 0xc000)
/* 0xc000 tag versions, second ushort; valid if the first ushort is 0
X100F 0x0259
X100T 0x0153
X-E2 0x014f 0x024f depends on firmware
X-A1 0x014e
XQ2 0x0150
XQ1 0x0150
X100S 0x0149 0x0249 depends on firmware
X30 0x0152
X20 0x0146
X-T10 0x0154
X-T2 0x0258
X-M1 0x014d
X-E2s 0x0355
X-A2 0x014e
X-T20 0x025b
GFX 50S 0x025a
X-T1 0x0151 0x0251 0x0351 depends on firmware
X70 0x0155
X-Pro2 0x0255
*/
{
c = order;
order = 0x4949;
if ((tag = get4()) > 10000)
tag = get4();
if (tag > 10000)
tag = get4();
width = tag;
height = get4();
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10"))
{
int wb[4];
int nWB, tWB, pWB;
int iCCT = 0;
int cnt;
fseek(ifp, save + 0x200, SEEK_SET);
for (int wb_ind = 0; wb_ind < 42; wb_ind++)
{
nWB = get4();
tWB = get4();
wb[0] = get4() << 1;
wb[1] = get4();
wb[3] = get4();
wb[2] = get4() << 1;
if (tWB && (iCCT < 255))
{
imgdata.color.WBCT_Coeffs[iCCT][0] = tWB;
for (cnt = 0; cnt < 4; cnt++)
imgdata.color.WBCT_Coeffs[iCCT][cnt + 1] = wb[cnt];
iCCT++;
}
if (nWB != 70)
{
for (pWB = 1; pWB < nFuji_wb_list2; pWB += 2)
{
if (Fuji_wb_list2[pWB] == nWB)
{
for (cnt = 0; cnt < 4; cnt++)
imgdata.color.WB_Coeffs[Fuji_wb_list2[pWB - 1]][cnt] = wb[cnt];
break;
}
}
}
}
}
else
{
libraw_internal_data.unpacker_data.posRAFData = save;
libraw_internal_data.unpacker_data.lenRAFData = (len >> 1);
}
#endif
order = c;
}
fseek(ifp, save + len, SEEK_SET);
}
height <<= fuji_layout;
width >>= fuji_layout;
}
int CLASS parse_jpeg(int offset)
{
int len, save, hlen, mark;
fseek(ifp, offset, SEEK_SET);
if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)
return 0;
while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda)
{
order = 0x4d4d;
len = get2() - 2;
save = ftell(ifp);
if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9)
{
fgetc(ifp);
raw_height = get2();
raw_width = get2();
}
order = get2();
hlen = get4();
if (get4() == 0x48454150
#ifdef LIBRAW_LIBRARY_BUILD
&& (save + hlen) >= 0 && (save + hlen) <= ifp->size()
#endif
) /* "HEAP" */
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
#endif
parse_ciff(save + hlen, len - hlen, 0);
}
if (parse_tiff(save + 6))
apply_tiff();
fseek(ifp, save + len, SEEK_SET);
}
return 1;
}
void CLASS parse_riff()
{
unsigned i, size, end;
char tag[4], date[64], month[64];
static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
struct tm t;
order = 0x4949;
fread(tag, 4, 1, ifp);
size = get4();
end = ftell(ifp) + size;
if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4))
{
int maxloop = 1000;
get4();
while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--)
parse_riff();
}
else if (!memcmp(tag, "nctg", 4))
{
while (ftell(ifp) + 7 < end)
{
i = get2();
size = get2();
if ((i + 1) >> 1 == 10 && size == 20)
get_timestamp(0);
else
fseek(ifp, size, SEEK_CUR);
}
}
else if (!memcmp(tag, "IDIT", 4) && size < 64)
{
fread(date, 64, 1, ifp);
date[size] = 0;
memset(&t, 0, sizeof t);
if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6)
{
for (i = 0; i < 12 && strcasecmp(mon[i], month); i++)
;
t.tm_mon = i;
t.tm_year -= 1900;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
}
else
fseek(ifp, size, SEEK_CUR);
}
void CLASS parse_qt(int end)
{
unsigned save, size;
char tag[4];
order = 0x4d4d;
while (ftell(ifp) + 7 < end)
{
save = ftell(ifp);
if ((size = get4()) < 8)
return;
fread(tag, 4, 1, ifp);
if (!memcmp(tag, "moov", 4) || !memcmp(tag, "udta", 4) || !memcmp(tag, "CNTH", 4))
parse_qt(save + size);
if (!memcmp(tag, "CNDA", 4))
parse_jpeg(ftell(ifp));
fseek(ifp, save + size, SEEK_SET);
}
}
void CLASS parse_smal(int offset, int fsize)
{
int ver;
fseek(ifp, offset + 2, SEEK_SET);
order = 0x4949;
ver = fgetc(ifp);
if (ver == 6)
fseek(ifp, 5, SEEK_CUR);
if (get4() != fsize)
return;
if (ver > 6)
data_offset = get4();
raw_height = height = get2();
raw_width = width = get2();
strcpy(make, "SMaL");
sprintf(model, "v%d %dx%d", ver, width, height);
if (ver == 6)
load_raw = &CLASS smal_v6_load_raw;
if (ver == 9)
load_raw = &CLASS smal_v9_load_raw;
}
void CLASS parse_cine()
{
unsigned off_head, off_setup, off_image, i;
order = 0x4949;
fseek(ifp, 4, SEEK_SET);
is_raw = get2() == 2;
fseek(ifp, 14, SEEK_CUR);
is_raw *= get4();
off_head = get4();
off_setup = get4();
off_image = get4();
timestamp = get4();
if ((i = get4()))
timestamp = i;
fseek(ifp, off_head + 4, SEEK_SET);
raw_width = get4();
raw_height = get4();
switch (get2(), get2())
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 16:
load_raw = &CLASS unpacked_load_raw;
}
fseek(ifp, off_setup + 792, SEEK_SET);
strcpy(make, "CINE");
sprintf(model, "%d", get4());
fseek(ifp, 12, SEEK_CUR);
switch ((i = get4()) & 0xffffff)
{
case 3:
filters = 0x94949494;
break;
case 4:
filters = 0x49494949;
break;
default:
is_raw = 0;
}
fseek(ifp, 72, SEEK_CUR);
switch ((get4() + 3600) % 360)
{
case 270:
flip = 4;
break;
case 180:
flip = 1;
break;
case 90:
flip = 7;
break;
case 0:
flip = 2;
}
cam_mul[0] = getreal(11);
cam_mul[2] = getreal(11);
maximum = ~((~0u) << get4());
fseek(ifp, 668, SEEK_CUR);
shutter = get4() / 1000000000.0;
fseek(ifp, off_image, SEEK_SET);
if (shot_select < is_raw)
fseek(ifp, shot_select * 8, SEEK_CUR);
data_offset = (INT64)get4() + 8;
data_offset += (INT64)get4() << 32;
}
void CLASS parse_redcine()
{
unsigned i, len, rdvo;
order = 0x4d4d;
is_raw = 0;
fseek(ifp, 52, SEEK_SET);
width = get4();
height = get4();
fseek(ifp, 0, SEEK_END);
fseek(ifp, -(i = ftello(ifp) & 511), SEEK_CUR);
if (get4() != i || get4() != 0x52454f42)
{
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: Tail is missing, parsing from head...\n"), ifname);
#endif
fseek(ifp, 0, SEEK_SET);
while ((len = get4()) != EOF)
{
if (get4() == 0x52454456)
if (is_raw++ == shot_select)
data_offset = ftello(ifp) - 8;
fseek(ifp, len - 8, SEEK_CUR);
}
}
else
{
rdvo = get4();
fseek(ifp, 12, SEEK_CUR);
is_raw = get4();
fseeko(ifp, rdvo + 8 + shot_select * 4, SEEK_SET);
data_offset = get4();
}
}
//@end COMMON
char *CLASS foveon_gets(int offset, char *str, int len)
{
int i;
fseek(ifp, offset, SEEK_SET);
for (i = 0; i < len - 1; i++)
if ((str[i] = get2()) == 0)
break;
str[i] = 0;
return str;
}
void CLASS parse_foveon()
{
int entries, img = 0, off, len, tag, save, i, wide, high, pent, poff[256][2];
char name[64], value[64];
order = 0x4949; /* Little-endian */
fseek(ifp, 36, SEEK_SET);
flip = get4();
fseek(ifp, -4, SEEK_END);
fseek(ifp, get4(), SEEK_SET);
if (get4() != 0x64434553)
return; /* SECd */
entries = (get4(), get4());
while (entries--)
{
off = get4();
len = get4();
tag = get4();
save = ftell(ifp);
fseek(ifp, off, SEEK_SET);
if (get4() != (0x20434553 | (tag << 24)))
return;
switch (tag)
{
case 0x47414d49: /* IMAG */
case 0x32414d49: /* IMA2 */
fseek(ifp, 8, SEEK_CUR);
pent = get4();
wide = get4();
high = get4();
if (wide > raw_width && high > raw_height)
{
switch (pent)
{
case 5:
load_flags = 1;
case 6:
load_raw = &CLASS foveon_sd_load_raw;
break;
case 30:
load_raw = &CLASS foveon_dp_load_raw;
break;
default:
load_raw = 0;
}
raw_width = wide;
raw_height = high;
data_offset = off + 28;
is_foveon = 1;
}
fseek(ifp, off + 28, SEEK_SET);
if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8 && thumb_length < len - 28)
{
thumb_offset = off + 28;
thumb_length = len - 28;
write_thumb = &CLASS jpeg_thumb;
}
if (++img == 2 && !thumb_length)
{
thumb_offset = off + 24;
thumb_width = wide;
thumb_height = high;
write_thumb = &CLASS foveon_thumb;
}
break;
case 0x464d4143: /* CAMF */
meta_offset = off + 8;
meta_length = len - 28;
break;
case 0x504f5250: /* PROP */
pent = (get4(), get4());
fseek(ifp, 12, SEEK_CUR);
off += pent * 8 + 24;
if ((unsigned)pent > 256)
pent = 256;
for (i = 0; i < pent * 2; i++)
((int *)poff)[i] = off + get4() * 2;
for (i = 0; i < pent; i++)
{
foveon_gets(poff[i][0], name, 64);
foveon_gets(poff[i][1], value, 64);
if (!strcmp(name, "ISO"))
iso_speed = atoi(value);
if (!strcmp(name, "CAMMANUF"))
strcpy(make, value);
if (!strcmp(name, "CAMMODEL"))
strcpy(model, value);
if (!strcmp(name, "WB_DESC"))
strcpy(model2, value);
if (!strcmp(name, "TIME"))
timestamp = atoi(value);
if (!strcmp(name, "EXPTIME"))
shutter = atoi(value) / 1000000.0;
if (!strcmp(name, "APERTURE"))
aperture = atof(value);
if (!strcmp(name, "FLENGTH"))
focal_len = atof(value);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(name, "CAMSERIAL"))
strcpy(imgdata.shootinginfo.BodySerial, value);
if (!strcmp(name, "FLEQ35MM"))
imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value);
if (!strcmp(name, "IMAGERTEMP"))
imgdata.other.SensorTemperature = atof(value);
if (!strcmp(name, "LENSARANGE"))
{
char *sp;
imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value);
sp = strrchr(value, ' ');
if (sp)
{
imgdata.lens.makernotes.MinAp4CurFocal = atof(sp);
if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal)
my_swap(float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal);
}
}
if (!strcmp(name, "LENSFRANGE"))
{
char *sp;
imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value);
sp = strrchr(value, ' ');
if (sp)
{
imgdata.lens.makernotes.MaxFocal = atof(sp);
if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal)
my_swap(float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal);
}
}
if (!strcmp(name, "LENSMODEL"))
{
char *sp;
imgdata.lens.makernotes.LensID = strtol(value, &sp, 16); // atoi(value);
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = Sigma_X3F;
}
}
#endif
}
#ifdef LOCALTIME
timestamp = mktime(gmtime(×tamp));
#endif
}
fseek(ifp, save, SEEK_SET);
}
}
//@out COMMON
/*
All matrices are from Adobe DNG Converter unless otherwise noted.
*/
void CLASS adobe_coeff(const char *t_make, const char *t_model
#ifdef LIBRAW_LIBRARY_BUILD
,
int internal_only
#endif
)
{
// clang-format off
static const struct
{
const char *prefix;
int t_black, t_maximum, trans[12];
} table[] = {
{ "AgfaPhoto DC-833m", 0, 0, /* DJC */
{ 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } },
{ "Apple QuickTake", 0, 0, /* DJC */
{ 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } },
{"Broadcom RPi IMX219", 66, 0x3ff,
{ 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */
{ "Broadcom RPi OV5647", 16, 0x3ff,
{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */
{ "Canon EOS D2000", 0, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Canon EOS D6000", 0, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Canon EOS D30", 0, 0, /* updated */
{ 9900,-2771,-1324,-7072,14229,3140,-2790,3344,8861 } },
{ "Canon EOS D60", 0, 0xfa0, /* updated */
{ 6211,-1358,-896,-8557,15766,3012,-3001,3507,8567 } },
{ "Canon EOS 5DS", 0, 0x3c96,
{ 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } },
{ "Canon EOS 5D Mark IV", 0, 0,
{ 6446,-366,-864,-4436,12204,2513,-952,2496,6348 } },
{ "Canon EOS 5D Mark III", 0, 0x3c80,
{ 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } },
{ "Canon EOS 5D Mark II", 0, 0x3cf0,
{ 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } },
{ "Canon EOS 5D", 0, 0xe6c,
{ 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } },
{ "Canon EOS 6D Mark II", 0, 0x38de, /* updated */
{ 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } },
{ "Canon EOS 6D", 0, 0x3c82, /* skipped update */
{ 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } },
{ "Canon EOS 77D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 7D Mark II", 0, 0x3510,
{ 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } },
{ "Canon EOS 7D", 0, 0x3510,
{ 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } },
{ "Canon EOS 800D", 0, 0,
{ 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } },
{ "Canon EOS 80D", 0, 0,
{ 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } },
{ "Canon EOS 10D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 200D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 20Da", 0, 0,
{ 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
{ "Canon EOS 20D", 0, 0xfff,
{ 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
{ "Canon EOS 30D", 0, 0,
{ 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
{ "Canon EOS 40D", 0, 0x3f60,
{ 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } },
{ "Canon EOS 50D", 0, 0x3d93,
{ 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } },
{ "Canon EOS 60Da", 0, 0x2ff7, /* added */
{ 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } },
{ "Canon EOS 60D", 0, 0x2ff7,
{ 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } },
{ "Canon EOS 70D", 0, 0x3bc7,
{ 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } },
{ "Canon EOS 100D", 0, 0x350f,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 300D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 350D", 0, 0xfff,
{ 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
{ "Canon EOS 400D", 0, 0xe8e,
{ 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
{ "Canon EOS 450D", 0, 0x390d,
{ 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } },
{ "Canon EOS 500D", 0, 0x3479,
{ 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } },
{ "Canon EOS 550D", 0, 0x3dd7,
{ 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } },
{ "Canon EOS 600D", 0, 0x3510,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 650D", 0, 0x354d,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 750D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 760D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 700D", 0, 0x3c00,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 1000D", 0, 0xe43,
{ 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } },
{ "Canon EOS 1100D", 0, 0x3510,
{ 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } },
{ "Canon EOS 1200D", 0, 0x37c2,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 1300D", 0, 0x37c2,
{ 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } },
{ "Canon EOS M6", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M5", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M3", 0, 0,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS M2", 0, 0, /* added */
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M100", 0, 0, /* temp */
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M10", 0, 0,
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M", 0, 0,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS-1Ds Mark III", 0, 0x3bb0,
{ 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } },
{ "Canon EOS-1Ds Mark II", 0, 0xe80,
{ 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
{ "Canon EOS-1D Mark IV", 0, 0x3bb0,
{ 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } },
{ "Canon EOS-1D Mark III", 0, 0x3bb0,
{ 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } },
{ "Canon EOS-1D Mark II N", 0, 0xe80,
{ 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
{ "Canon EOS-1D Mark II", 0, 0xe80,
{ 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
{ "Canon EOS-1DS", 0, 0xe20, /* updated */
{ 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } },
{ "Canon EOS-1D C", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */
{ 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } },
{ "Canon EOS-1D X", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D", 0, 0xe20,
{ 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
{ "Canon EOS C500", 853, 0, /* DJC */
{ 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } },
{"Canon PowerShot 600", 0, 0, /* added */
{ -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } },
{ "Canon PowerShot A530", 0, 0,
{ 0 } }, /* don't want the A5 matrix */
{ "Canon PowerShot A50", 0, 0,
{ -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
{ "Canon PowerShot A5", 0, 0,
{ -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
{ "Canon PowerShot G10", 0, 0,
{ 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } },
{ "Canon PowerShot G11", 0, 0,
{ 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } },
{ "Canon PowerShot G12", 0, 0,
{ 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } },
{ "Canon PowerShot G15", 0, 0,
{ 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } },
{ "Canon PowerShot G16", 0, 0, /* updated */
{ 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } },
{ "Canon PowerShot G1 X Mark III", 0, 0, /* temp */
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon PowerShot G1 X Mark II", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1 X", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1", 0, 0, /* updated */
{ -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } },
{ "Canon PowerShot G2", 0, 0, /* updated */
{ 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } },
{ "Canon PowerShot G3 X", 0, 0,
{ 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } },
{ "Canon PowerShot G3", 0, 0, /* updated */
{ 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } },
{ "Canon PowerShot G5 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G5", 0, 0, /* updated */
{ 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } },
{ "Canon PowerShot G6", 0, 0,
{ 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
{ "Canon PowerShot G7 X Mark II", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G7 X", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9 X Mark II", 0, 0,
{ 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } },
{ "Canon PowerShot G9 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9", 0, 0,
{ 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } },
{ "Canon PowerShot Pro1", 0, 0,
{ 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
{ "Canon PowerShot Pro70", 34, 0, /* updated */
{ -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } },
{ "Canon PowerShot Pro90", 0, 0, /* updated */
{ -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } },
{ "Canon PowerShot S30", 0, 0, /* updated */
{ 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } },
{ "Canon PowerShot S40", 0, 0, /* updated */
{ 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } },
{ "Canon PowerShot S45", 0, 0, /* updated */
{ 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } },
{ "Canon PowerShot S50", 0, 0, /* updated */
{ 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } },
{ "Canon PowerShot S60", 0, 0,
{ 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
{ "Canon PowerShot S70", 0, 0,
{ 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
{ "Canon PowerShot S90", 0, 0,
{ 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } },
{ "Canon PowerShot S95", 0, 0,
{ 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } },
{ "Canon PowerShot S120", 0, 0,
{ 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } },
{ "Canon PowerShot S110", 0, 0,
{ 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } },
{ "Canon PowerShot S100", 0, 0,
{ 7968,-2565,-636,-2873,10697,2513,180,667,4211 } },
{ "Canon PowerShot SX1 IS", 0, 0,
{ 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } },
{ "Canon PowerShot SX50 HS", 0, 0,
{ 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } },
{ "Canon PowerShot SX60 HS", 0, 0,
{ 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } },
{ "Canon PowerShot A3300", 0, 0, /* DJC */
{ 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } },
{ "Canon PowerShot A470", 0, 0, /* DJC */
{ 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } },
{ "Canon PowerShot A610", 0, 0, /* DJC */
{ 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } },
{ "Canon PowerShot A620", 0, 0, /* DJC */
{ 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
{ "Canon PowerShot A630", 0, 0, /* DJC */
{ 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } },
{ "Canon PowerShot A640", 0, 0, /* DJC */
{ 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } },
{ "Canon PowerShot A650", 0, 0, /* DJC */
{ 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } },
{ "Canon PowerShot A720", 0, 0, /* DJC */
{ 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } },
{ "Canon PowerShot D10", 127, 0, /* DJC */
{ 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } },
{ "Canon PowerShot S3 IS", 0, 0, /* DJC */
{ 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } },
{ "Canon PowerShot SX110 IS", 0, 0, /* DJC */
{ 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } },
{ "Canon PowerShot SX220", 0, 0, /* DJC */
{ 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } },
{ "Canon IXUS 160", 0, 0, /* DJC */
{ 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } },
{ "Casio EX-F1", 0, 0, /* added */
{ 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } },
{ "Casio EX-FH100", 0, 0, /* added */
{ 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } },
{ "Casio EX-S20", 0, 0, /* DJC */
{ 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } },
{ "Casio EX-Z750", 0, 0, /* DJC */
{ 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } },
{ "Casio EX-Z10", 128, 0xfff, /* DJC */
{ 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } },
{ "CINE 650", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE 660", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE", 0, 0,
{ 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } },
{ "Contax N Digital", 0, 0xf1e,
{ 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
{ "DXO ONE", 0, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Epson R-D1", 0, 0,
{ 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
{ "Fujifilm E550", 0, 0, /* updated */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm E900", 0, 0,
{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
{ "Fujifilm F5", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F6", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F77", 0, 0xfe9,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F7", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm F810", 0, 0, /* added */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm F8", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm S100FS", 514, 0,
{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
{ "Fujifilm S1", 0, 0,
{ 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } },
{ "Fujifilm S20Pro", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm S20", 512, 0x3fff,
{ 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } },
{ "Fujifilm S2Pro", 128, 0, /* updated */
{ 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } },
{ "Fujifilm S3Pro", 0, 0,
{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
{ "Fujifilm S5Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm S5000", 0, 0,
{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
{ "Fujifilm S5100", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5500", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5200", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S5600", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S6", 0, 0,
{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
{ "Fujifilm S7000", 0, 0,
{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
{ "Fujifilm S9000", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9500", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9100", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm S9600", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm SL1000", 0, 0,
{ 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } },
{ "Fujifilm IS-1", 0, 0,
{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
{ "Fujifilm IS Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm HS10 HS11", 0, 0xf68,
{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
{ "Fujifilm HS2", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS3", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS50EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm F900EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm X100S", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100F", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X100T", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100", 0, 0,
{ 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } },
{ "Fujifilm X10", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X20", 0, 0,
{ 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } },
{ "Fujifilm X30", 0, 0,
{ 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } },
{ "Fujifilm X70", 0, 0,
{ 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } },
{ "Fujifilm X-Pro1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-Pro2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-A10", 0, 0,
{ 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} },
{ "Fujifilm X-A1", 0, 0,
{ 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } },
{ "Fujifilm X-A2", 0, 0,
{ 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } },
{ "Fujifilm X-A3", 0, 0,
{ 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } },
{ "Fujifilm X-E1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-E2S", 0, 0,
{ 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } },
{ "Fujifilm X-E2", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-E3", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm XF1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-M1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-S1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-T20", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T10", 0, 0, /* updated */
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-T1", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm XQ1", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm XQ2", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm GFX 50S", 0, 0,
{ 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } },
{ "GITUP GIT2P", 4160, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "GITUP GIT2", 3200, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Hasselblad HV", 0, 0, /* added */
{ 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } },
{ "Hasselblad Lunar", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Hasselblad Lusso", 0, 0, /* added */
{ 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } },
{ "Hasselblad Stellar", -800, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{ "Hasselblad 500 mech.", 0, 0, /* added */
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad CFV", 0, 0,
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad H-16MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-22MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-31MP",0, 0, /* LibRaw */
{ 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } },
{ "Hasselblad 39-Coated", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H-39MP",0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H2D-39", 0, 0, /* added */
{ 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } },
{ "Hasselblad H3D-50", 0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H3D", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H4D-40",0, 0, /* LibRaw */
{ 6325,-860,-957,-6559,15945,266,167,770,5936 } },
{ "Hasselblad H4D-50",0, 0, /* LibRaw */
{ 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } },
{ "Hasselblad H4D-60",0, 0,
{ 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } },
{ "Hasselblad H5D-50c",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "Hasselblad H5D-50",0, 0,
{ 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } },
{ "Hasselblad H6D-100c",0, 0,
{ 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } },
{ "Hasselblad X1D",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "HTC One A9", 64, 1023, /* this is CM1 transposed */
{ 101, -20, -2, -11, 145, 41, -24, 1, 56 } },
{ "Imacon Ixpress", 0, 0, /* DJC */
{ 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
{ "Kodak NC2000", 0, 0,
{ 13891,-6055,-803,-465,9919,642,2121,82,1291 } },
{ "Kodak DCS315C", -8, 0,
{ 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
{ "Kodak DCS330C", -8, 0,
{ 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
{ "Kodak DCS420", 0, 0,
{ 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
{ "Kodak DCS460", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS1", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS3B", 0, 0,
{ 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
{ "Kodak DCS520C", -178, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Kodak DCS560C", -177, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Kodak DCS620C", -177, 0,
{ 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
{ "Kodak DCS620X", -176, 0,
{ 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
{ "Kodak DCS660C", -173, 0,
{ 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
{ "Kodak DCS720X", 0, 0,
{ 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
{ "Kodak DCS760C", 0, 0,
{ 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
{ "Kodak DCS Pro SLR", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14nx", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Photo Control Camerz ZDS 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Kodak ProBack645", 0, 0,
{ 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
{ "Kodak ProBack", 0, 0,
{ 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
{ "Kodak P712", 0, 0,
{ 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
{ "Kodak P850", 0, 0xf7c,
{ 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
{ "Kodak P880", 0, 0xfff,
{ 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
{ "Kodak EasyShare Z980", 0, 0,
{ 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } },
{ "Kodak EasyShare Z981", 0, 0,
{ 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } },
{ "Kodak EasyShare Z990", 0, 0xfed,
{ 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } },
{ "Kodak EASYSHARE Z1015", 0, 0xef1,
{ 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } },
{ "Leaf C-Most", 0, 0, /* updated */
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Valeo 6", 0, 0,
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Aptus 54S", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leaf Aptus-II 8", 0, 0, /* added */
{ 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } },
{ "Leaf AFi-II 7", 0, 0, /* added */
{ 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } },
{ "Leaf Aptus-II 5", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 65", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 65S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 75", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 75S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Credo 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 50", 0, 0,
{ 3984,0,0,0,10000,0,0,0,7666 } },
{ "Leaf Credo 60", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 80", 0, 0,
{ 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } },
{ "Leaf", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leica M10", 0, 0, /* added */
{ 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } },
{ "Leica M9", 0, 0, /* added */
{ 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } },
{ "Leica M8", 0, 0, /* added */
{ 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } },
{ "Leica M (Typ 240)", 0, 0, /* added */
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica M (Typ 262)", 0, 0,
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica SL (Typ 601)", 0, 0,
{ 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} },
{ "Leica S2", 0, 0, /* added */
{ 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } },
{"Leica S-E (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{"Leica S (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{ "Leica S (Typ 007)", 0, 0,
{ 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } },
{ "Leica Q (Typ 116)", 0, 0, /* updated */
{ 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } },
{ "Leica T (Typ 701)", 0, 0, /* added */
{ 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } },
{ "Leica X2", 0, 0, /* added */
{ 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } },
{ "Leica X1", 0, 0, /* added */
{ 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } },
{ "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */
{ 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } },
{ "Mamiya M31", 0, 0, /* added */
{ 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } },
{ "Mamiya M22", 0, 0, /* added */
{ 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } },
{ "Mamiya M18", 0, 0, /* added */
{ 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } },
{ "Mamiya ZD", 0, 0,
{ 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } },
{ "Micron 2010", 110, 0, /* DJC */
{ 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
{ "Minolta DiMAGE 5", 0, 0xf7d, /* updated */
{ 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } },
{ "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */
{ 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } },
{ "Minolta DiMAGE 7i", 0, 0xf7d, /* added */
{ 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } },
{ "Minolta DiMAGE 7", 0, 0xf7d, /* updated */
{ 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } },
{ "Minolta DiMAGE A1", 0, 0xf8b, /* updated */
{ 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } },
{ "Minolta DiMAGE A200", 0, 0,
{ 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
{ "Minolta DiMAGE A2", 0, 0xf8f,
{ 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
{ "Minolta DiMAGE Z2", 0, 0, /* DJC */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Minolta DYNAX 5", 0, 0xffb,
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta Maxxum 5D", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta DYNAX 7", 0, 0xffb,
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta Maxxum 7D", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Motorola PIXL", 0, 0, /* DJC */
{ 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } },
{ "Nikon D100", 0, 0,
{ 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
{ "Nikon D1H", 0, 0, /* updated */
{ 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } },
{ "Nikon D1X", 0, 0,
{ 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
{ "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */
{ 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
{ "Nikon D200", 0, 0xfbc,
{ 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
{ "Nikon D2H", 0, 0,
{ 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } },
{ "Nikon D2X", 0, 0, /* updated */
{ 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } },
{ "Nikon D3000", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D3100", 0, 0,
{ 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } },
{ "Nikon D3200", 0, 0xfb9,
{ 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } },
{ "Nikon D3300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D3400", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D300", 0, 0,
{ 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } },
{ "Nikon D3X", 0, 0,
{ 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } },
{ "Nikon D3S", 0, 0,
{ 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } },
{ "Nikon D3", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D40X", 0, 0,
{ 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } },
{ "Nikon D40", 0, 0,
{ 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } },
{ "Nikon D4S", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D4", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon Df", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D5000", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } },
{ "Nikon D5100", 0, 0x3de6,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D5200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D5300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D5500", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D5600", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D50", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D5", 0, 0,
{ 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } },
{ "Nikon D600", 0, 0x3e07,
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D610",0, 0, /* updated */
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D60", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D7000", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D7100", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D750", -600, 0,
{ 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } },
{ "Nikon D700", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D70", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D850", 0, 0,
{ 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } },
{ "Nikon D810A", 0, 0,
{ 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } },
{ "Nikon D810", 0, 0,
{ 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } },
{ "Nikon D800", 0, 0,
{ 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } },
{ "Nikon D80", 0, 0,
{ 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
{ "Nikon D90", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } },
{ "Nikon E700", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E800", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E950", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E995", 0, 0, /* copied from E5000 */
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E2100", 0, 0, /* copied from Z2, new white balance */
{ 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } },
{ "Nikon E2500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E3200", 0, 0, /* DJC */
{ 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } },
{ "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Nikon E4500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E5000", 0, 0, /* updated */
{ -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } },
{ "Nikon E5400", 0, 0, /* updated */
{ 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } },
{ "Nikon E5700", 0, 0, /* updated */
{ -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } },
{ "Nikon E8400", 0, 0,
{ 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
{ "Nikon E8700", 0, 0,
{ 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Nikon E8800", 0, 0,
{ 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
{ "Nikon COOLPIX A", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon COOLPIX B700", 0, 0,
{ 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } },
{ "Nikon COOLPIX P330", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P340", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Kalon", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Deneb", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P6000", 0, 0,
{ 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } },
{ "Nikon COOLPIX P7000", 0, 0,
{ 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } },
{ "Nikon COOLPIX P7100", 0, 0,
{ 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } },
{ "Nikon COOLPIX P7700", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P7800", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon 1 V3", -200, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J4", 0, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J5", 0, 0,
{ 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } },
{ "Nikon 1 S2", -200, 0,
{ 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } },
{ "Nikon 1 V2", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 J3", 0, 0, /* updated */
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 AW1", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */
{ 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } },
{ "Olympus AIR-A01", 0, 0xfe1,
{ 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } },
{ "Olympus C5050", 0, 0, /* updated */
{ 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } },
{ "Olympus C5060", 0, 0,
{ 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
{ "Olympus C7070", 0, 0,
{ 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
{ "Olympus C70", 0, 0,
{ 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
{ "Olympus C80", 0, 0,
{ 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
{ "Olympus E-10", 0, 0xffc, /* updated */
{ 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } },
{ "Olympus E-1", 0, 0,
{ 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
{ "Olympus E-20", 0, 0xffc, /* updated */
{ 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } },
{ "Olympus E-300", 0, 0,
{ 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
{ "Olympus E-330", 0, 0,
{ 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
{ "Olympus E-30", 0, 0xfbc,
{ 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } },
{ "Olympus E-3", 0, 0xf99,
{ 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } },
{ "Olympus E-400", 0, 0,
{ 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
{ "Olympus E-410", 0, 0xf6a,
{ 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } },
{ "Olympus E-420", 0, 0xfd7,
{ 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } },
{ "Olympus E-450", 0, 0xfd2,
{ 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } },
{ "Olympus E-500", 0, 0,
{ 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
{ "Olympus E-510", 0, 0xf6a,
{ 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } },
{ "Olympus E-520", 0, 0xfd2,
{ 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } },
{ "Olympus E-5", 0, 0xeec,
{ 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } },
{ "Olympus E-600", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-620", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-P1", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P2", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-P5", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL1s", 0, 0,
{ 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } },
{ "Olympus E-PL1", 0, 0,
{ 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } },
{ "Olympus E-PL2", 0, 0xcf3,
{ 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } },
{ "Olympus E-PL3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PL5", 0, 0xfcb,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL6", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL7", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PL8", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PM1", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PM2", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M10", 0, 0, /* Same for E-M10MarkII, E-M10MarkIII */
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M1MarkII", 0, 0,
{ 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } },
{ "Olympus E-M1", 0, 0,
{ 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } },
{ "Olympus E-M5MarkII", 0, 0,
{ 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } },
{ "Olympus E-M5", 0, 0xfe1,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus PEN-F",0, 0,
{ 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } },
{ "Olympus SP350", 0, 0,
{ 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
{ "Olympus SP3", 0, 0,
{ 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
{ "Olympus SP500UZ", 0, 0xfff,
{ 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
{ "Olympus SP510UZ", 0, 0xffe,
{ 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } },
{ "Olympus SP550UZ", 0, 0xffe,
{ 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } },
{ "Olympus SP560UZ", 0, 0xff9,
{ 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } },
{ "Olympus SP565UZ", 0, 0, /* added */
{ 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } },
{ "Olympus SP570UZ", 0, 0,
{ 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } },
{ "Olympus SH-2", 0, 0,
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus SH-3", 0, 0, /* Alias of SH-2 */
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus STYLUS1",0, 0, /* updated */
{ 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } },
{ "Olympus TG-4", 0, 0,
{ 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } },
{ "Olympus TG-5", 0, 0,
{ 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } },
{ "Olympus XZ-10", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "Olympus XZ-1", 0, 0,
{ 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } },
{ "Olympus XZ-2", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "OmniVision", 16, 0x3ff,
{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */
{ "Pentax *ist DL2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DL", 0, 0,
{ 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
{ "Pentax *ist DS2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DS", 0, 0,
{ 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
{ "Pentax *ist D", 0, 0,
{ 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
{ "Pentax GR", 0, 0, /* added */
{ 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } },
{ "Pentax K-01", 0, 0, /* added */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K10D", 0, 0, /* updated */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Pentax K1", 0, 0,
{ 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
{ "Pentax K20D", 0, 0,
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Pentax K200D", 0, 0,
{ 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } },
{ "Pentax K2000", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax K-m", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax KP", 0, 0,
{ 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } },
{ "Pentax K-x", 0, 0,
{ 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } },
{ "Pentax K-r", 0, 0,
{ 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } },
{ "Pentax K-1", 0, 0, /* updated */
{ 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } },
{ "Pentax K-30", 0, 0, /* updated */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K-3 II", 0, 0, /* updated */
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-3", 0, 0,
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-5 II", 0, 0,
{ 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } },
{ "Pentax K-500", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-50", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-5", 0, 0,
{ 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } },
{ "Pentax K-70", 0, 0,
{ 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } },
{ "Pentax K-7", 0, 0,
{ 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } },
{ "Pentax KP", 0, 0, /* temp */
{ 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } },
{ "Pentax K-S1", 0, 0,
{ 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } },
{ "Pentax K-S2", 0, 0,
{ 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } },
{ "Pentax Q-S1", 0, 0,
{ 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } },
{ "Pentax Q7", 0, 0, /* added */
{ 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } },
{ "Pentax Q10", 0, 0, /* updated */
{ 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } },
{ "Pentax Q", 0, 0, /* added */
{ 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } },
{ "Pentax MX-1", 0, 0, /* updated */
{ 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } },
{ "Pentax 645D", 0, 0x3e00,
{ 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } },
{ "Pentax 645Z", 0, 0, /* updated */
{ 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } },
{ "Panasonic DMC-CM10", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DMC-CM1", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DMC-FZ8", 0, 0xf7f,
{ 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } },
{ "Panasonic DMC-FZ18", 0, 0,
{ 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } },
{ "Panasonic DMC-FZ28", -15, 0xf96,
{ 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } },
{ "Panasonic DMC-FZ300", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ330", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ30", 0, 0xf94,
{ 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
{ "Panasonic DMC-FZ3", -15, 0,
{ 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } },
{ "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */
{ 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } },
{ "Panasonic DMC-FZ50", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-FZ7", -15, 0,
{ 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } },
{ "Leica V-LUX1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Leica V-LUX 1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-L10", -15, 0xf96,
{ 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } },
{ "Panasonic DMC-L1", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX3", 0, 0xf7f, /* added */
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX 3", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Panasonic DMC-LC1", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX2", 0, 0, /* added */
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX 2", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Panasonic DMC-LX100", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX (Typ 109)", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Panasonic DMC-LF1", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Leica C (Typ 112)", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX1", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-Lux (Typ 109)", 0, 0xf7f,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX2", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-LUX 2", 0, 0xf7f, /* added */
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Panasonic DMC-LX2", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX3", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX 3", 0, 0, /* added */
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Panasonic DMC-LX3", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Leica D-LUX 4", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Panasonic DMC-LX5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Leica D-LUX 5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Panasonic DMC-LX7", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Leica D-LUX 6", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Panasonic DMC-FZ1000", -15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Leica V-LUX (Typ 114)", 15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Panasonic DMC-FZ100", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Leica V-LUX 2", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Panasonic DMC-FZ150", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Leica V-LUX 3", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ2500", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZH1", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ200", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Leica V-LUX 4", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Panasonic DMC-FX150", -15, 0xfff,
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-FX180", -15, 0xfff, /* added */
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-G10", 0, 0,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G1", -15, 0xf94,
{ 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } },
{ "Panasonic DMC-G2", -15, 0xf3c,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G3", -15, 0xfff,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{ "Panasonic DMC-G5", -15, 0xfff,
{ 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } },
{ "Panasonic DMC-G6", -15, 0xfff,
{ 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } },
{ "Panasonic DMC-G7", -15, 0xfff,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-G9", -15, 0, /* temp */
{ 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } },
{ "Panasonic DMC-GF1", -15, 0xf92,
{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
{ "Panasonic DMC-GF2", -15, 0xfff,
{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
{ "Panasonic DMC-GF3", -15, 0xfff,
{ 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } },
{ "Panasonic DMC-GF5", -15, 0xfff,
{ 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } },
{ "Panasonic DMC-GF6", -15, 0,
{ 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } },
{ "Panasonic DMC-GF7", -15, 0,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GF8", -15, 0,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GH1", -15, 0xf92,
{ 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } },
{ "Panasonic DMC-GH2", -15, 0xf95,
{ 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } },
{ "Panasonic DMC-GH3", -15, 0,
{ 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } },
{ "Panasonic DMC-GH4", -15, 0,
{ 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } },
{ "Panasonic AG-GH4", -15, 0, /* added */
{ 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } },
{ "Panasonic DC-GH5", -15, 0,
{ 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } },
{ "Yuneec CGO4", -15, 0,
{ 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } },
{ "Panasonic DMC-GM1", -15, 0,
{ 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } },
{ "Panasonic DMC-GM5", -15, 0,
{ 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } },
{ "Panasonic DMC-GX1", -15, 0,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{ "Panasonic DC-GX850", -15, 0, /* markets: GX850 GX800 GF9 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-GX800", -15, 0, /* markets: GX850 GX800 GF9 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-GF9", -15, 0, /* markets: GX850 GX800 GF9 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */
{ 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } },
{ "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */
{ 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } },
{ "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */
{ 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } },
{ "Panasonic DMC-GX7", -15,0,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GX8", -15,0,
{ 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } },
{ "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */
{ 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } },
{ "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ82 TZ85 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DC-TZ90", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */
{ 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } },
{ "Panasonic DC-TZ91", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */
{ 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } },
{ "Panasonic DC-TZ92", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */
{ 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } },
{ "Panasonic DC-T93", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */
{ 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } },
{ "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */
{ 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } },
{ "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */
{ 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } },
{ "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */
{ 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } },
{ "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DC-ZS70", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */
{ 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } },
{ "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Phase One H 20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H 25", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One H25", 0, 0, /* added */
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ280", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ260", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ250",0, 0,
// {3984,0,0,0,10000,0,0,0,7666}},
{10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* emb */
{ "Phase One IQ180", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ160", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ150", 0, 0, /* added */
{10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* temp */ /* emb */
// { 3984,0,0,0,10000,0,0,0,7666 } },
{ "Phase One IQ140", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P 45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P 30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P 21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One P2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ3 100MP", 0, 0, /* added */
// {2423,0,0,0,9901,0,0,0,7989}},
{ 10999,354,-742,-4590,13342,937,-1060,2166,8120} }, /* emb */
{ "Phase One IQ3 80MP", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ3 60MP", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ3 50MP", 0, 0, /* added */
// { 3984,0,0,0,10000,0,0,0,7666 } },
{10058,1079,-587,-4135,12903,944,-916,2726,7480}}, /* emb */
{ "Photron BC2-HD", 0, 0, /* DJC */
{ 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } },
{ "Polaroid x530", 0, 0,
{ 13458,-2556,-510,-5444,15081,205,0,0,12120 } },
{ "Red One", 704, 0xffff, /* DJC */
{ 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } },
{ "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */
{ 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } },
{ "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */
{ 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } },
{ "Ricoh GR DIGITAL 3", 0, 0, /* added */
{ 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } },
{ "Ricoh GR DIGITAL 4", 0, 0, /* added */
{ 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } },
{ "Ricoh GR II", 0, 0,
{ 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } },
{ "Ricoh GR", 0, 0,
{ 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } },
{ "Ricoh GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh RICOH GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh GXR MOUNT A12", 0, 0, /* added */
{ 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } },
{ "Ricoh GXR A16", 0, 0, /* added */
{ 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } },
{ "Ricoh GXR A12", 0, 0, /* added */
{ 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } },
{ "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN120", 0, 0, /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EX1", 0, 0x3e00,
{ 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } },
{ "Samsung EX2F", 0, 0x7ff,
{ 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } },
{ "Samsung Galaxy S7 Edge", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy S7", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy NX", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX U", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX mini", 0, 0,
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung NX3300", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX3000", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2000", 0, 0,
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1000", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1100", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX11", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX10", 0, 0, /* used for NX10/NX100 */
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX500", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NX5", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX1", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NXF1", 0, 0, /* added */
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung WB2000", 0, 0xfff,
{ 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } },
{ "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Samsung GX20", 0, 0, /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung S85", 0, 0, /* DJC */
{ 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } },
// Foveon: LibRaw color data
{ "Sigma dp0 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp1 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp2 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp3 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma sd Quattro H", 256, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma sd Quattro", 2047, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma SD9", 15, 4095, /* updated */
{ 13564,-2537,-751,-5465,15154,194,-67,116,10425 } },
{ "Sigma SD10", 15, 16383, /* updated */
{ 6787,-1682,575,-3091,8357,160,217,-369,12314 } },
{ "Sigma SD14", 15, 16383, /* updated */
{ 13589,-2509,-739,-5440,15104,193,-61,105,10554 } },
{ "Sigma SD15", 15, 4095, /* updated */
{ 13556,-2537,-730,-5462,15144,195,-61,106,10577 } },
// Merills + SD1
{ "Sigma SD1", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP1 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP2 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP3 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
// Sigma DP (non-Merill Versions)
{ "Sigma DP1X", 0, 4095, /* updated */
{ 13704,-2452,-857,-5413,15073,186,-89,151,9820 } },
{ "Sigma DP1", 0, 4095, /* updated */
{ 12774,-2591,-394,-5333,14676,207,15,-21,12127 } },
{ "Sigma DP", 0, 4095, /* LibRaw */
// { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } },
{ 13100,-3638,-847,6855,2369,580,2723,3218,3251 } },
{ "Sinar", 0, 0, /* DJC */
{ 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
{ "Sony DSC-F828", 0, 0,
{ 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
{ "Sony DSC-R1", 0, 0,
{ 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
{ "Sony DSC-V3", 0, 0,
{ 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
{"Sony DSC-RX100M5", -800, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100", 0, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{"Sony DSC-RX10M4", -800, 0, /* prelim */
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX10",0, 0, /* same for M2/M3 */
{ 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } },
{ "Sony DSC-RX1RM2", 0, 0,
{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
{ "Sony DSC-RX1R", 0, 0, /* updated */
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{ "Sony DSC-RX1", 0, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{"Sony DSC-RX0", -800, 0, /* temp */
{ 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } },
{ "Sony DSLR-A100", 0, 0xfeb,
{ 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } },
{ "Sony DSLR-A290", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A2", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A300", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A330", 0, 0,
{ 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } },
{ "Sony DSLR-A350", 0, 0xffc,
{ 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } },
{ "Sony DSLR-A380", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A390", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A450", 0, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A580", 0, 0xfeb,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony DSLR-A500", 0, 0xfeb,
{ 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } },
{ "Sony DSLR-A5", 0, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A700", 0, 0,
{ 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } },
{ "Sony DSLR-A850", 0, 0,
{ 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } },
{ "Sony DSLR-A900", 0, 0,
{ 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } },
{ "Sony ILCA-68", 0, 0,
{ 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } },
{ "Sony ILCA-77M2", 0, 0,
{ 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } },
{ "Sony ILCA-99M2", 0, 0,
{ 6660,-1918,-471,-4613,12398,2485,-649,1433,6447 } },
{ "Sony ILCE-9", 0, 0,
{ 6389,-1703,-378,-4562,12265,2587,-670,1489,6550 } },
{ "Sony ILCE-7M2", 0, 0,
{ 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } },
{ "Sony ILCE-7SM2", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7S", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7RM3", 0, 0, /* temp */
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony ILCE-7RM2", 0, 0,
{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
{ "Sony ILCE-7R", 0, 0,
{ 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } },
{ "Sony ILCE-7", 0, 0,
{ 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } },
{ "Sony ILCE-6300", 0, 0,
{ 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } },
{ "Sony ILCE-6500", 0, 0,
{ 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } },
{ "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony MODEL-NAME", 0, 0, /* added */
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony NEX-5N", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony NEX-5R", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-5T", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-3N", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-3", 0, 0,
{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
{ "Sony NEX-5", 0, 0,
{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
{ "Sony NEX-6", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-7", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony NEX-VG30", 0, 0, /* added */
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-VG900", 0, 0, /* added */
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{ "Sony NEX", 0, 0, /* NEX-C3, NEX-F3, NEX-VG20 */
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A33", 0, 0,
{ 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } },
{ "Sony SLT-A35", 0, 0,
{ 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } },
{ "Sony SLT-A37", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A55", 0, 0,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony SLT-A57", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A58", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A65", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony SLT-A77", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony SLT-A99", 0, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
};
// clang-format on
double cam_xyz[4][3];
char name[130];
int i, j;
if (colors > 4 || colors < 1)
return;
int bl4 = (cblack[0] + cblack[1] + cblack[2] + cblack[3]) / 4, bl64 = 0;
if (cblack[4] * cblack[5] > 0)
{
for (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++)
bl64 += cblack[c + 6];
bl64 /= cblack[4] * cblack[5];
}
int rblack = black + bl4 + bl64;
sprintf(name, "%s %s", t_make, t_model);
for (i = 0; i < sizeof table / sizeof *table; i++)
if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix)))
{
if (!dng_version)
{
if (table[i].t_black > 0)
{
black = (ushort)table[i].t_black;
memset(cblack, 0, sizeof(cblack));
}
else if (table[i].t_black < 0 && rblack == 0)
{
black = (ushort)(-table[i].t_black);
memset(cblack, 0, sizeof(cblack));
}
if (table[i].t_maximum)
maximum = (ushort)table[i].t_maximum;
}
if (table[i].trans[0])
{
for (raw_color = j = 0; j < 12; j++)
#ifdef LIBRAW_LIBRARY_BUILD
if (internal_only)
imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0;
else
imgdata.color.cam_xyz[0][j] =
#endif
((double *)cam_xyz)[j] = table[i].trans[j] / 10000.0;
#ifdef LIBRAW_LIBRARY_BUILD
if (!internal_only)
#endif
cam_xyz_coeff(rgb_cam, cam_xyz);
}
break;
}
}
void CLASS simple_coeff(int index)
{
static const float table[][12] = {/* index 0 -- all Foveon cameras */
{1.4032, -0.2231, -0.1016, -0.5263, 1.4816, 0.017, -0.0112, 0.0183, 0.9113},
/* index 1 -- Kodak DC20 and DC25 */
{2.25, 0.75, -1.75, -0.25, -0.25, 0.75, 0.75, -0.25, -0.25, -1.75, 0.75, 2.25},
/* index 2 -- Logitech Fotoman Pixtura */
{1.893, -0.418, -0.476, -0.495, 1.773, -0.278, -1.017, -0.655, 2.672},
/* index 3 -- Nikon E880, E900, and E990 */
{-1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680,
-1.204965, 1.082304, 2.941367, -1.818705}};
int i, c;
for (raw_color = i = 0; i < 3; i++)
FORCC rgb_cam[i][c] = table[index][i * colors + c];
}
short CLASS guess_byte_order(int words)
{
uchar test[4][2];
int t = 2, msb;
double diff, sum[2] = {0, 0};
fread(test[0], 2, 2, ifp);
for (words -= 2; words--;)
{
fread(test[t], 2, 1, ifp);
for (msb = 0; msb < 2; msb++)
{
diff = (test[t ^ 2][msb] << 8 | test[t ^ 2][!msb]) - (test[t][msb] << 8 | test[t][!msb]);
sum[msb] += diff * diff;
}
t = (t + 1) & 3;
}
return sum[0] < sum[1] ? 0x4d4d : 0x4949;
}
float CLASS find_green(int bps, int bite, int off0, int off1)
{
UINT64 bitbuf = 0;
int vbits, col, i, c;
ushort img[2][2064];
double sum[] = {0, 0};
FORC(2)
{
fseek(ifp, c ? off1 : off0, SEEK_SET);
for (vbits = col = 0; col < width; col++)
{
for (vbits -= bps; vbits < 0; vbits += bite)
{
bitbuf <<= bite;
for (i = 0; i < bite; i += 8)
bitbuf |= (unsigned)(fgetc(ifp) << i);
}
img[c][col] = bitbuf << (64 - bps - vbits) >> (64 - bps);
}
}
FORC(width - 1)
{
sum[c & 1] += ABS(img[0][c] - img[1][c + 1]);
sum[~c & 1] += ABS(img[1][c] - img[0][c + 1]);
}
return 100 * log(sum[0] / sum[1]);
}
#ifdef LIBRAW_LIBRARY_BUILD
static void remove_trailing_spaces(char *string, size_t len)
{
if (len < 1)
return; // not needed, b/c sizeof of make/model is 64
string[len - 1] = 0;
if (len < 3)
return; // also not needed
len = strnlen(string, len - 1);
for (int i = len - 1; i >= 0; i--)
{
if (isspace(string[i]))
string[i] = 0;
else
break;
}
}
void CLASS initdata()
{
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
for (int i = 0; i < 0x10000; i++)
curve[i] = i;
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
}
#endif
/*
Identify which camera created this file, and set global variables
accordingly.
*/
void CLASS identify()
{
static const short pana[][6] = {
{3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0},
{3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0},
{3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4},
{3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21},
{3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2},
{3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0},
{4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19},
{4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6},
};
static const ushort canon[][11] = {
{1944, 1416, 0, 0, 48, 0},
{2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25},
{2224, 1456, 48, 6, 0, 2},
{2376, 1728, 12, 6, 52, 2},
{2672, 1968, 12, 6, 44, 2},
{3152, 2068, 64, 12, 0, 0, 16},
{3160, 2344, 44, 12, 4, 4},
{3344, 2484, 4, 6, 52, 6},
{3516, 2328, 42, 14, 0, 0},
{3596, 2360, 74, 12, 0, 0},
{3744, 2784, 52, 12, 8, 12},
{3944, 2622, 30, 18, 6, 2},
{3948, 2622, 42, 18, 0, 2},
{3984, 2622, 76, 20, 0, 2, 14},
{4104, 3048, 48, 12, 24, 12},
{4116, 2178, 4, 2, 0, 0},
{4152, 2772, 192, 12, 0, 0},
{4160, 3124, 104, 11, 8, 65},
{4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49},
{4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49},
{4312, 2876, 22, 18, 0, 2},
{4352, 2874, 62, 18, 0, 0},
{4476, 2954, 90, 34, 0, 0},
{4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49},
{4480, 3366, 80, 50, 0, 0},
{4496, 3366, 80, 50, 12, 0},
{4768, 3516, 96, 16, 0, 0, 0, 16},
{4832, 3204, 62, 26, 0, 0},
{4832, 3228, 62, 51, 0, 0},
{5108, 3349, 98, 13, 0, 0},
{5120, 3318, 142, 45, 62, 0},
{5280, 3528, 72, 52, 0, 0}, /* EOS M */
{5344, 3516, 142, 51, 0, 0},
{5344, 3584, 126, 100, 0, 2},
{5360, 3516, 158, 51, 0, 0},
{5568, 3708, 72, 38, 0, 0},
{5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49},
{5712, 3774, 62, 20, 10, 2},
{5792, 3804, 158, 51, 0, 0},
{5920, 3950, 122, 80, 2, 0},
{6096, 4056, 72, 34, 0, 0}, /* EOS M3 */
{6288, 4056, 266, 36, 0, 0}, /* EOS 80D */
{6384, 4224, 120, 44, 0, 0}, /* 6D II */
{6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */
{8896, 5920, 160, 64, 0, 0},
};
static const struct
{
ushort id;
char t_model[20];
} unique[] =
{
{0x001, "EOS-1D"},
{0x167, "EOS-1DS"},
{0x168, "EOS 10D"},
{0x169, "EOS-1D Mark III"},
{0x170, "EOS 300D"},
{0x174, "EOS-1D Mark II"},
{0x175, "EOS 20D"},
{0x176, "EOS 450D"},
{0x188, "EOS-1Ds Mark II"},
{0x189, "EOS 350D"},
{0x190, "EOS 40D"},
{0x213, "EOS 5D"},
{0x215, "EOS-1Ds Mark III"},
{0x218, "EOS 5D Mark II"},
{0x232, "EOS-1D Mark II N"},
{0x234, "EOS 30D"},
{0x236, "EOS 400D"},
{0x250, "EOS 7D"},
{0x252, "EOS 500D"},
{0x254, "EOS 1000D"},
{0x261, "EOS 50D"},
{0x269, "EOS-1D X"},
{0x270, "EOS 550D"},
{0x281, "EOS-1D Mark IV"},
{0x285, "EOS 5D Mark III"},
{0x286, "EOS 600D"},
{0x287, "EOS 60D"},
{0x288, "EOS 1100D"},
{0x289, "EOS 7D Mark II"},
{0x301, "EOS 650D"},
{0x302, "EOS 6D"},
{0x324, "EOS-1D C"},
{0x325, "EOS 70D"},
{0x326, "EOS 700D"},
{0x327, "EOS 1200D"},
{0x328, "EOS-1D X Mark II"},
{0x331, "EOS M"},
{0x335, "EOS M2"},
{0x374, "EOS M3"}, /* temp */
{0x384, "EOS M10"}, /* temp */
{0x394, "EOS M5"}, /* temp */
{0x398, "EOS M100"}, /* temp */
{0x346, "EOS 100D"},
{0x347, "EOS 760D"},
{0x349, "EOS 5D Mark IV"},
{0x350, "EOS 80D"},
{0x382, "EOS 5DS"},
{0x393, "EOS 750D"},
{0x401, "EOS 5DS R"},
{0x404, "EOS 1300D"},
{0x405, "EOS 800D"},
{0x406, "EOS 6D Mark II"},
{0x407, "EOS M6"},
{0x408, "EOS 77D"},
{0x417, "EOS 200D"},
},
sonique[] = {
{0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"},
{0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"},
{0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"},
{0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"},
{0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"},
{0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"},
{0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"},
{0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"},
{0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"},
{0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"},
{0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"},
{0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"},
{0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"},
{0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"},
{0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"},
{0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"},
{0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"},
{0x168, "ILCE-6500"}, {0x16a, "ILCE-7RM3"}, {0x16c, "DSC-RX0"}, {0x16d, "DSC-RX10M4"},
};
#ifdef LIBRAW_LIBRARY_BUILD
static const libraw_custom_camera_t const_table[]
#else
static const struct
{
unsigned fsize;
ushort rw, rh;
uchar lm, tm, rm, bm, lf, cf, max, flags;
char t_make[10], t_model[20];
ushort offset;
} table[]
#endif
= {
{786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"},
{1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"},
{1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"},
{5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"},
{5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12},
{10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"},
{10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12},
{16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"},
{15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"},
{31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"},
{23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"},
{32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"},
// Android Raw dumps id start
// File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb
{1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"},
{2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"},
{2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"},
{2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"},
{3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"},
{3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"},
{5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"},
{5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"},
{6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"},
{6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"},
{9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"},
{10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"},
{10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"},
{10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"},
{10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"},
{15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"},
{16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"},
{16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"},
{17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"},
{17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"},
{19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"},
{19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"},
{20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"},
{20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"},
{21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"},
{26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"},
{26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"},
{26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"},
{41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"},
{42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"},
// Android Raw dumps id end
{20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff},
{2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078},
{5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"},
{6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"},
{6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"},
{6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"},
{7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"},
{9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"},
{9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"},
{10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"},
{10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"},
{12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"},
{15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"},
{15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"},
{15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"},
{18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"},
{18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"},
{19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"},
{21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"},
{24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"},
{30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"},
{1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"},
{3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"},
{6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"},
{7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"},
{2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"},
{4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"},
{6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"},
{7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"},
{7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"},
{7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"},
{7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"},
{7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"},
{9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"},
{10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"},
{10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"},
{10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"},
{12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"},
{12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"},
{15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"},
{18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"},
{7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"},
{787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"},
{28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"},
{15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"},
{3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"},
{307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"},
{62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"},
{4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"},
{4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160},
{2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"},
{6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160},
{460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"},
{12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556},
{18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"},
{614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"},
{15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"},
{3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212},
{1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513},
{1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"},
{2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"},
{2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"},
{4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"},
{4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"},
{5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"},
{5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"},
{7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"},
{8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"},
{5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"},
{3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"},
{4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"},
{6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"},
{10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"},
{4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"},
{4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8},
{13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"},
{6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"},
{311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"},
{16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
{2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
};
#ifdef LIBRAW_LIBRARY_BUILD
libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])];
#endif
static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta",
"Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus",
"Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"};
#ifdef LIBRAW_LIBRARY_BUILD
char head[64], *cp;
#else
char head[32], *cp;
#endif
int hlen, flen, fsize, zero_fsize = 1, i, c;
struct jhead jh;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings);
for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++)
memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0]));
camera_count += sizeof(const_table) / sizeof(const_table[0]);
#endif
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.other.CameraTemperature =
imgdata.other.SensorTemperature =
imgdata.other.SensorTemperature2 =
imgdata.other.LensTemperature =
imgdata.other.AmbientTemperature =
imgdata.other.BatteryTemperature =
imgdata.other.exifAmbientTemperature = -1000.0f;
for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
#endif
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
for (i = 0; i < 4; i++)
{
cam_mul[i] = i == 1;
pre_mul[i] = i < 3;
FORC3 cmatrix[c][i] = 0;
FORC3 rgb_cam[c][i] = c == i;
}
colors = 3;
for (i = 0; i < 0x10000; i++)
curve[i] = i;
order = get2();
hlen = get4();
fseek(ifp, 0, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
fread(head, 1, 64, ifp);
libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0;
#else
fread(head, 1, 32, ifp);
#endif
fseek(ifp, 0, SEEK_END);
flen = fsize = ftell(ifp);
if ((cp = (char *)memmem(head, 32, (char *)"MMMM", 4)) || (cp = (char *)memmem(head, 32, (char *)"IIII", 4)))
{
parse_phase_one(cp - head);
if (cp - head && parse_tiff(0))
apply_tiff();
}
else if (order == 0x4949 || order == 0x4d4d)
{
if (!memcmp(head + 6, "HEAPCCDR", 8))
{
data_offset = hlen;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
#endif
parse_ciff(hlen, flen - hlen, 0);
load_raw = &CLASS canon_load_raw;
}
else if (parse_tiff(0))
apply_tiff();
}
else if (!memcmp(head, "\xff\xd8\xff\xe1", 4) && !memcmp(head + 6, "Exif", 4))
{
fseek(ifp, 4, SEEK_SET);
data_offset = 4 + get2();
fseek(ifp, data_offset, SEEK_SET);
if (fgetc(ifp) != 0xff)
parse_tiff(12);
thumb_offset = 0;
}
else if (!memcmp(head + 25, "ARECOYK", 7))
{
strcpy(make, "Contax");
strcpy(model, "N Digital");
fseek(ifp, 33, SEEK_SET);
get_timestamp(1);
fseek(ifp, 52, SEEK_SET);
switch (get4())
{
case 7:
iso_speed = 25;
break;
case 8:
iso_speed = 32;
break;
case 9:
iso_speed = 40;
break;
case 10:
iso_speed = 50;
break;
case 11:
iso_speed = 64;
break;
case 12:
iso_speed = 80;
break;
case 13:
iso_speed = 100;
break;
case 14:
iso_speed = 125;
break;
case 15:
iso_speed = 160;
break;
case 16:
iso_speed = 200;
break;
case 17:
iso_speed = 250;
break;
case 18:
iso_speed = 320;
break;
case 19:
iso_speed = 400;
break;
}
shutter = powf64(2.0f, (((float)get4()) / 8.0f)) / 16000.0f;
FORC4 cam_mul[c ^ (c >> 1)] = get4();
fseek(ifp, 88, SEEK_SET);
aperture = powf64(2.0f, ((float)get4()) / 16.0f);
fseek(ifp, 112, SEEK_SET);
focal_len = get4();
#ifdef LIBRAW_LIBRARY_BUILD
fseek(ifp, 104, SEEK_SET);
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4()) / 16.0f);
fseek(ifp, 124, SEEK_SET);
stmread(imgdata.lens.makernotes.Lens, 32, ifp);
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N;
#endif
}
else if (!strcmp(head, "PXN"))
{
strcpy(make, "Logitech");
strcpy(model, "Fotoman Pixtura");
}
else if (!strcmp(head, "qktk"))
{
strcpy(make, "Apple");
strcpy(model, "QuickTake 100");
load_raw = &CLASS quicktake_100_load_raw;
}
else if (!strcmp(head, "qktn"))
{
strcpy(make, "Apple");
strcpy(model, "QuickTake 150");
load_raw = &CLASS kodak_radc_load_raw;
}
else if (!memcmp(head, "FUJIFILM", 8))
{
#ifdef LIBRAW_LIBRARY_BUILD
strcpy(model, head + 0x1c);
memcpy(model2, head + 0x3c, 4);
model2[4] = 0;
#endif
fseek(ifp, 84, SEEK_SET);
thumb_offset = get4();
thumb_length = get4();
fseek(ifp, 92, SEEK_SET);
parse_fuji(get4());
if (thumb_offset > 120)
{
fseek(ifp, 120, SEEK_SET);
is_raw += (i = get4()) ? 1 : 0;
if (is_raw == 2 && shot_select)
parse_fuji(i);
}
load_raw = &CLASS unpacked_load_raw;
fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET);
parse_tiff(data_offset = get4());
parse_tiff(thumb_offset + 12);
apply_tiff();
}
else if (!memcmp(head, "RIFF", 4))
{
fseek(ifp, 0, SEEK_SET);
parse_riff();
}
else if (!memcmp(head + 4, "ftypqt ", 9))
{
fseek(ifp, 0, SEEK_SET);
parse_qt(fsize);
is_raw = 0;
}
else if (!memcmp(head, "\0\001\0\001\0@", 6))
{
fseek(ifp, 6, SEEK_SET);
fread(make, 1, 8, ifp);
fread(model, 1, 8, ifp);
fread(model2, 1, 16, ifp);
data_offset = get2();
get2();
raw_width = get2();
raw_height = get2();
load_raw = &CLASS nokia_load_raw;
filters = 0x61616161;
}
else if (!memcmp(head, "NOKIARAW", 8))
{
strcpy(make, "NOKIA");
order = 0x4949;
fseek(ifp, 300, SEEK_SET);
data_offset = get4();
i = get4(); // bytes count
width = get2();
height = get2();
#ifdef LIBRAW_LIBRARY_BUILD
// Data integrity check
if(width < 1 || width > 16000 || height < 1 || height > 16000
|| i < (width*height) || i > (2* width*height))
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
switch (tiff_bps = i * 8 / (width * height))
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
load_raw = &CLASS nokia_load_raw;
}
raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height);
mask[0][3] = 1;
filters = 0x61616161;
}
else if (!memcmp(head, "ARRI", 4))
{
order = 0x4949;
fseek(ifp, 20, SEEK_SET);
width = get4();
height = get4();
strcpy(make, "ARRI");
fseek(ifp, 668, SEEK_SET);
fread(model, 1, 64, ifp);
data_offset = 4096;
load_raw = &CLASS packed_load_raw;
load_flags = 88;
filters = 0x61616161;
}
else if (!memcmp(head, "XPDS", 4))
{
order = 0x4949;
fseek(ifp, 0x800, SEEK_SET);
fread(make, 1, 41, ifp);
raw_height = get2();
raw_width = get2();
fseek(ifp, 56, SEEK_CUR);
fread(model, 1, 30, ifp);
data_offset = 0x10000;
load_raw = &CLASS canon_rmf_load_raw;
gamma_curve(0, 12.25, 1, 1023);
}
else if (!memcmp(head + 4, "RED1", 4))
{
strcpy(make, "Red");
strcpy(model, "One");
parse_redcine();
load_raw = &CLASS redcine_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
filters = 0x49494949;
}
else if (!memcmp(head, "DSC-Image", 9))
parse_rollei();
else if (!memcmp(head, "PWAD", 4))
parse_sinar_ia();
else if (!memcmp(head, "\0MRM", 4))
parse_minolta(0);
else if (!memcmp(head, "FOVb", 4))
{
#ifdef LIBRAW_LIBRARY_BUILD
/* no foveon support for dcraw build from libraw source */
parse_x3f();
#endif
}
else if (!memcmp(head, "CI", 2))
parse_cine();
if (make[0] == 0)
#ifdef LIBRAW_LIBRARY_BUILD
for (zero_fsize = i = 0; i < camera_count; i++)
#else
for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++)
#endif
if (fsize == table[i].fsize)
{
strcpy(make, table[i].t_make);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "Canon", 5))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
#endif
strcpy(model, table[i].t_model);
flip = table[i].flags >> 2;
zero_is_bad = table[i].flags & 2;
if (table[i].flags & 1)
parse_external_jpeg();
data_offset = table[i].offset == 0xffff ? 0 : table[i].offset;
raw_width = table[i].rw;
raw_height = table[i].rh;
left_margin = table[i].lm;
top_margin = table[i].tm;
width = raw_width - left_margin - table[i].rm;
height = raw_height - top_margin - table[i].bm;
filters = 0x1010101 * table[i].cf;
colors = 4 - !((filters & filters >> 1) & 0x5555);
load_flags = table[i].lf;
switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height))
{
case 6:
load_raw = &CLASS minolta_rd175_load_raw;
break;
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4)
{
load_raw = &CLASS android_loose_load_raw;
break;
}
else if (load_flags & 1)
{
load_raw = &CLASS android_tight_load_raw;
break;
}
case 12:
load_flags |= 128;
load_raw = &CLASS packed_load_raw;
break;
case 16:
order = 0x4949 | 0x404 * (load_flags & 1);
tiff_bps -= load_flags >> 4;
tiff_bps -= load_flags = load_flags >> 1 & 7;
load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw;
}
maximum = (1 << tiff_bps) - (1 << table[i].max);
break;
}
if (zero_fsize)
fsize = 0;
if (make[0] == 0)
parse_smal(0, flen);
if (make[0] == 0)
{
parse_jpeg(0);
fseek(ifp, 0, SEEK_END);
int sz = ftell(ifp);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) &&
fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
strcpy(model, "RPi IMX219");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 66;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x9cb600 - 1;
}
else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 &&
!fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
if (!strncmp(model, "ov5647", 6))
strcpy(model, "RPi OV5647 v.1");
else
strcpy(model, "RPi OV5647 v.2");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 16;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x61b800 - 1;
#else
if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) &&
fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn"))
{
strcpy(make, "OmniVision");
data_offset = ftell(ifp) + 0x8000 - 32;
width = raw_width;
raw_width = 2611;
load_raw = &CLASS nokia_load_raw;
filters = 0x16161616;
#endif
}
else
is_raw = 0;
}
#ifdef LIBRAW_LIBRARY_BUILD
// make sure strings are terminated
desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
#endif
for (i = 0; i < sizeof corp / sizeof *corp; i++)
if (strcasestr(make, corp[i])) /* Simplify company names */
strcpy(make, corp[i]);
if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) &&
((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION"))))
*cp = 0;
if (!strncasecmp(model, "PENTAX", 6))
strcpy(make, "Pentax");
#ifdef LIBRAW_LIBRARY_BUILD
remove_trailing_spaces(make, sizeof(make));
remove_trailing_spaces(model, sizeof(model));
#else
cp = make + strlen(make); /* Remove trailing spaces */
while (*--cp == ' ')
*cp = 0;
cp = model + strlen(model);
while (*--cp == ' ')
*cp = 0;
#endif
i = strbuflen(make); /* Remove make from model */
if (!strncasecmp(model, make, i) && model[i++] == ' ')
memmove(model, model + i, 64 - i);
if (!strncmp(model, "FinePix ", 8))
strcpy(model, model + 8);
if (!strncmp(model, "Digital Camera ", 15))
strcpy(model, model + 15);
desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
if (!is_raw)
goto notraw;
if (!height)
height = raw_height;
if (!width)
width = raw_width;
if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */
{
height = 2616;
width = 3896;
}
if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */
{
height = 3124;
width = 4688;
filters = 0x16161616;
}
if (width == 4352 && (!strcmp(model, "K-r") || !strcmp(model, "K-x")))
{
width = 4309;
filters = 0x16161616;
}
if (width >= 4960 && !strncmp(model, "K-5", 3))
{
left_margin = 10;
width = 4950;
filters = 0x16161616;
}
if (width == 6080 && !strcmp(model, "K-70"))
{
height = 4016;
top_margin = 32;
width = 6020;
left_margin = 60;
}
if (width == 4736 && !strcmp(model, "K-7"))
{
height = 3122;
width = 4684;
filters = 0x16161616;
top_margin = 2;
}
if (width == 6080 && !strcmp(model, "K-3 II")) /* moved back */
{
left_margin = 4;
width = 6040;
}
if (width == 6112 && !strcmp(model, "KP"))
{
/* From DNG, maybe too strict */
left_margin = 54;
top_margin = 28;
width = 6028;
height = raw_height - top_margin;
}
if (width == 6080 && !strcmp(model, "K-3"))
{
left_margin = 4;
width = 6040;
}
if (width == 7424 && !strcmp(model, "645D"))
{
height = 5502;
width = 7328;
filters = 0x61616161;
top_margin = 29;
left_margin = 48;
}
if (height == 3014 && width == 4096) /* Ricoh GX200 */
width = 4014;
if (dng_version)
{
if (filters == UINT_MAX)
filters = 0;
if (filters)
is_raw *= tiff_samples;
else
colors = tiff_samples;
switch (tiff_compress)
{
case 0: /* Compression not set, assuming uncompressed */
case 1:
load_raw = &CLASS packed_dng_load_raw;
break;
case 7:
load_raw = &CLASS lossless_dng_load_raw;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 8:
load_raw = &CLASS deflate_dng_load_raw;
break;
#endif
case 34892:
load_raw = &CLASS lossy_dng_load_raw;
break;
default:
load_raw = 0;
}
if (!strncmp(make, "Canon", 5) && unique_id)
{
for (i = 0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
strcpy(model, unique[i].t_model);
break;
}
}
if (!strncasecmp(make, "Sony", 4) && unique_id)
{
for (i = 0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
strcpy(model, sonique[i].t_model);
break;
}
}
goto dng_skip;
}
if (!strncmp(make, "Canon", 5) && !fsize && tiff_bps != 15)
{
if (!load_raw)
load_raw = &CLASS lossless_jpeg_load_raw;
for (i = 0; i < sizeof canon / sizeof *canon; i++)
if (raw_width == canon[i][0] && raw_height == canon[i][1])
{
width = raw_width - (left_margin = canon[i][2]);
height = raw_height - (top_margin = canon[i][3]);
width -= canon[i][4];
height -= canon[i][5];
mask[0][1] = canon[i][6];
mask[0][3] = -canon[i][7];
mask[1][1] = canon[i][8];
mask[1][3] = -canon[i][9];
if (canon[i][10])
filters = canon[i][10] * 0x01010101;
}
if ((unique_id | 0x20000) == 0x2720000)
{
left_margin = 8;
top_margin = 16;
}
}
if (!strncmp(make, "Canon", 5) && unique_id)
{
for (i = 0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
adobe_coeff("Canon", unique[i].t_model);
strcpy(model, unique[i].t_model);
}
}
if (!strncasecmp(make, "Sony", 4) && unique_id)
{
for (i = 0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
adobe_coeff("Sony", sonique[i].t_model);
strcpy(model, sonique[i].t_model);
}
}
if (!strncmp(make, "Nikon", 5))
{
if (!load_raw)
load_raw = &CLASS packed_load_raw;
if (model[0] == 'E')
load_flags |= !data_offset << 2 | 2;
}
/* Set parameters based on camera name (for non-DNG files). */
if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25)
{
height = 480;
top_margin = filters = 0;
strcpy(model, "C603");
}
#ifndef LIBRAW_LIBRARY_BUILD
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = 128 << (tiff_bps - 12);
#else
/* Always 512 for arw2_load_raw */
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12));
#endif
if (is_foveon)
{
if (height * 2 < width)
pixel_aspect = 0.5;
if (height > width)
pixel_aspect = 2;
filters = 0;
}
else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3))
{
top_margin = 18;
height = raw_height - top_margin;
if (raw_width == 7392)
{
left_margin = 6;
width = 7376;
}
}
else if (!strncmp(make, "Canon", 5) && tiff_bps == 15)
{
switch (width)
{
case 3344:
width -= 66;
case 3872:
width -= 6;
}
if (height > width)
{
SWAP(height, width);
SWAP(raw_height, raw_width);
}
if (width == 7200 && height == 3888)
{
raw_width = width = 6480;
raw_height = height = 4320;
}
filters = 0;
tiff_samples = colors = 3;
load_raw = &CLASS canon_sraw_load_raw;
}
else if (!strcmp(model, "PowerShot 600"))
{
height = 613;
width = 854;
raw_width = 896;
colors = 4;
filters = 0xe1e4e1e4;
load_raw = &CLASS canon_600_load_raw;
}
else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom"))
{
height = 773;
width = 960;
raw_width = 992;
pixel_aspect = 256 / 235.0;
filters = 0x1e4e1e4e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot A50"))
{
height = 968;
width = 1290;
raw_width = 1320;
filters = 0x1b4e4b1e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot Pro70"))
{
height = 1024;
width = 1552;
filters = 0x1e4b4e1b;
canon_a5:
colors = 4;
tiff_bps = 10;
load_raw = &CLASS packed_load_raw;
load_flags = 40;
}
else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1"))
{
colors = 4;
filters = 0xb4b4b4b4;
}
else if (!strcmp(model, "PowerShot A610"))
{
if (canon_s2is())
strcpy(model + 10, "S2 IS");
}
else if (!strcmp(model, "PowerShot SX220 HS"))
{
mask[1][3] = -4;
top_margin = 16;
left_margin = 92;
}
else if (!strcmp(model, "PowerShot S120"))
{
raw_width = 4192;
raw_height = 3062;
width = 4022;
height = 3016;
mask[0][0] = top_margin = 31;
mask[0][2] = top_margin + height;
left_margin = 120;
mask[0][1] = 23;
mask[0][3] = 72;
}
else if (!strcmp(model, "PowerShot G16"))
{
mask[0][0] = 0;
mask[0][2] = 80;
mask[0][1] = 0;
mask[0][3] = 16;
top_margin = 29;
left_margin = 120;
width = raw_width - left_margin - 48;
height = raw_height - top_margin - 14;
}
else if (!strcmp(model, "PowerShot SX50 HS"))
{
top_margin = 17;
}
else if (!strcmp(model, "EOS D2000C"))
{
filters = 0x61616161;
if (!black)
black = curve[200];
}
else if (!strcmp(model, "D1"))
{
cam_mul[0] *= 256 / 527.0;
cam_mul[2] *= 256 / 317.0;
}
else if (!strcmp(model, "D1X"))
{
width -= 4;
pixel_aspect = 0.5;
}
else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000"))
{
height -= 3;
width -= 4;
}
else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700"))
{
width -= 4;
left_margin = 2;
}
else if (!strcmp(model, "D3100"))
{
width -= 28;
left_margin = 6;
}
else if (!strcmp(model, "D5000") || !strcmp(model, "D90"))
{
width -= 42;
}
else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A"))
{
width -= 44;
}
else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4))
{
width -= 46;
}
else if (!strcmp(model, "D4") || !strcmp(model, "Df"))
{
width -= 52;
left_margin = 2;
}
else if (!strcmp(model, "D500"))
{
// Empty - to avoid width-1 below
}
else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3))
{
width--;
}
else if (!strcmp(model, "D100"))
{
if (load_flags)
raw_width = (width += 3) + 3;
}
else if (!strcmp(model, "D200"))
{
left_margin = 1;
width -= 4;
filters = 0x94949494;
}
else if (!strncmp(model, "D2H", 3))
{
left_margin = 6;
width -= 14;
}
else if (!strncmp(model, "D2X", 3))
{
if (width == 3264)
width -= 32;
else
width -= 8;
}
else if (!strncmp(model, "D300", 4))
{
width -= 32;
}
else if (!strncmp(make, "Nikon", 5) && raw_width == 4032)
{
if (!strcmp(model, "COOLPIX P7700"))
{
adobe_coeff("Nikon", "COOLPIX P7700");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P7800"))
{
adobe_coeff("Nikon", "COOLPIX P7800");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P340"))
load_flags = 0;
}
else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032)
{
load_flags = 24;
filters = 0x94949494;
if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2"))
black = 255;
}
else if (!strncmp(model, "COOLPIX B700", 12))
{
load_flags = 24;
black = 200;
}
else if (!strncmp(model, "1 ", 2))
{
height -= 2;
}
else if (fsize == 1581060)
{
simple_coeff(3);
pre_mul[0] = 1.2085;
pre_mul[1] = 1.0943;
pre_mul[3] = 1.1103;
}
else if (fsize == 3178560)
{
cam_mul[0] *= 4;
cam_mul[2] *= 4;
}
else if (fsize == 4771840)
{
if (!timestamp && nikon_e995())
strcpy(model, "E995");
if (strcmp(model, "E995"))
{
filters = 0xb4b4b4b4;
simple_coeff(3);
pre_mul[0] = 1.196;
pre_mul[1] = 1.246;
pre_mul[2] = 1.018;
}
}
else if (fsize == 2940928)
{
if (!timestamp && !nikon_e2100())
strcpy(model, "E2500");
if (!strcmp(model, "E2500"))
{
height -= 2;
load_flags = 6;
colors = 4;
filters = 0x4b4b4b4b;
}
}
else if (fsize == 4775936)
{
if (!timestamp)
nikon_3700();
if (model[0] == 'E' && atoi(model + 1) < 3700)
filters = 0x49494949;
if (!strcmp(model, "Optio 33WR"))
{
flip = 1;
filters = 0x16161616;
}
if (make[0] == 'O')
{
i = find_green(12, 32, 1188864, 3576832);
c = find_green(12, 32, 2383920, 2387016);
if (abs(i) < abs(c))
{
SWAP(i, c);
load_flags = 24;
}
if (i < 0)
filters = 0x61616161;
}
}
else if (fsize == 5869568)
{
if (!timestamp && minolta_z2())
{
strcpy(make, "Minolta");
strcpy(model, "DiMAGE Z2");
}
load_flags = 6 + 24 * (make[0] == 'M');
}
else if (fsize == 6291456)
{
fseek(ifp, 0x300000, SEEK_SET);
if ((order = guess_byte_order(0x10000)) == 0x4d4d)
{
height -= (top_margin = 16);
width -= (left_margin = 28);
maximum = 0xf5c0;
strcpy(make, "ISG");
model[0] = 0;
}
}
else if (!strncmp(make, "Fujifilm", 8))
{
if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10"))
{
left_margin = 0;
top_margin = 0;
width = raw_width;
height = raw_height;
}
if (!strcmp(model + 7, "S2Pro"))
{
strcpy(model, "S2Pro");
height = 2144;
width = 2880;
flip = 6;
}
else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2))
maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00;
top_margin = (raw_height - height) >> 2 << 1;
left_margin = (raw_width - width) >> 2 << 1;
if (width == 2848 || width == 3664)
filters = 0x16161616;
if (width == 4032 || width == 4952)
left_margin = 0;
if (width == 3328 && (width -= 66))
left_margin = 34;
if (width == 4936)
left_margin = 4;
if (width == 6032)
left_margin = 0;
if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR"))
{
width += 2;
left_margin = 0;
filters = 0x16161616;
}
if (!strcmp(model, "GFX 50S"))
{
left_margin = 0;
top_margin = 0;
}
if (!strcmp(model, "S5500"))
{
height -= (top_margin = 6);
}
if (fuji_layout)
raw_width *= is_raw;
if (filters == 9)
FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6];
}
else if (!strcmp(model, "KD-400Z"))
{
height = 1712;
width = 2312;
raw_width = 2336;
goto konica_400z;
}
else if (!strcmp(model, "KD-510Z"))
{
goto konica_510z;
}
else if (!strncasecmp(make, "Minolta", 7))
{
if (!load_raw && (maximum = 0xfff))
load_raw = &CLASS unpacked_load_raw;
if (!strncmp(model, "DiMAGE A", 8))
{
if (!strcmp(model, "DiMAGE A200"))
filters = 0x49494949;
tiff_bps = 12;
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6))
{
sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M'));
adobe_coeff(make, model + 20);
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "DiMAGE G", 8))
{
if (model[8] == '4')
{
height = 1716;
width = 2304;
}
else if (model[8] == '5')
{
konica_510z:
height = 1956;
width = 2607;
raw_width = 2624;
}
else if (model[8] == '6')
{
height = 2136;
width = 2848;
}
data_offset += 14;
filters = 0x61616161;
konica_400z:
load_raw = &CLASS unpacked_load_raw;
maximum = 0x3df;
order = 0x4d4d;
}
}
else if (!strcmp(model, "*ist D"))
{
load_raw = &CLASS unpacked_load_raw;
data_error = -1;
}
else if (!strcmp(model, "*ist DS"))
{
height -= 2;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 4704)
{
height -= top_margin = 8;
width -= 2 * (left_margin = 8);
load_flags = 32;
}
else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000"))
{
top_margin = 38;
left_margin = 92;
width = 5456;
height = 3634;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_height == 3714)
{
height -= top_margin = 18;
left_margin = raw_width - (width = 5536);
if (raw_width != 5600)
left_margin = top_margin = 0;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5632)
{
order = 0x4949;
height = 3694;
top_margin = 2;
width = 5574 - (left_margin = 32 + tiff_bps);
if (tiff_bps == 12)
load_flags = 80;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5664)
{
height -= top_margin = 17;
left_margin = 96;
width = 5544;
filters = 0x49494949;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 6496)
{
filters = 0x61616161;
#ifdef LIBRAW_LIBRARY_BUILD
if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3])
#endif
black = 1 << (tiff_bps - 7);
}
else if (!strcmp(model, "EX1"))
{
order = 0x4949;
height -= 20;
top_margin = 2;
if ((width -= 6) > 3682)
{
height -= 10;
width -= 46;
top_margin = 8;
}
}
else if (!strcmp(model, "WB2000"))
{
order = 0x4949;
height -= 3;
top_margin = 2;
if ((width -= 10) > 3718)
{
height -= 28;
width -= 56;
top_margin = 8;
}
}
else if (strstr(model, "WB550"))
{
strcpy(model, "WB550");
}
else if (!strcmp(model, "EX2F"))
{
height = 3030;
width = 4040;
top_margin = 15;
left_margin = 24;
order = 0x4949;
filters = 0x49494949;
load_raw = &CLASS unpacked_load_raw;
}
else if (!strcmp(model, "STV680 VGA"))
{
black = 16;
}
else if (!strcmp(model, "N95"))
{
height = raw_height - (top_margin = 2);
}
else if (!strcmp(model, "640x480"))
{
gamma_curve(0.45, 4.5, 1, 255);
}
else if (!strncmp(make, "Hasselblad", 10))
{
if (load_raw == &CLASS lossless_jpeg_load_raw)
load_raw = &CLASS hasselblad_load_raw;
if (raw_width == 7262)
{
height = 5444;
width = 7248;
top_margin = 4;
left_margin = 7;
filters = 0x61616161;
if (!strncasecmp(model, "H3D", 3))
{
adobe_coeff("Hasselblad", "H3DII-39");
strcpy(model, "H3DII-39");
}
}
else if (raw_width == 12000) // H6D 100c, A6D 100c
{
left_margin = 64;
width = 11608;
top_margin = 108;
height = raw_height - top_margin;
adobe_coeff("Hasselblad", "H6D-100c");
}
else if (raw_width == 7410 || raw_width == 8282)
{
height -= 84;
width -= 82;
top_margin = 4;
left_margin = 41;
filters = 0x61616161;
adobe_coeff("Hasselblad", "H4D-40");
strcpy(model, "H4D-40");
}
else if (raw_width == 8384) // X1D
{
top_margin = 96;
height -= 96;
left_margin = 48;
width -= 106;
adobe_coeff("Hasselblad", "X1D");
maximum = 0xffff;
tiff_bps = 16;
}
else if (raw_width == 9044)
{
if (black > 500)
{
top_margin = 12;
left_margin = 44;
width = 8956;
height = 6708;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H4D-60");
strcpy(model, "H4D-60");
black = 512;
}
else
{
height = 6716;
width = 8964;
top_margin = 8;
left_margin = 40;
black += load_flags = 256;
maximum = 0x8101;
strcpy(model, "H3DII-60");
}
}
else if (raw_width == 4090)
{
strcpy(model, "V96C");
height -= (top_margin = 6);
width -= (left_margin = 3) + 7;
filters = 0x61616161;
}
else if (raw_width == 8282 && raw_height == 6240)
{
if (!strncasecmp(model, "H5D", 3))
{
/* H5D 50*/
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
black = 256;
strcpy(model, "H5D-50");
}
else if (!strncasecmp(model, "H3D", 3))
{
black = 0;
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H3D-50");
strcpy(model, "H3D-50");
}
}
else if (raw_width == 8374 && raw_height == 6304)
{
/* H5D 50c*/
left_margin = 52;
top_margin = 100;
width = 8272;
height = 6200;
black = 256;
strcpy(model, "H5D-50c");
}
if (tiff_samples > 1)
{
is_raw = tiff_samples + 1;
if (!shot_select && !half_size)
filters = 0;
}
}
else if (!strncmp(make, "Sinar", 5))
{
if (!load_raw)
load_raw = &CLASS unpacked_load_raw;
if (is_raw > 1 && !shot_select && !half_size)
filters = 0;
maximum = 0x3fff;
}
else if (!strncmp(make, "Leaf", 4))
{
maximum = 0x3fff;
fseek(ifp, data_offset, SEEK_SET);
if (ljpeg_start(&jh, 1) && jh.bits == 15)
maximum = 0x1fff;
if (tiff_samples > 1)
filters = 0;
if (tiff_samples > 1 || tile_length < raw_height)
{
load_raw = &CLASS leaf_hdr_load_raw;
raw_width = tile_width;
}
if ((width | height) == 2048)
{
if (tiff_samples == 1)
{
filters = 1;
strcpy(cdesc, "RBTG");
strcpy(model, "CatchLight");
top_margin = 8;
left_margin = 18;
height = 2032;
width = 2016;
}
else
{
strcpy(model, "DCB2");
top_margin = 10;
left_margin = 16;
height = 2028;
width = 2022;
}
}
else if (width + height == 3144 + 2060)
{
if (!model[0])
strcpy(model, "Cantare");
if (width > height)
{
top_margin = 6;
left_margin = 32;
height = 2048;
width = 3072;
filters = 0x61616161;
}
else
{
left_margin = 6;
top_margin = 32;
width = 2048;
height = 3072;
filters = 0x16161616;
}
if (!cam_mul[0] || model[0] == 'V')
filters = 0;
else
is_raw = tiff_samples;
}
else if (width == 2116)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 30);
width -= 2 * (left_margin = 55);
filters = 0x49494949;
}
else if (width == 3171)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 24);
width -= 2 * (left_margin = 24);
filters = 0x16161616;
}
}
else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6))
{
if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height))
load_raw = &CLASS panasonic_load_raw;
if (!load_raw)
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
}
zero_is_bad = 1;
#ifdef LIBRAW_LIBRARY_BUILD
float fratio = float(data_size) / (float(raw_height) * float(raw_width));
if(!(raw_width % 10) && !(data_size % 16384) && fratio >= 1.6f && fratio <= 1.6001f)
{
load_raw = &CLASS panasonic_16x10_load_raw;
zero_is_bad = 0;
}
#endif
if ((height += 12) > raw_height)
height = raw_height;
for (i = 0; i < sizeof pana / sizeof *pana; i++)
if (raw_width == pana[i][0] && raw_height == pana[i][1])
{
left_margin = pana[i][2];
top_margin = pana[i][3];
width += pana[i][4];
height += pana[i][5];
}
filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"[((filters - 1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3];
}
else if (!strcmp(model, "C770UZ"))
{
height = 1718;
width = 2304;
filters = 0x16161616;
load_raw = &CLASS packed_load_raw;
load_flags = 30;
}
else if (!strncmp(make, "Olympus", 7))
{
height += height & 1;
if (exif_cfa)
filters = exif_cfa;
if (width == 4100)
width -= 4;
if (width == 4080)
width -= 24;
if (width == 9280)
{
width -= 6;
height -= 6;
}
if (load_raw == &CLASS unpacked_load_raw)
load_flags = 4;
tiff_bps = 12;
if (!strcmp(model, "E-300") || !strcmp(model, "E-500"))
{
width -= 20;
if (load_raw == &CLASS unpacked_load_raw)
{
maximum = 0xfc3;
memset(cblack, 0, sizeof cblack);
}
}
else if (!strcmp(model, "STYLUS1"))
{
width -= 14;
maximum = 0xfff;
}
else if (!strcmp(model, "E-330"))
{
width -= 30;
if (load_raw == &CLASS unpacked_load_raw)
maximum = 0xf79;
}
else if (!strcmp(model, "SP550UZ"))
{
thumb_length = flen - (thumb_offset = 0xa39800);
thumb_height = 480;
thumb_width = 640;
}
else if (!strcmp(model, "TG-4"))
{
width -= 16;
}
else if (!strcmp(model, "TG-5"))
{
width -= 26;
}
}
else if (!strcmp(model, "N Digital"))
{
height = 2047;
width = 3072;
filters = 0x61616161;
data_offset = 0x1a00;
load_raw = &CLASS packed_load_raw;
}
else if (!strcmp(model, "DSC-F828"))
{
width = 3288;
left_margin = 5;
mask[1][3] = -17;
data_offset = 862144;
load_raw = &CLASS sony_load_raw;
filters = 0x9c9c9c9c;
colors = 4;
strcpy(cdesc, "RGBE");
}
else if (!strcmp(model, "DSC-V3"))
{
width = 3109;
left_margin = 59;
mask[0][1] = 9;
data_offset = 787392;
load_raw = &CLASS sony_load_raw;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 3984)
{
width = 3925;
order = 0x4d4d;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 4288)
{
width -= 32;
}
else if (!strcmp(make, "Sony") && raw_width == 4600)
{
if (!strcmp(model, "DSLR-A350"))
height -= 4;
black = 0;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 4928)
{
if (height < 3280)
width -= 8;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 5504)
{ // ILCE-3000//5000
width -= height > 3664 ? 8 : 32;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 6048)
{
width -= 24;
if (strstr(model, "RX1") || strstr(model, "A99"))
width -= 6;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 7392)
{
width -= 30;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 8000)
{
width -= 32;
}
else if (!strcmp(model, "DSLR-A100"))
{
if (width == 3880)
{
height--;
width = ++raw_width;
}
else
{
height -= 4;
width -= 4;
order = 0x4d4d;
load_flags = 2;
}
filters = 0x61616161;
}
else if (!strcmp(model, "PIXL"))
{
height -= top_margin = 4;
width -= left_margin = 32;
gamma_curve(0, 7, 1, 255);
}
else if (!strcmp(model, "C603") || !strcmp(model, "C330") || !strcmp(model, "12MP"))
{
order = 0x4949;
if (filters && data_offset)
{
fseek(ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET);
read_shorts(curve, 256);
}
else
gamma_curve(0, 3.875, 1, 255);
load_raw = filters ? &CLASS eight_bit_load_raw
: strcmp(model, "C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw;
load_flags = tiff_bps > 16;
tiff_bps = 8;
}
else if (!strncasecmp(model, "EasyShare", 9))
{
data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000;
load_raw = &CLASS packed_load_raw;
}
else if (!strncasecmp(make, "Kodak", 5))
{
if (filters == UINT_MAX)
filters = 0x61616161;
if (!strncmp(model, "NC2000", 6) || !strncmp(model, "EOSDCS", 6) || !strncmp(model, "DCS4", 4))
{
width -= 4;
left_margin = 2;
if (model[6] == ' ')
model[6] = 0;
if (!strcmp(model, "DCS460A"))
goto bw;
}
else if (!strcmp(model, "DCS660M"))
{
black = 214;
goto bw;
}
else if (!strcmp(model, "DCS760M"))
{
bw:
colors = 1;
filters = 0;
}
if (!strcmp(model + 4, "20X"))
strcpy(cdesc, "MYCY");
if (strstr(model, "DC25"))
{
strcpy(model, "DC25");
data_offset = 15424;
}
if (!strncmp(model, "DC2", 3))
{
raw_height = 2 + (height = 242);
if (!strncmp(model, "DC290", 5))
iso_speed = 100;
if (!strncmp(model, "DC280", 5))
iso_speed = 70;
if (flen < 100000)
{
raw_width = 256;
width = 249;
pixel_aspect = (4.0 * height) / (3.0 * width);
}
else
{
raw_width = 512;
width = 501;
pixel_aspect = (493.0 * height) / (373.0 * width);
}
top_margin = left_margin = 1;
colors = 4;
filters = 0x8d8d8d8d;
simple_coeff(1);
pre_mul[1] = 1.179;
pre_mul[2] = 1.209;
pre_mul[3] = 1.036;
load_raw = &CLASS eight_bit_load_raw;
}
else if (!strcmp(model, "40"))
{
strcpy(model, "DC40");
height = 512;
width = 768;
data_offset = 1152;
load_raw = &CLASS kodak_radc_load_raw;
tiff_bps = 12;
}
else if (strstr(model, "DC50"))
{
strcpy(model, "DC50");
height = 512;
width = 768;
iso_speed = 84;
data_offset = 19712;
load_raw = &CLASS kodak_radc_load_raw;
}
else if (strstr(model, "DC120"))
{
strcpy(model, "DC120");
raw_height = height = 976;
raw_width = width = 848;
iso_speed = 160;
pixel_aspect = height / 0.75 / width;
load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw;
}
else if (!strcmp(model, "DCS200"))
{
thumb_height = 128;
thumb_width = 192;
thumb_offset = 6144;
thumb_misc = 360;
iso_speed = 140;
write_thumb = &CLASS layer_thumb;
black = 17;
}
}
else if (!strcmp(model, "Fotoman Pixtura"))
{
height = 512;
width = 768;
data_offset = 3632;
load_raw = &CLASS kodak_radc_load_raw;
filters = 0x61616161;
simple_coeff(2);
}
else if (!strncmp(model, "QuickTake", 9))
{
if (head[5])
strcpy(model + 10, "200");
fseek(ifp, 544, SEEK_SET);
height = get2();
width = get2();
data_offset = (get4(), get2()) == 30 ? 738 : 736;
if (height > width)
{
SWAP(height, width);
fseek(ifp, data_offset - 6, SEEK_SET);
flip = ~get2() & 3 ? 5 : 6;
}
filters = 0x61616161;
}
else if (!strncmp(make, "Rollei", 6) && !load_raw)
{
switch (raw_width)
{
case 1316:
height = 1030;
width = 1300;
top_margin = 1;
left_margin = 6;
break;
case 2568:
height = 1960;
width = 2560;
top_margin = 2;
left_margin = 8;
}
filters = 0x16161616;
load_raw = &CLASS rollei_load_raw;
}
else if (!strcmp(model, "GRAS-50S5C"))
{
height = 2048;
width = 2440;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x49494949;
order = 0x4949;
maximum = 0xfffC;
}
else if (!strcmp(model, "BB-500CL"))
{
height = 2058;
width = 2448;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x3fff;
}
else if (!strcmp(model, "BB-500GE"))
{
height = 2058;
width = 2456;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x3fff;
}
else if (!strcmp(model, "SVS625CL"))
{
height = 2050;
width = 2448;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x0fff;
}
/* Early reject for damaged images */
if (!load_raw || height < 22 || width < 22 ||
#ifdef LIBRAW_LIBRARY_BUILD
(tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw)
#else
tiff_bps > 16
#endif
|| tiff_samples > 4 || colors > 4 || colors < 1)
{
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2);
#endif
return;
}
if (!model[0])
sprintf(model, "%dx%d", width, height);
if (filters == UINT_MAX)
filters = 0x94949494;
if (thumb_offset && !thumb_height)
{
fseek(ifp, thumb_offset, SEEK_SET);
if (ljpeg_start(&jh, 1))
{
thumb_width = jh.wide;
thumb_height = jh.high;
}
}
dng_skip:
#ifdef LIBRAW_LIBRARY_BUILD
if (dng_version) /* Override black level by DNG tags */
{
/* copy DNG data from per-IFD field to color.dng */
int iifd = 0; // Active IFD we'll show to user.
for (; iifd < tiff_nifds; iifd++)
if (tiff_ifd[iifd].offset == data_offset) // found
break;
int pifd = -1;
for (int ii = 0; ii < tiff_nifds; ii++)
if (tiff_ifd[ii].offset == thumb_offset) // found
{
pifd = ii;
break;
}
#define CFAROUND(value, filters) filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) : value
#define IFDCOLORINDEX(ifd, subset, bit) \
(tiff_ifd[ifd].dng_color[subset].parsedfields & bit) ? ifd \
: ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1)
#define IFDLEVELINDEX(ifd, bit) \
(tiff_ifd[ifd].dng_levels.parsedfields & bit) ? ifd : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1)
#define COPYARR(to, from) memmove(&to, &from, sizeof(from))
if (iifd < tiff_nifds)
{
int sidx;
// Per field, not per structure
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP)
{
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN);
int sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE);
if (sidx >= 0 && sidx == sidx2)
{
int lm = tiff_ifd[sidx].dng_levels.default_crop[0];
int lmm = CFAROUND(lm, filters);
int tm = tiff_ifd[sidx].dng_levels.default_crop[1];
int tmm = CFAROUND(tm, filters);
int ww = tiff_ifd[sidx].dng_levels.default_crop[2];
int hh = tiff_ifd[sidx].dng_levels.default_crop[3];
if (lmm > lm)
ww -= (lmm - lm);
if (tmm > tm)
hh -= (tmm - tm);
if (left_margin + lm + ww <= raw_width && top_margin + tm + hh <= raw_height)
{
left_margin += lmm;
top_margin += tmm;
width = ww;
height = hh;
}
}
}
if (!(imgdata.color.dng_color[0].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes)
{
sidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX);
if (sidx >= 0)
COPYARR(imgdata.color.dng_color[0].forwardmatrix, tiff_ifd[sidx].dng_color[0].forwardmatrix);
}
if (!(imgdata.color.dng_color[1].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes)
{
sidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX);
if (sidx >= 0)
COPYARR(imgdata.color.dng_color[1].forwardmatrix, tiff_ifd[sidx].dng_color[1].forwardmatrix);
}
for (int ss = 0; ss < 2; ss++)
{
sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX);
if (sidx >= 0)
COPYARR(imgdata.color.dng_color[ss].colormatrix, tiff_ifd[sidx].dng_color[ss].colormatrix);
sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION);
if (sidx >= 0)
COPYARR(imgdata.color.dng_color[ss].calibration, tiff_ifd[sidx].dng_color[ss].calibration);
sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT);
if (sidx >= 0)
imgdata.color.dng_color[ss].illuminant = tiff_ifd[sidx].dng_color[ss].illuminant;
}
// Levels
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE);
if (sidx >= 0)
COPYARR(imgdata.color.dng_levels.analogbalance, tiff_ifd[sidx].dng_levels.analogbalance);
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE);
if (sidx >= 0)
COPYARR(imgdata.color.dng_levels.dng_whitelevel, tiff_ifd[sidx].dng_levels.dng_whitelevel);
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK);
if (sidx >= 0)
{
imgdata.color.dng_levels.dng_black = tiff_ifd[sidx].dng_levels.dng_black;
COPYARR(imgdata.color.dng_levels.dng_cblack, tiff_ifd[sidx].dng_levels.dng_cblack);
}
if (pifd >= 0)
{
sidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS);
if (sidx >= 0)
imgdata.color.dng_levels.preview_colorspace = tiff_ifd[sidx].dng_levels.preview_colorspace;
}
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2);
if (sidx >= 0)
meta_offset = tiff_ifd[sidx].opcode2_offset;
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE);
INT64 linoff = -1;
int linlen = 0;
if (sidx >= 0)
{
linoff = tiff_ifd[sidx].lineartable_offset;
linlen = tiff_ifd[sidx].lineartable_len;
}
if (linoff >= 0 && linlen > 0)
{
INT64 pos = ftell(ifp);
fseek(ifp, linoff, SEEK_SET);
linear_table(linlen);
fseek(ifp, pos, SEEK_SET);
}
// Need to add curve too
}
/* Copy DNG black level to LibRaw's */
maximum = imgdata.color.dng_levels.dng_whitelevel[0];
black = imgdata.color.dng_levels.dng_black;
int ll = LIM(0, (sizeof(cblack) / sizeof(cblack[0])),
(sizeof(imgdata.color.dng_levels.dng_cblack) / sizeof(imgdata.color.dng_levels.dng_cblack[0])));
for (int i = 0; i < ll; i++)
cblack[i] = imgdata.color.dng_levels.dng_cblack[i];
}
#endif
/* Early reject for damaged images */
if (!load_raw || height < 22 || width < 22 ||
#ifdef LIBRAW_LIBRARY_BUILD
(tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw)
#else
tiff_bps > 16
#endif
|| tiff_samples > 4 || colors > 4 || colors < 1)
{
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2);
#endif
return;
}
if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2)) && cmatrix[0][0] > 0.125)
{
memcpy(rgb_cam, cmatrix, sizeof cmatrix);
raw_color = 0;
}
if (raw_color)
adobe_coeff(make, model);
#ifdef LIBRAW_LIBRARY_BUILD
else if (imgdata.color.cam_xyz[0][0] < 0.01)
adobe_coeff(make, model, 1);
#endif
if (load_raw == &CLASS kodak_radc_load_raw)
if (raw_color)
adobe_coeff("Apple", "Quicktake");
if (fuji_width)
{
fuji_width = width >> !fuji_layout;
filters = fuji_width & 1 ? 0x94949494 : 0x49494949;
width = (height >> fuji_layout) + fuji_width;
height = width - 1;
pixel_aspect = 1;
}
else
{
if (raw_height < height)
raw_height = height;
if (raw_width < width)
raw_width = width;
}
if (!tiff_bps)
tiff_bps = 12;
if (!maximum)
{
maximum = (1 << tiff_bps) - 1;
if (maximum < 0x10000 && curve[maximum] > 0 && load_raw == &CLASS sony_arw2_load_raw)
maximum = curve[maximum];
}
if (!load_raw || height < 22 || width < 22 ||
#ifdef LIBRAW_LIBRARY_BUILD
(tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw)
#else
tiff_bps > 16
#endif
|| tiff_samples > 6 || colors > 4)
is_raw = 0;
if (raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_height > 64000)
is_raw = 0;
#ifdef NO_JASPER
if (load_raw == &CLASS redcine_load_raw)
{
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjasper");
#endif
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER;
#endif
}
#endif
#ifdef NO_JPEG
if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw)
{
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg");
#endif
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB;
#endif
}
#endif
if (!cdesc[0])
strcpy(cdesc, colors == 3 ? "RGBG" : "GMCY");
if (!raw_height)
raw_height = height;
if (!raw_width)
raw_width = width;
if (filters > 999 && colors == 3)
filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1;
notraw:
if (flip == UINT_MAX)
flip = tiff_flip;
if (flip == UINT_MAX)
flip = 0;
// Convert from degrees to bit-field if needed
if (flip > 89 || flip < -89)
{
switch ((flip + 3600) % 360)
{
case 270:
flip = 5;
break;
case 180:
flip = 3;
break;
case 90:
flip = 6;
break;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2);
#endif
}
//@end COMMON
//@out FILEIO
#ifndef NO_LCMS
void CLASS apply_profile(const char *input, const char *output)
{
char *prof;
cmsHPROFILE hInProfile = 0, hOutProfile = 0;
cmsHTRANSFORM hTransform;
FILE *fp;
unsigned size;
if (strcmp(input, "embed"))
hInProfile = cmsOpenProfileFromFile(input, "r");
else if (profile_length)
{
#ifndef LIBRAW_LIBRARY_BUILD
prof = (char *)malloc(profile_length);
merror(prof, "apply_profile()");
fseek(ifp, profile_offset, SEEK_SET);
fread(prof, 1, profile_length, ifp);
hInProfile = cmsOpenProfileFromMem(prof, profile_length);
free(prof);
#else
hInProfile = cmsOpenProfileFromMem(imgdata.color.profile, profile_length);
#endif
}
else
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_EMBEDDED_PROFILE;
#endif
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s has no embedded profile.\n"), ifname);
#endif
}
if (!hInProfile)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_INPUT_PROFILE;
#endif
return;
}
if (!output)
hOutProfile = cmsCreate_sRGBProfile();
else if ((fp = fopen(output, "rb")))
{
fread(&size, 4, 1, fp);
fseek(fp, 0, SEEK_SET);
oprof = (unsigned *)malloc(size = ntohl(size));
merror(oprof, "apply_profile()");
fread(oprof, 1, size, fp);
fclose(fp);
if (!(hOutProfile = cmsOpenProfileFromMem(oprof, size)))
{
free(oprof);
oprof = 0;
}
}
#ifdef DCRAW_VERBOSE
else
fprintf(stderr, _("Cannot open file %s!\n"), output);
#endif
if (!hOutProfile)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_OUTPUT_PROFILE;
#endif
goto quit;
}
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Applying color profile...\n"));
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE, 0, 2);
#endif
hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_16, hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0);
cmsDoTransform(hTransform, image, image, width * height);
raw_color = 1; /* Don't use rgb_cam with a profile */
cmsDeleteTransform(hTransform);
cmsCloseProfile(hOutProfile);
quit:
cmsCloseProfile(hInProfile);
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE, 1, 2);
#endif
}
#endif
//@end FILEIO
//@out COMMON
void CLASS convert_to_rgb()
{
#ifndef LIBRAW_LIBRARY_BUILD
int row, col, c;
#endif
int i, j, k;
#ifndef LIBRAW_LIBRARY_BUILD
ushort *img;
float out[3];
#endif
float out_cam[3][4];
double num, inverse[3][3];
static const double xyzd50_srgb[3][3] = {
{0.436083, 0.385083, 0.143055}, {0.222507, 0.716888, 0.060608}, {0.013930, 0.097097, 0.714022}};
static const double rgb_rgb[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
static const double adobe_rgb[3][3] = {
{0.715146, 0.284856, 0.000000}, {0.000000, 1.000000, 0.000000}, {0.000000, 0.041166, 0.958839}};
static const double wide_rgb[3][3] = {
{0.593087, 0.404710, 0.002206}, {0.095413, 0.843149, 0.061439}, {0.011621, 0.069091, 0.919288}};
static const double prophoto_rgb[3][3] = {
{0.529317, 0.330092, 0.140588}, {0.098368, 0.873465, 0.028169}, {0.016879, 0.117663, 0.865457}};
static const double aces_rgb[3][3] = {
{0.432996, 0.375380, 0.189317}, {0.089427, 0.816523, 0.102989}, {0.019165, 0.118150, 0.941914}};
static const double(*out_rgb[])[3] = {rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb};
static const char *name[] = {"sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES"};
static const unsigned phead[] = {1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0,
0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0,
0, 0, 0, 0xf6d6, 0x10000, 0xd32d};
unsigned pbody[] = {10, 0x63707274, 0, 36, /* cprt */
0x64657363, 0, 40, /* desc */
0x77747074, 0, 20, /* wtpt */
0x626b7074, 0, 20, /* bkpt */
0x72545243, 0, 14, /* rTRC */
0x67545243, 0, 14, /* gTRC */
0x62545243, 0, 14, /* bTRC */
0x7258595a, 0, 20, /* rXYZ */
0x6758595a, 0, 20, /* gXYZ */
0x6258595a, 0, 20}; /* bXYZ */
static const unsigned pwhite[] = {0xf351, 0x10000, 0x116cc};
unsigned pcurve[] = {0x63757276, 0, 1, 0x1000000};
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 0, 2);
#endif
gamma_curve(gamm[0], gamm[1], 0, 0);
memcpy(out_cam, rgb_cam, sizeof out_cam);
#ifndef LIBRAW_LIBRARY_BUILD
raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6;
#else
raw_color |= colors == 1 || output_color < 1 || output_color > 6;
#endif
if (!raw_color)
{
oprof = (unsigned *)calloc(phead[0], 1);
merror(oprof, "convert_to_rgb()");
memcpy(oprof, phead, sizeof phead);
if (output_color == 5)
oprof[4] = oprof[5];
oprof[0] = 132 + 12 * pbody[0];
for (i = 0; i < pbody[0]; i++)
{
oprof[oprof[0] / 4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874;
pbody[i * 3 + 2] = oprof[0];
oprof[0] += (pbody[i * 3 + 3] + 3) & -4;
}
memcpy(oprof + 32, pbody, sizeof pbody);
oprof[pbody[5] / 4 + 2] = strlen(name[output_color - 1]) + 1;
memcpy((char *)oprof + pbody[8] + 8, pwhite, sizeof pwhite);
pcurve[3] = (short)(256 / gamm[5] + 0.5) << 16;
for (i = 4; i < 7; i++)
memcpy((char *)oprof + pbody[i * 3 + 2], pcurve, sizeof pcurve);
pseudoinverse((double(*)[3])out_rgb[output_color - 1], inverse, 3);
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
{
for (num = k = 0; k < 3; k++)
num += xyzd50_srgb[i][k] * inverse[j][k];
oprof[pbody[j * 3 + 23] / 4 + i + 2] = num * 0x10000 + 0.5;
}
for (i = 0; i < phead[0] / 4; i++)
oprof[i] = htonl(oprof[i]);
strcpy((char *)oprof + pbody[2] + 8, "auto-generated by dcraw");
strcpy((char *)oprof + pbody[5] + 12, name[output_color - 1]);
for (i = 0; i < 3; i++)
for (j = 0; j < colors; j++)
for (out_cam[i][j] = k = 0; k < 3; k++)
out_cam[i][j] += out_rgb[output_color - 1][i][k] * rgb_cam[k][j];
}
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"),
name[output_color - 1]);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
convert_to_rgb_loop(out_cam);
#else
memset(histogram, 0, sizeof histogram);
for (img = image[0], row = 0; row < height; row++)
for (col = 0; col < width; col++, img += 4)
{
if (!raw_color)
{
out[0] = out[1] = out[2] = 0;
FORCC
{
out[0] += out_cam[0][c] * img[c];
out[1] += out_cam[1][c] * img[c];
out[2] += out_cam[2][c] * img[c];
}
FORC3 img[c] = CLIP((int)out[c]);
}
else if (document_mode)
img[0] = img[fcol(row, col)];
FORCC histogram[c][img[c] >> 3]++;
}
#endif
if (colors == 4 && output_color)
colors = 3;
#ifndef LIBRAW_LIBRARY_BUILD
if (document_mode && filters)
colors = 1;
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 1, 2);
#endif
}
void CLASS fuji_rotate()
{
int i, row, col;
double step;
float r, c, fr, fc;
unsigned ur, uc;
ushort wide, high, (*img)[4], (*pix)[4];
if (!fuji_width)
return;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Rotating image 45 degrees...\n"));
#endif
fuji_width = (fuji_width - 1 + shrink) >> shrink;
step = sqrt(0.5);
wide = fuji_width / step;
high = (height - fuji_width) / step;
img = (ushort(*)[4])calloc(high, wide * sizeof *img);
merror(img, "fuji_rotate()");
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 0, 2);
#endif
for (row = 0; row < high; row++)
for (col = 0; col < wide; col++)
{
ur = r = fuji_width + (row - col) * step;
uc = c = (row + col) * step;
if (ur > height - 2 || uc > width - 2)
continue;
fr = r - ur;
fc = c - uc;
pix = image + ur * width + uc;
for (i = 0; i < colors; i++)
img[row * wide + col][i] = (pix[0][i] * (1 - fc) + pix[1][i] * fc) * (1 - fr) +
(pix[width][i] * (1 - fc) + pix[width + 1][i] * fc) * fr;
}
free(image);
width = wide;
height = high;
image = img;
fuji_width = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 1, 2);
#endif
}
void CLASS stretch()
{
ushort newdim, (*img)[4], *pix0, *pix1;
int row, col, c;
double rc, frac;
if (pixel_aspect == 1)
return;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 0, 2);
#endif
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Stretching the image...\n"));
#endif
if (pixel_aspect < 1)
{
newdim = height / pixel_aspect + 0.5;
img = (ushort(*)[4])calloc(width, newdim * sizeof *img);
merror(img, "stretch()");
for (rc = row = 0; row < newdim; row++, rc += pixel_aspect)
{
frac = rc - (c = rc);
pix0 = pix1 = image[c * width];
if (c + 1 < height)
pix1 += width * 4;
for (col = 0; col < width; col++, pix0 += 4, pix1 += 4)
FORCC img[row * width + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5;
}
height = newdim;
}
else
{
newdim = width * pixel_aspect + 0.5;
img = (ushort(*)[4])calloc(height, newdim * sizeof *img);
merror(img, "stretch()");
for (rc = col = 0; col < newdim; col++, rc += 1 / pixel_aspect)
{
frac = rc - (c = rc);
pix0 = pix1 = image[c];
if (c + 1 < width)
pix1 += 4;
for (row = 0; row < height; row++, pix0 += width * 4, pix1 += width * 4)
FORCC img[row * newdim + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5;
}
width = newdim;
}
free(image);
image = img;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 1, 2);
#endif
}
int CLASS flip_index(int row, int col)
{
if (flip & 4)
SWAP(row, col);
if (flip & 2)
row = iheight - 1 - row;
if (flip & 1)
col = iwidth - 1 - col;
return row * iwidth + col;
}
//@end COMMON
struct tiff_tag
{
ushort tag, type;
int count;
union {
char c[4];
short s[2];
int i;
} val;
};
struct tiff_hdr
{
ushort t_order, magic;
int ifd;
ushort pad, ntag;
struct tiff_tag tag[23];
int nextifd;
ushort pad2, nexif;
struct tiff_tag exif[4];
ushort pad3, ngps;
struct tiff_tag gpst[10];
short bps[4];
int rat[10];
unsigned gps[26];
char t_desc[512], t_make[64], t_model[64], soft[32], date[20], t_artist[64];
};
//@out COMMON
void CLASS tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val)
{
struct tiff_tag *tt;
int c;
tt = (struct tiff_tag *)(ntag + 1) + (*ntag)++;
tt->val.i = val;
if (type == 1 && count <= 4)
FORC(4) tt->val.c[c] = val >> (c << 3);
else if (type == 2)
{
count = strnlen((char *)th + val, count - 1) + 1;
if (count <= 4)
FORC(4) tt->val.c[c] = ((char *)th)[val + c];
}
else if (type == 3 && count <= 2)
FORC(2) tt->val.s[c] = val >> (c << 4);
tt->count = count;
tt->type = type;
tt->tag = tag;
}
#define TOFF(ptr) ((char *)(&(ptr)) - (char *)th)
void CLASS tiff_head(struct tiff_hdr *th, int full)
{
int c, psize = 0;
struct tm *t;
memset(th, 0, sizeof *th);
th->t_order = htonl(0x4d4d4949) >> 16;
th->magic = 42;
th->ifd = 10;
th->rat[0] = th->rat[2] = 300;
th->rat[1] = th->rat[3] = 1;
FORC(6) th->rat[4 + c] = 1000000;
th->rat[4] *= shutter;
th->rat[6] *= aperture;
th->rat[8] *= focal_len;
strncpy(th->t_desc, desc, 512);
strncpy(th->t_make, make, 64);
strncpy(th->t_model, model, 64);
strcpy(th->soft, "dcraw v" DCRAW_VERSION);
t = localtime(×tamp);
sprintf(th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour,
t->tm_min, t->tm_sec);
strncpy(th->t_artist, artist, 64);
if (full)
{
tiff_set(th, &th->ntag, 254, 4, 1, 0);
tiff_set(th, &th->ntag, 256, 4, 1, width);
tiff_set(th, &th->ntag, 257, 4, 1, height);
tiff_set(th, &th->ntag, 258, 3, colors, output_bps);
if (colors > 2)
th->tag[th->ntag - 1].val.i = TOFF(th->bps);
FORC4 th->bps[c] = output_bps;
tiff_set(th, &th->ntag, 259, 3, 1, 1);
tiff_set(th, &th->ntag, 262, 3, 1, 1 + (colors > 1));
}
tiff_set(th, &th->ntag, 270, 2, 512, TOFF(th->t_desc));
tiff_set(th, &th->ntag, 271, 2, 64, TOFF(th->t_make));
tiff_set(th, &th->ntag, 272, 2, 64, TOFF(th->t_model));
if (full)
{
if (oprof)
psize = ntohl(oprof[0]);
tiff_set(th, &th->ntag, 273, 4, 1, sizeof *th + psize);
tiff_set(th, &th->ntag, 277, 3, 1, colors);
tiff_set(th, &th->ntag, 278, 4, 1, height);
tiff_set(th, &th->ntag, 279, 4, 1, height * width * colors * output_bps / 8);
}
else
tiff_set(th, &th->ntag, 274, 3, 1, "12435867"[flip] - '0');
tiff_set(th, &th->ntag, 282, 5, 1, TOFF(th->rat[0]));
tiff_set(th, &th->ntag, 283, 5, 1, TOFF(th->rat[2]));
tiff_set(th, &th->ntag, 284, 3, 1, 1);
tiff_set(th, &th->ntag, 296, 3, 1, 2);
tiff_set(th, &th->ntag, 305, 2, 32, TOFF(th->soft));
tiff_set(th, &th->ntag, 306, 2, 20, TOFF(th->date));
tiff_set(th, &th->ntag, 315, 2, 64, TOFF(th->t_artist));
tiff_set(th, &th->ntag, 34665, 4, 1, TOFF(th->nexif));
if (psize)
tiff_set(th, &th->ntag, 34675, 7, psize, sizeof *th);
tiff_set(th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4]));
tiff_set(th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6]));
tiff_set(th, &th->nexif, 34855, 3, 1, iso_speed);
tiff_set(th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8]));
if (gpsdata[1])
{
tiff_set(th, &th->ntag, 34853, 4, 1, TOFF(th->ngps));
tiff_set(th, &th->ngps, 0, 1, 4, 0x202);
tiff_set(th, &th->ngps, 1, 2, 2, gpsdata[29]);
tiff_set(th, &th->ngps, 2, 5, 3, TOFF(th->gps[0]));
tiff_set(th, &th->ngps, 3, 2, 2, gpsdata[30]);
tiff_set(th, &th->ngps, 4, 5, 3, TOFF(th->gps[6]));
tiff_set(th, &th->ngps, 5, 1, 1, gpsdata[31]);
tiff_set(th, &th->ngps, 6, 5, 1, TOFF(th->gps[18]));
tiff_set(th, &th->ngps, 7, 5, 3, TOFF(th->gps[12]));
tiff_set(th, &th->ngps, 18, 2, 12, TOFF(th->gps[20]));
tiff_set(th, &th->ngps, 29, 2, 12, TOFF(th->gps[23]));
memcpy(th->gps, gpsdata, sizeof th->gps);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS jpeg_thumb_writer(FILE *tfp, char *t_humb, int t_humb_length)
{
ushort exif[5];
struct tiff_hdr th;
fputc(0xff, tfp);
fputc(0xd8, tfp);
if (strcmp(t_humb + 6, "Exif"))
{
memcpy(exif, "\xff\xe1 Exif\0\0", 10);
exif[1] = htons(8 + sizeof th);
fwrite(exif, 1, sizeof exif, tfp);
tiff_head(&th, 0);
fwrite(&th, 1, sizeof th, tfp);
}
fwrite(t_humb + 2, 1, t_humb_length - 2, tfp);
}
void CLASS jpeg_thumb()
{
char *thumb;
thumb = (char *)malloc(thumb_length);
merror(thumb, "jpeg_thumb()");
fread(thumb, 1, thumb_length, ifp);
jpeg_thumb_writer(ofp, thumb, thumb_length);
free(thumb);
}
#else
void CLASS jpeg_thumb()
{
char *thumb;
ushort exif[5];
struct tiff_hdr th;
thumb = (char *)malloc(thumb_length);
merror(thumb, "jpeg_thumb()");
fread(thumb, 1, thumb_length, ifp);
fputc(0xff, ofp);
fputc(0xd8, ofp);
if (strcmp(thumb + 6, "Exif"))
{
memcpy(exif, "\xff\xe1 Exif\0\0", 10);
exif[1] = htons(8 + sizeof th);
fwrite(exif, 1, sizeof exif, ofp);
tiff_head(&th, 0);
fwrite(&th, 1, sizeof th, ofp);
}
fwrite(thumb + 2, 1, thumb_length - 2, ofp);
free(thumb);
}
#endif
void CLASS write_ppm_tiff()
{
struct tiff_hdr th;
uchar *ppm;
ushort *ppm2;
int c, row, col, soff, rstep, cstep;
int perc, val, total, t_white = 0x2000;
#ifdef LIBRAW_LIBRARY_BUILD
perc = width * height * auto_bright_thr;
#else
perc = width * height * 0.01; /* 99th percentile white level */
#endif
if (fuji_width)
perc /= 2;
if (!((highlight & ~2) || no_auto_bright))
for (t_white = c = 0; c < colors; c++)
{
for (val = 0x2000, total = 0; --val > 32;)
if ((total += histogram[c][val]) > perc)
break;
if (t_white < val)
t_white = val;
}
gamma_curve(gamm[0], gamm[1], 2, (t_white << 3) / bright);
iheight = height;
iwidth = width;
if (flip & 4)
SWAP(height, width);
ppm = (uchar *)calloc(width, colors * output_bps / 8);
ppm2 = (ushort *)ppm;
merror(ppm, "write_ppm_tiff()");
if (output_tiff)
{
tiff_head(&th, 1);
fwrite(&th, sizeof th, 1, ofp);
if (oprof)
fwrite(oprof, ntohl(oprof[0]), 1, ofp);
}
else if (colors > 3)
fprintf(ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors,
(1 << output_bps) - 1, cdesc);
else
fprintf(ofp, "P%d\n%d %d\n%d\n", colors / 2 + 5, width, height, (1 << output_bps) - 1);
soff = flip_index(0, 0);
cstep = flip_index(0, 1) - soff;
rstep = flip_index(1, 0) - flip_index(0, width);
for (row = 0; row < height; row++, soff += rstep)
{
for (col = 0; col < width; col++, soff += cstep)
if (output_bps == 8)
FORCC ppm[col * colors + c] = curve[image[soff][c]] >> 8;
else
FORCC ppm2[col * colors + c] = curve[image[soff][c]];
if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa)
swab((char *)ppm2, (char *)ppm2, width * colors * 2);
fwrite(ppm, colors * output_bps / 8, width, ofp);
}
free(ppm);
}
//@end COMMON
int CLASS main(int argc, const char **argv)
{
int arg, status = 0, quality, i, c;
int timestamp_only = 0, thumbnail_only = 0, identify_only = 0;
int user_qual = -1, user_black = -1, user_sat = -1, user_flip = -1;
int use_fuji_rotate = 1, write_to_stdout = 0, read_from_stdin = 0;
const char *sp, *bpfile = 0, *dark_frame = 0, *write_ext;
char opm, opt, *ofname, *cp;
struct utimbuf ut;
#ifndef NO_LCMS
const char *cam_profile = 0, *out_profile = 0;
#endif
#ifndef LOCALTIME
putenv((char *)"TZ=UTC");
#endif
#ifdef LOCALEDIR
setlocale(LC_CTYPE, "");
setlocale(LC_MESSAGES, "");
bindtextdomain("dcraw", LOCALEDIR);
textdomain("dcraw");
#endif
if (argc == 1)
{
printf(_("\nRaw photo decoder \"dcraw\" v%s"), DCRAW_VERSION);
printf(_("\nby Dave Coffin, dcoffin a cybercom o net\n"));
printf(_("\nUsage: %s [OPTION]... [FILE]...\n\n"), argv[0]);
puts(_("-v Print verbose messages"));
puts(_("-c Write image data to standard output"));
puts(_("-e Extract embedded thumbnail image"));
puts(_("-i Identify files without decoding them"));
puts(_("-i -v Identify files and show metadata"));
puts(_("-z Change file dates to camera timestamp"));
puts(_("-w Use camera white balance, if possible"));
puts(_("-a Average the whole image for white balance"));
puts(_("-A <x y w h> Average a grey box for white balance"));
puts(_("-r <r g b g> Set custom white balance"));
puts(_("+M/-M Use/don't use an embedded color matrix"));
puts(_("-C <r b> Correct chromatic aberration"));
puts(_("-P <file> Fix the dead pixels listed in this file"));
puts(_("-K <file> Subtract dark frame (16-bit raw PGM)"));
puts(_("-k <num> Set the darkness level"));
puts(_("-S <num> Set the saturation level"));
puts(_("-n <num> Set threshold for wavelet denoising"));
puts(_("-H [0-9] Highlight mode (0=clip, 1=unclip, 2=blend, 3+=rebuild)"));
puts(_("-t [0-7] Flip image (0=none, 3=180, 5=90CCW, 6=90CW)"));
puts(_("-o [0-5] Output colorspace (raw,sRGB,Adobe,Wide,ProPhoto,XYZ)"));
#ifndef NO_LCMS
puts(_("-o <file> Apply output ICC profile from file"));
puts(_("-p <file> Apply camera ICC profile from file or \"embed\""));
#endif
puts(_("-d Document mode (no color, no interpolation)"));
puts(_("-D Document mode without scaling (totally raw)"));
puts(_("-j Don't stretch or rotate raw pixels"));
puts(_("-W Don't automatically brighten the image"));
puts(_("-b <num> Adjust brightness (default = 1.0)"));
puts(_("-g <p ts> Set custom gamma curve (default = 2.222 4.5)"));
puts(_("-q [0-3] Set the interpolation quality"));
puts(_("-h Half-size color image (twice as fast as \"-q 0\")"));
puts(_("-f Interpolate RGGB as four colors"));
puts(_("-m <num> Apply a 3x3 median filter to R-G and B-G"));
puts(_("-s [0..N-1] Select one raw image or \"all\" from each file"));
puts(_("-6 Write 16-bit instead of 8-bit"));
puts(_("-4 Linear 16-bit, same as \"-6 -W -g 1 1\""));
puts(_("-T Write TIFF instead of PPM"));
puts("");
return 1;
}
argv[argc] = "";
for (arg = 1; (((opm = argv[arg][0]) - 2) | 2) == '+';)
{
opt = argv[arg++][1];
if ((cp = (char *)strchr(sp = "nbrkStqmHACg", opt)))
for (i = 0; i < "114111111422"[cp - sp] - '0'; i++)
if (!isdigit(argv[arg + i][0]))
{
fprintf(stderr, _("Non-numeric argument to \"-%c\"\n"), opt);
return 1;
}
switch (opt)
{
case 'n':
threshold = atof(argv[arg++]);
break;
case 'b':
bright = atof(argv[arg++]);
break;
case 'r':
FORC4 user_mul[c] = atof(argv[arg++]);
break;
case 'C':
aber[0] = 1 / atof(argv[arg++]);
aber[2] = 1 / atof(argv[arg++]);
break;
case 'g':
gamm[0] = atof(argv[arg++]);
gamm[1] = atof(argv[arg++]);
if (gamm[0])
gamm[0] = 1 / gamm[0];
break;
case 'k':
user_black = atoi(argv[arg++]);
break;
case 'S':
user_sat = atoi(argv[arg++]);
break;
case 't':
user_flip = atoi(argv[arg++]);
break;
case 'q':
user_qual = atoi(argv[arg++]);
break;
case 'm':
med_passes = atoi(argv[arg++]);
break;
case 'H':
highlight = atoi(argv[arg++]);
break;
case 's':
shot_select = abs(atoi(argv[arg]));
multi_out = !strcmp(argv[arg++], "all");
break;
case 'o':
if (isdigit(argv[arg][0]) && !argv[arg][1])
output_color = atoi(argv[arg++]);
#ifndef NO_LCMS
else
out_profile = argv[arg++];
break;
case 'p':
cam_profile = argv[arg++];
#endif
break;
case 'P':
bpfile = argv[arg++];
break;
case 'K':
dark_frame = argv[arg++];
break;
case 'z':
timestamp_only = 1;
break;
case 'e':
thumbnail_only = 1;
break;
case 'i':
identify_only = 1;
break;
case 'c':
write_to_stdout = 1;
break;
case 'v':
verbose = 1;
break;
case 'h':
half_size = 1;
break;
case 'f':
four_color_rgb = 1;
break;
case 'A':
FORC4 greybox[c] = atoi(argv[arg++]);
case 'a':
use_auto_wb = 1;
break;
case 'w':
use_camera_wb = 1;
break;
case 'M':
use_camera_matrix = 3 * (opm == '+');
break;
case 'I':
read_from_stdin = 1;
break;
case 'E':
document_mode++;
case 'D':
document_mode++;
case 'd':
document_mode++;
case 'j':
use_fuji_rotate = 0;
break;
case 'W':
no_auto_bright = 1;
break;
case 'T':
output_tiff = 1;
break;
case '4':
gamm[0] = gamm[1] = no_auto_bright = 1;
case '6':
output_bps = 16;
break;
default:
fprintf(stderr, _("Unknown option \"-%c\".\n"), opt);
return 1;
}
}
if (arg == argc)
{
fprintf(stderr, _("No files to process.\n"));
return 1;
}
if (write_to_stdout)
{
if (isatty(1))
{
fprintf(stderr, _("Will not write an image to the terminal!\n"));
return 1;
}
#if defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__)
if (setmode(1, O_BINARY) < 0)
{
perror("setmode()");
return 1;
}
#endif
}
for (; arg < argc; arg++)
{
status = 1;
raw_image = 0;
image = 0;
oprof = 0;
meta_data = ofname = 0;
ofp = stdout;
if (setjmp(failure))
{
if (fileno(ifp) > 2)
fclose(ifp);
if (fileno(ofp) > 2)
fclose(ofp);
status = 1;
goto cleanup;
}
ifname = argv[arg];
if (!(ifp = fopen(ifname, "rb")))
{
perror(ifname);
continue;
}
status = (identify(), !is_raw);
if (user_flip >= 0)
flip = user_flip;
switch ((flip + 3600) % 360)
{
case 270:
flip = 5;
break;
case 180:
flip = 3;
break;
case 90:
flip = 6;
}
if (timestamp_only)
{
if ((status = !timestamp))
fprintf(stderr, _("%s has no timestamp.\n"), ifname);
else if (identify_only)
printf("%10ld%10d %s\n", (long)timestamp, shot_order, ifname);
else
{
if (verbose)
fprintf(stderr, _("%s time set to %d.\n"), ifname, (int)timestamp);
ut.actime = ut.modtime = timestamp;
utime(ifname, &ut);
}
goto next;
}
write_fun = &CLASS write_ppm_tiff;
if (thumbnail_only)
{
if ((status = !thumb_offset))
{
fprintf(stderr, _("%s has no thumbnail.\n"), ifname);
goto next;
}
else if (thumb_load_raw)
{
load_raw = thumb_load_raw;
data_offset = thumb_offset;
height = thumb_height;
width = thumb_width;
filters = 0;
colors = 3;
}
else
{
fseek(ifp, thumb_offset, SEEK_SET);
write_fun = write_thumb;
goto thumbnail;
}
}
if (load_raw == &CLASS kodak_ycbcr_load_raw)
{
height += height & 1;
width += width & 1;
}
if (identify_only && verbose && make[0])
{
printf(_("\nFilename: %s\n"), ifname);
printf(_("Timestamp: %s"), ctime(×tamp));
printf(_("Camera: %s %s\n"), make, model);
if (artist[0])
printf(_("Owner: %s\n"), artist);
if (dng_version)
{
printf(_("DNG Version: "));
for (i = 24; i >= 0; i -= 8)
printf("%d%c", dng_version >> i & 255, i ? '.' : '\n');
}
printf(_("ISO speed: %d\n"), (int)iso_speed);
printf(_("Shutter: "));
if (shutter > 0 && shutter < 1)
shutter = (printf("1/"), 1 / shutter);
printf(_("%0.1f sec\n"), shutter);
printf(_("Aperture: f/%0.1f\n"), aperture);
printf(_("Focal length: %0.1f mm\n"), focal_len);
printf(_("Embedded ICC profile: %s\n"), profile_length ? _("yes") : _("no"));
printf(_("Number of raw images: %d\n"), is_raw);
if (pixel_aspect != 1)
printf(_("Pixel Aspect Ratio: %0.6f\n"), pixel_aspect);
if (thumb_offset)
printf(_("Thumb size: %4d x %d\n"), thumb_width, thumb_height);
printf(_("Full size: %4d x %d\n"), raw_width, raw_height);
}
else if (!is_raw)
fprintf(stderr, _("Cannot decode file %s\n"), ifname);
if (!is_raw)
goto next;
shrink = filters && (half_size || (!identify_only && (threshold || aber[0] != 1 || aber[2] != 1)));
iheight = (height + shrink) >> shrink;
iwidth = (width + shrink) >> shrink;
if (identify_only)
{
if (verbose)
{
if (document_mode == 3)
{
top_margin = left_margin = fuji_width = 0;
height = raw_height;
width = raw_width;
}
iheight = (height + shrink) >> shrink;
iwidth = (width + shrink) >> shrink;
if (use_fuji_rotate)
{
if (fuji_width)
{
fuji_width = (fuji_width - 1 + shrink) >> shrink;
iwidth = fuji_width / sqrt(0.5);
iheight = (iheight - fuji_width) / sqrt(0.5);
}
else
{
if (pixel_aspect < 1)
iheight = iheight / pixel_aspect + 0.5;
if (pixel_aspect > 1)
iwidth = iwidth * pixel_aspect + 0.5;
}
}
if (flip & 4)
SWAP(iheight, iwidth);
printf(_("Image size: %4d x %d\n"), width, height);
printf(_("Output size: %4d x %d\n"), iwidth, iheight);
printf(_("Raw colors: %d"), colors);
if (filters)
{
int fhigh = 2, fwide = 2;
if ((filters ^ (filters >> 8)) & 0xff)
fhigh = 4;
if ((filters ^ (filters >> 16)) & 0xffff)
fhigh = 8;
if (filters == 1)
fhigh = fwide = 16;
if (filters == 9)
fhigh = fwide = 6;
printf(_("\nFilter pattern: "));
for (i = 0; i < fhigh; i++)
for (c = i && putchar('/') && 0; c < fwide; c++)
putchar(cdesc[fcol(i, c)]);
}
printf(_("\nDaylight multipliers:"));
FORCC printf(" %f", pre_mul[c]);
if (cam_mul[0] > 0)
{
printf(_("\nCamera multipliers:"));
FORC4 printf(" %f", cam_mul[c]);
}
putchar('\n');
}
else
printf(_("%s is a %s %s image.\n"), ifname, make, model);
next:
fclose(ifp);
continue;
}
if (meta_length)
{
meta_data = (char *)malloc(meta_length);
merror(meta_data, "main()");
}
if (filters || colors == 1)
{
raw_image = (ushort *)calloc((raw_height + 7), raw_width * 2);
merror(raw_image, "main()");
}
else
{
image = (ushort(*)[4])calloc(iheight, iwidth * sizeof *image);
merror(image, "main()");
}
if (verbose)
fprintf(stderr, _("Loading %s %s image from %s ...\n"), make, model, ifname);
if (shot_select >= is_raw)
fprintf(stderr, _("%s: \"-s %d\" requests a nonexistent image!\n"), ifname, shot_select);
fseeko(ifp, data_offset, SEEK_SET);
if (raw_image && read_from_stdin)
fread(raw_image, 2, raw_height * raw_width, stdin);
else
(*load_raw)();
if (document_mode == 3)
{
top_margin = left_margin = fuji_width = 0;
height = raw_height;
width = raw_width;
}
iheight = (height + shrink) >> shrink;
iwidth = (width + shrink) >> shrink;
if (raw_image)
{
image = (ushort(*)[4])calloc(iheight, iwidth * sizeof *image);
merror(image, "main()");
crop_masked_pixels();
free(raw_image);
}
if (zero_is_bad)
remove_zeroes();
bad_pixels(bpfile);
if (dark_frame)
subtract(dark_frame);
quality = 2 + !fuji_width;
if (user_qual >= 0)
quality = user_qual;
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black += i;
i = cblack[6];
FORC(cblack[4] * cblack[5])
if (i > cblack[6 + c])
i = cblack[6 + c];
FORC(cblack[4] * cblack[5])
cblack[6 + c] -= i;
black += i;
if (user_black >= 0)
black = user_black;
FORC4 cblack[c] += black;
if (user_sat > 0)
maximum = user_sat;
#ifdef COLORCHECK
colorcheck();
#endif
if (is_foveon)
{
if (document_mode || load_raw == &CLASS foveon_dp_load_raw)
{
for (i = 0; i < height * width * 4; i++)
if ((short)image[0][i] < 0)
image[0][i] = 0;
}
else
foveon_interpolate();
}
else if (document_mode < 2)
scale_colors();
pre_interpolate();
if (filters && !document_mode)
{
if (quality == 0)
lin_interpolate();
else if (quality == 1 || colors > 3)
vng_interpolate();
else if (quality == 2 && filters > 1000)
ppg_interpolate();
else if (filters == 9)
xtrans_interpolate(quality * 2 - 3);
else
ahd_interpolate();
}
if (mix_green)
for (colors = 3, i = 0; i < height * width; i++)
image[i][1] = (image[i][1] + image[i][3]) >> 1;
if (!is_foveon && colors == 3)
median_filter();
if (!is_foveon && highlight == 2)
blend_highlights();
if (!is_foveon && highlight > 2)
recover_highlights();
if (use_fuji_rotate)
fuji_rotate();
#ifndef NO_LCMS
if (cam_profile)
apply_profile(cam_profile, out_profile);
#endif
convert_to_rgb();
if (use_fuji_rotate)
stretch();
thumbnail:
if (write_fun == &CLASS jpeg_thumb)
write_ext = ".jpg";
else if (output_tiff && write_fun == &CLASS write_ppm_tiff)
write_ext = ".tiff";
else
write_ext = ".pgm\0.ppm\0.ppm\0.pam" + colors * 5 - 5;
ofname = (char *)malloc(strlen(ifname) + 64);
merror(ofname, "main()");
if (write_to_stdout)
strcpy(ofname, _("standard output"));
else
{
strcpy(ofname, ifname);
if ((cp = strrchr(ofname, '.')))
*cp = 0;
if (multi_out)
sprintf(ofname + strlen(ofname), "_%0*d", snprintf(0, 0, "%d", is_raw - 1), shot_select);
if (thumbnail_only)
strcat(ofname, ".thumb");
strcat(ofname, write_ext);
ofp = fopen(ofname, "wb");
if (!ofp)
{
status = 1;
perror(ofname);
goto cleanup;
}
}
if (verbose)
fprintf(stderr, _("Writing data to %s ...\n"), ofname);
(*write_fun)();
fclose(ifp);
if (ofp != stdout)
fclose(ofp);
cleanup:
if (meta_data)
free(meta_data);
if (ofname)
free(ofname);
if (oprof)
free(oprof);
if (image)
free(image);
if (multi_out)
{
if (++shot_select < is_raw)
arg--;
else
shot_select = 0;
}
}
return status;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2945_0 |
crossvul-cpp_data_good_3071_0 | /*
* Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Implementation of RFC 3779 section 2.2.
*/
#include <stdio.h>
#include <stdlib.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/buffer.h>
#include <openssl/x509v3.h>
#include "internal/x509_int.h"
#include "ext_dat.h"
#ifndef OPENSSL_NO_RFC3779
/*
* OpenSSL ASN.1 template translation of RFC 3779 2.2.3.
*/
ASN1_SEQUENCE(IPAddressRange) = {
ASN1_SIMPLE(IPAddressRange, min, ASN1_BIT_STRING),
ASN1_SIMPLE(IPAddressRange, max, ASN1_BIT_STRING)
} ASN1_SEQUENCE_END(IPAddressRange)
ASN1_CHOICE(IPAddressOrRange) = {
ASN1_SIMPLE(IPAddressOrRange, u.addressPrefix, ASN1_BIT_STRING),
ASN1_SIMPLE(IPAddressOrRange, u.addressRange, IPAddressRange)
} ASN1_CHOICE_END(IPAddressOrRange)
ASN1_CHOICE(IPAddressChoice) = {
ASN1_SIMPLE(IPAddressChoice, u.inherit, ASN1_NULL),
ASN1_SEQUENCE_OF(IPAddressChoice, u.addressesOrRanges, IPAddressOrRange)
} ASN1_CHOICE_END(IPAddressChoice)
ASN1_SEQUENCE(IPAddressFamily) = {
ASN1_SIMPLE(IPAddressFamily, addressFamily, ASN1_OCTET_STRING),
ASN1_SIMPLE(IPAddressFamily, ipAddressChoice, IPAddressChoice)
} ASN1_SEQUENCE_END(IPAddressFamily)
ASN1_ITEM_TEMPLATE(IPAddrBlocks) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0,
IPAddrBlocks, IPAddressFamily)
static_ASN1_ITEM_TEMPLATE_END(IPAddrBlocks)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressRange)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressOrRange)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressChoice)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressFamily)
/*
* How much buffer space do we need for a raw address?
*/
#define ADDR_RAW_BUF_LEN 16
/*
* What's the address length associated with this AFI?
*/
static int length_from_afi(const unsigned afi)
{
switch (afi) {
case IANA_AFI_IPV4:
return 4;
case IANA_AFI_IPV6:
return 16;
default:
return 0;
}
}
/*
* Extract the AFI from an IPAddressFamily.
*/
unsigned int X509v3_addr_get_afi(const IPAddressFamily *f)
{
if (f == NULL
|| f->addressFamily == NULL
|| f->addressFamily->data == NULL
|| f->addressFamily->length < 2)
return 0;
return (f->addressFamily->data[0] << 8) | f->addressFamily->data[1];
}
/*
* Expand the bitstring form of an address into a raw byte array.
* At the moment this is coded for simplicity, not speed.
*/
static int addr_expand(unsigned char *addr,
const ASN1_BIT_STRING *bs,
const int length, const unsigned char fill)
{
if (bs->length < 0 || bs->length > length)
return 0;
if (bs->length > 0) {
memcpy(addr, bs->data, bs->length);
if ((bs->flags & 7) != 0) {
unsigned char mask = 0xFF >> (8 - (bs->flags & 7));
if (fill == 0)
addr[bs->length - 1] &= ~mask;
else
addr[bs->length - 1] |= mask;
}
}
memset(addr + bs->length, fill, length - bs->length);
return 1;
}
/*
* Extract the prefix length from a bitstring.
*/
#define addr_prefixlen(bs) ((int) ((bs)->length * 8 - ((bs)->flags & 7)))
/*
* i2r handler for one address bitstring.
*/
static int i2r_address(BIO *out,
const unsigned afi,
const unsigned char fill, const ASN1_BIT_STRING *bs)
{
unsigned char addr[ADDR_RAW_BUF_LEN];
int i, n;
if (bs->length < 0)
return 0;
switch (afi) {
case IANA_AFI_IPV4:
if (!addr_expand(addr, bs, 4, fill))
return 0;
BIO_printf(out, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]);
break;
case IANA_AFI_IPV6:
if (!addr_expand(addr, bs, 16, fill))
return 0;
for (n = 16; n > 1 && addr[n - 1] == 0x00 && addr[n - 2] == 0x00;
n -= 2) ;
for (i = 0; i < n; i += 2)
BIO_printf(out, "%x%s", (addr[i] << 8) | addr[i + 1],
(i < 14 ? ":" : ""));
if (i < 16)
BIO_puts(out, ":");
if (i == 0)
BIO_puts(out, ":");
break;
default:
for (i = 0; i < bs->length; i++)
BIO_printf(out, "%s%02x", (i > 0 ? ":" : ""), bs->data[i]);
BIO_printf(out, "[%d]", (int)(bs->flags & 7));
break;
}
return 1;
}
/*
* i2r handler for a sequence of addresses and ranges.
*/
static int i2r_IPAddressOrRanges(BIO *out,
const int indent,
const IPAddressOrRanges *aors,
const unsigned afi)
{
int i;
for (i = 0; i < sk_IPAddressOrRange_num(aors); i++) {
const IPAddressOrRange *aor = sk_IPAddressOrRange_value(aors, i);
BIO_printf(out, "%*s", indent, "");
switch (aor->type) {
case IPAddressOrRange_addressPrefix:
if (!i2r_address(out, afi, 0x00, aor->u.addressPrefix))
return 0;
BIO_printf(out, "/%d\n", addr_prefixlen(aor->u.addressPrefix));
continue;
case IPAddressOrRange_addressRange:
if (!i2r_address(out, afi, 0x00, aor->u.addressRange->min))
return 0;
BIO_puts(out, "-");
if (!i2r_address(out, afi, 0xFF, aor->u.addressRange->max))
return 0;
BIO_puts(out, "\n");
continue;
}
}
return 1;
}
/*
* i2r handler for an IPAddrBlocks extension.
*/
static int i2r_IPAddrBlocks(const X509V3_EXT_METHOD *method,
void *ext, BIO *out, int indent)
{
const IPAddrBlocks *addr = ext;
int i;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
const unsigned int afi = X509v3_addr_get_afi(f);
switch (afi) {
case IANA_AFI_IPV4:
BIO_printf(out, "%*sIPv4", indent, "");
break;
case IANA_AFI_IPV6:
BIO_printf(out, "%*sIPv6", indent, "");
break;
default:
BIO_printf(out, "%*sUnknown AFI %u", indent, "", afi);
break;
}
if (f->addressFamily->length > 2) {
switch (f->addressFamily->data[2]) {
case 1:
BIO_puts(out, " (Unicast)");
break;
case 2:
BIO_puts(out, " (Multicast)");
break;
case 3:
BIO_puts(out, " (Unicast/Multicast)");
break;
case 4:
BIO_puts(out, " (MPLS)");
break;
case 64:
BIO_puts(out, " (Tunnel)");
break;
case 65:
BIO_puts(out, " (VPLS)");
break;
case 66:
BIO_puts(out, " (BGP MDT)");
break;
case 128:
BIO_puts(out, " (MPLS-labeled VPN)");
break;
default:
BIO_printf(out, " (Unknown SAFI %u)",
(unsigned)f->addressFamily->data[2]);
break;
}
}
switch (f->ipAddressChoice->type) {
case IPAddressChoice_inherit:
BIO_puts(out, ": inherit\n");
break;
case IPAddressChoice_addressesOrRanges:
BIO_puts(out, ":\n");
if (!i2r_IPAddressOrRanges(out,
indent + 2,
f->ipAddressChoice->
u.addressesOrRanges, afi))
return 0;
break;
}
}
return 1;
}
/*
* Sort comparison function for a sequence of IPAddressOrRange
* elements.
*
* There's no sane answer we can give if addr_expand() fails, and an
* assertion failure on externally supplied data is seriously uncool,
* so we just arbitrarily declare that if given invalid inputs this
* function returns -1. If this messes up your preferred sort order
* for garbage input, tough noogies.
*/
static int IPAddressOrRange_cmp(const IPAddressOrRange *a,
const IPAddressOrRange *b, const int length)
{
unsigned char addr_a[ADDR_RAW_BUF_LEN], addr_b[ADDR_RAW_BUF_LEN];
int prefixlen_a = 0, prefixlen_b = 0;
int r;
switch (a->type) {
case IPAddressOrRange_addressPrefix:
if (!addr_expand(addr_a, a->u.addressPrefix, length, 0x00))
return -1;
prefixlen_a = addr_prefixlen(a->u.addressPrefix);
break;
case IPAddressOrRange_addressRange:
if (!addr_expand(addr_a, a->u.addressRange->min, length, 0x00))
return -1;
prefixlen_a = length * 8;
break;
}
switch (b->type) {
case IPAddressOrRange_addressPrefix:
if (!addr_expand(addr_b, b->u.addressPrefix, length, 0x00))
return -1;
prefixlen_b = addr_prefixlen(b->u.addressPrefix);
break;
case IPAddressOrRange_addressRange:
if (!addr_expand(addr_b, b->u.addressRange->min, length, 0x00))
return -1;
prefixlen_b = length * 8;
break;
}
if ((r = memcmp(addr_a, addr_b, length)) != 0)
return r;
else
return prefixlen_a - prefixlen_b;
}
/*
* IPv4-specific closure over IPAddressOrRange_cmp, since sk_sort()
* comparison routines are only allowed two arguments.
*/
static int v4IPAddressOrRange_cmp(const IPAddressOrRange *const *a,
const IPAddressOrRange *const *b)
{
return IPAddressOrRange_cmp(*a, *b, 4);
}
/*
* IPv6-specific closure over IPAddressOrRange_cmp, since sk_sort()
* comparison routines are only allowed two arguments.
*/
static int v6IPAddressOrRange_cmp(const IPAddressOrRange *const *a,
const IPAddressOrRange *const *b)
{
return IPAddressOrRange_cmp(*a, *b, 16);
}
/*
* Calculate whether a range collapses to a prefix.
* See last paragraph of RFC 3779 2.2.3.7.
*/
static int range_should_be_prefix(const unsigned char *min,
const unsigned char *max, const int length)
{
unsigned char mask;
int i, j;
OPENSSL_assert(memcmp(min, max, length) <= 0);
for (i = 0; i < length && min[i] == max[i]; i++) ;
for (j = length - 1; j >= 0 && min[j] == 0x00 && max[j] == 0xFF; j--) ;
if (i < j)
return -1;
if (i > j)
return i * 8;
mask = min[i] ^ max[i];
switch (mask) {
case 0x01:
j = 7;
break;
case 0x03:
j = 6;
break;
case 0x07:
j = 5;
break;
case 0x0F:
j = 4;
break;
case 0x1F:
j = 3;
break;
case 0x3F:
j = 2;
break;
case 0x7F:
j = 1;
break;
default:
return -1;
}
if ((min[i] & mask) != 0 || (max[i] & mask) != mask)
return -1;
else
return i * 8 + j;
}
/*
* Construct a prefix.
*/
static int make_addressPrefix(IPAddressOrRange **result,
unsigned char *addr, const int prefixlen)
{
int bytelen = (prefixlen + 7) / 8, bitlen = prefixlen % 8;
IPAddressOrRange *aor = IPAddressOrRange_new();
if (aor == NULL)
return 0;
aor->type = IPAddressOrRange_addressPrefix;
if (aor->u.addressPrefix == NULL &&
(aor->u.addressPrefix = ASN1_BIT_STRING_new()) == NULL)
goto err;
if (!ASN1_BIT_STRING_set(aor->u.addressPrefix, addr, bytelen))
goto err;
aor->u.addressPrefix->flags &= ~7;
aor->u.addressPrefix->flags |= ASN1_STRING_FLAG_BITS_LEFT;
if (bitlen > 0) {
aor->u.addressPrefix->data[bytelen - 1] &= ~(0xFF >> bitlen);
aor->u.addressPrefix->flags |= 8 - bitlen;
}
*result = aor;
return 1;
err:
IPAddressOrRange_free(aor);
return 0;
}
/*
* Construct a range. If it can be expressed as a prefix,
* return a prefix instead. Doing this here simplifies
* the rest of the code considerably.
*/
static int make_addressRange(IPAddressOrRange **result,
unsigned char *min,
unsigned char *max, const int length)
{
IPAddressOrRange *aor;
int i, prefixlen;
if ((prefixlen = range_should_be_prefix(min, max, length)) >= 0)
return make_addressPrefix(result, min, prefixlen);
if ((aor = IPAddressOrRange_new()) == NULL)
return 0;
aor->type = IPAddressOrRange_addressRange;
OPENSSL_assert(aor->u.addressRange == NULL);
if ((aor->u.addressRange = IPAddressRange_new()) == NULL)
goto err;
if (aor->u.addressRange->min == NULL &&
(aor->u.addressRange->min = ASN1_BIT_STRING_new()) == NULL)
goto err;
if (aor->u.addressRange->max == NULL &&
(aor->u.addressRange->max = ASN1_BIT_STRING_new()) == NULL)
goto err;
for (i = length; i > 0 && min[i - 1] == 0x00; --i) ;
if (!ASN1_BIT_STRING_set(aor->u.addressRange->min, min, i))
goto err;
aor->u.addressRange->min->flags &= ~7;
aor->u.addressRange->min->flags |= ASN1_STRING_FLAG_BITS_LEFT;
if (i > 0) {
unsigned char b = min[i - 1];
int j = 1;
while ((b & (0xFFU >> j)) != 0)
++j;
aor->u.addressRange->min->flags |= 8 - j;
}
for (i = length; i > 0 && max[i - 1] == 0xFF; --i) ;
if (!ASN1_BIT_STRING_set(aor->u.addressRange->max, max, i))
goto err;
aor->u.addressRange->max->flags &= ~7;
aor->u.addressRange->max->flags |= ASN1_STRING_FLAG_BITS_LEFT;
if (i > 0) {
unsigned char b = max[i - 1];
int j = 1;
while ((b & (0xFFU >> j)) != (0xFFU >> j))
++j;
aor->u.addressRange->max->flags |= 8 - j;
}
*result = aor;
return 1;
err:
IPAddressOrRange_free(aor);
return 0;
}
/*
* Construct a new address family or find an existing one.
*/
static IPAddressFamily *make_IPAddressFamily(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi)
{
IPAddressFamily *f;
unsigned char key[3];
int keylen;
int i;
key[0] = (afi >> 8) & 0xFF;
key[1] = afi & 0xFF;
if (safi != NULL) {
key[2] = *safi & 0xFF;
keylen = 3;
} else {
keylen = 2;
}
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
f = sk_IPAddressFamily_value(addr, i);
OPENSSL_assert(f->addressFamily->data != NULL);
if (f->addressFamily->length == keylen &&
!memcmp(f->addressFamily->data, key, keylen))
return f;
}
if ((f = IPAddressFamily_new()) == NULL)
goto err;
if (f->ipAddressChoice == NULL &&
(f->ipAddressChoice = IPAddressChoice_new()) == NULL)
goto err;
if (f->addressFamily == NULL &&
(f->addressFamily = ASN1_OCTET_STRING_new()) == NULL)
goto err;
if (!ASN1_OCTET_STRING_set(f->addressFamily, key, keylen))
goto err;
if (!sk_IPAddressFamily_push(addr, f))
goto err;
return f;
err:
IPAddressFamily_free(f);
return NULL;
}
/*
* Add an inheritance element.
*/
int X509v3_addr_add_inherit(IPAddrBlocks *addr,
const unsigned afi, const unsigned *safi)
{
IPAddressFamily *f = make_IPAddressFamily(addr, afi, safi);
if (f == NULL ||
f->ipAddressChoice == NULL ||
(f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges &&
f->ipAddressChoice->u.addressesOrRanges != NULL))
return 0;
if (f->ipAddressChoice->type == IPAddressChoice_inherit &&
f->ipAddressChoice->u.inherit != NULL)
return 1;
if (f->ipAddressChoice->u.inherit == NULL &&
(f->ipAddressChoice->u.inherit = ASN1_NULL_new()) == NULL)
return 0;
f->ipAddressChoice->type = IPAddressChoice_inherit;
return 1;
}
/*
* Construct an IPAddressOrRange sequence, or return an existing one.
*/
static IPAddressOrRanges *make_prefix_or_range(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi)
{
IPAddressFamily *f = make_IPAddressFamily(addr, afi, safi);
IPAddressOrRanges *aors = NULL;
if (f == NULL ||
f->ipAddressChoice == NULL ||
(f->ipAddressChoice->type == IPAddressChoice_inherit &&
f->ipAddressChoice->u.inherit != NULL))
return NULL;
if (f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges)
aors = f->ipAddressChoice->u.addressesOrRanges;
if (aors != NULL)
return aors;
if ((aors = sk_IPAddressOrRange_new_null()) == NULL)
return NULL;
switch (afi) {
case IANA_AFI_IPV4:
(void)sk_IPAddressOrRange_set_cmp_func(aors, v4IPAddressOrRange_cmp);
break;
case IANA_AFI_IPV6:
(void)sk_IPAddressOrRange_set_cmp_func(aors, v6IPAddressOrRange_cmp);
break;
}
f->ipAddressChoice->type = IPAddressChoice_addressesOrRanges;
f->ipAddressChoice->u.addressesOrRanges = aors;
return aors;
}
/*
* Add a prefix.
*/
int X509v3_addr_add_prefix(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi,
unsigned char *a, const int prefixlen)
{
IPAddressOrRanges *aors = make_prefix_or_range(addr, afi, safi);
IPAddressOrRange *aor;
if (aors == NULL || !make_addressPrefix(&aor, a, prefixlen))
return 0;
if (sk_IPAddressOrRange_push(aors, aor))
return 1;
IPAddressOrRange_free(aor);
return 0;
}
/*
* Add a range.
*/
int X509v3_addr_add_range(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi,
unsigned char *min, unsigned char *max)
{
IPAddressOrRanges *aors = make_prefix_or_range(addr, afi, safi);
IPAddressOrRange *aor;
int length = length_from_afi(afi);
if (aors == NULL)
return 0;
if (!make_addressRange(&aor, min, max, length))
return 0;
if (sk_IPAddressOrRange_push(aors, aor))
return 1;
IPAddressOrRange_free(aor);
return 0;
}
/*
* Extract min and max values from an IPAddressOrRange.
*/
static int extract_min_max(IPAddressOrRange *aor,
unsigned char *min, unsigned char *max, int length)
{
if (aor == NULL || min == NULL || max == NULL)
return 0;
switch (aor->type) {
case IPAddressOrRange_addressPrefix:
return (addr_expand(min, aor->u.addressPrefix, length, 0x00) &&
addr_expand(max, aor->u.addressPrefix, length, 0xFF));
case IPAddressOrRange_addressRange:
return (addr_expand(min, aor->u.addressRange->min, length, 0x00) &&
addr_expand(max, aor->u.addressRange->max, length, 0xFF));
}
return 0;
}
/*
* Public wrapper for extract_min_max().
*/
int X509v3_addr_get_range(IPAddressOrRange *aor,
const unsigned afi,
unsigned char *min,
unsigned char *max, const int length)
{
int afi_length = length_from_afi(afi);
if (aor == NULL || min == NULL || max == NULL ||
afi_length == 0 || length < afi_length ||
(aor->type != IPAddressOrRange_addressPrefix &&
aor->type != IPAddressOrRange_addressRange) ||
!extract_min_max(aor, min, max, afi_length))
return 0;
return afi_length;
}
/*
* Sort comparison function for a sequence of IPAddressFamily.
*
* The last paragraph of RFC 3779 2.2.3.3 is slightly ambiguous about
* the ordering: I can read it as meaning that IPv6 without a SAFI
* comes before IPv4 with a SAFI, which seems pretty weird. The
* examples in appendix B suggest that the author intended the
* null-SAFI rule to apply only within a single AFI, which is what I
* would have expected and is what the following code implements.
*/
static int IPAddressFamily_cmp(const IPAddressFamily *const *a_,
const IPAddressFamily *const *b_)
{
const ASN1_OCTET_STRING *a = (*a_)->addressFamily;
const ASN1_OCTET_STRING *b = (*b_)->addressFamily;
int len = ((a->length <= b->length) ? a->length : b->length);
int cmp = memcmp(a->data, b->data, len);
return cmp ? cmp : a->length - b->length;
}
/*
* Check whether an IPAddrBLocks is in canonical form.
*/
int X509v3_addr_is_canonical(IPAddrBlocks *addr)
{
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN];
IPAddressOrRanges *aors;
int i, j, k;
/*
* Empty extension is canonical.
*/
if (addr == NULL)
return 1;
/*
* Check whether the top-level list is in order.
*/
for (i = 0; i < sk_IPAddressFamily_num(addr) - 1; i++) {
const IPAddressFamily *a = sk_IPAddressFamily_value(addr, i);
const IPAddressFamily *b = sk_IPAddressFamily_value(addr, i + 1);
if (IPAddressFamily_cmp(&a, &b) >= 0)
return 0;
}
/*
* Top level's ok, now check each address family.
*/
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
int length = length_from_afi(X509v3_addr_get_afi(f));
/*
* Inheritance is canonical. Anything other than inheritance or
* a SEQUENCE OF IPAddressOrRange is an ASN.1 error or something.
*/
if (f == NULL || f->ipAddressChoice == NULL)
return 0;
switch (f->ipAddressChoice->type) {
case IPAddressChoice_inherit:
continue;
case IPAddressChoice_addressesOrRanges:
break;
default:
return 0;
}
/*
* It's an IPAddressOrRanges sequence, check it.
*/
aors = f->ipAddressChoice->u.addressesOrRanges;
if (sk_IPAddressOrRange_num(aors) == 0)
return 0;
for (j = 0; j < sk_IPAddressOrRange_num(aors) - 1; j++) {
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
IPAddressOrRange *b = sk_IPAddressOrRange_value(aors, j + 1);
if (!extract_min_max(a, a_min, a_max, length) ||
!extract_min_max(b, b_min, b_max, length))
return 0;
/*
* Punt misordered list, overlapping start, or inverted range.
*/
if (memcmp(a_min, b_min, length) >= 0 ||
memcmp(a_min, a_max, length) > 0 ||
memcmp(b_min, b_max, length) > 0)
return 0;
/*
* Punt if adjacent or overlapping. Check for adjacency by
* subtracting one from b_min first.
*/
for (k = length - 1; k >= 0 && b_min[k]-- == 0x00; k--) ;
if (memcmp(a_max, b_min, length) >= 0)
return 0;
/*
* Check for range that should be expressed as a prefix.
*/
if (a->type == IPAddressOrRange_addressRange &&
range_should_be_prefix(a_min, a_max, length) >= 0)
return 0;
}
/*
* Check range to see if it's inverted or should be a
* prefix.
*/
j = sk_IPAddressOrRange_num(aors) - 1;
{
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
if (a != NULL && a->type == IPAddressOrRange_addressRange) {
if (!extract_min_max(a, a_min, a_max, length))
return 0;
if (memcmp(a_min, a_max, length) > 0 ||
range_should_be_prefix(a_min, a_max, length) >= 0)
return 0;
}
}
}
/*
* If we made it through all that, we're happy.
*/
return 1;
}
/*
* Whack an IPAddressOrRanges into canonical form.
*/
static int IPAddressOrRanges_canonize(IPAddressOrRanges *aors,
const unsigned afi)
{
int i, j, length = length_from_afi(afi);
/*
* Sort the IPAddressOrRanges sequence.
*/
sk_IPAddressOrRange_sort(aors);
/*
* Clean up representation issues, punt on duplicates or overlaps.
*/
for (i = 0; i < sk_IPAddressOrRange_num(aors) - 1; i++) {
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, i);
IPAddressOrRange *b = sk_IPAddressOrRange_value(aors, i + 1);
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN];
if (!extract_min_max(a, a_min, a_max, length) ||
!extract_min_max(b, b_min, b_max, length))
return 0;
/*
* Punt inverted ranges.
*/
if (memcmp(a_min, a_max, length) > 0 ||
memcmp(b_min, b_max, length) > 0)
return 0;
/*
* Punt overlaps.
*/
if (memcmp(a_max, b_min, length) >= 0)
return 0;
/*
* Merge if a and b are adjacent. We check for
* adjacency by subtracting one from b_min first.
*/
for (j = length - 1; j >= 0 && b_min[j]-- == 0x00; j--) ;
if (memcmp(a_max, b_min, length) == 0) {
IPAddressOrRange *merged;
if (!make_addressRange(&merged, a_min, b_max, length))
return 0;
(void)sk_IPAddressOrRange_set(aors, i, merged);
(void)sk_IPAddressOrRange_delete(aors, i + 1);
IPAddressOrRange_free(a);
IPAddressOrRange_free(b);
--i;
continue;
}
}
/*
* Check for inverted final range.
*/
j = sk_IPAddressOrRange_num(aors) - 1;
{
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
if (a != NULL && a->type == IPAddressOrRange_addressRange) {
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
if (!extract_min_max(a, a_min, a_max, length))
return 0;
if (memcmp(a_min, a_max, length) > 0)
return 0;
}
}
return 1;
}
/*
* Whack an IPAddrBlocks extension into canonical form.
*/
int X509v3_addr_canonize(IPAddrBlocks *addr)
{
int i;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
if (f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges &&
!IPAddressOrRanges_canonize(f->ipAddressChoice->
u.addressesOrRanges,
X509v3_addr_get_afi(f)))
return 0;
}
(void)sk_IPAddressFamily_set_cmp_func(addr, IPAddressFamily_cmp);
sk_IPAddressFamily_sort(addr);
OPENSSL_assert(X509v3_addr_is_canonical(addr));
return 1;
}
/*
* v2i handler for the IPAddrBlocks extension.
*/
static void *v2i_IPAddrBlocks(const struct v3_ext_method *method,
struct v3_ext_ctx *ctx,
STACK_OF(CONF_VALUE) *values)
{
static const char v4addr_chars[] = "0123456789.";
static const char v6addr_chars[] = "0123456789.:abcdefABCDEF";
IPAddrBlocks *addr = NULL;
char *s = NULL, *t;
int i;
if ((addr = sk_IPAddressFamily_new(IPAddressFamily_cmp)) == NULL) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(values); i++) {
CONF_VALUE *val = sk_CONF_VALUE_value(values, i);
unsigned char min[ADDR_RAW_BUF_LEN], max[ADDR_RAW_BUF_LEN];
unsigned afi, *safi = NULL, safi_;
const char *addr_chars = NULL;
int prefixlen, i1, i2, delim, length;
if (!name_cmp(val->name, "IPv4")) {
afi = IANA_AFI_IPV4;
} else if (!name_cmp(val->name, "IPv6")) {
afi = IANA_AFI_IPV6;
} else if (!name_cmp(val->name, "IPv4-SAFI")) {
afi = IANA_AFI_IPV4;
safi = &safi_;
} else if (!name_cmp(val->name, "IPv6-SAFI")) {
afi = IANA_AFI_IPV6;
safi = &safi_;
} else {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_EXTENSION_NAME_ERROR);
X509V3_conf_err(val);
goto err;
}
switch (afi) {
case IANA_AFI_IPV4:
addr_chars = v4addr_chars;
break;
case IANA_AFI_IPV6:
addr_chars = v6addr_chars;
break;
}
length = length_from_afi(afi);
/*
* Handle SAFI, if any, and OPENSSL_strdup() so we can null-terminate
* the other input values.
*/
if (safi != NULL) {
*safi = strtoul(val->value, &t, 0);
t += strspn(t, " \t");
if (*safi > 0xFF || *t++ != ':') {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_INVALID_SAFI);
X509V3_conf_err(val);
goto err;
}
t += strspn(t, " \t");
s = OPENSSL_strdup(t);
} else {
s = OPENSSL_strdup(val->value);
}
if (s == NULL) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE);
goto err;
}
/*
* Check for inheritance. Not worth additional complexity to
* optimize this (seldom-used) case.
*/
if (strcmp(s, "inherit") == 0) {
if (!X509v3_addr_add_inherit(addr, afi, safi)) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_INVALID_INHERITANCE);
X509V3_conf_err(val);
goto err;
}
OPENSSL_free(s);
s = NULL;
continue;
}
i1 = strspn(s, addr_chars);
i2 = i1 + strspn(s + i1, " \t");
delim = s[i2++];
s[i1] = '\0';
if (a2i_ipadd(min, s) != length) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_INVALID_IPADDRESS);
X509V3_conf_err(val);
goto err;
}
switch (delim) {
case '/':
prefixlen = (int)strtoul(s + i2, &t, 10);
if (t == s + i2 || *t != '\0') {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_err(val);
goto err;
}
if (!X509v3_addr_add_prefix(addr, afi, safi, min, prefixlen)) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE);
goto err;
}
break;
case '-':
i1 = i2 + strspn(s + i2, " \t");
i2 = i1 + strspn(s + i1, addr_chars);
if (i1 == i2 || s[i2] != '\0') {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_err(val);
goto err;
}
if (a2i_ipadd(max, s + i1) != length) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_INVALID_IPADDRESS);
X509V3_conf_err(val);
goto err;
}
if (memcmp(min, max, length_from_afi(afi)) > 0) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_err(val);
goto err;
}
if (!X509v3_addr_add_range(addr, afi, safi, min, max)) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE);
goto err;
}
break;
case '\0':
if (!X509v3_addr_add_prefix(addr, afi, safi, min, length * 8)) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE);
goto err;
}
break;
default:
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_err(val);
goto err;
}
OPENSSL_free(s);
s = NULL;
}
/*
* Canonize the result, then we're done.
*/
if (!X509v3_addr_canonize(addr))
goto err;
return addr;
err:
OPENSSL_free(s);
sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free);
return NULL;
}
/*
* OpenSSL dispatch
*/
const X509V3_EXT_METHOD v3_addr = {
NID_sbgp_ipAddrBlock, /* nid */
0, /* flags */
ASN1_ITEM_ref(IPAddrBlocks), /* template */
0, 0, 0, 0, /* old functions, ignored */
0, /* i2s */
0, /* s2i */
0, /* i2v */
v2i_IPAddrBlocks, /* v2i */
i2r_IPAddrBlocks, /* i2r */
0, /* r2i */
NULL /* extension-specific data */
};
/*
* Figure out whether extension sues inheritance.
*/
int X509v3_addr_inherits(IPAddrBlocks *addr)
{
int i;
if (addr == NULL)
return 0;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
if (f->ipAddressChoice->type == IPAddressChoice_inherit)
return 1;
}
return 0;
}
/*
* Figure out whether parent contains child.
*/
static int addr_contains(IPAddressOrRanges *parent,
IPAddressOrRanges *child, int length)
{
unsigned char p_min[ADDR_RAW_BUF_LEN], p_max[ADDR_RAW_BUF_LEN];
unsigned char c_min[ADDR_RAW_BUF_LEN], c_max[ADDR_RAW_BUF_LEN];
int p, c;
if (child == NULL || parent == child)
return 1;
if (parent == NULL)
return 0;
p = 0;
for (c = 0; c < sk_IPAddressOrRange_num(child); c++) {
if (!extract_min_max(sk_IPAddressOrRange_value(child, c),
c_min, c_max, length))
return -1;
for (;; p++) {
if (p >= sk_IPAddressOrRange_num(parent))
return 0;
if (!extract_min_max(sk_IPAddressOrRange_value(parent, p),
p_min, p_max, length))
return 0;
if (memcmp(p_max, c_max, length) < 0)
continue;
if (memcmp(p_min, c_min, length) > 0)
return 0;
break;
}
}
return 1;
}
/*
* Test whether a is a subset of b.
*/
int X509v3_addr_subset(IPAddrBlocks *a, IPAddrBlocks *b)
{
int i;
if (a == NULL || a == b)
return 1;
if (b == NULL || X509v3_addr_inherits(a) || X509v3_addr_inherits(b))
return 0;
(void)sk_IPAddressFamily_set_cmp_func(b, IPAddressFamily_cmp);
for (i = 0; i < sk_IPAddressFamily_num(a); i++) {
IPAddressFamily *fa = sk_IPAddressFamily_value(a, i);
int j = sk_IPAddressFamily_find(b, fa);
IPAddressFamily *fb;
fb = sk_IPAddressFamily_value(b, j);
if (fb == NULL)
return 0;
if (!addr_contains(fb->ipAddressChoice->u.addressesOrRanges,
fa->ipAddressChoice->u.addressesOrRanges,
length_from_afi(X509v3_addr_get_afi(fb))))
return 0;
}
return 1;
}
/*
* Validation error handling via callback.
*/
#define validation_err(_err_) \
do { \
if (ctx != NULL) { \
ctx->error = _err_; \
ctx->error_depth = i; \
ctx->current_cert = x; \
ret = ctx->verify_cb(0, ctx); \
} else { \
ret = 0; \
} \
if (!ret) \
goto done; \
} while (0)
/*
* Core code for RFC 3779 2.3 path validation.
*
* Returns 1 for success, 0 on error.
*
* When returning 0, ctx->error MUST be set to an appropriate value other than
* X509_V_OK.
*/
static int addr_validate_path_internal(X509_STORE_CTX *ctx,
STACK_OF(X509) *chain,
IPAddrBlocks *ext)
{
IPAddrBlocks *child = NULL;
int i, j, ret = 1;
X509 *x;
OPENSSL_assert(chain != NULL && sk_X509_num(chain) > 0);
OPENSSL_assert(ctx != NULL || ext != NULL);
OPENSSL_assert(ctx == NULL || ctx->verify_cb != NULL);
/*
* Figure out where to start. If we don't have an extension to
* check, we're done. Otherwise, check canonical form and
* set up for walking up the chain.
*/
if (ext != NULL) {
i = -1;
x = NULL;
} else {
i = 0;
x = sk_X509_value(chain, i);
OPENSSL_assert(x != NULL);
if ((ext = x->rfc3779_addr) == NULL)
goto done;
}
if (!X509v3_addr_is_canonical(ext))
validation_err(X509_V_ERR_INVALID_EXTENSION);
(void)sk_IPAddressFamily_set_cmp_func(ext, IPAddressFamily_cmp);
if ((child = sk_IPAddressFamily_dup(ext)) == NULL) {
X509V3err(X509V3_F_ADDR_VALIDATE_PATH_INTERNAL,
ERR_R_MALLOC_FAILURE);
ctx->error = X509_V_ERR_OUT_OF_MEM;
ret = 0;
goto done;
}
/*
* Now walk up the chain. No cert may list resources that its
* parent doesn't list.
*/
for (i++; i < sk_X509_num(chain); i++) {
x = sk_X509_value(chain, i);
OPENSSL_assert(x != NULL);
if (!X509v3_addr_is_canonical(x->rfc3779_addr))
validation_err(X509_V_ERR_INVALID_EXTENSION);
if (x->rfc3779_addr == NULL) {
for (j = 0; j < sk_IPAddressFamily_num(child); j++) {
IPAddressFamily *fc = sk_IPAddressFamily_value(child, j);
if (fc->ipAddressChoice->type != IPAddressChoice_inherit) {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
break;
}
}
continue;
}
(void)sk_IPAddressFamily_set_cmp_func(x->rfc3779_addr,
IPAddressFamily_cmp);
for (j = 0; j < sk_IPAddressFamily_num(child); j++) {
IPAddressFamily *fc = sk_IPAddressFamily_value(child, j);
int k = sk_IPAddressFamily_find(x->rfc3779_addr, fc);
IPAddressFamily *fp =
sk_IPAddressFamily_value(x->rfc3779_addr, k);
if (fp == NULL) {
if (fc->ipAddressChoice->type ==
IPAddressChoice_addressesOrRanges) {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
break;
}
continue;
}
if (fp->ipAddressChoice->type ==
IPAddressChoice_addressesOrRanges) {
if (fc->ipAddressChoice->type == IPAddressChoice_inherit
|| addr_contains(fp->ipAddressChoice->u.addressesOrRanges,
fc->ipAddressChoice->u.addressesOrRanges,
length_from_afi(X509v3_addr_get_afi(fc))))
sk_IPAddressFamily_set(child, j, fp);
else
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
}
}
}
/*
* Trust anchor can't inherit.
*/
OPENSSL_assert(x != NULL);
if (x->rfc3779_addr != NULL) {
for (j = 0; j < sk_IPAddressFamily_num(x->rfc3779_addr); j++) {
IPAddressFamily *fp =
sk_IPAddressFamily_value(x->rfc3779_addr, j);
if (fp->ipAddressChoice->type == IPAddressChoice_inherit
&& sk_IPAddressFamily_find(child, fp) >= 0)
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
}
}
done:
sk_IPAddressFamily_free(child);
return ret;
}
#undef validation_err
/*
* RFC 3779 2.3 path validation -- called from X509_verify_cert().
*/
int X509v3_addr_validate_path(X509_STORE_CTX *ctx)
{
return addr_validate_path_internal(ctx, ctx->chain, NULL);
}
/*
* RFC 3779 2.3 path validation of an extension.
* Test whether chain covers extension.
*/
int X509v3_addr_validate_resource_set(STACK_OF(X509) *chain,
IPAddrBlocks *ext, int allow_inheritance)
{
if (ext == NULL)
return 1;
if (chain == NULL || sk_X509_num(chain) == 0)
return 0;
if (!allow_inheritance && X509v3_addr_inherits(ext))
return 0;
return addr_validate_path_internal(NULL, chain, ext);
}
#endif /* OPENSSL_NO_RFC3779 */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3071_0 |
crossvul-cpp_data_good_346_8 | /*
* cryptoflex-tool.c: Tool for doing various Cryptoflex related stuff
*
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include "libopensc/sc-ossl-compat.h"
#include "libopensc/internal.h"
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include "libopensc/pkcs15.h"
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#include "util.h"
static const char *app_name = "cryptoflex-tool";
static char * opt_reader = NULL;
static int opt_wait = 0;
static int opt_key_num = 1, opt_pin_num = -1;
static int verbose = 0;
static int opt_exponent = 3;
static int opt_mod_length = 1024;
static int opt_key_count = 1;
static int opt_pin_attempts = 10;
static int opt_puk_attempts = 10;
static const char *opt_appdf = NULL, *opt_prkeyf = NULL, *opt_pubkeyf = NULL;
static u8 *pincode = NULL;
static const struct option options[] = {
{ "list-keys", 0, NULL, 'l' },
{ "create-key-files", 1, NULL, 'c' },
{ "create-pin-file", 1, NULL, 'P' },
{ "generate-key", 0, NULL, 'g' },
{ "read-key", 0, NULL, 'R' },
{ "verify-pin", 0, NULL, 'V' },
{ "key-num", 1, NULL, 'k' },
{ "app-df", 1, NULL, 'a' },
{ "prkey-file", 1, NULL, 'p' },
{ "pubkey-file", 1, NULL, 'u' },
{ "exponent", 1, NULL, 'e' },
{ "modulus-length", 1, NULL, 'm' },
{ "reader", 1, NULL, 'r' },
{ "wait", 0, NULL, 'w' },
{ "verbose", 0, NULL, 'v' },
{ NULL, 0, NULL, 0 }
};
static const char *option_help[] = {
"Lists all keys in a public key file",
"Creates new RSA key files for <arg> keys",
"Creates a new CHV<arg> file",
"Generates a new RSA key pair",
"Reads a public key from the card",
"Verifies CHV1 before issuing commands",
"Selects which key number to operate on [1]",
"Selects the DF to operate in",
"Private key file",
"Public key file",
"The RSA exponent to use in key generation [3]",
"Modulus length to use in key generation [1024]",
"Uses reader <arg>",
"Wait for card insertion",
"Verbose operation. Use several times to enable debug output.",
};
static sc_context_t *ctx = NULL;
static sc_card_t *card = NULL;
static char *getpin(const char *prompt)
{
char *buf, pass[20];
int i;
printf("%s", prompt);
fflush(stdout);
if (fgets(pass, 20, stdin) == NULL)
return NULL;
for (i = 0; i < 20; i++)
if (pass[i] == '\n')
pass[i] = 0;
if (strlen(pass) == 0)
return NULL;
buf = malloc(8);
if (buf == NULL)
return NULL;
if (strlen(pass) > 8) {
fprintf(stderr, "PIN code too long.\n");
free(buf);
return NULL;
}
memset(buf, 0, 8);
strlcpy(buf, pass, 8);
return buf;
}
static int verify_pin(int pin)
{
char prompt[50];
int r, tries_left = -1;
if (pincode == NULL) {
sprintf(prompt, "Please enter CHV%d: ", pin);
pincode = (u8 *) getpin(prompt);
if (pincode == NULL || strlen((char *) pincode) == 0)
return -1;
}
if (pin != 1 && pin != 2)
return -3;
r = sc_verify(card, SC_AC_CHV, pin, pincode, 8, &tries_left);
if (r) {
memset(pincode, 0, 8);
free(pincode);
pincode = NULL;
fprintf(stderr, "PIN code verification failed: %s\n", sc_strerror(r));
return -1;
}
return 0;
}
static int select_app_df(void)
{
sc_path_t path;
sc_file_t *file;
char str[80];
int r;
strcpy(str, "3F00");
if (opt_appdf != NULL)
strlcat(str, opt_appdf, sizeof str);
sc_format_path(str, &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select application DF: %s\n", sc_strerror(r));
return -1;
}
if (file->type != SC_FILE_TYPE_DF) {
fprintf(stderr, "Selected application DF is not a DF.\n");
return -1;
}
sc_file_free(file);
if (opt_pin_num >= 0)
return verify_pin(opt_pin_num);
else
return 0;
}
static void invert_buf(u8 *dest, const u8 *src, size_t c)
{
size_t i;
for (i = 0; i < c; i++)
dest[i] = src[c-1-i];
}
static BIGNUM * cf2bn(const u8 *buf, size_t bufsize, BIGNUM *num)
{
u8 tmp[512];
invert_buf(tmp, buf, bufsize);
return BN_bin2bn(tmp, bufsize, num);
}
static int bn2cf(const BIGNUM *num, u8 *buf)
{
u8 tmp[512];
int r;
r = BN_bn2bin(num, tmp);
if (r <= 0)
return r;
invert_buf(buf, tmp, r);
return r;
}
static int parse_public_key(const u8 *key, size_t keysize, RSA *rsa)
{
const u8 *p = key;
BIGNUM *n, *e;
int base;
base = (keysize - 7) / 5;
if (base != 32 && base != 48 && base != 64 && base != 128) {
fprintf(stderr, "Invalid public key.\n");
return -1;
}
p += 3;
n = BN_new();
if (n == NULL)
return -1;
cf2bn(p, 2 * base, n);
p += 2 * base;
p += base;
p += 2 * base;
e = BN_new();
if (e == NULL)
return -1;
cf2bn(p, 4, e);
if (RSA_set0_key(rsa, n, e, NULL) != 1)
return -1;
return 0;
}
static int gen_d(RSA *rsa)
{
BN_CTX *bnctx;
BIGNUM *r0, *r1, *r2;
const BIGNUM *rsa_p, *rsa_q, *rsa_n, *rsa_e, *rsa_d;
BIGNUM *rsa_n_new, *rsa_e_new, *rsa_d_new;
bnctx = BN_CTX_new();
if (bnctx == NULL)
return -1;
BN_CTX_start(bnctx);
r0 = BN_CTX_get(bnctx);
r1 = BN_CTX_get(bnctx);
r2 = BN_CTX_get(bnctx);
RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d);
RSA_get0_factors(rsa, &rsa_p, &rsa_q);
BN_sub(r1, rsa_p, BN_value_one());
BN_sub(r2, rsa_q, BN_value_one());
BN_mul(r0, r1, r2, bnctx);
if ((rsa_d_new = BN_mod_inverse(NULL, rsa_e, r0, bnctx)) == NULL) {
fprintf(stderr, "BN_mod_inverse() failed.\n");
return -1;
}
/* RSA_set0_key will free previous value, and replace with new value
* Thus the need to copy the contents of rsa_n and rsa_e
*/
rsa_n_new = BN_dup(rsa_n);
rsa_e_new = BN_dup(rsa_e);
if (RSA_set0_key(rsa, rsa_n_new, rsa_e_new, rsa_d_new) != 1)
return -1;
BN_CTX_end(bnctx);
BN_CTX_free(bnctx);
return 0;
}
static int parse_private_key(const u8 *key, size_t keysize, RSA *rsa)
{
const u8 *p = key;
BIGNUM *bn_p, *q, *dmp1, *dmq1, *iqmp;
int base;
base = (keysize - 3) / 5;
if (base != 32 && base != 48 && base != 64 && base != 128) {
fprintf(stderr, "Invalid private key.\n");
return -1;
}
p += 3;
bn_p = BN_new();
if (bn_p == NULL)
return -1;
cf2bn(p, base, bn_p);
p += base;
q = BN_new();
if (q == NULL)
return -1;
cf2bn(p, base, q);
p += base;
iqmp = BN_new();
if (iqmp == NULL)
return -1;
cf2bn(p, base, iqmp);
p += base;
dmp1 = BN_new();
if (dmp1 == NULL)
return -1;
cf2bn(p, base, dmp1);
p += base;
dmq1 = BN_new();
if (dmq1 == NULL)
return -1;
cf2bn(p, base, dmq1);
p += base;
if (RSA_set0_factors(rsa, bn_p, q) != 1)
return -1;
if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) != 1)
return -1;
if (gen_d(rsa))
return -1;
return 0;
}
static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = MIN(file->size, sizeof buf);
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
static int read_private_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
const sc_acl_entry_t *e;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
e = sc_file_get_acl_entry(file, SC_AC_OP_READ);
if (e == NULL || e->method == SC_AC_NEVER)
return 10;
bufsize = MIN(file->size, sizeof buf);
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_private_key(p, keysize, rsa);
}
static int read_key(void)
{
RSA *rsa = RSA_new();
u8 buf[1024], *p = buf;
u8 b64buf[2048];
int r;
if (rsa == NULL)
return -1;
r = read_public_key(rsa);
if (r)
return r;
r = i2d_RSA_PUBKEY(rsa, &p);
if (r <= 0) {
fprintf(stderr, "Error encoding public key.\n");
return -1;
}
r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64);
if (r < 0) {
fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r));
return -1;
}
printf("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n", b64buf);
r = read_private_key(rsa);
if (r == 10)
return 0;
else if (r)
return r;
p = buf;
r = i2d_RSAPrivateKey(rsa, &p);
if (r <= 0) {
fprintf(stderr, "Error encoding private key.\n");
return -1;
}
r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64);
if (r < 0) {
fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r));
return -1;
}
printf("-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n", b64buf);
return 0;
}
static int list_keys(void)
{
int r, idx = 0;
sc_path_t path;
u8 buf[2048], *p = buf;
size_t keysize, i;
int mod_lens[] = { 512, 768, 1024, 2048 };
size_t sizes[] = { 167, 247, 327, 647 };
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
do {
int mod_len = -1;
r = sc_read_binary(card, idx, buf, 3, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
idx += keysize;
for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++)
if (sizes[i] == keysize)
mod_len = mod_lens[i];
if (mod_len < 0)
printf("Key %d -- unknown modulus length\n", p[2] & 0x0F);
else
printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len);
} while (1);
return 0;
}
static int generate_key(void)
{
sc_apdu_t apdu;
u8 sbuf[4];
u8 p2;
int r;
switch (opt_mod_length) {
case 512:
p2 = 0x40;
break;
case 768:
p2 = 0x60;
break;
case 1024:
p2 = 0x80;
break;
case 2048:
p2 = 0x00;
break;
default:
fprintf(stderr, "Invalid modulus length.\n");
return 2;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, (u8) opt_key_num-1, p2);
apdu.cla = 0xF0;
apdu.lc = 4;
apdu.datalen = 4;
apdu.data = sbuf;
sbuf[0] = opt_exponent & 0xFF;
sbuf[1] = (opt_exponent >> 8) & 0xFF;
sbuf[2] = (opt_exponent >> 16) & 0xFF;
sbuf[3] = (opt_exponent >> 24) & 0xFF;
r = select_app_df();
if (r)
return 1;
if (verbose)
printf("Generating key...\n");
r = sc_transmit_apdu(card, &apdu);
if (r) {
fprintf(stderr, "APDU transmit failed: %s\n", sc_strerror(r));
if (r == SC_ERROR_TRANSMIT_FAILED)
fprintf(stderr, "Reader has timed out. It is still possible that the key generation has\n"
"succeeded.\n");
return 1;
}
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
printf("Key generation successful.\n");
return 0;
}
if (apdu.sw1 == 0x69 && apdu.sw2 == 0x82)
fprintf(stderr, "CHV1 not verified or invalid exponent value.\n");
else
fprintf(stderr, "Card returned SW1=%02X, SW2=%02X.\n", apdu.sw1, apdu.sw2);
return 1;
}
static int create_key_files(void)
{
sc_file_t *file;
int mod_lens[] = { 512, 768, 1024, 2048 };
int sizes[] = { 163, 243, 323, 643 };
int size = -1;
int r;
size_t i;
for (i = 0; i < sizeof(mod_lens) / sizeof(int); i++)
if (mod_lens[i] == opt_mod_length) {
size = sizes[i];
break;
}
if (size == -1) {
fprintf(stderr, "Invalid modulus length.\n");
return 1;
}
if (verbose)
printf("Creating key files for %d keys.\n", opt_key_count);
file = sc_file_new();
if (!file) {
fprintf(stderr, "out of memory.\n");
return 1;
}
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
file->id = 0x0012;
file->size = opt_key_count * size + 3;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1);
if (select_app_df()) {
sc_file_free(file);
return 1;
}
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "Unable to create private key file: %s\n", sc_strerror(r));
return 1;
}
file = sc_file_new();
if (!file) {
fprintf(stderr, "out of memory.\n");
return 1;
}
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
file->id = 0x1012;
file->size = opt_key_count * (size + 4) + 3;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1);
if (select_app_df()) {
sc_file_free(file);
return 1;
}
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "Unable to create public key file: %s\n", sc_strerror(r));
return 1;
}
if (verbose)
printf("Key files generated successfully.\n");
return 0;
}
static int read_rsa_privkey(RSA **rsa_out)
{
RSA *rsa = NULL;
BIO *in = NULL;
int r;
in = BIO_new(BIO_s_file());
if (opt_prkeyf == NULL) {
fprintf(stderr, "Private key file must be set.\n");
return 2;
}
r = BIO_read_filename(in, opt_prkeyf);
if (r <= 0) {
perror(opt_prkeyf);
return 2;
}
rsa = PEM_read_bio_RSAPrivateKey(in, NULL, NULL, NULL);
if (rsa == NULL) {
fprintf(stderr, "Unable to load private key.\n");
return 2;
}
BIO_free(in);
*rsa_out = rsa;
return 0;
}
static int encode_private_key(RSA *rsa, u8 *key, size_t *keysize)
{
u8 buf[1024], *p = buf;
u8 bnbuf[256];
int base = 0;
int r;
const BIGNUM *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp;
switch (RSA_bits(rsa)) {
case 512:
base = 32;
break;
case 768:
base = 48;
break;
case 1024:
base = 64;
break;
case 2048:
base = 128;
break;
}
if (base == 0) {
fprintf(stderr, "Key length invalid.\n");
return 2;
}
*p++ = (5 * base + 3) >> 8;
*p++ = (5 * base + 3) & 0xFF;
*p++ = opt_key_num;
RSA_get0_factors(rsa, &rsa_p, &rsa_q);
r = bn2cf(rsa_p, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_q, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
RSA_get0_crt_params(rsa, &rsa_dmp1, &rsa_dmq1, &rsa_iqmp);
r = bn2cf(rsa_iqmp, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_dmp1, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_dmq1, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
memcpy(key, buf, p - buf);
*keysize = p - buf;
return 0;
}
static int encode_public_key(RSA *rsa, u8 *key, size_t *keysize)
{
u8 buf[1024], *p = buf;
u8 bnbuf[256];
int base = 0;
int r;
const BIGNUM *rsa_n, *rsa_e;
switch (RSA_bits(rsa)) {
case 512:
base = 32;
break;
case 768:
base = 48;
break;
case 1024:
base = 64;
break;
case 2048:
base = 128;
break;
}
if (base == 0) {
fprintf(stderr, "Key length invalid.\n");
return 2;
}
*p++ = (5 * base + 7) >> 8;
*p++ = (5 * base + 7) & 0xFF;
*p++ = opt_key_num;
RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL);
r = bn2cf(rsa_n, bnbuf);
if (r != 2*base) {
fprintf(stderr, "Invalid public key.\n");
return 2;
}
memcpy(p, bnbuf, 2*base);
p += 2*base;
memset(p, 0, base);
p += base;
memset(bnbuf, 0, 2*base);
memcpy(p, bnbuf, 2*base);
p += 2*base;
r = bn2cf(rsa_e, bnbuf);
memcpy(p, bnbuf, 4);
p += 4;
memcpy(key, buf, p - buf);
*keysize = p - buf;
return 0;
}
static int update_public_key(const u8 *key, size_t keysize)
{
int r, idx = 0;
sc_path_t path;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
idx = keysize * (opt_key_num-1);
r = sc_update_binary(card, idx, key, keysize, 0);
if (r < 0) {
fprintf(stderr, "Unable to write public key: %s\n", sc_strerror(r));
return 2;
}
return 0;
}
static int update_private_key(const u8 *key, size_t keysize)
{
int r, idx = 0;
sc_path_t path;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
idx = keysize * (opt_key_num-1);
r = sc_update_binary(card, idx, key, keysize, 0);
if (r < 0) {
fprintf(stderr, "Unable to write private key: %s\n", sc_strerror(r));
return 2;
}
return 0;
}
static int store_key(void)
{
u8 prv[1024], pub[1024];
size_t prvsize, pubsize;
int r;
RSA *rsa;
r = read_rsa_privkey(&rsa);
if (r)
return r;
r = encode_private_key(rsa, prv, &prvsize);
if (r)
return r;
r = encode_public_key(rsa, pub, &pubsize);
if (r)
return r;
if (verbose)
printf("Storing private key...\n");
r = select_app_df();
if (r)
return r;
r = update_private_key(prv, prvsize);
if (r)
return r;
if (verbose)
printf("Storing public key...\n");
r = select_app_df();
if (r)
return r;
r = update_public_key(pub, pubsize);
if (r)
return r;
return 0;
}
static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id)
{
char prompt[40], *pin, *puk;
char buf[30], *p = buf;
sc_path_t file_id, path;
sc_file_t *file;
size_t len;
int r;
file_id = *inpath;
if (file_id.len < 2)
return -1;
if (chv == 1)
sc_format_path("I0000", &file_id);
else if (chv == 2)
sc_format_path("I0100", &file_id);
else
return -1;
r = sc_select_file(card, inpath, NULL);
if (r)
return -1;
r = sc_select_file(card, &file_id, NULL);
if (r == 0)
return 0;
sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id);
pin = getpin(prompt);
if (pin == NULL)
return -1;
sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id);
puk = getpin(prompt);
if (puk == NULL) {
free(pin);
return -1;
}
memset(p, 0xFF, 3);
p += 3;
memcpy(p, pin, 8);
p += 8;
*p++ = opt_pin_attempts;
*p++ = opt_pin_attempts;
memcpy(p, puk, 8);
p += 8;
*p++ = opt_puk_attempts;
*p++ = opt_puk_attempts;
len = p - buf;
free(pin);
free(puk);
file = sc_file_new();
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE);
if (inpath->len == 2 && inpath->value[0] == 0x3F &&
inpath->value[1] == 0x00)
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1);
else
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1);
file->size = len;
file->id = (file_id.value[0] << 8) | file_id.value[1];
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r));
return r;
}
path = *inpath;
sc_append_path(&path, &file_id);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r));
return r;
}
r = sc_update_binary(card, 0, (const u8 *) buf, len, 0);
if (r < 0) {
fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r));
return r;
}
return 0;
}
static int create_pin(void)
{
sc_path_t path;
char buf[80];
if (opt_pin_num != 1 && opt_pin_num != 2) {
fprintf(stderr, "Invalid PIN number. Possible values: 1, 2.\n");
return 2;
}
strcpy(buf, "3F00");
if (opt_appdf != NULL)
strlcat(buf, opt_appdf, sizeof buf);
sc_format_path(buf, &path);
return create_pin_file(&path, opt_pin_num, "");
}
int main(int argc, char *argv[])
{
int err = 0, r, c, long_optind = 0;
int action_count = 0;
int do_read_key = 0;
int do_generate_key = 0;
int do_create_key_files = 0;
int do_list_keys = 0;
int do_store_key = 0;
int do_create_pin_file = 0;
sc_context_param_t ctx_param;
while (1) {
c = getopt_long(argc, argv, "P:Vslgc:Rk:r:p:u:e:m:vwa:", options, &long_optind);
if (c == -1)
break;
if (c == '?')
util_print_usage_and_die(app_name, options, option_help, NULL);
switch (c) {
case 'l':
do_list_keys = 1;
action_count++;
break;
case 'P':
do_create_pin_file = 1;
opt_pin_num = atoi(optarg);
action_count++;
break;
case 'R':
do_read_key = 1;
action_count++;
break;
case 'g':
do_generate_key = 1;
action_count++;
break;
case 'c':
do_create_key_files = 1;
opt_key_count = atoi(optarg);
action_count++;
break;
case 's':
do_store_key = 1;
action_count++;
break;
case 'k':
opt_key_num = atoi(optarg);
if (opt_key_num < 1 || opt_key_num > 15) {
fprintf(stderr, "Key number invalid.\n");
exit(2);
}
break;
case 'V':
opt_pin_num = 1;
break;
case 'e':
opt_exponent = atoi(optarg);
break;
case 'm':
opt_mod_length = atoi(optarg);
break;
case 'p':
opt_prkeyf = optarg;
break;
case 'u':
opt_pubkeyf = optarg;
break;
case 'r':
opt_reader = optarg;
break;
case 'v':
verbose++;
break;
case 'w':
opt_wait = 1;
break;
case 'a':
opt_appdf = optarg;
break;
}
}
if (action_count == 0)
util_print_usage_and_die(app_name, options, option_help, NULL);
memset(&ctx_param, 0, sizeof(ctx_param));
ctx_param.ver = 0;
ctx_param.app_name = app_name;
r = sc_context_create(&ctx, &ctx_param);
if (r) {
fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r));
return 1;
}
if (verbose > 1) {
ctx->debug = verbose;
sc_ctx_log_to_file(ctx, "stderr");
}
err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose);
printf("Using card driver: %s\n", card->driver->name);
if (do_create_pin_file) {
if ((err = create_pin()) != 0)
goto end;
action_count--;
}
if (do_create_key_files) {
if ((err = create_key_files()) != 0)
goto end;
action_count--;
}
if (do_generate_key) {
if ((err = generate_key()) != 0)
goto end;
action_count--;
}
if (do_store_key) {
if ((err = store_key()) != 0)
goto end;
action_count--;
}
if (do_list_keys) {
if ((err = list_keys()) != 0)
goto end;
action_count--;
}
if (do_read_key) {
if ((err = read_key()) != 0)
goto end;
action_count--;
}
if (pincode != NULL) {
memset(pincode, 0, 8);
free(pincode);
}
end:
if (card) {
sc_unlock(card);
sc_disconnect_card(card);
}
if (ctx)
sc_release_context(ctx);
return err;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_346_8 |
crossvul-cpp_data_bad_2796_0 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* PACKET - implements raw packet sockets.
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Alan Cox, <gw4pts@gw4pts.ampr.org>
*
* Fixes:
* Alan Cox : verify_area() now used correctly
* Alan Cox : new skbuff lists, look ma no backlogs!
* Alan Cox : tidied skbuff lists.
* Alan Cox : Now uses generic datagram routines I
* added. Also fixed the peek/read crash
* from all old Linux datagram code.
* Alan Cox : Uses the improved datagram code.
* Alan Cox : Added NULL's for socket options.
* Alan Cox : Re-commented the code.
* Alan Cox : Use new kernel side addressing
* Rob Janssen : Correct MTU usage.
* Dave Platt : Counter leaks caused by incorrect
* interrupt locking and some slightly
* dubious gcc output. Can you read
* compiler: it said _VOLATILE_
* Richard Kooijman : Timestamp fixes.
* Alan Cox : New buffers. Use sk->mac.raw.
* Alan Cox : sendmsg/recvmsg support.
* Alan Cox : Protocol setting support
* Alexey Kuznetsov : Untied from IPv4 stack.
* Cyrus Durgin : Fixed kerneld for kmod.
* Michal Ostrowski : Module initialization cleanup.
* Ulises Alonso : Frame number limit removal and
* packet_set_ring memory leak.
* Eric Biederman : Allow for > 8 byte hardware addresses.
* The convention is that longer addresses
* will simply extend the hardware address
* byte arrays at the end of sockaddr_ll
* and packet_mreq.
* Johann Baudy : Added TX RING.
* Chetan Loke : Implemented TPACKET_V3 block abstraction
* layer.
* Copyright (C) 2011, <lokec@ccs.neu.edu>
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/capability.h>
#include <linux/fcntl.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/if_packet.h>
#include <linux/wireless.h>
#include <linux/kernel.h>
#include <linux/kmod.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <net/net_namespace.h>
#include <net/ip.h>
#include <net/protocol.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/uaccess.h>
#include <asm/ioctls.h>
#include <asm/page.h>
#include <asm/cacheflush.h>
#include <asm/io.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/poll.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/if_vlan.h>
#include <linux/virtio_net.h>
#include <linux/errqueue.h>
#include <linux/net_tstamp.h>
#include <linux/percpu.h>
#ifdef CONFIG_INET
#include <net/inet_common.h>
#endif
#include <linux/bpf.h>
#include <net/compat.h>
#include "internal.h"
/*
Assumptions:
- if device has no dev->hard_header routine, it adds and removes ll header
inside itself. In this case ll header is invisible outside of device,
but higher levels still should reserve dev->hard_header_len.
Some devices are enough clever to reallocate skb, when header
will not fit to reserved space (tunnel), another ones are silly
(PPP).
- packet socket receives packets with pulled ll header,
so that SOCK_RAW should push it back.
On receive:
-----------
Incoming, dev->hard_header!=NULL
mac_header -> ll header
data -> data
Outgoing, dev->hard_header!=NULL
mac_header -> ll header
data -> ll header
Incoming, dev->hard_header==NULL
mac_header -> UNKNOWN position. It is very likely, that it points to ll
header. PPP makes it, that is wrong, because introduce
assymetry between rx and tx paths.
data -> data
Outgoing, dev->hard_header==NULL
mac_header -> data. ll header is still not built!
data -> data
Resume
If dev->hard_header==NULL we are unlikely to restore sensible ll header.
On transmit:
------------
dev->hard_header != NULL
mac_header -> ll header
data -> ll header
dev->hard_header == NULL (ll header is added by device, we cannot control it)
mac_header -> data
data -> data
We should set nh.raw on output to correct posistion,
packet classifier depends on it.
*/
/* Private packet socket structures. */
/* identical to struct packet_mreq except it has
* a longer address field.
*/
struct packet_mreq_max {
int mr_ifindex;
unsigned short mr_type;
unsigned short mr_alen;
unsigned char mr_address[MAX_ADDR_LEN];
};
union tpacket_uhdr {
struct tpacket_hdr *h1;
struct tpacket2_hdr *h2;
struct tpacket3_hdr *h3;
void *raw;
};
static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
int closing, int tx_ring);
#define V3_ALIGNMENT (8)
#define BLK_HDR_LEN (ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
#define BLK_PLUS_PRIV(sz_of_priv) \
(BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
#define PGV_FROM_VMALLOC 1
#define BLOCK_STATUS(x) ((x)->hdr.bh1.block_status)
#define BLOCK_NUM_PKTS(x) ((x)->hdr.bh1.num_pkts)
#define BLOCK_O2FP(x) ((x)->hdr.bh1.offset_to_first_pkt)
#define BLOCK_LEN(x) ((x)->hdr.bh1.blk_len)
#define BLOCK_SNUM(x) ((x)->hdr.bh1.seq_num)
#define BLOCK_O2PRIV(x) ((x)->offset_to_priv)
#define BLOCK_PRIV(x) ((void *)((char *)(x) + BLOCK_O2PRIV(x)))
struct packet_sock;
static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev);
static void *packet_previous_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status);
static void packet_increment_head(struct packet_ring_buffer *buff);
static int prb_curr_blk_in_use(struct tpacket_block_desc *);
static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
struct packet_sock *);
static void prb_retire_current_block(struct tpacket_kbdq_core *,
struct packet_sock *, unsigned int status);
static int prb_queue_frozen(struct tpacket_kbdq_core *);
static void prb_open_block(struct tpacket_kbdq_core *,
struct tpacket_block_desc *);
static void prb_retire_rx_blk_timer_expired(unsigned long);
static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *);
static void prb_init_blk_timer(struct packet_sock *,
struct tpacket_kbdq_core *,
void (*func) (unsigned long));
static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
static void prb_clear_rxhash(struct tpacket_kbdq_core *,
struct tpacket3_hdr *);
static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
struct tpacket3_hdr *);
static void packet_flush_mclist(struct sock *sk);
static void packet_pick_tx_queue(struct net_device *dev, struct sk_buff *skb);
struct packet_skb_cb {
union {
struct sockaddr_pkt pkt;
union {
/* Trick: alias skb original length with
* ll.sll_family and ll.protocol in order
* to save room.
*/
unsigned int origlen;
struct sockaddr_ll ll;
};
} sa;
};
#define vio_le() virtio_legacy_is_little_endian()
#define PACKET_SKB_CB(__skb) ((struct packet_skb_cb *)((__skb)->cb))
#define GET_PBDQC_FROM_RB(x) ((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
#define GET_PBLOCK_DESC(x, bid) \
((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
#define GET_CURR_PBLOCK_DESC_FROM_CORE(x) \
((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
#define GET_NEXT_PRB_BLK_NUM(x) \
(((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
((x)->kactive_blk_num+1) : 0)
static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
static void __fanout_link(struct sock *sk, struct packet_sock *po);
static int packet_direct_xmit(struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
struct sk_buff *orig_skb = skb;
struct netdev_queue *txq;
int ret = NETDEV_TX_BUSY;
if (unlikely(!netif_running(dev) ||
!netif_carrier_ok(dev)))
goto drop;
skb = validate_xmit_skb_list(skb, dev);
if (skb != orig_skb)
goto drop;
packet_pick_tx_queue(dev, skb);
txq = skb_get_tx_queue(dev, skb);
local_bh_disable();
HARD_TX_LOCK(dev, txq, smp_processor_id());
if (!netif_xmit_frozen_or_drv_stopped(txq))
ret = netdev_start_xmit(skb, dev, txq, false);
HARD_TX_UNLOCK(dev, txq);
local_bh_enable();
if (!dev_xmit_complete(ret))
kfree_skb(skb);
return ret;
drop:
atomic_long_inc(&dev->tx_dropped);
kfree_skb_list(skb);
return NET_XMIT_DROP;
}
static struct net_device *packet_cached_dev_get(struct packet_sock *po)
{
struct net_device *dev;
rcu_read_lock();
dev = rcu_dereference(po->cached_dev);
if (likely(dev))
dev_hold(dev);
rcu_read_unlock();
return dev;
}
static void packet_cached_dev_assign(struct packet_sock *po,
struct net_device *dev)
{
rcu_assign_pointer(po->cached_dev, dev);
}
static void packet_cached_dev_reset(struct packet_sock *po)
{
RCU_INIT_POINTER(po->cached_dev, NULL);
}
static bool packet_use_direct_xmit(const struct packet_sock *po)
{
return po->xmit == packet_direct_xmit;
}
static u16 __packet_pick_tx_queue(struct net_device *dev, struct sk_buff *skb)
{
return (u16) raw_smp_processor_id() % dev->real_num_tx_queues;
}
static void packet_pick_tx_queue(struct net_device *dev, struct sk_buff *skb)
{
const struct net_device_ops *ops = dev->netdev_ops;
u16 queue_index;
if (ops->ndo_select_queue) {
queue_index = ops->ndo_select_queue(dev, skb, NULL,
__packet_pick_tx_queue);
queue_index = netdev_cap_txqueue(dev, queue_index);
} else {
queue_index = __packet_pick_tx_queue(dev, skb);
}
skb_set_queue_mapping(skb, queue_index);
}
/* register_prot_hook must be invoked with the po->bind_lock held,
* or from a context in which asynchronous accesses to the packet
* socket is not possible (packet_create()).
*/
static void register_prot_hook(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
if (!po->running) {
if (po->fanout)
__fanout_link(sk, po);
else
dev_add_pack(&po->prot_hook);
sock_hold(sk);
po->running = 1;
}
}
/* {,__}unregister_prot_hook() must be invoked with the po->bind_lock
* held. If the sync parameter is true, we will temporarily drop
* the po->bind_lock and do a synchronize_net to make sure no
* asynchronous packet processing paths still refer to the elements
* of po->prot_hook. If the sync parameter is false, it is the
* callers responsibility to take care of this.
*/
static void __unregister_prot_hook(struct sock *sk, bool sync)
{
struct packet_sock *po = pkt_sk(sk);
po->running = 0;
if (po->fanout)
__fanout_unlink(sk, po);
else
__dev_remove_pack(&po->prot_hook);
__sock_put(sk);
if (sync) {
spin_unlock(&po->bind_lock);
synchronize_net();
spin_lock(&po->bind_lock);
}
}
static void unregister_prot_hook(struct sock *sk, bool sync)
{
struct packet_sock *po = pkt_sk(sk);
if (po->running)
__unregister_prot_hook(sk, sync);
}
static inline struct page * __pure pgv_to_page(void *addr)
{
if (is_vmalloc_addr(addr))
return vmalloc_to_page(addr);
return virt_to_page(addr);
}
static void __packet_set_status(struct packet_sock *po, void *frame, int status)
{
union tpacket_uhdr h;
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_status = status;
flush_dcache_page(pgv_to_page(&h.h1->tp_status));
break;
case TPACKET_V2:
h.h2->tp_status = status;
flush_dcache_page(pgv_to_page(&h.h2->tp_status));
break;
case TPACKET_V3:
h.h3->tp_status = status;
flush_dcache_page(pgv_to_page(&h.h3->tp_status));
break;
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
}
smp_wmb();
}
static int __packet_get_status(struct packet_sock *po, void *frame)
{
union tpacket_uhdr h;
smp_rmb();
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
flush_dcache_page(pgv_to_page(&h.h1->tp_status));
return h.h1->tp_status;
case TPACKET_V2:
flush_dcache_page(pgv_to_page(&h.h2->tp_status));
return h.h2->tp_status;
case TPACKET_V3:
flush_dcache_page(pgv_to_page(&h.h3->tp_status));
return h.h3->tp_status;
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
return 0;
}
}
static __u32 tpacket_get_timestamp(struct sk_buff *skb, struct timespec *ts,
unsigned int flags)
{
struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
if (shhwtstamps &&
(flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
ktime_to_timespec_cond(shhwtstamps->hwtstamp, ts))
return TP_STATUS_TS_RAW_HARDWARE;
if (ktime_to_timespec_cond(skb->tstamp, ts))
return TP_STATUS_TS_SOFTWARE;
return 0;
}
static __u32 __packet_set_timestamp(struct packet_sock *po, void *frame,
struct sk_buff *skb)
{
union tpacket_uhdr h;
struct timespec ts;
__u32 ts_status;
if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
return 0;
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_sec = ts.tv_sec;
h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
break;
case TPACKET_V2:
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
break;
case TPACKET_V3:
h.h3->tp_sec = ts.tv_sec;
h.h3->tp_nsec = ts.tv_nsec;
break;
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
}
/* one flush is safe, as both fields always lie on the same cacheline */
flush_dcache_page(pgv_to_page(&h.h1->tp_sec));
smp_wmb();
return ts_status;
}
static void *packet_lookup_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
unsigned int position,
int status)
{
unsigned int pg_vec_pos, frame_offset;
union tpacket_uhdr h;
pg_vec_pos = position / rb->frames_per_block;
frame_offset = position % rb->frames_per_block;
h.raw = rb->pg_vec[pg_vec_pos].buffer +
(frame_offset * rb->frame_size);
if (status != __packet_get_status(po, h.raw))
return NULL;
return h.raw;
}
static void *packet_current_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
return packet_lookup_frame(po, rb, rb->head, status);
}
static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
{
del_timer_sync(&pkc->retire_blk_timer);
}
static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
struct sk_buff_head *rb_queue)
{
struct tpacket_kbdq_core *pkc;
pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
spin_lock_bh(&rb_queue->lock);
pkc->delete_blk_timer = 1;
spin_unlock_bh(&rb_queue->lock);
prb_del_retire_blk_timer(pkc);
}
static void prb_init_blk_timer(struct packet_sock *po,
struct tpacket_kbdq_core *pkc,
void (*func) (unsigned long))
{
init_timer(&pkc->retire_blk_timer);
pkc->retire_blk_timer.data = (long)po;
pkc->retire_blk_timer.function = func;
pkc->retire_blk_timer.expires = jiffies;
}
static void prb_setup_retire_blk_timer(struct packet_sock *po)
{
struct tpacket_kbdq_core *pkc;
pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
prb_init_blk_timer(po, pkc, prb_retire_rx_blk_timer_expired);
}
static int prb_calc_retire_blk_tmo(struct packet_sock *po,
int blk_size_in_bytes)
{
struct net_device *dev;
unsigned int mbits = 0, msec = 0, div = 0, tmo = 0;
struct ethtool_link_ksettings ecmd;
int err;
rtnl_lock();
dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
if (unlikely(!dev)) {
rtnl_unlock();
return DEFAULT_PRB_RETIRE_TOV;
}
err = __ethtool_get_link_ksettings(dev, &ecmd);
rtnl_unlock();
if (!err) {
/*
* If the link speed is so slow you don't really
* need to worry about perf anyways
*/
if (ecmd.base.speed < SPEED_1000 ||
ecmd.base.speed == SPEED_UNKNOWN) {
return DEFAULT_PRB_RETIRE_TOV;
} else {
msec = 1;
div = ecmd.base.speed / 1000;
}
}
mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
if (div)
mbits /= div;
tmo = mbits * msec;
if (div)
return tmo+1;
return tmo;
}
static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
union tpacket_req_u *req_u)
{
p1->feature_req_word = req_u->req3.tp_feature_req_word;
}
static void init_prb_bdqc(struct packet_sock *po,
struct packet_ring_buffer *rb,
struct pgv *pg_vec,
union tpacket_req_u *req_u)
{
struct tpacket_kbdq_core *p1 = GET_PBDQC_FROM_RB(rb);
struct tpacket_block_desc *pbd;
memset(p1, 0x0, sizeof(*p1));
p1->knxt_seq_num = 1;
p1->pkbdq = pg_vec;
pbd = (struct tpacket_block_desc *)pg_vec[0].buffer;
p1->pkblk_start = pg_vec[0].buffer;
p1->kblk_size = req_u->req3.tp_block_size;
p1->knum_blocks = req_u->req3.tp_block_nr;
p1->hdrlen = po->tp_hdrlen;
p1->version = po->tp_version;
p1->last_kactive_blk_num = 0;
po->stats.stats3.tp_freeze_q_cnt = 0;
if (req_u->req3.tp_retire_blk_tov)
p1->retire_blk_tov = req_u->req3.tp_retire_blk_tov;
else
p1->retire_blk_tov = prb_calc_retire_blk_tmo(po,
req_u->req3.tp_block_size);
p1->tov_in_jiffies = msecs_to_jiffies(p1->retire_blk_tov);
p1->blk_sizeof_priv = req_u->req3.tp_sizeof_priv;
p1->max_frame_len = p1->kblk_size - BLK_PLUS_PRIV(p1->blk_sizeof_priv);
prb_init_ft_ops(p1, req_u);
prb_setup_retire_blk_timer(po);
prb_open_block(p1, pbd);
}
/* Do NOT update the last_blk_num first.
* Assumes sk_buff_head lock is held.
*/
static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *pkc)
{
mod_timer(&pkc->retire_blk_timer,
jiffies + pkc->tov_in_jiffies);
pkc->last_kactive_blk_num = pkc->kactive_blk_num;
}
/*
* Timer logic:
* 1) We refresh the timer only when we open a block.
* By doing this we don't waste cycles refreshing the timer
* on packet-by-packet basis.
*
* With a 1MB block-size, on a 1Gbps line, it will take
* i) ~8 ms to fill a block + ii) memcpy etc.
* In this cut we are not accounting for the memcpy time.
*
* So, if the user sets the 'tmo' to 10ms then the timer
* will never fire while the block is still getting filled
* (which is what we want). However, the user could choose
* to close a block early and that's fine.
*
* But when the timer does fire, we check whether or not to refresh it.
* Since the tmo granularity is in msecs, it is not too expensive
* to refresh the timer, lets say every '8' msecs.
* Either the user can set the 'tmo' or we can derive it based on
* a) line-speed and b) block-size.
* prb_calc_retire_blk_tmo() calculates the tmo.
*
*/
static void prb_retire_rx_blk_timer_expired(unsigned long data)
{
struct packet_sock *po = (struct packet_sock *)data;
struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
unsigned int frozen;
struct tpacket_block_desc *pbd;
spin_lock(&po->sk.sk_receive_queue.lock);
frozen = prb_queue_frozen(pkc);
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
if (unlikely(pkc->delete_blk_timer))
goto out;
/* We only need to plug the race when the block is partially filled.
* tpacket_rcv:
* lock(); increment BLOCK_NUM_PKTS; unlock()
* copy_bits() is in progress ...
* timer fires on other cpu:
* we can't retire the current block because copy_bits
* is in progress.
*
*/
if (BLOCK_NUM_PKTS(pbd)) {
while (atomic_read(&pkc->blk_fill_in_prog)) {
/* Waiting for skb_copy_bits to finish... */
cpu_relax();
}
}
if (pkc->last_kactive_blk_num == pkc->kactive_blk_num) {
if (!frozen) {
if (!BLOCK_NUM_PKTS(pbd)) {
/* An empty block. Just refresh the timer. */
goto refresh_timer;
}
prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
if (!prb_dispatch_next_block(pkc, po))
goto refresh_timer;
else
goto out;
} else {
/* Case 1. Queue was frozen because user-space was
* lagging behind.
*/
if (prb_curr_blk_in_use(pbd)) {
/*
* Ok, user-space is still behind.
* So just refresh the timer.
*/
goto refresh_timer;
} else {
/* Case 2. queue was frozen,user-space caught up,
* now the link went idle && the timer fired.
* We don't have a block to close.So we open this
* block and restart the timer.
* opening a block thaws the queue,restarts timer
* Thawing/timer-refresh is a side effect.
*/
prb_open_block(pkc, pbd);
goto out;
}
}
}
refresh_timer:
_prb_refresh_rx_retire_blk_timer(pkc);
out:
spin_unlock(&po->sk.sk_receive_queue.lock);
}
static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1, __u32 status)
{
/* Flush everything minus the block header */
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
u8 *start, *end;
start = (u8 *)pbd1;
/* Skip the block header(we know header WILL fit in 4K) */
start += PAGE_SIZE;
end = (u8 *)PAGE_ALIGN((unsigned long)pkc1->pkblk_end);
for (; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
smp_wmb();
#endif
/* Now update the block status. */
BLOCK_STATUS(pbd1) = status;
/* Flush the block header */
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
start = (u8 *)pbd1;
flush_dcache_page(pgv_to_page(start));
smp_wmb();
#endif
}
/*
* Side effect:
*
* 1) flush the block
* 2) Increment active_blk_num
*
* Note:We DONT refresh the timer on purpose.
* Because almost always the next block will be opened.
*/
static void prb_close_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1,
struct packet_sock *po, unsigned int stat)
{
__u32 status = TP_STATUS_USER | stat;
struct tpacket3_hdr *last_pkt;
struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
struct sock *sk = &po->sk;
if (po->stats.stats3.tp_drops)
status |= TP_STATUS_LOSING;
last_pkt = (struct tpacket3_hdr *)pkc1->prev;
last_pkt->tp_next_offset = 0;
/* Get the ts of the last pkt */
if (BLOCK_NUM_PKTS(pbd1)) {
h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
h1->ts_last_pkt.ts_nsec = last_pkt->tp_nsec;
} else {
/* Ok, we tmo'd - so get the current time.
*
* It shouldn't really happen as we don't close empty
* blocks. See prb_retire_rx_blk_timer_expired().
*/
struct timespec ts;
getnstimeofday(&ts);
h1->ts_last_pkt.ts_sec = ts.tv_sec;
h1->ts_last_pkt.ts_nsec = ts.tv_nsec;
}
smp_wmb();
/* Flush the block */
prb_flush_block(pkc1, pbd1, status);
sk->sk_data_ready(sk);
pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
}
static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
{
pkc->reset_pending_on_curr_blk = 0;
}
/*
* Side effect of opening a block:
*
* 1) prb_queue is thawed.
* 2) retire_blk_timer is refreshed.
*
*/
static void prb_open_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1)
{
struct timespec ts;
struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
smp_rmb();
/* We could have just memset this but we will lose the
* flexibility of making the priv area sticky
*/
BLOCK_SNUM(pbd1) = pkc1->knxt_seq_num++;
BLOCK_NUM_PKTS(pbd1) = 0;
BLOCK_LEN(pbd1) = BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
getnstimeofday(&ts);
h1->ts_first_pkt.ts_sec = ts.tv_sec;
h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
pkc1->pkblk_start = (char *)pbd1;
pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
pbd1->version = pkc1->version;
pkc1->prev = pkc1->nxt_offset;
pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
prb_thaw_queue(pkc1);
_prb_refresh_rx_retire_blk_timer(pkc1);
smp_wmb();
}
/*
* Queue freeze logic:
* 1) Assume tp_block_nr = 8 blocks.
* 2) At time 't0', user opens Rx ring.
* 3) Some time past 't0', kernel starts filling blocks starting from 0 .. 7
* 4) user-space is either sleeping or processing block '0'.
* 5) tpacket_rcv is currently filling block '7', since there is no space left,
* it will close block-7,loop around and try to fill block '0'.
* call-flow:
* __packet_lookup_frame_in_block
* prb_retire_current_block()
* prb_dispatch_next_block()
* |->(BLOCK_STATUS == USER) evaluates to true
* 5.1) Since block-0 is currently in-use, we just freeze the queue.
* 6) Now there are two cases:
* 6.1) Link goes idle right after the queue is frozen.
* But remember, the last open_block() refreshed the timer.
* When this timer expires,it will refresh itself so that we can
* re-open block-0 in near future.
* 6.2) Link is busy and keeps on receiving packets. This is a simple
* case and __packet_lookup_frame_in_block will check if block-0
* is free and can now be re-used.
*/
static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
struct packet_sock *po)
{
pkc->reset_pending_on_curr_blk = 1;
po->stats.stats3.tp_freeze_q_cnt++;
}
#define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
/*
* If the next block is free then we will dispatch it
* and return a good offset.
* Else, we will freeze the queue.
* So, caller must check the return value.
*/
static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
struct packet_sock *po)
{
struct tpacket_block_desc *pbd;
smp_rmb();
/* 1. Get current block num */
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* 2. If this block is currently in_use then freeze the queue */
if (TP_STATUS_USER & BLOCK_STATUS(pbd)) {
prb_freeze_queue(pkc, po);
return NULL;
}
/*
* 3.
* open this block and return the offset where the first packet
* needs to get stored.
*/
prb_open_block(pkc, pbd);
return (void *)pkc->nxt_offset;
}
static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
struct packet_sock *po, unsigned int status)
{
struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* retire/close the current block */
if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
/*
* Plug the case where copy_bits() is in progress on
* cpu-0 and tpacket_rcv() got invoked on cpu-1, didn't
* have space to copy the pkt in the current block and
* called prb_retire_current_block()
*
* We don't need to worry about the TMO case because
* the timer-handler already handled this case.
*/
if (!(status & TP_STATUS_BLK_TMO)) {
while (atomic_read(&pkc->blk_fill_in_prog)) {
/* Waiting for skb_copy_bits to finish... */
cpu_relax();
}
}
prb_close_block(pkc, pbd, po, status);
return;
}
}
static int prb_curr_blk_in_use(struct tpacket_block_desc *pbd)
{
return TP_STATUS_USER & BLOCK_STATUS(pbd);
}
static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
{
return pkc->reset_pending_on_curr_blk;
}
static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
{
struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
atomic_dec(&pkc->blk_fill_in_prog);
}
static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
ppd->hv1.tp_rxhash = skb_get_hash(pkc->skb);
}
static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
ppd->hv1.tp_rxhash = 0;
}
static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
if (skb_vlan_tag_present(pkc->skb)) {
ppd->hv1.tp_vlan_tci = skb_vlan_tag_get(pkc->skb);
ppd->hv1.tp_vlan_tpid = ntohs(pkc->skb->vlan_proto);
ppd->tp_status = TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
} else {
ppd->hv1.tp_vlan_tci = 0;
ppd->hv1.tp_vlan_tpid = 0;
ppd->tp_status = TP_STATUS_AVAILABLE;
}
}
static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
ppd->hv1.tp_padding = 0;
prb_fill_vlan_info(pkc, ppd);
if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
prb_fill_rxhash(pkc, ppd);
else
prb_clear_rxhash(pkc, ppd);
}
static void prb_fill_curr_block(char *curr,
struct tpacket_kbdq_core *pkc,
struct tpacket_block_desc *pbd,
unsigned int len)
{
struct tpacket3_hdr *ppd;
ppd = (struct tpacket3_hdr *)curr;
ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
pkc->prev = curr;
pkc->nxt_offset += TOTAL_PKT_LEN_INCL_ALIGN(len);
BLOCK_LEN(pbd) += TOTAL_PKT_LEN_INCL_ALIGN(len);
BLOCK_NUM_PKTS(pbd) += 1;
atomic_inc(&pkc->blk_fill_in_prog);
prb_run_all_ft_ops(pkc, ppd);
}
/* Assumes caller has the sk->rx_queue.lock */
static void *__packet_lookup_frame_in_block(struct packet_sock *po,
struct sk_buff *skb,
int status,
unsigned int len
)
{
struct tpacket_kbdq_core *pkc;
struct tpacket_block_desc *pbd;
char *curr, *end;
pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* Queue is frozen when user space is lagging behind */
if (prb_queue_frozen(pkc)) {
/*
* Check if that last block which caused the queue to freeze,
* is still in_use by user-space.
*/
if (prb_curr_blk_in_use(pbd)) {
/* Can't record this packet */
return NULL;
} else {
/*
* Ok, the block was released by user-space.
* Now let's open that block.
* opening a block also thaws the queue.
* Thawing is a side effect.
*/
prb_open_block(pkc, pbd);
}
}
smp_mb();
curr = pkc->nxt_offset;
pkc->skb = skb;
end = (char *)pbd + pkc->kblk_size;
/* first try the current block */
if (curr+TOTAL_PKT_LEN_INCL_ALIGN(len) < end) {
prb_fill_curr_block(curr, pkc, pbd, len);
return (void *)curr;
}
/* Ok, close the current block */
prb_retire_current_block(pkc, po, 0);
/* Now, try to dispatch the next block */
curr = (char *)prb_dispatch_next_block(pkc, po);
if (curr) {
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
prb_fill_curr_block(curr, pkc, pbd, len);
return (void *)curr;
}
/*
* No free blocks are available.user_space hasn't caught up yet.
* Queue was just frozen and now this packet will get dropped.
*/
return NULL;
}
static void *packet_current_rx_frame(struct packet_sock *po,
struct sk_buff *skb,
int status, unsigned int len)
{
char *curr = NULL;
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
curr = packet_lookup_frame(po, &po->rx_ring,
po->rx_ring.head, status);
return curr;
case TPACKET_V3:
return __packet_lookup_frame_in_block(po, skb, status, len);
default:
WARN(1, "TPACKET version not supported\n");
BUG();
return NULL;
}
}
static void *prb_lookup_block(struct packet_sock *po,
struct packet_ring_buffer *rb,
unsigned int idx,
int status)
{
struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
if (status != BLOCK_STATUS(pbd))
return NULL;
return pbd;
}
static int prb_previous_blk_num(struct packet_ring_buffer *rb)
{
unsigned int prev;
if (rb->prb_bdqc.kactive_blk_num)
prev = rb->prb_bdqc.kactive_blk_num-1;
else
prev = rb->prb_bdqc.knum_blocks-1;
return prev;
}
/* Assumes caller has held the rx_queue.lock */
static void *__prb_previous_block(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
unsigned int previous = prb_previous_blk_num(rb);
return prb_lookup_block(po, rb, previous, status);
}
static void *packet_previous_rx_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
if (po->tp_version <= TPACKET_V2)
return packet_previous_frame(po, rb, status);
return __prb_previous_block(po, rb, status);
}
static void packet_increment_rx_head(struct packet_sock *po,
struct packet_ring_buffer *rb)
{
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
return packet_increment_head(rb);
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
return;
}
}
static void *packet_previous_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
return packet_lookup_frame(po, rb, previous, status);
}
static void packet_increment_head(struct packet_ring_buffer *buff)
{
buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
}
static void packet_inc_pending(struct packet_ring_buffer *rb)
{
this_cpu_inc(*rb->pending_refcnt);
}
static void packet_dec_pending(struct packet_ring_buffer *rb)
{
this_cpu_dec(*rb->pending_refcnt);
}
static unsigned int packet_read_pending(const struct packet_ring_buffer *rb)
{
unsigned int refcnt = 0;
int cpu;
/* We don't use pending refcount in rx_ring. */
if (rb->pending_refcnt == NULL)
return 0;
for_each_possible_cpu(cpu)
refcnt += *per_cpu_ptr(rb->pending_refcnt, cpu);
return refcnt;
}
static int packet_alloc_pending(struct packet_sock *po)
{
po->rx_ring.pending_refcnt = NULL;
po->tx_ring.pending_refcnt = alloc_percpu(unsigned int);
if (unlikely(po->tx_ring.pending_refcnt == NULL))
return -ENOBUFS;
return 0;
}
static void packet_free_pending(struct packet_sock *po)
{
free_percpu(po->tx_ring.pending_refcnt);
}
#define ROOM_POW_OFF 2
#define ROOM_NONE 0x0
#define ROOM_LOW 0x1
#define ROOM_NORMAL 0x2
static bool __tpacket_has_room(struct packet_sock *po, int pow_off)
{
int idx, len;
len = po->rx_ring.frame_max + 1;
idx = po->rx_ring.head;
if (pow_off)
idx += len >> pow_off;
if (idx >= len)
idx -= len;
return packet_lookup_frame(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
}
static bool __tpacket_v3_has_room(struct packet_sock *po, int pow_off)
{
int idx, len;
len = po->rx_ring.prb_bdqc.knum_blocks;
idx = po->rx_ring.prb_bdqc.kactive_blk_num;
if (pow_off)
idx += len >> pow_off;
if (idx >= len)
idx -= len;
return prb_lookup_block(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
}
static int __packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
{
struct sock *sk = &po->sk;
int ret = ROOM_NONE;
if (po->prot_hook.func != tpacket_rcv) {
int avail = sk->sk_rcvbuf - atomic_read(&sk->sk_rmem_alloc)
- (skb ? skb->truesize : 0);
if (avail > (sk->sk_rcvbuf >> ROOM_POW_OFF))
return ROOM_NORMAL;
else if (avail > 0)
return ROOM_LOW;
else
return ROOM_NONE;
}
if (po->tp_version == TPACKET_V3) {
if (__tpacket_v3_has_room(po, ROOM_POW_OFF))
ret = ROOM_NORMAL;
else if (__tpacket_v3_has_room(po, 0))
ret = ROOM_LOW;
} else {
if (__tpacket_has_room(po, ROOM_POW_OFF))
ret = ROOM_NORMAL;
else if (__tpacket_has_room(po, 0))
ret = ROOM_LOW;
}
return ret;
}
static int packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
{
int ret;
bool has_room;
spin_lock_bh(&po->sk.sk_receive_queue.lock);
ret = __packet_rcv_has_room(po, skb);
has_room = ret == ROOM_NORMAL;
if (po->pressure == has_room)
po->pressure = !has_room;
spin_unlock_bh(&po->sk.sk_receive_queue.lock);
return ret;
}
static void packet_sock_destruct(struct sock *sk)
{
skb_queue_purge(&sk->sk_error_queue);
WARN_ON(atomic_read(&sk->sk_rmem_alloc));
WARN_ON(refcount_read(&sk->sk_wmem_alloc));
if (!sock_flag(sk, SOCK_DEAD)) {
pr_err("Attempt to release alive packet socket: %p\n", sk);
return;
}
sk_refcnt_debug_dec(sk);
}
static bool fanout_flow_is_huge(struct packet_sock *po, struct sk_buff *skb)
{
u32 rxhash;
int i, count = 0;
rxhash = skb_get_hash(skb);
for (i = 0; i < ROLLOVER_HLEN; i++)
if (po->rollover->history[i] == rxhash)
count++;
po->rollover->history[prandom_u32() % ROLLOVER_HLEN] = rxhash;
return count > (ROLLOVER_HLEN >> 1);
}
static unsigned int fanout_demux_hash(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return reciprocal_scale(__skb_get_hash_symmetric(skb), num);
}
static unsigned int fanout_demux_lb(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
unsigned int val = atomic_inc_return(&f->rr_cur);
return val % num;
}
static unsigned int fanout_demux_cpu(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return smp_processor_id() % num;
}
static unsigned int fanout_demux_rnd(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return prandom_u32_max(num);
}
static unsigned int fanout_demux_rollover(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int idx, bool try_self,
unsigned int num)
{
struct packet_sock *po, *po_next, *po_skip = NULL;
unsigned int i, j, room = ROOM_NONE;
po = pkt_sk(f->arr[idx]);
if (try_self) {
room = packet_rcv_has_room(po, skb);
if (room == ROOM_NORMAL ||
(room == ROOM_LOW && !fanout_flow_is_huge(po, skb)))
return idx;
po_skip = po;
}
i = j = min_t(int, po->rollover->sock, num - 1);
do {
po_next = pkt_sk(f->arr[i]);
if (po_next != po_skip && !po_next->pressure &&
packet_rcv_has_room(po_next, skb) == ROOM_NORMAL) {
if (i != j)
po->rollover->sock = i;
atomic_long_inc(&po->rollover->num);
if (room == ROOM_LOW)
atomic_long_inc(&po->rollover->num_huge);
return i;
}
if (++i == num)
i = 0;
} while (i != j);
atomic_long_inc(&po->rollover->num_failed);
return idx;
}
static unsigned int fanout_demux_qm(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return skb_get_queue_mapping(skb) % num;
}
static unsigned int fanout_demux_bpf(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
struct bpf_prog *prog;
unsigned int ret = 0;
rcu_read_lock();
prog = rcu_dereference(f->bpf_prog);
if (prog)
ret = bpf_prog_run_clear_cb(prog, skb) % num;
rcu_read_unlock();
return ret;
}
static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
{
return f->flags & (flag >> 8);
}
static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct packet_fanout *f = pt->af_packet_priv;
unsigned int num = READ_ONCE(f->num_members);
struct net *net = read_pnet(&f->net);
struct packet_sock *po;
unsigned int idx;
if (!net_eq(dev_net(dev), net) || !num) {
kfree_skb(skb);
return 0;
}
if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
skb = ip_check_defrag(net, skb, IP_DEFRAG_AF_PACKET);
if (!skb)
return 0;
}
switch (f->type) {
case PACKET_FANOUT_HASH:
default:
idx = fanout_demux_hash(f, skb, num);
break;
case PACKET_FANOUT_LB:
idx = fanout_demux_lb(f, skb, num);
break;
case PACKET_FANOUT_CPU:
idx = fanout_demux_cpu(f, skb, num);
break;
case PACKET_FANOUT_RND:
idx = fanout_demux_rnd(f, skb, num);
break;
case PACKET_FANOUT_QM:
idx = fanout_demux_qm(f, skb, num);
break;
case PACKET_FANOUT_ROLLOVER:
idx = fanout_demux_rollover(f, skb, 0, false, num);
break;
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
idx = fanout_demux_bpf(f, skb, num);
break;
}
if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER))
idx = fanout_demux_rollover(f, skb, idx, true, num);
po = pkt_sk(f->arr[idx]);
return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
}
DEFINE_MUTEX(fanout_mutex);
EXPORT_SYMBOL_GPL(fanout_mutex);
static LIST_HEAD(fanout_list);
static u16 fanout_next_id;
static void __fanout_link(struct sock *sk, struct packet_sock *po)
{
struct packet_fanout *f = po->fanout;
spin_lock(&f->lock);
f->arr[f->num_members] = sk;
smp_wmb();
f->num_members++;
if (f->num_members == 1)
dev_add_pack(&f->prot_hook);
spin_unlock(&f->lock);
}
static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
{
struct packet_fanout *f = po->fanout;
int i;
spin_lock(&f->lock);
for (i = 0; i < f->num_members; i++) {
if (f->arr[i] == sk)
break;
}
BUG_ON(i >= f->num_members);
f->arr[i] = f->arr[f->num_members - 1];
f->num_members--;
if (f->num_members == 0)
__dev_remove_pack(&f->prot_hook);
spin_unlock(&f->lock);
}
static bool match_fanout_group(struct packet_type *ptype, struct sock *sk)
{
if (sk->sk_family != PF_PACKET)
return false;
return ptype->af_packet_priv == pkt_sk(sk)->fanout;
}
static void fanout_init_data(struct packet_fanout *f)
{
switch (f->type) {
case PACKET_FANOUT_LB:
atomic_set(&f->rr_cur, 0);
break;
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
RCU_INIT_POINTER(f->bpf_prog, NULL);
break;
}
}
static void __fanout_set_data_bpf(struct packet_fanout *f, struct bpf_prog *new)
{
struct bpf_prog *old;
spin_lock(&f->lock);
old = rcu_dereference_protected(f->bpf_prog, lockdep_is_held(&f->lock));
rcu_assign_pointer(f->bpf_prog, new);
spin_unlock(&f->lock);
if (old) {
synchronize_net();
bpf_prog_destroy(old);
}
}
static int fanout_set_data_cbpf(struct packet_sock *po, char __user *data,
unsigned int len)
{
struct bpf_prog *new;
struct sock_fprog fprog;
int ret;
if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
return -EPERM;
if (len != sizeof(fprog))
return -EINVAL;
if (copy_from_user(&fprog, data, len))
return -EFAULT;
ret = bpf_prog_create_from_user(&new, &fprog, NULL, false);
if (ret)
return ret;
__fanout_set_data_bpf(po->fanout, new);
return 0;
}
static int fanout_set_data_ebpf(struct packet_sock *po, char __user *data,
unsigned int len)
{
struct bpf_prog *new;
u32 fd;
if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
return -EPERM;
if (len != sizeof(fd))
return -EINVAL;
if (copy_from_user(&fd, data, len))
return -EFAULT;
new = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
if (IS_ERR(new))
return PTR_ERR(new);
__fanout_set_data_bpf(po->fanout, new);
return 0;
}
static int fanout_set_data(struct packet_sock *po, char __user *data,
unsigned int len)
{
switch (po->fanout->type) {
case PACKET_FANOUT_CBPF:
return fanout_set_data_cbpf(po, data, len);
case PACKET_FANOUT_EBPF:
return fanout_set_data_ebpf(po, data, len);
default:
return -EINVAL;
};
}
static void fanout_release_data(struct packet_fanout *f)
{
switch (f->type) {
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
__fanout_set_data_bpf(f, NULL);
};
}
static bool __fanout_id_is_free(struct sock *sk, u16 candidate_id)
{
struct packet_fanout *f;
list_for_each_entry(f, &fanout_list, list) {
if (f->id == candidate_id &&
read_pnet(&f->net) == sock_net(sk)) {
return false;
}
}
return true;
}
static bool fanout_find_new_id(struct sock *sk, u16 *new_id)
{
u16 id = fanout_next_id;
do {
if (__fanout_id_is_free(sk, id)) {
*new_id = id;
fanout_next_id = id + 1;
return true;
}
id++;
} while (id != fanout_next_id);
return false;
}
static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
{
struct packet_rollover *rollover = NULL;
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f, *match;
u8 type = type_flags & 0xff;
u8 flags = type_flags >> 8;
int err;
switch (type) {
case PACKET_FANOUT_ROLLOVER:
if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
return -EINVAL;
case PACKET_FANOUT_HASH:
case PACKET_FANOUT_LB:
case PACKET_FANOUT_CPU:
case PACKET_FANOUT_RND:
case PACKET_FANOUT_QM:
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
break;
default:
return -EINVAL;
}
mutex_lock(&fanout_mutex);
err = -EINVAL;
if (!po->running)
goto out;
err = -EALREADY;
if (po->fanout)
goto out;
if (type == PACKET_FANOUT_ROLLOVER ||
(type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
err = -ENOMEM;
rollover = kzalloc(sizeof(*rollover), GFP_KERNEL);
if (!rollover)
goto out;
atomic_long_set(&rollover->num, 0);
atomic_long_set(&rollover->num_huge, 0);
atomic_long_set(&rollover->num_failed, 0);
po->rollover = rollover;
}
if (type_flags & PACKET_FANOUT_FLAG_UNIQUEID) {
if (id != 0) {
err = -EINVAL;
goto out;
}
if (!fanout_find_new_id(sk, &id)) {
err = -ENOMEM;
goto out;
}
/* ephemeral flag for the first socket in the group: drop it */
flags &= ~(PACKET_FANOUT_FLAG_UNIQUEID >> 8);
}
match = NULL;
list_for_each_entry(f, &fanout_list, list) {
if (f->id == id &&
read_pnet(&f->net) == sock_net(sk)) {
match = f;
break;
}
}
err = -EINVAL;
if (match && match->flags != flags)
goto out;
if (!match) {
err = -ENOMEM;
match = kzalloc(sizeof(*match), GFP_KERNEL);
if (!match)
goto out;
write_pnet(&match->net, sock_net(sk));
match->id = id;
match->type = type;
match->flags = flags;
INIT_LIST_HEAD(&match->list);
spin_lock_init(&match->lock);
refcount_set(&match->sk_ref, 0);
fanout_init_data(match);
match->prot_hook.type = po->prot_hook.type;
match->prot_hook.dev = po->prot_hook.dev;
match->prot_hook.func = packet_rcv_fanout;
match->prot_hook.af_packet_priv = match;
match->prot_hook.id_match = match_fanout_group;
list_add(&match->list, &fanout_list);
}
err = -EINVAL;
if (match->type == type &&
match->prot_hook.type == po->prot_hook.type &&
match->prot_hook.dev == po->prot_hook.dev) {
err = -ENOSPC;
if (refcount_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
__dev_remove_pack(&po->prot_hook);
po->fanout = match;
refcount_set(&match->sk_ref, refcount_read(&match->sk_ref) + 1);
__fanout_link(sk, po);
err = 0;
}
}
out:
if (err && rollover) {
kfree(rollover);
po->rollover = NULL;
}
mutex_unlock(&fanout_mutex);
return err;
}
/* If pkt_sk(sk)->fanout->sk_ref is zero, this function removes
* pkt_sk(sk)->fanout from fanout_list and returns pkt_sk(sk)->fanout.
* It is the responsibility of the caller to call fanout_release_data() and
* free the returned packet_fanout (after synchronize_net())
*/
static struct packet_fanout *fanout_release(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f;
mutex_lock(&fanout_mutex);
f = po->fanout;
if (f) {
po->fanout = NULL;
if (refcount_dec_and_test(&f->sk_ref))
list_del(&f->list);
else
f = NULL;
if (po->rollover)
kfree_rcu(po->rollover, rcu);
}
mutex_unlock(&fanout_mutex);
return f;
}
static bool packet_extra_vlan_len_allowed(const struct net_device *dev,
struct sk_buff *skb)
{
/* Earlier code assumed this would be a VLAN pkt, double-check
* this now that we have the actual packet in hand. We can only
* do this check on Ethernet devices.
*/
if (unlikely(dev->type != ARPHRD_ETHER))
return false;
skb_reset_mac_header(skb);
return likely(eth_hdr(skb)->h_proto == htons(ETH_P_8021Q));
}
static const struct proto_ops packet_ops;
static const struct proto_ops packet_ops_spkt;
static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct sockaddr_pkt *spkt;
/*
* When we registered the protocol we saved the socket in the data
* field for just this event.
*/
sk = pt->af_packet_priv;
/*
* Yank back the headers [hope the device set this
* right or kerboom...]
*
* Incoming packets have ll header pulled,
* push it back.
*
* For outgoing ones skb->data == skb_mac_header(skb)
* so that this procedure is noop.
*/
if (skb->pkt_type == PACKET_LOOPBACK)
goto out;
if (!net_eq(dev_net(dev), sock_net(sk)))
goto out;
skb = skb_share_check(skb, GFP_ATOMIC);
if (skb == NULL)
goto oom;
/* drop any routing info */
skb_dst_drop(skb);
/* drop conntrack reference */
nf_reset(skb);
spkt = &PACKET_SKB_CB(skb)->sa.pkt;
skb_push(skb, skb->data - skb_mac_header(skb));
/*
* The SOCK_PACKET socket receives _all_ frames.
*/
spkt->spkt_family = dev->type;
strlcpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
spkt->spkt_protocol = skb->protocol;
/*
* Charge the memory to the socket. This is done specifically
* to prevent sockets using all the memory up.
*/
if (sock_queue_rcv_skb(sk, skb) == 0)
return 0;
out:
kfree_skb(skb);
oom:
return 0;
}
/*
* Output a raw packet to a device layer. This bypasses all the other
* protocol layers and you must therefore supply it with a complete frame
*/
static int packet_sendmsg_spkt(struct socket *sock, struct msghdr *msg,
size_t len)
{
struct sock *sk = sock->sk;
DECLARE_SOCKADDR(struct sockaddr_pkt *, saddr, msg->msg_name);
struct sk_buff *skb = NULL;
struct net_device *dev;
struct sockcm_cookie sockc;
__be16 proto = 0;
int err;
int extra_len = 0;
/*
* Get and verify the address.
*/
if (saddr) {
if (msg->msg_namelen < sizeof(struct sockaddr))
return -EINVAL;
if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
proto = saddr->spkt_protocol;
} else
return -ENOTCONN; /* SOCK_PACKET must be sent giving an address */
/*
* Find the device first to size check it
*/
saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
retry:
rcu_read_lock();
dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
err = -ENODEV;
if (dev == NULL)
goto out_unlock;
err = -ENETDOWN;
if (!(dev->flags & IFF_UP))
goto out_unlock;
/*
* You may not queue a frame bigger than the mtu. This is the lowest level
* raw protocol and you must do your own fragmentation at this level.
*/
if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
if (!netif_supports_nofcs(dev)) {
err = -EPROTONOSUPPORT;
goto out_unlock;
}
extra_len = 4; /* We're doing our own CRC */
}
err = -EMSGSIZE;
if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
goto out_unlock;
if (!skb) {
size_t reserved = LL_RESERVED_SPACE(dev);
int tlen = dev->needed_tailroom;
unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
rcu_read_unlock();
skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
if (skb == NULL)
return -ENOBUFS;
/* FIXME: Save some space for broken drivers that write a hard
* header at transmission time by themselves. PPP is the notable
* one here. This should really be fixed at the driver level.
*/
skb_reserve(skb, reserved);
skb_reset_network_header(skb);
/* Try to align data part correctly */
if (hhlen) {
skb->data -= hhlen;
skb->tail -= hhlen;
if (len < hhlen)
skb_reset_network_header(skb);
}
err = memcpy_from_msg(skb_put(skb, len), msg, len);
if (err)
goto out_free;
goto retry;
}
if (!dev_validate_header(dev, skb->data, len)) {
err = -EINVAL;
goto out_unlock;
}
if (len > (dev->mtu + dev->hard_header_len + extra_len) &&
!packet_extra_vlan_len_allowed(dev, skb)) {
err = -EMSGSIZE;
goto out_unlock;
}
sockc.tsflags = sk->sk_tsflags;
if (msg->msg_controllen) {
err = sock_cmsg_send(sk, msg, &sockc);
if (unlikely(err))
goto out_unlock;
}
skb->protocol = proto;
skb->dev = dev;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
sock_tx_timestamp(sk, sockc.tsflags, &skb_shinfo(skb)->tx_flags);
if (unlikely(extra_len == 4))
skb->no_fcs = 1;
skb_probe_transport_header(skb, 0);
dev_queue_xmit(skb);
rcu_read_unlock();
return len;
out_unlock:
rcu_read_unlock();
out_free:
kfree_skb(skb);
return err;
}
static unsigned int run_filter(struct sk_buff *skb,
const struct sock *sk,
unsigned int res)
{
struct sk_filter *filter;
rcu_read_lock();
filter = rcu_dereference(sk->sk_filter);
if (filter != NULL)
res = bpf_prog_run_clear_cb(filter->prog, skb);
rcu_read_unlock();
return res;
}
static int packet_rcv_vnet(struct msghdr *msg, const struct sk_buff *skb,
size_t *len)
{
struct virtio_net_hdr vnet_hdr;
if (*len < sizeof(vnet_hdr))
return -EINVAL;
*len -= sizeof(vnet_hdr);
if (virtio_net_hdr_from_skb(skb, &vnet_hdr, vio_le(), true))
return -EINVAL;
return memcpy_to_msg(msg, (void *)&vnet_hdr, sizeof(vnet_hdr));
}
/*
* This function makes lazy skb cloning in hope that most of packets
* are discarded by BPF.
*
* Note tricky part: we DO mangle shared skb! skb->data, skb->len
* and skb->cb are mangled. It works because (and until) packets
* falling here are owned by current CPU. Output packets are cloned
* by dev_queue_xmit_nit(), input packets are processed by net_bh
* sequencially, so that if we return skb to original state on exit,
* we will not harm anyone.
*/
static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct sockaddr_ll *sll;
struct packet_sock *po;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
bool is_drop_n_account = false;
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
skb->dev = dev;
if (dev->header_ops) {
/* The device has an explicit notion of ll header,
* exported to higher levels.
*
* Otherwise, the device hides details of its frame
* structure, so that corresponding packet head is
* never delivered to user.
*/
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (snaplen > res)
snaplen = res;
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
goto drop_n_acct;
if (skb_shared(skb)) {
struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
if (nskb == NULL)
goto drop_n_acct;
if (skb_head != skb->data) {
skb->data = skb_head;
skb->len = skb_len;
}
consume_skb(skb);
skb = nskb;
}
sock_skb_cb_check_size(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8);
sll = &PACKET_SKB_CB(skb)->sa.ll;
sll->sll_hatype = dev->type;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
/* sll->sll_family and sll->sll_protocol are set in packet_recvmsg().
* Use their space for storing the original skb length.
*/
PACKET_SKB_CB(skb)->sa.origlen = skb->len;
if (pskb_trim(skb, snaplen))
goto drop_n_acct;
skb_set_owner_r(skb, sk);
skb->dev = NULL;
skb_dst_drop(skb);
/* drop conntrack reference */
nf_reset(skb);
spin_lock(&sk->sk_receive_queue.lock);
po->stats.stats1.tp_packets++;
sock_skb_set_dropcount(sk, skb);
__skb_queue_tail(&sk->sk_receive_queue, skb);
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk);
return 0;
drop_n_acct:
is_drop_n_account = true;
spin_lock(&sk->sk_receive_queue.lock);
po->stats.stats1.tp_drops++;
atomic_inc(&sk->sk_drops);
spin_unlock(&sk->sk_receive_queue.lock);
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
if (!is_drop_n_account)
consume_skb(skb);
else
kfree_skb(skb);
return 0;
}
static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct packet_sock *po;
struct sockaddr_ll *sll;
union tpacket_uhdr h;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
unsigned long status = TP_STATUS_USER;
unsigned short macoff, netoff, hdrlen;
struct sk_buff *copy_skb = NULL;
struct timespec ts;
__u32 ts_status;
bool is_drop_n_account = false;
/* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.
* We may add members to them until current aligned size without forcing
* userspace to call getsockopt(..., PACKET_HDRLEN, ...).
*/
BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);
BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
if (dev->header_ops) {
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (skb->ip_summed == CHECKSUM_PARTIAL)
status |= TP_STATUS_CSUMNOTREADY;
else if (skb->pkt_type != PACKET_OUTGOING &&
(skb->ip_summed == CHECKSUM_COMPLETE ||
skb_csum_unnecessary(skb)))
status |= TP_STATUS_CSUM_VALID;
if (snaplen > res)
snaplen = res;
if (sk->sk_type == SOCK_DGRAM) {
macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
po->tp_reserve;
} else {
unsigned int maclen = skb_network_offset(skb);
netoff = TPACKET_ALIGN(po->tp_hdrlen +
(maclen < 16 ? 16 : maclen)) +
po->tp_reserve;
if (po->has_vnet_hdr)
netoff += sizeof(struct virtio_net_hdr);
macoff = netoff - maclen;
}
if (po->tp_version <= TPACKET_V2) {
if (macoff + snaplen > po->rx_ring.frame_size) {
if (po->copy_thresh &&
atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
if (skb_shared(skb)) {
copy_skb = skb_clone(skb, GFP_ATOMIC);
} else {
copy_skb = skb_get(skb);
skb_head = skb->data;
}
if (copy_skb)
skb_set_owner_r(copy_skb, sk);
}
snaplen = po->rx_ring.frame_size - macoff;
if ((int)snaplen < 0)
snaplen = 0;
}
} else if (unlikely(macoff + snaplen >
GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {
u32 nval;
nval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;
pr_err_once("tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\n",
snaplen, nval, macoff);
snaplen = nval;
if (unlikely((int)snaplen < 0)) {
snaplen = 0;
macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;
}
}
spin_lock(&sk->sk_receive_queue.lock);
h.raw = packet_current_rx_frame(po, skb,
TP_STATUS_KERNEL, (macoff+snaplen));
if (!h.raw)
goto drop_n_account;
if (po->tp_version <= TPACKET_V2) {
packet_increment_rx_head(po, &po->rx_ring);
/*
* LOSING will be reported till you read the stats,
* because it's COR - Clear On Read.
* Anyways, moving it for V1/V2 only as V3 doesn't need this
* at packet level.
*/
if (po->stats.stats1.tp_drops)
status |= TP_STATUS_LOSING;
}
po->stats.stats1.tp_packets++;
if (copy_skb) {
status |= TP_STATUS_COPY;
__skb_queue_tail(&sk->sk_receive_queue, copy_skb);
}
spin_unlock(&sk->sk_receive_queue.lock);
if (po->has_vnet_hdr) {
if (virtio_net_hdr_from_skb(skb, h.raw + macoff -
sizeof(struct virtio_net_hdr),
vio_le(), true)) {
spin_lock(&sk->sk_receive_queue.lock);
goto drop_n_account;
}
}
skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
getnstimeofday(&ts);
status |= ts_status;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_len = skb->len;
h.h1->tp_snaplen = snaplen;
h.h1->tp_mac = macoff;
h.h1->tp_net = netoff;
h.h1->tp_sec = ts.tv_sec;
h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
hdrlen = sizeof(*h.h1);
break;
case TPACKET_V2:
h.h2->tp_len = skb->len;
h.h2->tp_snaplen = snaplen;
h.h2->tp_mac = macoff;
h.h2->tp_net = netoff;
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
if (skb_vlan_tag_present(skb)) {
h.h2->tp_vlan_tci = skb_vlan_tag_get(skb);
h.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);
status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
} else {
h.h2->tp_vlan_tci = 0;
h.h2->tp_vlan_tpid = 0;
}
memset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));
hdrlen = sizeof(*h.h2);
break;
case TPACKET_V3:
/* tp_nxt_offset,vlan are already populated above.
* So DONT clear those fields here
*/
h.h3->tp_status |= status;
h.h3->tp_len = skb->len;
h.h3->tp_snaplen = snaplen;
h.h3->tp_mac = macoff;
h.h3->tp_net = netoff;
h.h3->tp_sec = ts.tv_sec;
h.h3->tp_nsec = ts.tv_nsec;
memset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));
hdrlen = sizeof(*h.h3);
break;
default:
BUG();
}
sll = h.raw + TPACKET_ALIGN(hdrlen);
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
sll->sll_family = AF_PACKET;
sll->sll_hatype = dev->type;
sll->sll_protocol = skb->protocol;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
smp_mb();
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
if (po->tp_version <= TPACKET_V2) {
u8 *start, *end;
end = (u8 *) PAGE_ALIGN((unsigned long) h.raw +
macoff + snaplen);
for (start = h.raw; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
}
smp_wmb();
#endif
if (po->tp_version <= TPACKET_V2) {
__packet_set_status(po, h.raw, status);
sk->sk_data_ready(sk);
} else {
prb_clear_blk_fill_status(&po->rx_ring);
}
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
if (!is_drop_n_account)
consume_skb(skb);
else
kfree_skb(skb);
return 0;
drop_n_account:
is_drop_n_account = true;
po->stats.stats1.tp_drops++;
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk);
kfree_skb(copy_skb);
goto drop_n_restore;
}
static void tpacket_destruct_skb(struct sk_buff *skb)
{
struct packet_sock *po = pkt_sk(skb->sk);
if (likely(po->tx_ring.pg_vec)) {
void *ph;
__u32 ts;
ph = skb_shinfo(skb)->destructor_arg;
packet_dec_pending(&po->tx_ring);
ts = __packet_set_timestamp(po, ph, skb);
__packet_set_status(po, ph, TP_STATUS_AVAILABLE | ts);
}
sock_wfree(skb);
}
static void tpacket_set_protocol(const struct net_device *dev,
struct sk_buff *skb)
{
if (dev->type == ARPHRD_ETHER) {
skb_reset_mac_header(skb);
skb->protocol = eth_hdr(skb)->h_proto;
}
}
static int __packet_snd_vnet_parse(struct virtio_net_hdr *vnet_hdr, size_t len)
{
if ((vnet_hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
(__virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
__virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2 >
__virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len)))
vnet_hdr->hdr_len = __cpu_to_virtio16(vio_le(),
__virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
__virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2);
if (__virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len) > len)
return -EINVAL;
return 0;
}
static int packet_snd_vnet_parse(struct msghdr *msg, size_t *len,
struct virtio_net_hdr *vnet_hdr)
{
if (*len < sizeof(*vnet_hdr))
return -EINVAL;
*len -= sizeof(*vnet_hdr);
if (!copy_from_iter_full(vnet_hdr, sizeof(*vnet_hdr), &msg->msg_iter))
return -EFAULT;
return __packet_snd_vnet_parse(vnet_hdr, *len);
}
static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
void *frame, struct net_device *dev, void *data, int tp_len,
__be16 proto, unsigned char *addr, int hlen, int copylen,
const struct sockcm_cookie *sockc)
{
union tpacket_uhdr ph;
int to_write, offset, len, nr_frags, len_max;
struct socket *sock = po->sk.sk_socket;
struct page *page;
int err;
ph.raw = frame;
skb->protocol = proto;
skb->dev = dev;
skb->priority = po->sk.sk_priority;
skb->mark = po->sk.sk_mark;
sock_tx_timestamp(&po->sk, sockc->tsflags, &skb_shinfo(skb)->tx_flags);
skb_shinfo(skb)->destructor_arg = ph.raw;
skb_reserve(skb, hlen);
skb_reset_network_header(skb);
to_write = tp_len;
if (sock->type == SOCK_DGRAM) {
err = dev_hard_header(skb, dev, ntohs(proto), addr,
NULL, tp_len);
if (unlikely(err < 0))
return -EINVAL;
} else if (copylen) {
int hdrlen = min_t(int, copylen, tp_len);
skb_push(skb, dev->hard_header_len);
skb_put(skb, copylen - dev->hard_header_len);
err = skb_store_bits(skb, 0, data, hdrlen);
if (unlikely(err))
return err;
if (!dev_validate_header(dev, skb->data, hdrlen))
return -EINVAL;
if (!skb->protocol)
tpacket_set_protocol(dev, skb);
data += hdrlen;
to_write -= hdrlen;
}
offset = offset_in_page(data);
len_max = PAGE_SIZE - offset;
len = ((to_write > len_max) ? len_max : to_write);
skb->data_len = to_write;
skb->len += to_write;
skb->truesize += to_write;
refcount_add(to_write, &po->sk.sk_wmem_alloc);
while (likely(to_write)) {
nr_frags = skb_shinfo(skb)->nr_frags;
if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
pr_err("Packet exceed the number of skb frags(%lu)\n",
MAX_SKB_FRAGS);
return -EFAULT;
}
page = pgv_to_page(data);
data += len;
flush_dcache_page(page);
get_page(page);
skb_fill_page_desc(skb, nr_frags, page, offset, len);
to_write -= len;
offset = 0;
len_max = PAGE_SIZE;
len = ((to_write > len_max) ? len_max : to_write);
}
skb_probe_transport_header(skb, 0);
return tp_len;
}
static int tpacket_parse_header(struct packet_sock *po, void *frame,
int size_max, void **data)
{
union tpacket_uhdr ph;
int tp_len, off;
ph.raw = frame;
switch (po->tp_version) {
case TPACKET_V3:
if (ph.h3->tp_next_offset != 0) {
pr_warn_once("variable sized slot not supported");
return -EINVAL;
}
tp_len = ph.h3->tp_len;
break;
case TPACKET_V2:
tp_len = ph.h2->tp_len;
break;
default:
tp_len = ph.h1->tp_len;
break;
}
if (unlikely(tp_len > size_max)) {
pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
return -EMSGSIZE;
}
if (unlikely(po->tp_tx_has_off)) {
int off_min, off_max;
off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
off_max = po->tx_ring.frame_size - tp_len;
if (po->sk.sk_type == SOCK_DGRAM) {
switch (po->tp_version) {
case TPACKET_V3:
off = ph.h3->tp_net;
break;
case TPACKET_V2:
off = ph.h2->tp_net;
break;
default:
off = ph.h1->tp_net;
break;
}
} else {
switch (po->tp_version) {
case TPACKET_V3:
off = ph.h3->tp_mac;
break;
case TPACKET_V2:
off = ph.h2->tp_mac;
break;
default:
off = ph.h1->tp_mac;
break;
}
}
if (unlikely((off < off_min) || (off_max < off)))
return -EINVAL;
} else {
off = po->tp_hdrlen - sizeof(struct sockaddr_ll);
}
*data = frame + off;
return tp_len;
}
static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
{
struct sk_buff *skb;
struct net_device *dev;
struct virtio_net_hdr *vnet_hdr = NULL;
struct sockcm_cookie sockc;
__be16 proto;
int err, reserve = 0;
void *ph;
DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
bool need_wait = !(msg->msg_flags & MSG_DONTWAIT);
int tp_len, size_max;
unsigned char *addr;
void *data;
int len_sum = 0;
int status = TP_STATUS_AVAILABLE;
int hlen, tlen, copylen = 0;
mutex_lock(&po->pg_vec_lock);
if (likely(saddr == NULL)) {
dev = packet_cached_dev_get(po);
proto = po->num;
addr = NULL;
} else {
err = -EINVAL;
if (msg->msg_namelen < sizeof(struct sockaddr_ll))
goto out;
if (msg->msg_namelen < (saddr->sll_halen
+ offsetof(struct sockaddr_ll,
sll_addr)))
goto out;
proto = saddr->sll_protocol;
addr = saddr->sll_addr;
dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
}
err = -ENXIO;
if (unlikely(dev == NULL))
goto out;
err = -ENETDOWN;
if (unlikely(!(dev->flags & IFF_UP)))
goto out_put;
sockc.tsflags = po->sk.sk_tsflags;
if (msg->msg_controllen) {
err = sock_cmsg_send(&po->sk, msg, &sockc);
if (unlikely(err))
goto out_put;
}
if (po->sk.sk_socket->type == SOCK_RAW)
reserve = dev->hard_header_len;
size_max = po->tx_ring.frame_size
- (po->tp_hdrlen - sizeof(struct sockaddr_ll));
if ((size_max > dev->mtu + reserve + VLAN_HLEN) && !po->has_vnet_hdr)
size_max = dev->mtu + reserve + VLAN_HLEN;
do {
ph = packet_current_frame(po, &po->tx_ring,
TP_STATUS_SEND_REQUEST);
if (unlikely(ph == NULL)) {
if (need_wait && need_resched())
schedule();
continue;
}
skb = NULL;
tp_len = tpacket_parse_header(po, ph, size_max, &data);
if (tp_len < 0)
goto tpacket_error;
status = TP_STATUS_SEND_REQUEST;
hlen = LL_RESERVED_SPACE(dev);
tlen = dev->needed_tailroom;
if (po->has_vnet_hdr) {
vnet_hdr = data;
data += sizeof(*vnet_hdr);
tp_len -= sizeof(*vnet_hdr);
if (tp_len < 0 ||
__packet_snd_vnet_parse(vnet_hdr, tp_len)) {
tp_len = -EINVAL;
goto tpacket_error;
}
copylen = __virtio16_to_cpu(vio_le(),
vnet_hdr->hdr_len);
}
copylen = max_t(int, copylen, dev->hard_header_len);
skb = sock_alloc_send_skb(&po->sk,
hlen + tlen + sizeof(struct sockaddr_ll) +
(copylen - dev->hard_header_len),
!need_wait, &err);
if (unlikely(skb == NULL)) {
/* we assume the socket was initially writeable ... */
if (likely(len_sum > 0))
err = len_sum;
goto out_status;
}
tp_len = tpacket_fill_skb(po, skb, ph, dev, data, tp_len, proto,
addr, hlen, copylen, &sockc);
if (likely(tp_len >= 0) &&
tp_len > dev->mtu + reserve &&
!po->has_vnet_hdr &&
!packet_extra_vlan_len_allowed(dev, skb))
tp_len = -EMSGSIZE;
if (unlikely(tp_len < 0)) {
tpacket_error:
if (po->tp_loss) {
__packet_set_status(po, ph,
TP_STATUS_AVAILABLE);
packet_increment_head(&po->tx_ring);
kfree_skb(skb);
continue;
} else {
status = TP_STATUS_WRONG_FORMAT;
err = tp_len;
goto out_status;
}
}
if (po->has_vnet_hdr && virtio_net_hdr_to_skb(skb, vnet_hdr,
vio_le())) {
tp_len = -EINVAL;
goto tpacket_error;
}
skb->destructor = tpacket_destruct_skb;
__packet_set_status(po, ph, TP_STATUS_SENDING);
packet_inc_pending(&po->tx_ring);
status = TP_STATUS_SEND_REQUEST;
err = po->xmit(skb);
if (unlikely(err > 0)) {
err = net_xmit_errno(err);
if (err && __packet_get_status(po, ph) ==
TP_STATUS_AVAILABLE) {
/* skb was destructed already */
skb = NULL;
goto out_status;
}
/*
* skb was dropped but not destructed yet;
* let's treat it like congestion or err < 0
*/
err = 0;
}
packet_increment_head(&po->tx_ring);
len_sum += tp_len;
} while (likely((ph != NULL) ||
/* Note: packet_read_pending() might be slow if we have
* to call it as it's per_cpu variable, but in fast-path
* we already short-circuit the loop with the first
* condition, and luckily don't have to go that path
* anyway.
*/
(need_wait && packet_read_pending(&po->tx_ring))));
err = len_sum;
goto out_put;
out_status:
__packet_set_status(po, ph, status);
kfree_skb(skb);
out_put:
dev_put(dev);
out:
mutex_unlock(&po->pg_vec_lock);
return err;
}
static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
size_t reserve, size_t len,
size_t linear, int noblock,
int *err)
{
struct sk_buff *skb;
/* Under a page? Don't bother with paged skb. */
if (prepad + len < PAGE_SIZE || !linear)
linear = len;
skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
err, 0);
if (!skb)
return NULL;
skb_reserve(skb, reserve);
skb_put(skb, linear);
skb->data_len = len - linear;
skb->len += len - linear;
return skb;
}
static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
struct sk_buff *skb;
struct net_device *dev;
__be16 proto;
unsigned char *addr;
int err, reserve = 0;
struct sockcm_cookie sockc;
struct virtio_net_hdr vnet_hdr = { 0 };
int offset = 0;
struct packet_sock *po = pkt_sk(sk);
int hlen, tlen, linear;
int extra_len = 0;
/*
* Get and verify the address.
*/
if (likely(saddr == NULL)) {
dev = packet_cached_dev_get(po);
proto = po->num;
addr = NULL;
} else {
err = -EINVAL;
if (msg->msg_namelen < sizeof(struct sockaddr_ll))
goto out;
if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
goto out;
proto = saddr->sll_protocol;
addr = saddr->sll_addr;
dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
}
err = -ENXIO;
if (unlikely(dev == NULL))
goto out_unlock;
err = -ENETDOWN;
if (unlikely(!(dev->flags & IFF_UP)))
goto out_unlock;
sockc.tsflags = sk->sk_tsflags;
sockc.mark = sk->sk_mark;
if (msg->msg_controllen) {
err = sock_cmsg_send(sk, msg, &sockc);
if (unlikely(err))
goto out_unlock;
}
if (sock->type == SOCK_RAW)
reserve = dev->hard_header_len;
if (po->has_vnet_hdr) {
err = packet_snd_vnet_parse(msg, &len, &vnet_hdr);
if (err)
goto out_unlock;
}
if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
if (!netif_supports_nofcs(dev)) {
err = -EPROTONOSUPPORT;
goto out_unlock;
}
extra_len = 4; /* We're doing our own CRC */
}
err = -EMSGSIZE;
if (!vnet_hdr.gso_type &&
(len > dev->mtu + reserve + VLAN_HLEN + extra_len))
goto out_unlock;
err = -ENOBUFS;
hlen = LL_RESERVED_SPACE(dev);
tlen = dev->needed_tailroom;
linear = __virtio16_to_cpu(vio_le(), vnet_hdr.hdr_len);
linear = max(linear, min_t(int, len, dev->hard_header_len));
skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, linear,
msg->msg_flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto out_unlock;
skb_set_network_header(skb, reserve);
err = -EINVAL;
if (sock->type == SOCK_DGRAM) {
offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len);
if (unlikely(offset < 0))
goto out_free;
}
/* Returns -EFAULT on error */
err = skb_copy_datagram_from_iter(skb, offset, &msg->msg_iter, len);
if (err)
goto out_free;
if (sock->type == SOCK_RAW &&
!dev_validate_header(dev, skb->data, len)) {
err = -EINVAL;
goto out_free;
}
sock_tx_timestamp(sk, sockc.tsflags, &skb_shinfo(skb)->tx_flags);
if (!vnet_hdr.gso_type && (len > dev->mtu + reserve + extra_len) &&
!packet_extra_vlan_len_allowed(dev, skb)) {
err = -EMSGSIZE;
goto out_free;
}
skb->protocol = proto;
skb->dev = dev;
skb->priority = sk->sk_priority;
skb->mark = sockc.mark;
if (po->has_vnet_hdr) {
err = virtio_net_hdr_to_skb(skb, &vnet_hdr, vio_le());
if (err)
goto out_free;
len += sizeof(vnet_hdr);
}
skb_probe_transport_header(skb, reserve);
if (unlikely(extra_len == 4))
skb->no_fcs = 1;
err = po->xmit(skb);
if (err > 0 && (err = net_xmit_errno(err)) != 0)
goto out_unlock;
dev_put(dev);
return len;
out_free:
kfree_skb(skb);
out_unlock:
if (dev)
dev_put(dev);
out:
return err;
}
static int packet_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
if (po->tx_ring.pg_vec)
return tpacket_snd(po, msg);
else
return packet_snd(sock, msg, len);
}
/*
* Close a PACKET socket. This is fairly simple. We immediately go
* to 'closed' state and remove our protocol entry in the device list.
*/
static int packet_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct packet_sock *po;
struct packet_fanout *f;
struct net *net;
union tpacket_req_u req_u;
if (!sk)
return 0;
net = sock_net(sk);
po = pkt_sk(sk);
mutex_lock(&net->packet.sklist_lock);
sk_del_node_init_rcu(sk);
mutex_unlock(&net->packet.sklist_lock);
preempt_disable();
sock_prot_inuse_add(net, sk->sk_prot, -1);
preempt_enable();
spin_lock(&po->bind_lock);
unregister_prot_hook(sk, false);
packet_cached_dev_reset(po);
if (po->prot_hook.dev) {
dev_put(po->prot_hook.dev);
po->prot_hook.dev = NULL;
}
spin_unlock(&po->bind_lock);
packet_flush_mclist(sk);
if (po->rx_ring.pg_vec) {
memset(&req_u, 0, sizeof(req_u));
packet_set_ring(sk, &req_u, 1, 0);
}
if (po->tx_ring.pg_vec) {
memset(&req_u, 0, sizeof(req_u));
packet_set_ring(sk, &req_u, 1, 1);
}
f = fanout_release(sk);
synchronize_net();
if (f) {
fanout_release_data(f);
kfree(f);
}
/*
* Now the socket is dead. No more input will appear.
*/
sock_orphan(sk);
sock->sk = NULL;
/* Purge queues */
skb_queue_purge(&sk->sk_receive_queue);
packet_free_pending(po);
sk_refcnt_debug_release(sk);
sock_put(sk);
return 0;
}
/*
* Attach a packet hook.
*/
static int packet_do_bind(struct sock *sk, const char *name, int ifindex,
__be16 proto)
{
struct packet_sock *po = pkt_sk(sk);
struct net_device *dev_curr;
__be16 proto_curr;
bool need_rehook;
struct net_device *dev = NULL;
int ret = 0;
bool unlisted = false;
if (po->fanout)
return -EINVAL;
lock_sock(sk);
spin_lock(&po->bind_lock);
rcu_read_lock();
if (name) {
dev = dev_get_by_name_rcu(sock_net(sk), name);
if (!dev) {
ret = -ENODEV;
goto out_unlock;
}
} else if (ifindex) {
dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
if (!dev) {
ret = -ENODEV;
goto out_unlock;
}
}
if (dev)
dev_hold(dev);
proto_curr = po->prot_hook.type;
dev_curr = po->prot_hook.dev;
need_rehook = proto_curr != proto || dev_curr != dev;
if (need_rehook) {
if (po->running) {
rcu_read_unlock();
__unregister_prot_hook(sk, true);
rcu_read_lock();
dev_curr = po->prot_hook.dev;
if (dev)
unlisted = !dev_get_by_index_rcu(sock_net(sk),
dev->ifindex);
}
po->num = proto;
po->prot_hook.type = proto;
if (unlikely(unlisted)) {
dev_put(dev);
po->prot_hook.dev = NULL;
po->ifindex = -1;
packet_cached_dev_reset(po);
} else {
po->prot_hook.dev = dev;
po->ifindex = dev ? dev->ifindex : 0;
packet_cached_dev_assign(po, dev);
}
}
if (dev_curr)
dev_put(dev_curr);
if (proto == 0 || !need_rehook)
goto out_unlock;
if (!unlisted && (!dev || (dev->flags & IFF_UP))) {
register_prot_hook(sk);
} else {
sk->sk_err = ENETDOWN;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_error_report(sk);
}
out_unlock:
rcu_read_unlock();
spin_unlock(&po->bind_lock);
release_sock(sk);
return ret;
}
/*
* Bind a packet socket to a device
*/
static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
int addr_len)
{
struct sock *sk = sock->sk;
char name[sizeof(uaddr->sa_data) + 1];
/*
* Check legality
*/
if (addr_len != sizeof(struct sockaddr))
return -EINVAL;
/* uaddr->sa_data comes from the userspace, it's not guaranteed to be
* zero-terminated.
*/
memcpy(name, uaddr->sa_data, sizeof(uaddr->sa_data));
name[sizeof(uaddr->sa_data)] = 0;
return packet_do_bind(sk, name, 0, pkt_sk(sk)->num);
}
static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
struct sock *sk = sock->sk;
/*
* Check legality
*/
if (addr_len < sizeof(struct sockaddr_ll))
return -EINVAL;
if (sll->sll_family != AF_PACKET)
return -EINVAL;
return packet_do_bind(sk, NULL, sll->sll_ifindex,
sll->sll_protocol ? : pkt_sk(sk)->num);
}
static struct proto packet_proto = {
.name = "PACKET",
.owner = THIS_MODULE,
.obj_size = sizeof(struct packet_sock),
};
/*
* Create a packet of type SOCK_PACKET.
*/
static int packet_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
struct packet_sock *po;
__be16 proto = (__force __be16)protocol; /* weird, but documented */
int err;
if (!ns_capable(net->user_ns, CAP_NET_RAW))
return -EPERM;
if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
sock->type != SOCK_PACKET)
return -ESOCKTNOSUPPORT;
sock->state = SS_UNCONNECTED;
err = -ENOBUFS;
sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto, kern);
if (sk == NULL)
goto out;
sock->ops = &packet_ops;
if (sock->type == SOCK_PACKET)
sock->ops = &packet_ops_spkt;
sock_init_data(sock, sk);
po = pkt_sk(sk);
sk->sk_family = PF_PACKET;
po->num = proto;
po->xmit = dev_queue_xmit;
err = packet_alloc_pending(po);
if (err)
goto out2;
packet_cached_dev_reset(po);
sk->sk_destruct = packet_sock_destruct;
sk_refcnt_debug_inc(sk);
/*
* Attach a protocol block
*/
spin_lock_init(&po->bind_lock);
mutex_init(&po->pg_vec_lock);
po->rollover = NULL;
po->prot_hook.func = packet_rcv;
if (sock->type == SOCK_PACKET)
po->prot_hook.func = packet_rcv_spkt;
po->prot_hook.af_packet_priv = sk;
if (proto) {
po->prot_hook.type = proto;
register_prot_hook(sk);
}
mutex_lock(&net->packet.sklist_lock);
sk_add_node_rcu(sk, &net->packet.sklist);
mutex_unlock(&net->packet.sklist_lock);
preempt_disable();
sock_prot_inuse_add(net, &packet_proto, 1);
preempt_enable();
return 0;
out2:
sk_free(sk);
out:
return err;
}
/*
* Pull a packet from our receive queue and hand it to the user.
* If necessary we block.
*/
static int packet_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int copied, err;
int vnet_hdr_len = 0;
unsigned int origlen = 0;
err = -EINVAL;
if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
goto out;
#if 0
/* What error should we return now? EUNATTACH? */
if (pkt_sk(sk)->ifindex < 0)
return -ENODEV;
#endif
if (flags & MSG_ERRQUEUE) {
err = sock_recv_errqueue(sk, msg, len,
SOL_PACKET, PACKET_TX_TIMESTAMP);
goto out;
}
/*
* Call the generic datagram receiver. This handles all sorts
* of horrible races and re-entrancy so we can forget about it
* in the protocol layers.
*
* Now it will return ENETDOWN, if device have just gone down,
* but then it will block.
*/
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
/*
* An error occurred so return it. Because skb_recv_datagram()
* handles the blocking we don't see and worry about blocking
* retries.
*/
if (skb == NULL)
goto out;
if (pkt_sk(sk)->pressure)
packet_rcv_has_room(pkt_sk(sk), NULL);
if (pkt_sk(sk)->has_vnet_hdr) {
err = packet_rcv_vnet(msg, skb, &len);
if (err)
goto out_free;
vnet_hdr_len = sizeof(struct virtio_net_hdr);
}
/* You lose any data beyond the buffer you gave. If it worries
* a user program they can ask the device for its MTU
* anyway.
*/
copied = skb->len;
if (copied > len) {
copied = len;
msg->msg_flags |= MSG_TRUNC;
}
err = skb_copy_datagram_msg(skb, 0, msg, copied);
if (err)
goto out_free;
if (sock->type != SOCK_PACKET) {
struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
/* Original length was stored in sockaddr_ll fields */
origlen = PACKET_SKB_CB(skb)->sa.origlen;
sll->sll_family = AF_PACKET;
sll->sll_protocol = skb->protocol;
}
sock_recv_ts_and_drops(msg, sk, skb);
if (msg->msg_name) {
/* If the address length field is there to be filled
* in, we fill it in now.
*/
if (sock->type == SOCK_PACKET) {
__sockaddr_check_size(sizeof(struct sockaddr_pkt));
msg->msg_namelen = sizeof(struct sockaddr_pkt);
} else {
struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
msg->msg_namelen = sll->sll_halen +
offsetof(struct sockaddr_ll, sll_addr);
}
memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,
msg->msg_namelen);
}
if (pkt_sk(sk)->auxdata) {
struct tpacket_auxdata aux;
aux.tp_status = TP_STATUS_USER;
if (skb->ip_summed == CHECKSUM_PARTIAL)
aux.tp_status |= TP_STATUS_CSUMNOTREADY;
else if (skb->pkt_type != PACKET_OUTGOING &&
(skb->ip_summed == CHECKSUM_COMPLETE ||
skb_csum_unnecessary(skb)))
aux.tp_status |= TP_STATUS_CSUM_VALID;
aux.tp_len = origlen;
aux.tp_snaplen = skb->len;
aux.tp_mac = 0;
aux.tp_net = skb_network_offset(skb);
if (skb_vlan_tag_present(skb)) {
aux.tp_vlan_tci = skb_vlan_tag_get(skb);
aux.tp_vlan_tpid = ntohs(skb->vlan_proto);
aux.tp_status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
} else {
aux.tp_vlan_tci = 0;
aux.tp_vlan_tpid = 0;
}
put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
}
/*
* Free or return the buffer as appropriate. Again this
* hides all the races and re-entrancy issues from us.
*/
err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
out_free:
skb_free_datagram(sk, skb);
out:
return err;
}
static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct net_device *dev;
struct sock *sk = sock->sk;
if (peer)
return -EOPNOTSUPP;
uaddr->sa_family = AF_PACKET;
memset(uaddr->sa_data, 0, sizeof(uaddr->sa_data));
rcu_read_lock();
dev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex);
if (dev)
strlcpy(uaddr->sa_data, dev->name, sizeof(uaddr->sa_data));
rcu_read_unlock();
*uaddr_len = sizeof(*uaddr);
return 0;
}
static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct net_device *dev;
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
if (peer)
return -EOPNOTSUPP;
sll->sll_family = AF_PACKET;
sll->sll_ifindex = po->ifindex;
sll->sll_protocol = po->num;
sll->sll_pkttype = 0;
rcu_read_lock();
dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex);
if (dev) {
sll->sll_hatype = dev->type;
sll->sll_halen = dev->addr_len;
memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
} else {
sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */
sll->sll_halen = 0;
}
rcu_read_unlock();
*uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
return 0;
}
static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
int what)
{
switch (i->type) {
case PACKET_MR_MULTICAST:
if (i->alen != dev->addr_len)
return -EINVAL;
if (what > 0)
return dev_mc_add(dev, i->addr);
else
return dev_mc_del(dev, i->addr);
break;
case PACKET_MR_PROMISC:
return dev_set_promiscuity(dev, what);
case PACKET_MR_ALLMULTI:
return dev_set_allmulti(dev, what);
case PACKET_MR_UNICAST:
if (i->alen != dev->addr_len)
return -EINVAL;
if (what > 0)
return dev_uc_add(dev, i->addr);
else
return dev_uc_del(dev, i->addr);
break;
default:
break;
}
return 0;
}
static void packet_dev_mclist_delete(struct net_device *dev,
struct packet_mclist **mlp)
{
struct packet_mclist *ml;
while ((ml = *mlp) != NULL) {
if (ml->ifindex == dev->ifindex) {
packet_dev_mc(dev, ml, -1);
*mlp = ml->next;
kfree(ml);
} else
mlp = &ml->next;
}
}
static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_mclist *ml, *i;
struct net_device *dev;
int err;
rtnl_lock();
err = -ENODEV;
dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
if (!dev)
goto done;
err = -EINVAL;
if (mreq->mr_alen > dev->addr_len)
goto done;
err = -ENOBUFS;
i = kmalloc(sizeof(*i), GFP_KERNEL);
if (i == NULL)
goto done;
err = 0;
for (ml = po->mclist; ml; ml = ml->next) {
if (ml->ifindex == mreq->mr_ifindex &&
ml->type == mreq->mr_type &&
ml->alen == mreq->mr_alen &&
memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
ml->count++;
/* Free the new element ... */
kfree(i);
goto done;
}
}
i->type = mreq->mr_type;
i->ifindex = mreq->mr_ifindex;
i->alen = mreq->mr_alen;
memcpy(i->addr, mreq->mr_address, i->alen);
memset(i->addr + i->alen, 0, sizeof(i->addr) - i->alen);
i->count = 1;
i->next = po->mclist;
po->mclist = i;
err = packet_dev_mc(dev, i, 1);
if (err) {
po->mclist = i->next;
kfree(i);
}
done:
rtnl_unlock();
return err;
}
static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
{
struct packet_mclist *ml, **mlp;
rtnl_lock();
for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
if (ml->ifindex == mreq->mr_ifindex &&
ml->type == mreq->mr_type &&
ml->alen == mreq->mr_alen &&
memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
if (--ml->count == 0) {
struct net_device *dev;
*mlp = ml->next;
dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
if (dev)
packet_dev_mc(dev, ml, -1);
kfree(ml);
}
break;
}
}
rtnl_unlock();
return 0;
}
static void packet_flush_mclist(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_mclist *ml;
if (!po->mclist)
return;
rtnl_lock();
while ((ml = po->mclist) != NULL) {
struct net_device *dev;
po->mclist = ml->next;
dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
if (dev != NULL)
packet_dev_mc(dev, ml, -1);
kfree(ml);
}
rtnl_unlock();
}
static int
packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
int ret;
if (level != SOL_PACKET)
return -ENOPROTOOPT;
switch (optname) {
case PACKET_ADD_MEMBERSHIP:
case PACKET_DROP_MEMBERSHIP:
{
struct packet_mreq_max mreq;
int len = optlen;
memset(&mreq, 0, sizeof(mreq));
if (len < sizeof(struct packet_mreq))
return -EINVAL;
if (len > sizeof(mreq))
len = sizeof(mreq);
if (copy_from_user(&mreq, optval, len))
return -EFAULT;
if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
return -EINVAL;
if (optname == PACKET_ADD_MEMBERSHIP)
ret = packet_mc_add(sk, &mreq);
else
ret = packet_mc_drop(sk, &mreq);
return ret;
}
case PACKET_RX_RING:
case PACKET_TX_RING:
{
union tpacket_req_u req_u;
int len;
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
len = sizeof(req_u.req);
break;
case TPACKET_V3:
default:
len = sizeof(req_u.req3);
break;
}
if (optlen < len)
return -EINVAL;
if (copy_from_user(&req_u.req, optval, len))
return -EFAULT;
return packet_set_ring(sk, &req_u, 0,
optname == PACKET_TX_RING);
}
case PACKET_COPY_THRESH:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
pkt_sk(sk)->copy_thresh = val;
return 0;
}
case PACKET_VERSION:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
switch (val) {
case TPACKET_V1:
case TPACKET_V2:
case TPACKET_V3:
break;
default:
return -EINVAL;
}
lock_sock(sk);
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
ret = -EBUSY;
} else {
po->tp_version = val;
ret = 0;
}
release_sock(sk);
return ret;
}
case PACKET_RESERVE:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
if (val > INT_MAX)
return -EINVAL;
lock_sock(sk);
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
ret = -EBUSY;
} else {
po->tp_reserve = val;
ret = 0;
}
release_sock(sk);
return ret;
}
case PACKET_LOSS:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_loss = !!val;
return 0;
}
case PACKET_AUXDATA:
{
int val;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->auxdata = !!val;
return 0;
}
case PACKET_ORIGDEV:
{
int val;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->origdev = !!val;
return 0;
}
case PACKET_VNET_HDR:
{
int val;
if (sock->type != SOCK_RAW)
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->has_vnet_hdr = !!val;
return 0;
}
case PACKET_TIMESTAMP:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_tstamp = val;
return 0;
}
case PACKET_FANOUT:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
return fanout_add(sk, val & 0xffff, val >> 16);
}
case PACKET_FANOUT_DATA:
{
if (!po->fanout)
return -EINVAL;
return fanout_set_data(po, optval, optlen);
}
case PACKET_TX_HAS_OFF:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_tx_has_off = !!val;
return 0;
}
case PACKET_QDISC_BYPASS:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->xmit = val ? packet_direct_xmit : dev_queue_xmit;
return 0;
}
default:
return -ENOPROTOOPT;
}
}
static int packet_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
int len;
int val, lv = sizeof(val);
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
void *data = &val;
union tpacket_stats_u st;
struct tpacket_rollover_stats rstats;
if (level != SOL_PACKET)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
switch (optname) {
case PACKET_STATISTICS:
spin_lock_bh(&sk->sk_receive_queue.lock);
memcpy(&st, &po->stats, sizeof(st));
memset(&po->stats, 0, sizeof(po->stats));
spin_unlock_bh(&sk->sk_receive_queue.lock);
if (po->tp_version == TPACKET_V3) {
lv = sizeof(struct tpacket_stats_v3);
st.stats3.tp_packets += st.stats3.tp_drops;
data = &st.stats3;
} else {
lv = sizeof(struct tpacket_stats);
st.stats1.tp_packets += st.stats1.tp_drops;
data = &st.stats1;
}
break;
case PACKET_AUXDATA:
val = po->auxdata;
break;
case PACKET_ORIGDEV:
val = po->origdev;
break;
case PACKET_VNET_HDR:
val = po->has_vnet_hdr;
break;
case PACKET_VERSION:
val = po->tp_version;
break;
case PACKET_HDRLEN:
if (len > sizeof(int))
len = sizeof(int);
if (len < sizeof(int))
return -EINVAL;
if (copy_from_user(&val, optval, len))
return -EFAULT;
switch (val) {
case TPACKET_V1:
val = sizeof(struct tpacket_hdr);
break;
case TPACKET_V2:
val = sizeof(struct tpacket2_hdr);
break;
case TPACKET_V3:
val = sizeof(struct tpacket3_hdr);
break;
default:
return -EINVAL;
}
break;
case PACKET_RESERVE:
val = po->tp_reserve;
break;
case PACKET_LOSS:
val = po->tp_loss;
break;
case PACKET_TIMESTAMP:
val = po->tp_tstamp;
break;
case PACKET_FANOUT:
val = (po->fanout ?
((u32)po->fanout->id |
((u32)po->fanout->type << 16) |
((u32)po->fanout->flags << 24)) :
0);
break;
case PACKET_ROLLOVER_STATS:
if (!po->rollover)
return -EINVAL;
rstats.tp_all = atomic_long_read(&po->rollover->num);
rstats.tp_huge = atomic_long_read(&po->rollover->num_huge);
rstats.tp_failed = atomic_long_read(&po->rollover->num_failed);
data = &rstats;
lv = sizeof(rstats);
break;
case PACKET_TX_HAS_OFF:
val = po->tp_tx_has_off;
break;
case PACKET_QDISC_BYPASS:
val = packet_use_direct_xmit(po);
break;
default:
return -ENOPROTOOPT;
}
if (len > lv)
len = lv;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, data, len))
return -EFAULT;
return 0;
}
#ifdef CONFIG_COMPAT
static int compat_packet_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct packet_sock *po = pkt_sk(sock->sk);
if (level != SOL_PACKET)
return -ENOPROTOOPT;
if (optname == PACKET_FANOUT_DATA &&
po->fanout && po->fanout->type == PACKET_FANOUT_CBPF) {
optval = (char __user *)get_compat_bpf_fprog(optval);
if (!optval)
return -EFAULT;
optlen = sizeof(struct sock_fprog);
}
return packet_setsockopt(sock, level, optname, optval, optlen);
}
#endif
static int packet_notifier(struct notifier_block *this,
unsigned long msg, void *ptr)
{
struct sock *sk;
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
struct net *net = dev_net(dev);
rcu_read_lock();
sk_for_each_rcu(sk, &net->packet.sklist) {
struct packet_sock *po = pkt_sk(sk);
switch (msg) {
case NETDEV_UNREGISTER:
if (po->mclist)
packet_dev_mclist_delete(dev, &po->mclist);
/* fallthrough */
case NETDEV_DOWN:
if (dev->ifindex == po->ifindex) {
spin_lock(&po->bind_lock);
if (po->running) {
__unregister_prot_hook(sk, false);
sk->sk_err = ENETDOWN;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_error_report(sk);
}
if (msg == NETDEV_UNREGISTER) {
packet_cached_dev_reset(po);
po->ifindex = -1;
if (po->prot_hook.dev)
dev_put(po->prot_hook.dev);
po->prot_hook.dev = NULL;
}
spin_unlock(&po->bind_lock);
}
break;
case NETDEV_UP:
if (dev->ifindex == po->ifindex) {
spin_lock(&po->bind_lock);
if (po->num)
register_prot_hook(sk);
spin_unlock(&po->bind_lock);
}
break;
}
}
rcu_read_unlock();
return NOTIFY_DONE;
}
static int packet_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
struct sock *sk = sock->sk;
switch (cmd) {
case SIOCOUTQ:
{
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ:
{
struct sk_buff *skb;
int amount = 0;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb)
amount = skb->len;
spin_unlock_bh(&sk->sk_receive_queue.lock);
return put_user(amount, (int __user *)arg);
}
case SIOCGSTAMP:
return sock_get_timestamp(sk, (struct timeval __user *)arg);
case SIOCGSTAMPNS:
return sock_get_timestampns(sk, (struct timespec __user *)arg);
#ifdef CONFIG_INET
case SIOCADDRT:
case SIOCDELRT:
case SIOCDARP:
case SIOCGARP:
case SIOCSARP:
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCSIFFLAGS:
return inet_dgram_ops.ioctl(sock, cmd, arg);
#endif
default:
return -ENOIOCTLCMD;
}
return 0;
}
static unsigned int packet_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
unsigned int mask = datagram_poll(file, sock, wait);
spin_lock_bh(&sk->sk_receive_queue.lock);
if (po->rx_ring.pg_vec) {
if (!packet_previous_rx_frame(po, &po->rx_ring,
TP_STATUS_KERNEL))
mask |= POLLIN | POLLRDNORM;
}
if (po->pressure && __packet_rcv_has_room(po, NULL) == ROOM_NORMAL)
po->pressure = 0;
spin_unlock_bh(&sk->sk_receive_queue.lock);
spin_lock_bh(&sk->sk_write_queue.lock);
if (po->tx_ring.pg_vec) {
if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
mask |= POLLOUT | POLLWRNORM;
}
spin_unlock_bh(&sk->sk_write_queue.lock);
return mask;
}
/* Dirty? Well, I still did not learn better way to account
* for user mmaps.
*/
static void packet_mm_open(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct socket *sock = file->private_data;
struct sock *sk = sock->sk;
if (sk)
atomic_inc(&pkt_sk(sk)->mapped);
}
static void packet_mm_close(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct socket *sock = file->private_data;
struct sock *sk = sock->sk;
if (sk)
atomic_dec(&pkt_sk(sk)->mapped);
}
static const struct vm_operations_struct packet_mmap_ops = {
.open = packet_mm_open,
.close = packet_mm_close,
};
static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
unsigned int len)
{
int i;
for (i = 0; i < len; i++) {
if (likely(pg_vec[i].buffer)) {
if (is_vmalloc_addr(pg_vec[i].buffer))
vfree(pg_vec[i].buffer);
else
free_pages((unsigned long)pg_vec[i].buffer,
order);
pg_vec[i].buffer = NULL;
}
}
kfree(pg_vec);
}
static char *alloc_one_pg_vec_page(unsigned long order)
{
char *buffer;
gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
__GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
buffer = (char *) __get_free_pages(gfp_flags, order);
if (buffer)
return buffer;
/* __get_free_pages failed, fall back to vmalloc */
buffer = vzalloc((1 << order) * PAGE_SIZE);
if (buffer)
return buffer;
/* vmalloc failed, lets dig into swap here */
gfp_flags &= ~__GFP_NORETRY;
buffer = (char *) __get_free_pages(gfp_flags, order);
if (buffer)
return buffer;
/* complete and utter failure */
return NULL;
}
static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
{
unsigned int block_nr = req->tp_block_nr;
struct pgv *pg_vec;
int i;
pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL);
if (unlikely(!pg_vec))
goto out;
for (i = 0; i < block_nr; i++) {
pg_vec[i].buffer = alloc_one_pg_vec_page(order);
if (unlikely(!pg_vec[i].buffer))
goto out_free_pgvec;
}
out:
return pg_vec;
out_free_pgvec:
free_pg_vec(pg_vec, order, block_nr);
pg_vec = NULL;
goto out;
}
static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
int closing, int tx_ring)
{
struct pgv *pg_vec = NULL;
struct packet_sock *po = pkt_sk(sk);
int was_running, order = 0;
struct packet_ring_buffer *rb;
struct sk_buff_head *rb_queue;
__be16 num;
int err = -EINVAL;
/* Added to avoid minimal code churn */
struct tpacket_req *req = &req_u->req;
lock_sock(sk);
rb = tx_ring ? &po->tx_ring : &po->rx_ring;
rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
err = -EBUSY;
if (!closing) {
if (atomic_read(&po->mapped))
goto out;
if (packet_read_pending(rb))
goto out;
}
if (req->tp_block_nr) {
/* Sanity tests and some calculations */
err = -EBUSY;
if (unlikely(rb->pg_vec))
goto out;
switch (po->tp_version) {
case TPACKET_V1:
po->tp_hdrlen = TPACKET_HDRLEN;
break;
case TPACKET_V2:
po->tp_hdrlen = TPACKET2_HDRLEN;
break;
case TPACKET_V3:
po->tp_hdrlen = TPACKET3_HDRLEN;
break;
}
err = -EINVAL;
if (unlikely((int)req->tp_block_size <= 0))
goto out;
if (unlikely(!PAGE_ALIGNED(req->tp_block_size)))
goto out;
if (po->tp_version >= TPACKET_V3 &&
req->tp_block_size <=
BLK_PLUS_PRIV((u64)req_u->req3.tp_sizeof_priv))
goto out;
if (unlikely(req->tp_frame_size < po->tp_hdrlen +
po->tp_reserve))
goto out;
if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
goto out;
rb->frames_per_block = req->tp_block_size / req->tp_frame_size;
if (unlikely(rb->frames_per_block == 0))
goto out;
if (unlikely(req->tp_block_size > UINT_MAX / req->tp_block_nr))
goto out;
if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
req->tp_frame_nr))
goto out;
err = -ENOMEM;
order = get_order(req->tp_block_size);
pg_vec = alloc_pg_vec(req, order);
if (unlikely(!pg_vec))
goto out;
switch (po->tp_version) {
case TPACKET_V3:
/* Block transmit is not supported yet */
if (!tx_ring) {
init_prb_bdqc(po, rb, pg_vec, req_u);
} else {
struct tpacket_req3 *req3 = &req_u->req3;
if (req3->tp_retire_blk_tov ||
req3->tp_sizeof_priv ||
req3->tp_feature_req_word) {
err = -EINVAL;
goto out;
}
}
break;
default:
break;
}
}
/* Done */
else {
err = -EINVAL;
if (unlikely(req->tp_frame_nr))
goto out;
}
/* Detach socket from network */
spin_lock(&po->bind_lock);
was_running = po->running;
num = po->num;
if (was_running) {
po->num = 0;
__unregister_prot_hook(sk, false);
}
spin_unlock(&po->bind_lock);
synchronize_net();
err = -EBUSY;
mutex_lock(&po->pg_vec_lock);
if (closing || atomic_read(&po->mapped) == 0) {
err = 0;
spin_lock_bh(&rb_queue->lock);
swap(rb->pg_vec, pg_vec);
rb->frame_max = (req->tp_frame_nr - 1);
rb->head = 0;
rb->frame_size = req->tp_frame_size;
spin_unlock_bh(&rb_queue->lock);
swap(rb->pg_vec_order, order);
swap(rb->pg_vec_len, req->tp_block_nr);
rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
po->prot_hook.func = (po->rx_ring.pg_vec) ?
tpacket_rcv : packet_rcv;
skb_queue_purge(rb_queue);
if (atomic_read(&po->mapped))
pr_err("packet_mmap: vma is busy: %d\n",
atomic_read(&po->mapped));
}
mutex_unlock(&po->pg_vec_lock);
spin_lock(&po->bind_lock);
if (was_running) {
po->num = num;
register_prot_hook(sk);
}
spin_unlock(&po->bind_lock);
if (pg_vec && (po->tp_version > TPACKET_V2)) {
/* Because we don't support block-based V3 on tx-ring */
if (!tx_ring)
prb_shutdown_retire_blk_timer(po, rb_queue);
}
if (pg_vec)
free_pg_vec(pg_vec, order, req->tp_block_nr);
out:
release_sock(sk);
return err;
}
static int packet_mmap(struct file *file, struct socket *sock,
struct vm_area_struct *vma)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
unsigned long size, expected_size;
struct packet_ring_buffer *rb;
unsigned long start;
int err = -EINVAL;
int i;
if (vma->vm_pgoff)
return -EINVAL;
mutex_lock(&po->pg_vec_lock);
expected_size = 0;
for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
if (rb->pg_vec) {
expected_size += rb->pg_vec_len
* rb->pg_vec_pages
* PAGE_SIZE;
}
}
if (expected_size == 0)
goto out;
size = vma->vm_end - vma->vm_start;
if (size != expected_size)
goto out;
start = vma->vm_start;
for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
if (rb->pg_vec == NULL)
continue;
for (i = 0; i < rb->pg_vec_len; i++) {
struct page *page;
void *kaddr = rb->pg_vec[i].buffer;
int pg_num;
for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
page = pgv_to_page(kaddr);
err = vm_insert_page(vma, start, page);
if (unlikely(err))
goto out;
start += PAGE_SIZE;
kaddr += PAGE_SIZE;
}
}
}
atomic_inc(&po->mapped);
vma->vm_ops = &packet_mmap_ops;
err = 0;
out:
mutex_unlock(&po->pg_vec_lock);
return err;
}
static const struct proto_ops packet_ops_spkt = {
.family = PF_PACKET,
.owner = THIS_MODULE,
.release = packet_release,
.bind = packet_bind_spkt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = packet_getname_spkt,
.poll = datagram_poll,
.ioctl = packet_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = packet_sendmsg_spkt,
.recvmsg = packet_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const struct proto_ops packet_ops = {
.family = PF_PACKET,
.owner = THIS_MODULE,
.release = packet_release,
.bind = packet_bind,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = packet_getname,
.poll = packet_poll,
.ioctl = packet_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = packet_setsockopt,
.getsockopt = packet_getsockopt,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_packet_setsockopt,
#endif
.sendmsg = packet_sendmsg,
.recvmsg = packet_recvmsg,
.mmap = packet_mmap,
.sendpage = sock_no_sendpage,
};
static const struct net_proto_family packet_family_ops = {
.family = PF_PACKET,
.create = packet_create,
.owner = THIS_MODULE,
};
static struct notifier_block packet_netdev_notifier = {
.notifier_call = packet_notifier,
};
#ifdef CONFIG_PROC_FS
static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
struct net *net = seq_file_net(seq);
rcu_read_lock();
return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
}
static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct net *net = seq_file_net(seq);
return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
}
static void packet_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
rcu_read_unlock();
}
static int packet_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, "sk RefCnt Type Proto Iface R Rmem User Inode\n");
else {
struct sock *s = sk_entry(v);
const struct packet_sock *po = pkt_sk(s);
seq_printf(seq,
"%pK %-6d %-4d %04x %-5d %1d %-6u %-6u %-6lu\n",
s,
refcount_read(&s->sk_refcnt),
s->sk_type,
ntohs(po->num),
po->ifindex,
po->running,
atomic_read(&s->sk_rmem_alloc),
from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
sock_i_ino(s));
}
return 0;
}
static const struct seq_operations packet_seq_ops = {
.start = packet_seq_start,
.next = packet_seq_next,
.stop = packet_seq_stop,
.show = packet_seq_show,
};
static int packet_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &packet_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations packet_seq_fops = {
.owner = THIS_MODULE,
.open = packet_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
static int __net_init packet_net_init(struct net *net)
{
mutex_init(&net->packet.sklist_lock);
INIT_HLIST_HEAD(&net->packet.sklist);
if (!proc_create("packet", 0, net->proc_net, &packet_seq_fops))
return -ENOMEM;
return 0;
}
static void __net_exit packet_net_exit(struct net *net)
{
remove_proc_entry("packet", net->proc_net);
}
static struct pernet_operations packet_net_ops = {
.init = packet_net_init,
.exit = packet_net_exit,
};
static void __exit packet_exit(void)
{
unregister_netdevice_notifier(&packet_netdev_notifier);
unregister_pernet_subsys(&packet_net_ops);
sock_unregister(PF_PACKET);
proto_unregister(&packet_proto);
}
static int __init packet_init(void)
{
int rc = proto_register(&packet_proto, 0);
if (rc != 0)
goto out;
sock_register(&packet_family_ops);
register_pernet_subsys(&packet_net_ops);
register_netdevice_notifier(&packet_netdev_notifier);
out:
return rc;
}
module_init(packet_init);
module_exit(packet_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_PACKET);
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2796_0 |
crossvul-cpp_data_bad_5795_5 | /*
* $Id: json_tokener.c,v 1.20 2006/07/25 03:24:50 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark <michael@metaparadigm.com>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See COPYING for details.
*
*
* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved.
* The copyrights to the contents of this file are licensed under the MIT License
* (http://www.opensource.org/licenses/mit-license.php)
*/
#include "config.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <ctype.h>
#include <string.h>
#include <limits.h>
#include "bits.h"
#include "debug.h"
#include "printbuf.h"
#include "arraylist.h"
#include "json_inttypes.h"
#include "json_object.h"
#include "json_tokener.h"
#include "json_util.h"
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif /* HAVE_LOCALE_H */
#if !HAVE_STRDUP && defined(_MSC_VER)
/* MSC has the version as _strdup */
# define strdup _strdup
#elif !HAVE_STRDUP
# error You do not have strdup on your system.
#endif /* HAVE_STRDUP */
#if !HAVE_STRNCASECMP && defined(_MSC_VER)
/* MSC has the version as _strnicmp */
# define strncasecmp _strnicmp
#elif !HAVE_STRNCASECMP
# error You do not have strncasecmp on your system.
#endif /* HAVE_STRNCASECMP */
/* Use C99 NAN by default; if not available, nan("") should work too. */
#ifndef NAN
#define NAN nan("")
#endif /* !NAN */
static const char json_null_str[] = "null";
static const int json_null_str_len = sizeof(json_null_str) - 1;
static const char json_inf_str[] = "Infinity";
static const int json_inf_str_len = sizeof(json_inf_str) - 1;
static const char json_nan_str[] = "NaN";
static const int json_nan_str_len = sizeof(json_nan_str) - 1;
static const char json_true_str[] = "true";
static const int json_true_str_len = sizeof(json_true_str) - 1;
static const char json_false_str[] = "false";
static const int json_false_str_len = sizeof(json_false_str) - 1;
static const char* json_tokener_errors[] = {
"success",
"continue",
"nesting too deep",
"unexpected end of data",
"unexpected character",
"null expected",
"boolean expected",
"number expected",
"array value separator ',' expected",
"quoted object property name expected",
"object property name separator ':' expected",
"object value separator ',' expected",
"invalid string sequence",
"expected comment",
};
const char *json_tokener_error_desc(enum json_tokener_error jerr)
{
int jerr_int = (int)jerr;
if (jerr_int < 0 || jerr_int >= (int)(sizeof(json_tokener_errors) / sizeof(json_tokener_errors[0])))
return "Unknown error, invalid json_tokener_error value passed to json_tokener_error_desc()";
return json_tokener_errors[jerr];
}
enum json_tokener_error json_tokener_get_error(json_tokener *tok)
{
return tok->err;
}
/* Stuff for decoding unicode sequences */
#define IS_HIGH_SURROGATE(uc) (((uc) & 0xFC00) == 0xD800)
#define IS_LOW_SURROGATE(uc) (((uc) & 0xFC00) == 0xDC00)
#define DECODE_SURROGATE_PAIR(hi,lo) ((((hi) & 0x3FF) << 10) + ((lo) & 0x3FF) + 0x10000)
static unsigned char utf8_replacement_char[3] = { 0xEF, 0xBF, 0xBD };
struct json_tokener* json_tokener_new_ex(int depth)
{
struct json_tokener *tok;
tok = (struct json_tokener*)calloc(1, sizeof(struct json_tokener));
if (!tok) return NULL;
tok->stack = (struct json_tokener_srec *)calloc(depth, sizeof(struct json_tokener_srec));
if (!tok->stack) {
free(tok);
return NULL;
}
tok->pb = printbuf_new();
tok->max_depth = depth;
json_tokener_reset(tok);
return tok;
}
struct json_tokener* json_tokener_new(void)
{
return json_tokener_new_ex(JSON_TOKENER_DEFAULT_DEPTH);
}
void json_tokener_free(struct json_tokener *tok)
{
json_tokener_reset(tok);
if (tok->pb) printbuf_free(tok->pb);
if (tok->stack) free(tok->stack);
free(tok);
}
static void json_tokener_reset_level(struct json_tokener *tok, int depth)
{
tok->stack[depth].state = json_tokener_state_eatws;
tok->stack[depth].saved_state = json_tokener_state_start;
json_object_put(tok->stack[depth].current);
tok->stack[depth].current = NULL;
free(tok->stack[depth].obj_field_name);
tok->stack[depth].obj_field_name = NULL;
}
void json_tokener_reset(struct json_tokener *tok)
{
int i;
if (!tok)
return;
for(i = tok->depth; i >= 0; i--)
json_tokener_reset_level(tok, i);
tok->depth = 0;
tok->err = json_tokener_success;
}
struct json_object* json_tokener_parse(const char *str)
{
enum json_tokener_error jerr_ignored;
struct json_object* obj;
obj = json_tokener_parse_verbose(str, &jerr_ignored);
return obj;
}
struct json_object* json_tokener_parse_verbose(const char *str, enum json_tokener_error *error)
{
struct json_tokener* tok;
struct json_object* obj;
tok = json_tokener_new();
if (!tok)
return NULL;
obj = json_tokener_parse_ex(tok, str, -1);
*error = tok->err;
if(tok->err != json_tokener_success) {
if (obj != NULL)
json_object_put(obj);
obj = NULL;
}
json_tokener_free(tok);
return obj;
}
#define state tok->stack[tok->depth].state
#define saved_state tok->stack[tok->depth].saved_state
#define current tok->stack[tok->depth].current
#define obj_field_name tok->stack[tok->depth].obj_field_name
/* Optimization:
* json_tokener_parse_ex() consumed a lot of CPU in its main loop,
* iterating character-by character. A large performance boost is
* achieved by using tighter loops to locally handle units such as
* comments and strings. Loops that handle an entire token within
* their scope also gather entire strings and pass them to
* printbuf_memappend() in a single call, rather than calling
* printbuf_memappend() one char at a time.
*
* PEEK_CHAR() and ADVANCE_CHAR() macros are used for code that is
* common to both the main loop and the tighter loops.
*/
/* PEEK_CHAR(dest, tok) macro:
* Peeks at the current char and stores it in dest.
* Returns 1 on success, sets tok->err and returns 0 if no more chars.
* Implicit inputs: str, len vars
*/
#define PEEK_CHAR(dest, tok) \
(((tok)->char_offset == len) ? \
(((tok)->depth == 0 && state == json_tokener_state_eatws && saved_state == json_tokener_state_finish) ? \
(((tok)->err = json_tokener_success), 0) \
: \
(((tok)->err = json_tokener_continue), 0) \
) : \
(((dest) = *str), 1) \
)
/* ADVANCE_CHAR() macro:
* Incrementes str & tok->char_offset.
* For convenience of existing conditionals, returns the old value of c (0 on eof)
* Implicit inputs: c var
*/
#define ADVANCE_CHAR(str, tok) \
( ++(str), ((tok)->char_offset)++, c)
/* End optimization macro defs */
struct json_object* json_tokener_parse_ex(struct json_tokener *tok,
const char *str, int len)
{
struct json_object *obj = NULL;
char c = '\1';
#ifdef HAVE_SETLOCALE
char *oldlocale=NULL, *tmplocale;
tmplocale = setlocale(LC_NUMERIC, NULL);
if (tmplocale) oldlocale = strdup(tmplocale);
setlocale(LC_NUMERIC, "C");
#endif
tok->char_offset = 0;
tok->err = json_tokener_success;
while (PEEK_CHAR(c, tok)) {
redo_char:
switch(state) {
case json_tokener_state_eatws:
/* Advance until we change state */
while (isspace((int)c)) {
if ((!ADVANCE_CHAR(str, tok)) || (!PEEK_CHAR(c, tok)))
goto out;
}
if(c == '/' && !(tok->flags & JSON_TOKENER_STRICT)) {
printbuf_reset(tok->pb);
printbuf_memappend_fast(tok->pb, &c, 1);
state = json_tokener_state_comment_start;
} else {
state = saved_state;
goto redo_char;
}
break;
case json_tokener_state_start:
switch(c) {
case '{':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_object_field_start;
current = json_object_new_object();
break;
case '[':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_array;
current = json_object_new_array();
break;
case 'I':
case 'i':
state = json_tokener_state_inf;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case 'N':
case 'n':
state = json_tokener_state_null; // or NaN
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case '\'':
if (tok->flags & JSON_TOKENER_STRICT) {
/* in STRICT mode only double-quote are allowed */
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
case '"':
state = json_tokener_state_string;
printbuf_reset(tok->pb);
tok->quote_char = c;
break;
case 'T':
case 't':
case 'F':
case 'f':
state = json_tokener_state_boolean;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
#if defined(__GNUC__)
case '0' ... '9':
#else
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
#endif
case '-':
state = json_tokener_state_number;
printbuf_reset(tok->pb);
tok->is_double = 0;
goto redo_char;
default:
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
break;
case json_tokener_state_finish:
if(tok->depth == 0) goto out;
obj = json_object_get(current);
json_tokener_reset_level(tok, tok->depth);
tok->depth--;
goto redo_char;
case json_tokener_state_inf: /* aka starts with 'i' */
{
int size;
int size_inf;
int is_negative = 0;
printbuf_memappend_fast(tok->pb, &c, 1);
size = json_min(tok->st_pos+1, json_null_str_len);
size_inf = json_min(tok->st_pos+1, json_inf_str_len);
char *infbuf = tok->pb->buf;
if (*infbuf == '-')
{
infbuf++;
is_negative = 1;
}
if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_inf_str, infbuf, size_inf) == 0) ||
(strncmp(json_inf_str, infbuf, size_inf) == 0)
)
{
if (tok->st_pos == json_inf_str_len)
{
current = json_object_new_double(is_negative ? -INFINITY : INFINITY);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_null: /* aka starts with 'n' */
{
int size;
int size_nan;
printbuf_memappend_fast(tok->pb, &c, 1);
size = json_min(tok->st_pos+1, json_null_str_len);
size_nan = json_min(tok->st_pos+1, json_nan_str_len);
if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_null_str, tok->pb->buf, size) == 0)
|| (strncmp(json_null_str, tok->pb->buf, size) == 0)
) {
if (tok->st_pos == json_null_str_len) {
current = NULL;
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
}
else if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_nan_str, tok->pb->buf, size_nan) == 0) ||
(strncmp(json_nan_str, tok->pb->buf, size_nan) == 0)
)
{
if (tok->st_pos == json_nan_str_len)
{
current = json_object_new_double(NAN);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_null;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_comment_start:
if(c == '*') {
state = json_tokener_state_comment;
} else if(c == '/') {
state = json_tokener_state_comment_eol;
} else {
tok->err = json_tokener_error_parse_comment;
goto out;
}
printbuf_memappend_fast(tok->pb, &c, 1);
break;
case json_tokener_state_comment:
{
/* Advance until we change state */
const char *case_start = str;
while(c != '*') {
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
printbuf_memappend_fast(tok->pb, case_start, 1+str-case_start);
state = json_tokener_state_comment_end;
}
break;
case json_tokener_state_comment_eol:
{
/* Advance until we change state */
const char *case_start = str;
while(c != '\n') {
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
}
break;
case json_tokener_state_comment_end:
printbuf_memappend_fast(tok->pb, &c, 1);
if(c == '/') {
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
} else {
state = json_tokener_state_comment;
}
break;
case json_tokener_state_string:
{
/* Advance until we change state */
const char *case_start = str;
while(1) {
if(c == tok->quote_char) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
current = json_object_new_string_len(tok->pb->buf, tok->pb->bpos);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
break;
} else if(c == '\\') {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
saved_state = json_tokener_state_string;
state = json_tokener_state_string_escape;
break;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
}
break;
case json_tokener_state_string_escape:
switch(c) {
case '"':
case '\\':
case '/':
printbuf_memappend_fast(tok->pb, &c, 1);
state = saved_state;
break;
case 'b':
case 'n':
case 'r':
case 't':
case 'f':
if(c == 'b') printbuf_memappend_fast(tok->pb, "\b", 1);
else if(c == 'n') printbuf_memappend_fast(tok->pb, "\n", 1);
else if(c == 'r') printbuf_memappend_fast(tok->pb, "\r", 1);
else if(c == 't') printbuf_memappend_fast(tok->pb, "\t", 1);
else if(c == 'f') printbuf_memappend_fast(tok->pb, "\f", 1);
state = saved_state;
break;
case 'u':
tok->ucs_char = 0;
tok->st_pos = 0;
state = json_tokener_state_escape_unicode;
break;
default:
tok->err = json_tokener_error_parse_string;
goto out;
}
break;
case json_tokener_state_escape_unicode:
{
unsigned int got_hi_surrogate = 0;
/* Handle a 4-byte sequence, or two sequences if a surrogate pair */
while(1) {
if(strchr(json_hex_chars, c)) {
tok->ucs_char += ((unsigned int)hexdigit(c) << ((3-tok->st_pos++)*4));
if(tok->st_pos == 4) {
unsigned char unescaped_utf[4];
if (got_hi_surrogate) {
if (IS_LOW_SURROGATE(tok->ucs_char)) {
/* Recalculate the ucs_char, then fall thru to process normally */
tok->ucs_char = DECODE_SURROGATE_PAIR(got_hi_surrogate, tok->ucs_char);
} else {
/* Hi surrogate was not followed by a low surrogate */
/* Replace the hi and process the rest normally */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
got_hi_surrogate = 0;
}
if (tok->ucs_char < 0x80) {
unescaped_utf[0] = tok->ucs_char;
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 1);
} else if (tok->ucs_char < 0x800) {
unescaped_utf[0] = 0xc0 | (tok->ucs_char >> 6);
unescaped_utf[1] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 2);
} else if (IS_HIGH_SURROGATE(tok->ucs_char)) {
/* Got a high surrogate. Remember it and look for the
* the beginning of another sequence, which should be the
* low surrogate.
*/
got_hi_surrogate = tok->ucs_char;
/* Not at end, and the next two chars should be "\u" */
if ((tok->char_offset+1 != len) &&
(tok->char_offset+2 != len) &&
(str[1] == '\\') &&
(str[2] == 'u'))
{
/* Advance through the 16 bit surrogate, and move on to the
* next sequence. The next step is to process the following
* characters.
*/
if( !ADVANCE_CHAR(str, tok) || !ADVANCE_CHAR(str, tok) ) {
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
/* Advance to the first char of the next sequence and
* continue processing with the next sequence.
*/
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
goto out;
}
tok->ucs_char = 0;
tok->st_pos = 0;
continue; /* other json_tokener_state_escape_unicode */
} else {
/* Got a high surrogate without another sequence following
* it. Put a replacement char in for the hi surrogate
* and pretend we finished.
*/
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
} else if (IS_LOW_SURROGATE(tok->ucs_char)) {
/* Got a low surrogate not preceded by a high */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
} else if (tok->ucs_char < 0x10000) {
unescaped_utf[0] = 0xe0 | (tok->ucs_char >> 12);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[2] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 3);
} else if (tok->ucs_char < 0x110000) {
unescaped_utf[0] = 0xf0 | ((tok->ucs_char >> 18) & 0x07);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 12) & 0x3f);
unescaped_utf[2] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[3] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 4);
} else {
/* Don't know what we got--insert the replacement char */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
state = saved_state;
break;
}
} else {
tok->err = json_tokener_error_parse_string;
goto out;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
if (got_hi_surrogate) /* Clean up any pending chars */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
goto out;
}
}
}
break;
case json_tokener_state_boolean:
{
int size1, size2;
printbuf_memappend_fast(tok->pb, &c, 1);
size1 = json_min(tok->st_pos+1, json_true_str_len);
size2 = json_min(tok->st_pos+1, json_false_str_len);
if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_true_str, tok->pb->buf, size1) == 0)
|| (strncmp(json_true_str, tok->pb->buf, size1) == 0)
) {
if(tok->st_pos == json_true_str_len) {
current = json_object_new_boolean(1);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_false_str, tok->pb->buf, size2) == 0)
|| (strncmp(json_false_str, tok->pb->buf, size2) == 0)) {
if(tok->st_pos == json_false_str_len) {
current = json_object_new_boolean(0);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_boolean;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_number:
{
/* Advance until we change state */
const char *case_start = str;
int case_len=0;
while(c && strchr(json_number_chars, c)) {
++case_len;
if(c == '.' || c == 'e' || c == 'E')
tok->is_double = 1;
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, case_len);
goto out;
}
}
if (case_len>0)
printbuf_memappend_fast(tok->pb, case_start, case_len);
// Check for -Infinity
if (tok->pb->buf[0] == '-' && case_len == 1 &&
(c == 'i' || c == 'I'))
{
state = json_tokener_state_inf;
goto redo_char;
}
}
{
int64_t num64;
double numd;
if (!tok->is_double && json_parse_int64(tok->pb->buf, &num64) == 0) {
if (num64 && tok->pb->buf[0]=='0' && (tok->flags & JSON_TOKENER_STRICT)) {
/* in strict mode, number must not start with 0 */
tok->err = json_tokener_error_parse_number;
goto out;
}
current = json_object_new_int64(num64);
}
else if(tok->is_double && json_parse_double(tok->pb->buf, &numd) == 0)
{
current = json_object_new_double_s(numd, tok->pb->buf);
} else {
tok->err = json_tokener_error_parse_number;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
break;
case json_tokener_state_array_after_sep:
case json_tokener_state_array:
if(c == ']') {
if (state == json_tokener_state_array_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else {
if(tok->depth >= tok->max_depth-1) {
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_array_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
}
break;
case json_tokener_state_array_add:
json_object_array_add(current, obj);
saved_state = json_tokener_state_array_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_array_sep:
if(c == ']') {
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if(c == ',') {
saved_state = json_tokener_state_array_after_sep;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_array;
goto out;
}
break;
case json_tokener_state_object_field_start:
case json_tokener_state_object_field_start_after_sep:
if(c == '}') {
if (state == json_tokener_state_object_field_start_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if (c == '"' || c == '\'') {
tok->quote_char = c;
printbuf_reset(tok->pb);
state = json_tokener_state_object_field;
} else {
tok->err = json_tokener_error_parse_object_key_name;
goto out;
}
break;
case json_tokener_state_object_field:
{
/* Advance until we change state */
const char *case_start = str;
while(1) {
if(c == tok->quote_char) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
obj_field_name = strdup(tok->pb->buf);
saved_state = json_tokener_state_object_field_end;
state = json_tokener_state_eatws;
break;
} else if(c == '\\') {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
saved_state = json_tokener_state_object_field;
state = json_tokener_state_string_escape;
break;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
}
break;
case json_tokener_state_object_field_end:
if(c == ':') {
saved_state = json_tokener_state_object_value;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_object_key_sep;
goto out;
}
break;
case json_tokener_state_object_value:
if(tok->depth >= tok->max_depth-1) {
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_object_value_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
case json_tokener_state_object_value_add:
json_object_object_add(current, obj_field_name, obj);
free(obj_field_name);
obj_field_name = NULL;
saved_state = json_tokener_state_object_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_object_sep:
if(c == '}') {
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if(c == ',') {
saved_state = json_tokener_state_object_field_start_after_sep;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_object_value_sep;
goto out;
}
break;
}
if (!ADVANCE_CHAR(str, tok))
goto out;
} /* while(POP_CHAR) */
out:
if (c &&
(state == json_tokener_state_finish) &&
(tok->depth == 0) &&
(tok->flags & JSON_TOKENER_STRICT)) {
/* unexpected char after JSON data */
tok->err = json_tokener_error_parse_unexpected;
}
if (!c) { /* We hit an eof char (0) */
if(state != json_tokener_state_finish &&
saved_state != json_tokener_state_finish)
tok->err = json_tokener_error_parse_eof;
}
#ifdef HAVE_SETLOCALE
setlocale(LC_NUMERIC, oldlocale);
if (oldlocale) free(oldlocale);
#endif
if (tok->err == json_tokener_success)
{
json_object *ret = json_object_get(current);
int ii;
/* Partially reset, so we parse additional objects on subsequent calls. */
for(ii = tok->depth; ii >= 0; ii--)
json_tokener_reset_level(tok, ii);
return ret;
}
MC_DEBUG("json_tokener_parse_ex: error %s at offset %d\n",
json_tokener_errors[tok->err], tok->char_offset);
return NULL;
}
void json_tokener_set_flags(struct json_tokener *tok, int flags)
{
tok->flags = flags;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5795_5 |
crossvul-cpp_data_bad_2915_0 | /*
* message.c - synchronous message handling
*
* Released under the GPLv2 only.
* SPDX-License-Identifier: GPL-2.0
*/
#include <linux/pci.h> /* for scatterlist macros */
#include <linux/usb.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/timer.h>
#include <linux/ctype.h>
#include <linux/nls.h>
#include <linux/device.h>
#include <linux/scatterlist.h>
#include <linux/usb/cdc.h>
#include <linux/usb/quirks.h>
#include <linux/usb/hcd.h> /* for usbcore internals */
#include <asm/byteorder.h>
#include "usb.h"
static void cancel_async_set_config(struct usb_device *udev);
struct api_context {
struct completion done;
int status;
};
static void usb_api_blocking_completion(struct urb *urb)
{
struct api_context *ctx = urb->context;
ctx->status = urb->status;
complete(&ctx->done);
}
/*
* Starts urb and waits for completion or timeout. Note that this call
* is NOT interruptible. Many device driver i/o requests should be
* interruptible and therefore these drivers should implement their
* own interruptible routines.
*/
static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length)
{
struct api_context ctx;
unsigned long expire;
int retval;
init_completion(&ctx.done);
urb->context = &ctx;
urb->actual_length = 0;
retval = usb_submit_urb(urb, GFP_NOIO);
if (unlikely(retval))
goto out;
expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
if (!wait_for_completion_timeout(&ctx.done, expire)) {
usb_kill_urb(urb);
retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status);
dev_dbg(&urb->dev->dev,
"%s timed out on ep%d%s len=%u/%u\n",
current->comm,
usb_endpoint_num(&urb->ep->desc),
usb_urb_dir_in(urb) ? "in" : "out",
urb->actual_length,
urb->transfer_buffer_length);
} else
retval = ctx.status;
out:
if (actual_length)
*actual_length = urb->actual_length;
usb_free_urb(urb);
return retval;
}
/*-------------------------------------------------------------------*/
/* returns status (negative) or length (positive) */
static int usb_internal_control_msg(struct usb_device *usb_dev,
unsigned int pipe,
struct usb_ctrlrequest *cmd,
void *data, int len, int timeout)
{
struct urb *urb;
int retv;
int length;
urb = usb_alloc_urb(0, GFP_NOIO);
if (!urb)
return -ENOMEM;
usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
len, usb_api_blocking_completion, NULL);
retv = usb_start_wait_urb(urb, timeout, &length);
if (retv < 0)
return retv;
else
return length;
}
/**
* usb_control_msg - Builds a control urb, sends it off and waits for completion
* @dev: pointer to the usb device to send the message to
* @pipe: endpoint "pipe" to send the message to
* @request: USB message request value
* @requesttype: USB message request type value
* @value: USB message value
* @index: USB message index value
* @data: pointer to the data to send
* @size: length in bytes of the data to send
* @timeout: time in msecs to wait for the message to complete before timing
* out (if 0 the wait is forever)
*
* Context: !in_interrupt ()
*
* This function sends a simple control message to a specified endpoint and
* waits for the message to complete, or timeout.
*
* Don't use this function from within an interrupt context. If you need
* an asynchronous message, or need to send a message from within interrupt
* context, use usb_submit_urb(). If a thread in your driver uses this call,
* make sure your disconnect() method can wait for it to complete. Since you
* don't have a handle on the URB used, you can't cancel the request.
*
* Return: If successful, the number of bytes transferred. Otherwise, a negative
* error number.
*/
int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
__u8 requesttype, __u16 value, __u16 index, void *data,
__u16 size, int timeout)
{
struct usb_ctrlrequest *dr;
int ret;
dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
if (!dr)
return -ENOMEM;
dr->bRequestType = requesttype;
dr->bRequest = request;
dr->wValue = cpu_to_le16(value);
dr->wIndex = cpu_to_le16(index);
dr->wLength = cpu_to_le16(size);
ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
kfree(dr);
return ret;
}
EXPORT_SYMBOL_GPL(usb_control_msg);
/**
* usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
* @usb_dev: pointer to the usb device to send the message to
* @pipe: endpoint "pipe" to send the message to
* @data: pointer to the data to send
* @len: length in bytes of the data to send
* @actual_length: pointer to a location to put the actual length transferred
* in bytes
* @timeout: time in msecs to wait for the message to complete before
* timing out (if 0 the wait is forever)
*
* Context: !in_interrupt ()
*
* This function sends a simple interrupt message to a specified endpoint and
* waits for the message to complete, or timeout.
*
* Don't use this function from within an interrupt context. If you need
* an asynchronous message, or need to send a message from within interrupt
* context, use usb_submit_urb() If a thread in your driver uses this call,
* make sure your disconnect() method can wait for it to complete. Since you
* don't have a handle on the URB used, you can't cancel the request.
*
* Return:
* If successful, 0. Otherwise a negative error number. The number of actual
* bytes transferred will be stored in the @actual_length parameter.
*/
int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
void *data, int len, int *actual_length, int timeout)
{
return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
}
EXPORT_SYMBOL_GPL(usb_interrupt_msg);
/**
* usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
* @usb_dev: pointer to the usb device to send the message to
* @pipe: endpoint "pipe" to send the message to
* @data: pointer to the data to send
* @len: length in bytes of the data to send
* @actual_length: pointer to a location to put the actual length transferred
* in bytes
* @timeout: time in msecs to wait for the message to complete before
* timing out (if 0 the wait is forever)
*
* Context: !in_interrupt ()
*
* This function sends a simple bulk message to a specified endpoint
* and waits for the message to complete, or timeout.
*
* Don't use this function from within an interrupt context. If you need
* an asynchronous message, or need to send a message from within interrupt
* context, use usb_submit_urb() If a thread in your driver uses this call,
* make sure your disconnect() method can wait for it to complete. Since you
* don't have a handle on the URB used, you can't cancel the request.
*
* Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
* users are forced to abuse this routine by using it to submit URBs for
* interrupt endpoints. We will take the liberty of creating an interrupt URB
* (with the default interval) if the target is an interrupt endpoint.
*
* Return:
* If successful, 0. Otherwise a negative error number. The number of actual
* bytes transferred will be stored in the @actual_length parameter.
*
*/
int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
void *data, int len, int *actual_length, int timeout)
{
struct urb *urb;
struct usb_host_endpoint *ep;
ep = usb_pipe_endpoint(usb_dev, pipe);
if (!ep || len < 0)
return -EINVAL;
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb)
return -ENOMEM;
if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_INT) {
pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
usb_fill_int_urb(urb, usb_dev, pipe, data, len,
usb_api_blocking_completion, NULL,
ep->desc.bInterval);
} else
usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
usb_api_blocking_completion, NULL);
return usb_start_wait_urb(urb, timeout, actual_length);
}
EXPORT_SYMBOL_GPL(usb_bulk_msg);
/*-------------------------------------------------------------------*/
static void sg_clean(struct usb_sg_request *io)
{
if (io->urbs) {
while (io->entries--)
usb_free_urb(io->urbs[io->entries]);
kfree(io->urbs);
io->urbs = NULL;
}
io->dev = NULL;
}
static void sg_complete(struct urb *urb)
{
struct usb_sg_request *io = urb->context;
int status = urb->status;
spin_lock(&io->lock);
/* In 2.5 we require hcds' endpoint queues not to progress after fault
* reports, until the completion callback (this!) returns. That lets
* device driver code (like this routine) unlink queued urbs first,
* if it needs to, since the HC won't work on them at all. So it's
* not possible for page N+1 to overwrite page N, and so on.
*
* That's only for "hard" faults; "soft" faults (unlinks) sometimes
* complete before the HCD can get requests away from hardware,
* though never during cleanup after a hard fault.
*/
if (io->status
&& (io->status != -ECONNRESET
|| status != -ECONNRESET)
&& urb->actual_length) {
dev_err(io->dev->bus->controller,
"dev %s ep%d%s scatterlist error %d/%d\n",
io->dev->devpath,
usb_endpoint_num(&urb->ep->desc),
usb_urb_dir_in(urb) ? "in" : "out",
status, io->status);
/* BUG (); */
}
if (io->status == 0 && status && status != -ECONNRESET) {
int i, found, retval;
io->status = status;
/* the previous urbs, and this one, completed already.
* unlink pending urbs so they won't rx/tx bad data.
* careful: unlink can sometimes be synchronous...
*/
spin_unlock(&io->lock);
for (i = 0, found = 0; i < io->entries; i++) {
if (!io->urbs[i])
continue;
if (found) {
usb_block_urb(io->urbs[i]);
retval = usb_unlink_urb(io->urbs[i]);
if (retval != -EINPROGRESS &&
retval != -ENODEV &&
retval != -EBUSY &&
retval != -EIDRM)
dev_err(&io->dev->dev,
"%s, unlink --> %d\n",
__func__, retval);
} else if (urb == io->urbs[i])
found = 1;
}
spin_lock(&io->lock);
}
/* on the last completion, signal usb_sg_wait() */
io->bytes += urb->actual_length;
io->count--;
if (!io->count)
complete(&io->complete);
spin_unlock(&io->lock);
}
/**
* usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
* @io: request block being initialized. until usb_sg_wait() returns,
* treat this as a pointer to an opaque block of memory,
* @dev: the usb device that will send or receive the data
* @pipe: endpoint "pipe" used to transfer the data
* @period: polling rate for interrupt endpoints, in frames or
* (for high speed endpoints) microframes; ignored for bulk
* @sg: scatterlist entries
* @nents: how many entries in the scatterlist
* @length: how many bytes to send from the scatterlist, or zero to
* send every byte identified in the list.
* @mem_flags: SLAB_* flags affecting memory allocations in this call
*
* This initializes a scatter/gather request, allocating resources such as
* I/O mappings and urb memory (except maybe memory used by USB controller
* drivers).
*
* The request must be issued using usb_sg_wait(), which waits for the I/O to
* complete (or to be canceled) and then cleans up all resources allocated by
* usb_sg_init().
*
* The request may be canceled with usb_sg_cancel(), either before or after
* usb_sg_wait() is called.
*
* Return: Zero for success, else a negative errno value.
*/
int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
unsigned pipe, unsigned period, struct scatterlist *sg,
int nents, size_t length, gfp_t mem_flags)
{
int i;
int urb_flags;
int use_sg;
if (!io || !dev || !sg
|| usb_pipecontrol(pipe)
|| usb_pipeisoc(pipe)
|| nents <= 0)
return -EINVAL;
spin_lock_init(&io->lock);
io->dev = dev;
io->pipe = pipe;
if (dev->bus->sg_tablesize > 0) {
use_sg = true;
io->entries = 1;
} else {
use_sg = false;
io->entries = nents;
}
/* initialize all the urbs we'll use */
io->urbs = kmalloc(io->entries * sizeof(*io->urbs), mem_flags);
if (!io->urbs)
goto nomem;
urb_flags = URB_NO_INTERRUPT;
if (usb_pipein(pipe))
urb_flags |= URB_SHORT_NOT_OK;
for_each_sg(sg, sg, io->entries, i) {
struct urb *urb;
unsigned len;
urb = usb_alloc_urb(0, mem_flags);
if (!urb) {
io->entries = i;
goto nomem;
}
io->urbs[i] = urb;
urb->dev = NULL;
urb->pipe = pipe;
urb->interval = period;
urb->transfer_flags = urb_flags;
urb->complete = sg_complete;
urb->context = io;
urb->sg = sg;
if (use_sg) {
/* There is no single transfer buffer */
urb->transfer_buffer = NULL;
urb->num_sgs = nents;
/* A length of zero means transfer the whole sg list */
len = length;
if (len == 0) {
struct scatterlist *sg2;
int j;
for_each_sg(sg, sg2, nents, j)
len += sg2->length;
}
} else {
/*
* Some systems can't use DMA; they use PIO instead.
* For their sakes, transfer_buffer is set whenever
* possible.
*/
if (!PageHighMem(sg_page(sg)))
urb->transfer_buffer = sg_virt(sg);
else
urb->transfer_buffer = NULL;
len = sg->length;
if (length) {
len = min_t(size_t, len, length);
length -= len;
if (length == 0)
io->entries = i + 1;
}
}
urb->transfer_buffer_length = len;
}
io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
/* transaction state */
io->count = io->entries;
io->status = 0;
io->bytes = 0;
init_completion(&io->complete);
return 0;
nomem:
sg_clean(io);
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(usb_sg_init);
/**
* usb_sg_wait - synchronously execute scatter/gather request
* @io: request block handle, as initialized with usb_sg_init().
* some fields become accessible when this call returns.
* Context: !in_interrupt ()
*
* This function blocks until the specified I/O operation completes. It
* leverages the grouping of the related I/O requests to get good transfer
* rates, by queueing the requests. At higher speeds, such queuing can
* significantly improve USB throughput.
*
* There are three kinds of completion for this function.
*
* (1) success, where io->status is zero. The number of io->bytes
* transferred is as requested.
* (2) error, where io->status is a negative errno value. The number
* of io->bytes transferred before the error is usually less
* than requested, and can be nonzero.
* (3) cancellation, a type of error with status -ECONNRESET that
* is initiated by usb_sg_cancel().
*
* When this function returns, all memory allocated through usb_sg_init() or
* this call will have been freed. The request block parameter may still be
* passed to usb_sg_cancel(), or it may be freed. It could also be
* reinitialized and then reused.
*
* Data Transfer Rates:
*
* Bulk transfers are valid for full or high speed endpoints.
* The best full speed data rate is 19 packets of 64 bytes each
* per frame, or 1216 bytes per millisecond.
* The best high speed data rate is 13 packets of 512 bytes each
* per microframe, or 52 KBytes per millisecond.
*
* The reason to use interrupt transfers through this API would most likely
* be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
* could be transferred. That capability is less useful for low or full
* speed interrupt endpoints, which allow at most one packet per millisecond,
* of at most 8 or 64 bytes (respectively).
*
* It is not necessary to call this function to reserve bandwidth for devices
* under an xHCI host controller, as the bandwidth is reserved when the
* configuration or interface alt setting is selected.
*/
void usb_sg_wait(struct usb_sg_request *io)
{
int i;
int entries = io->entries;
/* queue the urbs. */
spin_lock_irq(&io->lock);
i = 0;
while (i < entries && !io->status) {
int retval;
io->urbs[i]->dev = io->dev;
spin_unlock_irq(&io->lock);
retval = usb_submit_urb(io->urbs[i], GFP_NOIO);
switch (retval) {
/* maybe we retrying will recover */
case -ENXIO: /* hc didn't queue this one */
case -EAGAIN:
case -ENOMEM:
retval = 0;
yield();
break;
/* no error? continue immediately.
*
* NOTE: to work better with UHCI (4K I/O buffer may
* need 3K of TDs) it may be good to limit how many
* URBs are queued at once; N milliseconds?
*/
case 0:
++i;
cpu_relax();
break;
/* fail any uncompleted urbs */
default:
io->urbs[i]->status = retval;
dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
__func__, retval);
usb_sg_cancel(io);
}
spin_lock_irq(&io->lock);
if (retval && (io->status == 0 || io->status == -ECONNRESET))
io->status = retval;
}
io->count -= entries - i;
if (io->count == 0)
complete(&io->complete);
spin_unlock_irq(&io->lock);
/* OK, yes, this could be packaged as non-blocking.
* So could the submit loop above ... but it's easier to
* solve neither problem than to solve both!
*/
wait_for_completion(&io->complete);
sg_clean(io);
}
EXPORT_SYMBOL_GPL(usb_sg_wait);
/**
* usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
* @io: request block, initialized with usb_sg_init()
*
* This stops a request after it has been started by usb_sg_wait().
* It can also prevents one initialized by usb_sg_init() from starting,
* so that call just frees resources allocated to the request.
*/
void usb_sg_cancel(struct usb_sg_request *io)
{
unsigned long flags;
int i, retval;
spin_lock_irqsave(&io->lock, flags);
if (io->status) {
spin_unlock_irqrestore(&io->lock, flags);
return;
}
/* shut everything down */
io->status = -ECONNRESET;
spin_unlock_irqrestore(&io->lock, flags);
for (i = io->entries - 1; i >= 0; --i) {
usb_block_urb(io->urbs[i]);
retval = usb_unlink_urb(io->urbs[i]);
if (retval != -EINPROGRESS
&& retval != -ENODEV
&& retval != -EBUSY
&& retval != -EIDRM)
dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
__func__, retval);
}
}
EXPORT_SYMBOL_GPL(usb_sg_cancel);
/*-------------------------------------------------------------------*/
/**
* usb_get_descriptor - issues a generic GET_DESCRIPTOR request
* @dev: the device whose descriptor is being retrieved
* @type: the descriptor type (USB_DT_*)
* @index: the number of the descriptor
* @buf: where to put the descriptor
* @size: how big is "buf"?
* Context: !in_interrupt ()
*
* Gets a USB descriptor. Convenience functions exist to simplify
* getting some types of descriptors. Use
* usb_get_string() or usb_string() for USB_DT_STRING.
* Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
* are part of the device structure.
* In addition to a number of USB-standard descriptors, some
* devices also use class-specific or vendor-specific descriptors.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: The number of bytes received on success, or else the status code
* returned by the underlying usb_control_msg() call.
*/
int usb_get_descriptor(struct usb_device *dev, unsigned char type,
unsigned char index, void *buf, int size)
{
int i;
int result;
memset(buf, 0, size); /* Make sure we parse really received data */
for (i = 0; i < 3; ++i) {
/* retry on length 0 or error; some devices are flakey */
result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
(type << 8) + index, 0, buf, size,
USB_CTRL_GET_TIMEOUT);
if (result <= 0 && result != -ETIMEDOUT)
continue;
if (result > 1 && ((u8 *)buf)[1] != type) {
result = -ENODATA;
continue;
}
break;
}
return result;
}
EXPORT_SYMBOL_GPL(usb_get_descriptor);
/**
* usb_get_string - gets a string descriptor
* @dev: the device whose string descriptor is being retrieved
* @langid: code for language chosen (from string descriptor zero)
* @index: the number of the descriptor
* @buf: where to put the string
* @size: how big is "buf"?
* Context: !in_interrupt ()
*
* Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
* in little-endian byte order).
* The usb_string() function will often be a convenient way to turn
* these strings into kernel-printable form.
*
* Strings may be referenced in device, configuration, interface, or other
* descriptors, and could also be used in vendor-specific ways.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: The number of bytes received on success, or else the status code
* returned by the underlying usb_control_msg() call.
*/
static int usb_get_string(struct usb_device *dev, unsigned short langid,
unsigned char index, void *buf, int size)
{
int i;
int result;
for (i = 0; i < 3; ++i) {
/* retry on length 0 or stall; some devices are flakey */
result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
(USB_DT_STRING << 8) + index, langid, buf, size,
USB_CTRL_GET_TIMEOUT);
if (result == 0 || result == -EPIPE)
continue;
if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
result = -ENODATA;
continue;
}
break;
}
return result;
}
static void usb_try_string_workarounds(unsigned char *buf, int *length)
{
int newlength, oldlength = *length;
for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
if (!isprint(buf[newlength]) || buf[newlength + 1])
break;
if (newlength > 2) {
buf[0] = newlength;
*length = newlength;
}
}
static int usb_string_sub(struct usb_device *dev, unsigned int langid,
unsigned int index, unsigned char *buf)
{
int rc;
/* Try to read the string descriptor by asking for the maximum
* possible number of bytes */
if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
rc = -EIO;
else
rc = usb_get_string(dev, langid, index, buf, 255);
/* If that failed try to read the descriptor length, then
* ask for just that many bytes */
if (rc < 2) {
rc = usb_get_string(dev, langid, index, buf, 2);
if (rc == 2)
rc = usb_get_string(dev, langid, index, buf, buf[0]);
}
if (rc >= 2) {
if (!buf[0] && !buf[1])
usb_try_string_workarounds(buf, &rc);
/* There might be extra junk at the end of the descriptor */
if (buf[0] < rc)
rc = buf[0];
rc = rc - (rc & 1); /* force a multiple of two */
}
if (rc < 2)
rc = (rc < 0 ? rc : -EINVAL);
return rc;
}
static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
{
int err;
if (dev->have_langid)
return 0;
if (dev->string_langid < 0)
return -EPIPE;
err = usb_string_sub(dev, 0, 0, tbuf);
/* If the string was reported but is malformed, default to english
* (0x0409) */
if (err == -ENODATA || (err > 0 && err < 4)) {
dev->string_langid = 0x0409;
dev->have_langid = 1;
dev_err(&dev->dev,
"language id specifier not provided by device, defaulting to English\n");
return 0;
}
/* In case of all other errors, we assume the device is not able to
* deal with strings at all. Set string_langid to -1 in order to
* prevent any string to be retrieved from the device */
if (err < 0) {
dev_err(&dev->dev, "string descriptor 0 read error: %d\n",
err);
dev->string_langid = -1;
return -EPIPE;
}
/* always use the first langid listed */
dev->string_langid = tbuf[2] | (tbuf[3] << 8);
dev->have_langid = 1;
dev_dbg(&dev->dev, "default language 0x%04x\n",
dev->string_langid);
return 0;
}
/**
* usb_string - returns UTF-8 version of a string descriptor
* @dev: the device whose string descriptor is being retrieved
* @index: the number of the descriptor
* @buf: where to put the string
* @size: how big is "buf"?
* Context: !in_interrupt ()
*
* This converts the UTF-16LE encoded strings returned by devices, from
* usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
* that are more usable in most kernel contexts. Note that this function
* chooses strings in the first language supported by the device.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: length of the string (>= 0) or usb_control_msg status (< 0).
*/
int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
{
unsigned char *tbuf;
int err;
if (dev->state == USB_STATE_SUSPENDED)
return -EHOSTUNREACH;
if (size <= 0 || !buf || !index)
return -EINVAL;
buf[0] = 0;
tbuf = kmalloc(256, GFP_NOIO);
if (!tbuf)
return -ENOMEM;
err = usb_get_langid(dev, tbuf);
if (err < 0)
goto errout;
err = usb_string_sub(dev, dev->string_langid, index, tbuf);
if (err < 0)
goto errout;
size--; /* leave room for trailing NULL char in output buffer */
err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
UTF16_LITTLE_ENDIAN, buf, size);
buf[err] = 0;
if (tbuf[1] != USB_DT_STRING)
dev_dbg(&dev->dev,
"wrong descriptor type %02x for string %d (\"%s\")\n",
tbuf[1], index, buf);
errout:
kfree(tbuf);
return err;
}
EXPORT_SYMBOL_GPL(usb_string);
/* one UTF-8-encoded 16-bit character has at most three bytes */
#define MAX_USB_STRING_SIZE (127 * 3 + 1)
/**
* usb_cache_string - read a string descriptor and cache it for later use
* @udev: the device whose string descriptor is being read
* @index: the descriptor index
*
* Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
* or %NULL if the index is 0 or the string could not be read.
*/
char *usb_cache_string(struct usb_device *udev, int index)
{
char *buf;
char *smallbuf = NULL;
int len;
if (index <= 0)
return NULL;
buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
if (buf) {
len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
if (len > 0) {
smallbuf = kmalloc(++len, GFP_NOIO);
if (!smallbuf)
return buf;
memcpy(smallbuf, buf, len);
}
kfree(buf);
}
return smallbuf;
}
/*
* usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
* @dev: the device whose device descriptor is being updated
* @size: how much of the descriptor to read
* Context: !in_interrupt ()
*
* Updates the copy of the device descriptor stored in the device structure,
* which dedicates space for this purpose.
*
* Not exported, only for use by the core. If drivers really want to read
* the device descriptor directly, they can call usb_get_descriptor() with
* type = USB_DT_DEVICE and index = 0.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: The number of bytes received on success, or else the status code
* returned by the underlying usb_control_msg() call.
*/
int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
{
struct usb_device_descriptor *desc;
int ret;
if (size > sizeof(*desc))
return -EINVAL;
desc = kmalloc(sizeof(*desc), GFP_NOIO);
if (!desc)
return -ENOMEM;
ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
if (ret >= 0)
memcpy(&dev->descriptor, desc, size);
kfree(desc);
return ret;
}
/**
* usb_get_status - issues a GET_STATUS call
* @dev: the device whose status is being checked
* @type: USB_RECIP_*; for device, interface, or endpoint
* @target: zero (for device), else interface or endpoint number
* @data: pointer to two bytes of bitmap data
* Context: !in_interrupt ()
*
* Returns device, interface, or endpoint status. Normally only of
* interest to see if the device is self powered, or has enabled the
* remote wakeup facility; or whether a bulk or interrupt endpoint
* is halted ("stalled").
*
* Bits in these status bitmaps are set using the SET_FEATURE request,
* and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
* function should be used to clear halt ("stall") status.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Returns 0 and the status value in *@data (in host byte order) on success,
* or else the status code from the underlying usb_control_msg() call.
*/
int usb_get_status(struct usb_device *dev, int type, int target, void *data)
{
int ret;
__le16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
if (!status)
return -ENOMEM;
ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
sizeof(*status), USB_CTRL_GET_TIMEOUT);
if (ret == 2) {
*(u16 *) data = le16_to_cpu(*status);
ret = 0;
} else if (ret >= 0) {
ret = -EIO;
}
kfree(status);
return ret;
}
EXPORT_SYMBOL_GPL(usb_get_status);
/**
* usb_clear_halt - tells device to clear endpoint halt/stall condition
* @dev: device whose endpoint is halted
* @pipe: endpoint "pipe" being cleared
* Context: !in_interrupt ()
*
* This is used to clear halt conditions for bulk and interrupt endpoints,
* as reported by URB completion status. Endpoints that are halted are
* sometimes referred to as being "stalled". Such endpoints are unable
* to transmit or receive data until the halt status is cleared. Any URBs
* queued for such an endpoint should normally be unlinked by the driver
* before clearing the halt condition, as described in sections 5.7.5
* and 5.8.5 of the USB 2.0 spec.
*
* Note that control and isochronous endpoints don't halt, although control
* endpoints report "protocol stall" (for unsupported requests) using the
* same status code used to report a true stall.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: Zero on success, or else the status code returned by the
* underlying usb_control_msg() call.
*/
int usb_clear_halt(struct usb_device *dev, int pipe)
{
int result;
int endp = usb_pipeendpoint(pipe);
if (usb_pipein(pipe))
endp |= USB_DIR_IN;
/* we don't care if it wasn't halted first. in fact some devices
* (like some ibmcam model 1 units) seem to expect hosts to make
* this request for iso endpoints, which can't halt!
*/
result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
USB_ENDPOINT_HALT, endp, NULL, 0,
USB_CTRL_SET_TIMEOUT);
/* don't un-halt or force to DATA0 except on success */
if (result < 0)
return result;
/* NOTE: seems like Microsoft and Apple don't bother verifying
* the clear "took", so some devices could lock up if you check...
* such as the Hagiwara FlashGate DUAL. So we won't bother.
*
* NOTE: make sure the logic here doesn't diverge much from
* the copy in usb-storage, for as long as we need two copies.
*/
usb_reset_endpoint(dev, endp);
return 0;
}
EXPORT_SYMBOL_GPL(usb_clear_halt);
static int create_intf_ep_devs(struct usb_interface *intf)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
if (intf->ep_devs_created || intf->unregistering)
return 0;
for (i = 0; i < alt->desc.bNumEndpoints; ++i)
(void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
intf->ep_devs_created = 1;
return 0;
}
static void remove_intf_ep_devs(struct usb_interface *intf)
{
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
if (!intf->ep_devs_created)
return;
for (i = 0; i < alt->desc.bNumEndpoints; ++i)
usb_remove_ep_devs(&alt->endpoint[i]);
intf->ep_devs_created = 0;
}
/**
* usb_disable_endpoint -- Disable an endpoint by address
* @dev: the device whose endpoint is being disabled
* @epaddr: the endpoint's address. Endpoint number for output,
* endpoint number + USB_DIR_IN for input
* @reset_hardware: flag to erase any endpoint state stored in the
* controller hardware
*
* Disables the endpoint for URB submission and nukes all pending URBs.
* If @reset_hardware is set then also deallocates hcd/hardware state
* for the endpoint.
*/
void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
bool reset_hardware)
{
unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
struct usb_host_endpoint *ep;
if (!dev)
return;
if (usb_endpoint_out(epaddr)) {
ep = dev->ep_out[epnum];
if (reset_hardware)
dev->ep_out[epnum] = NULL;
} else {
ep = dev->ep_in[epnum];
if (reset_hardware)
dev->ep_in[epnum] = NULL;
}
if (ep) {
ep->enabled = 0;
usb_hcd_flush_endpoint(dev, ep);
if (reset_hardware)
usb_hcd_disable_endpoint(dev, ep);
}
}
/**
* usb_reset_endpoint - Reset an endpoint's state.
* @dev: the device whose endpoint is to be reset
* @epaddr: the endpoint's address. Endpoint number for output,
* endpoint number + USB_DIR_IN for input
*
* Resets any host-side endpoint state such as the toggle bit,
* sequence number or current window.
*/
void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
{
unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
struct usb_host_endpoint *ep;
if (usb_endpoint_out(epaddr))
ep = dev->ep_out[epnum];
else
ep = dev->ep_in[epnum];
if (ep)
usb_hcd_reset_endpoint(dev, ep);
}
EXPORT_SYMBOL_GPL(usb_reset_endpoint);
/**
* usb_disable_interface -- Disable all endpoints for an interface
* @dev: the device whose interface is being disabled
* @intf: pointer to the interface descriptor
* @reset_hardware: flag to erase any endpoint state stored in the
* controller hardware
*
* Disables all the endpoints for the interface's current altsetting.
*/
void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
bool reset_hardware)
{
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
usb_disable_endpoint(dev,
alt->endpoint[i].desc.bEndpointAddress,
reset_hardware);
}
}
/**
* usb_disable_device - Disable all the endpoints for a USB device
* @dev: the device whose endpoints are being disabled
* @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
*
* Disables all the device's endpoints, potentially including endpoint 0.
* Deallocates hcd/hardware state for the endpoints (nuking all or most
* pending urbs) and usbcore state for the interfaces, so that usbcore
* must usb_set_configuration() before any interfaces could be used.
*/
void usb_disable_device(struct usb_device *dev, int skip_ep0)
{
int i;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
/* getting rid of interfaces will disconnect
* any drivers bound to them (a key side effect)
*/
if (dev->actconfig) {
/*
* FIXME: In order to avoid self-deadlock involving the
* bandwidth_mutex, we have to mark all the interfaces
* before unregistering any of them.
*/
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
dev->actconfig->interface[i]->unregistering = 1;
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
struct usb_interface *interface;
/* remove this interface if it has been registered */
interface = dev->actconfig->interface[i];
if (!device_is_registered(&interface->dev))
continue;
dev_dbg(&dev->dev, "unregistering interface %s\n",
dev_name(&interface->dev));
remove_intf_ep_devs(interface);
device_del(&interface->dev);
}
/* Now that the interfaces are unbound, nobody should
* try to access them.
*/
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
put_device(&dev->actconfig->interface[i]->dev);
dev->actconfig->interface[i] = NULL;
}
if (dev->usb2_hw_lpm_enabled == 1)
usb_set_usb2_hardware_lpm(dev, 0);
usb_unlocked_disable_lpm(dev);
usb_disable_ltm(dev);
dev->actconfig = NULL;
if (dev->state == USB_STATE_CONFIGURED)
usb_set_device_state(dev, USB_STATE_ADDRESS);
}
dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
skip_ep0 ? "non-ep0" : "all");
if (hcd->driver->check_bandwidth) {
/* First pass: Cancel URBs, leave endpoint pointers intact. */
for (i = skip_ep0; i < 16; ++i) {
usb_disable_endpoint(dev, i, false);
usb_disable_endpoint(dev, i + USB_DIR_IN, false);
}
/* Remove endpoints from the host controller internal state */
mutex_lock(hcd->bandwidth_mutex);
usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
mutex_unlock(hcd->bandwidth_mutex);
/* Second pass: remove endpoint pointers */
}
for (i = skip_ep0; i < 16; ++i) {
usb_disable_endpoint(dev, i, true);
usb_disable_endpoint(dev, i + USB_DIR_IN, true);
}
}
/**
* usb_enable_endpoint - Enable an endpoint for USB communications
* @dev: the device whose interface is being enabled
* @ep: the endpoint
* @reset_ep: flag to reset the endpoint state
*
* Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
* For control endpoints, both the input and output sides are handled.
*/
void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
bool reset_ep)
{
int epnum = usb_endpoint_num(&ep->desc);
int is_out = usb_endpoint_dir_out(&ep->desc);
int is_control = usb_endpoint_xfer_control(&ep->desc);
if (reset_ep)
usb_hcd_reset_endpoint(dev, ep);
if (is_out || is_control)
dev->ep_out[epnum] = ep;
if (!is_out || is_control)
dev->ep_in[epnum] = ep;
ep->enabled = 1;
}
/**
* usb_enable_interface - Enable all the endpoints for an interface
* @dev: the device whose interface is being enabled
* @intf: pointer to the interface descriptor
* @reset_eps: flag to reset the endpoints' state
*
* Enables all the endpoints for the interface's current altsetting.
*/
void usb_enable_interface(struct usb_device *dev,
struct usb_interface *intf, bool reset_eps)
{
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
for (i = 0; i < alt->desc.bNumEndpoints; ++i)
usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
}
/**
* usb_set_interface - Makes a particular alternate setting be current
* @dev: the device whose interface is being updated
* @interface: the interface being updated
* @alternate: the setting being chosen.
* Context: !in_interrupt ()
*
* This is used to enable data transfers on interfaces that may not
* be enabled by default. Not all devices support such configurability.
* Only the driver bound to an interface may change its setting.
*
* Within any given configuration, each interface may have several
* alternative settings. These are often used to control levels of
* bandwidth consumption. For example, the default setting for a high
* speed interrupt endpoint may not send more than 64 bytes per microframe,
* while interrupt transfers of up to 3KBytes per microframe are legal.
* Also, isochronous endpoints may never be part of an
* interface's default setting. To access such bandwidth, alternate
* interface settings must be made current.
*
* Note that in the Linux USB subsystem, bandwidth associated with
* an endpoint in a given alternate setting is not reserved until an URB
* is submitted that needs that bandwidth. Some other operating systems
* allocate bandwidth early, when a configuration is chosen.
*
* This call is synchronous, and may not be used in an interrupt context.
* Also, drivers must not change altsettings while urbs are scheduled for
* endpoints in that interface; all such urbs must first be completed
* (perhaps forced by unlinking).
*
* Return: Zero on success, or else the status code returned by the
* underlying usb_control_msg() call.
*/
int usb_set_interface(struct usb_device *dev, int interface, int alternate)
{
struct usb_interface *iface;
struct usb_host_interface *alt;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
int i, ret, manual = 0;
unsigned int epaddr;
unsigned int pipe;
if (dev->state == USB_STATE_SUSPENDED)
return -EHOSTUNREACH;
iface = usb_ifnum_to_if(dev, interface);
if (!iface) {
dev_dbg(&dev->dev, "selecting invalid interface %d\n",
interface);
return -EINVAL;
}
if (iface->unregistering)
return -ENODEV;
alt = usb_altnum_to_altsetting(iface, alternate);
if (!alt) {
dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
alternate);
return -EINVAL;
}
/* Make sure we have enough bandwidth for this alternate interface.
* Remove the current alt setting and add the new alt setting.
*/
mutex_lock(hcd->bandwidth_mutex);
/* Disable LPM, and re-enable it once the new alt setting is installed,
* so that the xHCI driver can recalculate the U1/U2 timeouts.
*/
if (usb_disable_lpm(dev)) {
dev_err(&iface->dev, "%s Failed to disable LPM\n.", __func__);
mutex_unlock(hcd->bandwidth_mutex);
return -ENOMEM;
}
/* Changing alt-setting also frees any allocated streams */
for (i = 0; i < iface->cur_altsetting->desc.bNumEndpoints; i++)
iface->cur_altsetting->endpoint[i].streams = 0;
ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
if (ret < 0) {
dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
alternate);
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
return ret;
}
if (dev->quirks & USB_QUIRK_NO_SET_INTF)
ret = -EPIPE;
else
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
alternate, interface, NULL, 0, 5000);
/* 9.4.10 says devices don't need this and are free to STALL the
* request if the interface only has one alternate setting.
*/
if (ret == -EPIPE && iface->num_altsetting == 1) {
dev_dbg(&dev->dev,
"manual set_interface for iface %d, alt %d\n",
interface, alternate);
manual = 1;
} else if (ret < 0) {
/* Re-instate the old alt setting */
usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
return ret;
}
mutex_unlock(hcd->bandwidth_mutex);
/* FIXME drivers shouldn't need to replicate/bugfix the logic here
* when they implement async or easily-killable versions of this or
* other "should-be-internal" functions (like clear_halt).
* should hcd+usbcore postprocess control requests?
*/
/* prevent submissions using previous endpoint settings */
if (iface->cur_altsetting != alt) {
remove_intf_ep_devs(iface);
usb_remove_sysfs_intf_files(iface);
}
usb_disable_interface(dev, iface, true);
iface->cur_altsetting = alt;
/* Now that the interface is installed, re-enable LPM. */
usb_unlocked_enable_lpm(dev);
/* If the interface only has one altsetting and the device didn't
* accept the request, we attempt to carry out the equivalent action
* by manually clearing the HALT feature for each endpoint in the
* new altsetting.
*/
if (manual) {
for (i = 0; i < alt->desc.bNumEndpoints; i++) {
epaddr = alt->endpoint[i].desc.bEndpointAddress;
pipe = __create_pipe(dev,
USB_ENDPOINT_NUMBER_MASK & epaddr) |
(usb_endpoint_out(epaddr) ?
USB_DIR_OUT : USB_DIR_IN);
usb_clear_halt(dev, pipe);
}
}
/* 9.1.1.5: reset toggles for all endpoints in the new altsetting
*
* Note:
* Despite EP0 is always present in all interfaces/AS, the list of
* endpoints from the descriptor does not contain EP0. Due to its
* omnipresence one might expect EP0 being considered "affected" by
* any SetInterface request and hence assume toggles need to be reset.
* However, EP0 toggles are re-synced for every individual transfer
* during the SETUP stage - hence EP0 toggles are "don't care" here.
* (Likewise, EP0 never "halts" on well designed devices.)
*/
usb_enable_interface(dev, iface, true);
if (device_is_registered(&iface->dev)) {
usb_create_sysfs_intf_files(iface);
create_intf_ep_devs(iface);
}
return 0;
}
EXPORT_SYMBOL_GPL(usb_set_interface);
/**
* usb_reset_configuration - lightweight device reset
* @dev: the device whose configuration is being reset
*
* This issues a standard SET_CONFIGURATION request to the device using
* the current configuration. The effect is to reset most USB-related
* state in the device, including interface altsettings (reset to zero),
* endpoint halts (cleared), and endpoint state (only for bulk and interrupt
* endpoints). Other usbcore state is unchanged, including bindings of
* usb device drivers to interfaces.
*
* Because this affects multiple interfaces, avoid using this with composite
* (multi-interface) devices. Instead, the driver for each interface may
* use usb_set_interface() on the interfaces it claims. Be careful though;
* some devices don't support the SET_INTERFACE request, and others won't
* reset all the interface state (notably endpoint state). Resetting the whole
* configuration would affect other drivers' interfaces.
*
* The caller must own the device lock.
*
* Return: Zero on success, else a negative error code.
*/
int usb_reset_configuration(struct usb_device *dev)
{
int i, retval;
struct usb_host_config *config;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
if (dev->state == USB_STATE_SUSPENDED)
return -EHOSTUNREACH;
/* caller must have locked the device and must own
* the usb bus readlock (so driver bindings are stable);
* calls during probe() are fine
*/
for (i = 1; i < 16; ++i) {
usb_disable_endpoint(dev, i, true);
usb_disable_endpoint(dev, i + USB_DIR_IN, true);
}
config = dev->actconfig;
retval = 0;
mutex_lock(hcd->bandwidth_mutex);
/* Disable LPM, and re-enable it once the configuration is reset, so
* that the xHCI driver can recalculate the U1/U2 timeouts.
*/
if (usb_disable_lpm(dev)) {
dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
mutex_unlock(hcd->bandwidth_mutex);
return -ENOMEM;
}
/* Make sure we have enough bandwidth for each alternate setting 0 */
for (i = 0; i < config->desc.bNumInterfaces; i++) {
struct usb_interface *intf = config->interface[i];
struct usb_host_interface *alt;
alt = usb_altnum_to_altsetting(intf, 0);
if (!alt)
alt = &intf->altsetting[0];
if (alt != intf->cur_altsetting)
retval = usb_hcd_alloc_bandwidth(dev, NULL,
intf->cur_altsetting, alt);
if (retval < 0)
break;
}
/* If not, reinstate the old alternate settings */
if (retval < 0) {
reset_old_alts:
for (i--; i >= 0; i--) {
struct usb_interface *intf = config->interface[i];
struct usb_host_interface *alt;
alt = usb_altnum_to_altsetting(intf, 0);
if (!alt)
alt = &intf->altsetting[0];
if (alt != intf->cur_altsetting)
usb_hcd_alloc_bandwidth(dev, NULL,
alt, intf->cur_altsetting);
}
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
return retval;
}
retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_CONFIGURATION, 0,
config->desc.bConfigurationValue, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT);
if (retval < 0)
goto reset_old_alts;
mutex_unlock(hcd->bandwidth_mutex);
/* re-init hc/hcd interface/endpoint state */
for (i = 0; i < config->desc.bNumInterfaces; i++) {
struct usb_interface *intf = config->interface[i];
struct usb_host_interface *alt;
alt = usb_altnum_to_altsetting(intf, 0);
/* No altsetting 0? We'll assume the first altsetting.
* We could use a GetInterface call, but if a device is
* so non-compliant that it doesn't have altsetting 0
* then I wouldn't trust its reply anyway.
*/
if (!alt)
alt = &intf->altsetting[0];
if (alt != intf->cur_altsetting) {
remove_intf_ep_devs(intf);
usb_remove_sysfs_intf_files(intf);
}
intf->cur_altsetting = alt;
usb_enable_interface(dev, intf, true);
if (device_is_registered(&intf->dev)) {
usb_create_sysfs_intf_files(intf);
create_intf_ep_devs(intf);
}
}
/* Now that the interfaces are installed, re-enable LPM. */
usb_unlocked_enable_lpm(dev);
return 0;
}
EXPORT_SYMBOL_GPL(usb_reset_configuration);
static void usb_release_interface(struct device *dev)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_interface_cache *intfc =
altsetting_to_usb_interface_cache(intf->altsetting);
kref_put(&intfc->ref, usb_release_interface_cache);
usb_put_dev(interface_to_usbdev(intf));
kfree(intf);
}
/*
* usb_deauthorize_interface - deauthorize an USB interface
*
* @intf: USB interface structure
*/
void usb_deauthorize_interface(struct usb_interface *intf)
{
struct device *dev = &intf->dev;
device_lock(dev->parent);
if (intf->authorized) {
device_lock(dev);
intf->authorized = 0;
device_unlock(dev);
usb_forced_unbind_intf(intf);
}
device_unlock(dev->parent);
}
/*
* usb_authorize_interface - authorize an USB interface
*
* @intf: USB interface structure
*/
void usb_authorize_interface(struct usb_interface *intf)
{
struct device *dev = &intf->dev;
if (!intf->authorized) {
device_lock(dev);
intf->authorized = 1; /* authorize interface */
device_unlock(dev);
}
}
static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
{
struct usb_device *usb_dev;
struct usb_interface *intf;
struct usb_host_interface *alt;
intf = to_usb_interface(dev);
usb_dev = interface_to_usbdev(intf);
alt = intf->cur_altsetting;
if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
alt->desc.bInterfaceClass,
alt->desc.bInterfaceSubClass,
alt->desc.bInterfaceProtocol))
return -ENOMEM;
if (add_uevent_var(env,
"MODALIAS=usb:"
"v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
le16_to_cpu(usb_dev->descriptor.idVendor),
le16_to_cpu(usb_dev->descriptor.idProduct),
le16_to_cpu(usb_dev->descriptor.bcdDevice),
usb_dev->descriptor.bDeviceClass,
usb_dev->descriptor.bDeviceSubClass,
usb_dev->descriptor.bDeviceProtocol,
alt->desc.bInterfaceClass,
alt->desc.bInterfaceSubClass,
alt->desc.bInterfaceProtocol,
alt->desc.bInterfaceNumber))
return -ENOMEM;
return 0;
}
struct device_type usb_if_device_type = {
.name = "usb_interface",
.release = usb_release_interface,
.uevent = usb_if_uevent,
};
static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
struct usb_host_config *config,
u8 inum)
{
struct usb_interface_assoc_descriptor *retval = NULL;
struct usb_interface_assoc_descriptor *intf_assoc;
int first_intf;
int last_intf;
int i;
for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
intf_assoc = config->intf_assoc[i];
if (intf_assoc->bInterfaceCount == 0)
continue;
first_intf = intf_assoc->bFirstInterface;
last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
if (inum >= first_intf && inum <= last_intf) {
if (!retval)
retval = intf_assoc;
else
dev_err(&dev->dev, "Interface #%d referenced"
" by multiple IADs\n", inum);
}
}
return retval;
}
/*
* Internal function to queue a device reset
* See usb_queue_reset_device() for more details
*/
static void __usb_queue_reset_device(struct work_struct *ws)
{
int rc;
struct usb_interface *iface =
container_of(ws, struct usb_interface, reset_ws);
struct usb_device *udev = interface_to_usbdev(iface);
rc = usb_lock_device_for_reset(udev, iface);
if (rc >= 0) {
usb_reset_device(udev);
usb_unlock_device(udev);
}
usb_put_intf(iface); /* Undo _get_ in usb_queue_reset_device() */
}
/*
* usb_set_configuration - Makes a particular device setting be current
* @dev: the device whose configuration is being updated
* @configuration: the configuration being chosen.
* Context: !in_interrupt(), caller owns the device lock
*
* This is used to enable non-default device modes. Not all devices
* use this kind of configurability; many devices only have one
* configuration.
*
* @configuration is the value of the configuration to be installed.
* According to the USB spec (e.g. section 9.1.1.5), configuration values
* must be non-zero; a value of zero indicates that the device in
* unconfigured. However some devices erroneously use 0 as one of their
* configuration values. To help manage such devices, this routine will
* accept @configuration = -1 as indicating the device should be put in
* an unconfigured state.
*
* USB device configurations may affect Linux interoperability,
* power consumption and the functionality available. For example,
* the default configuration is limited to using 100mA of bus power,
* so that when certain device functionality requires more power,
* and the device is bus powered, that functionality should be in some
* non-default device configuration. Other device modes may also be
* reflected as configuration options, such as whether two ISDN
* channels are available independently; and choosing between open
* standard device protocols (like CDC) or proprietary ones.
*
* Note that a non-authorized device (dev->authorized == 0) will only
* be put in unconfigured mode.
*
* Note that USB has an additional level of device configurability,
* associated with interfaces. That configurability is accessed using
* usb_set_interface().
*
* This call is synchronous. The calling context must be able to sleep,
* must own the device lock, and must not hold the driver model's USB
* bus mutex; usb interface driver probe() methods cannot use this routine.
*
* Returns zero on success, or else the status code returned by the
* underlying call that failed. On successful completion, each interface
* in the original device configuration has been destroyed, and each one
* in the new configuration has been probed by all relevant usb device
* drivers currently known to the kernel.
*/
int usb_set_configuration(struct usb_device *dev, int configuration)
{
int i, ret;
struct usb_host_config *cp = NULL;
struct usb_interface **new_interfaces = NULL;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
int n, nintf;
if (dev->authorized == 0 || configuration == -1)
configuration = 0;
else {
for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
if (dev->config[i].desc.bConfigurationValue ==
configuration) {
cp = &dev->config[i];
break;
}
}
}
if ((!cp && configuration != 0))
return -EINVAL;
/* The USB spec says configuration 0 means unconfigured.
* But if a device includes a configuration numbered 0,
* we will accept it as a correctly configured state.
* Use -1 if you really want to unconfigure the device.
*/
if (cp && configuration == 0)
dev_warn(&dev->dev, "config 0 descriptor??\n");
/* Allocate memory for new interfaces before doing anything else,
* so that if we run out then nothing will have changed. */
n = nintf = 0;
if (cp) {
nintf = cp->desc.bNumInterfaces;
new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
GFP_NOIO);
if (!new_interfaces)
return -ENOMEM;
for (; n < nintf; ++n) {
new_interfaces[n] = kzalloc(
sizeof(struct usb_interface),
GFP_NOIO);
if (!new_interfaces[n]) {
ret = -ENOMEM;
free_interfaces:
while (--n >= 0)
kfree(new_interfaces[n]);
kfree(new_interfaces);
return ret;
}
}
i = dev->bus_mA - usb_get_max_power(dev, cp);
if (i < 0)
dev_warn(&dev->dev, "new config #%d exceeds power "
"limit by %dmA\n",
configuration, -i);
}
/* Wake up the device so we can send it the Set-Config request */
ret = usb_autoresume_device(dev);
if (ret)
goto free_interfaces;
/* if it's already configured, clear out old state first.
* getting rid of old interfaces means unbinding their drivers.
*/
if (dev->state != USB_STATE_ADDRESS)
usb_disable_device(dev, 1); /* Skip ep0 */
/* Get rid of pending async Set-Config requests for this device */
cancel_async_set_config(dev);
/* Make sure we have bandwidth (and available HCD resources) for this
* configuration. Remove endpoints from the schedule if we're dropping
* this configuration to set configuration 0. After this point, the
* host controller will not allow submissions to dropped endpoints. If
* this call fails, the device state is unchanged.
*/
mutex_lock(hcd->bandwidth_mutex);
/* Disable LPM, and re-enable it once the new configuration is
* installed, so that the xHCI driver can recalculate the U1/U2
* timeouts.
*/
if (dev->actconfig && usb_disable_lpm(dev)) {
dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
mutex_unlock(hcd->bandwidth_mutex);
ret = -ENOMEM;
goto free_interfaces;
}
ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
if (ret < 0) {
if (dev->actconfig)
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
usb_autosuspend_device(dev);
goto free_interfaces;
}
/*
* Initialize the new interface structures and the
* hc/hcd/usbcore interface/endpoint state.
*/
for (i = 0; i < nintf; ++i) {
struct usb_interface_cache *intfc;
struct usb_interface *intf;
struct usb_host_interface *alt;
cp->interface[i] = intf = new_interfaces[i];
intfc = cp->intf_cache[i];
intf->altsetting = intfc->altsetting;
intf->num_altsetting = intfc->num_altsetting;
intf->authorized = !!HCD_INTF_AUTHORIZED(hcd);
kref_get(&intfc->ref);
alt = usb_altnum_to_altsetting(intf, 0);
/* No altsetting 0? We'll assume the first altsetting.
* We could use a GetInterface call, but if a device is
* so non-compliant that it doesn't have altsetting 0
* then I wouldn't trust its reply anyway.
*/
if (!alt)
alt = &intf->altsetting[0];
intf->intf_assoc =
find_iad(dev, cp, alt->desc.bInterfaceNumber);
intf->cur_altsetting = alt;
usb_enable_interface(dev, intf, true);
intf->dev.parent = &dev->dev;
intf->dev.driver = NULL;
intf->dev.bus = &usb_bus_type;
intf->dev.type = &usb_if_device_type;
intf->dev.groups = usb_interface_groups;
/*
* Please refer to usb_alloc_dev() to see why we set
* dma_mask and dma_pfn_offset.
*/
intf->dev.dma_mask = dev->dev.dma_mask;
intf->dev.dma_pfn_offset = dev->dev.dma_pfn_offset;
INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
intf->minor = -1;
device_initialize(&intf->dev);
pm_runtime_no_callbacks(&intf->dev);
dev_set_name(&intf->dev, "%d-%s:%d.%d",
dev->bus->busnum, dev->devpath,
configuration, alt->desc.bInterfaceNumber);
usb_get_dev(dev);
}
kfree(new_interfaces);
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT);
if (ret < 0 && cp) {
/*
* All the old state is gone, so what else can we do?
* The device is probably useless now anyway.
*/
usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
for (i = 0; i < nintf; ++i) {
usb_disable_interface(dev, cp->interface[i], true);
put_device(&cp->interface[i]->dev);
cp->interface[i] = NULL;
}
cp = NULL;
}
dev->actconfig = cp;
mutex_unlock(hcd->bandwidth_mutex);
if (!cp) {
usb_set_device_state(dev, USB_STATE_ADDRESS);
/* Leave LPM disabled while the device is unconfigured. */
usb_autosuspend_device(dev);
return ret;
}
usb_set_device_state(dev, USB_STATE_CONFIGURED);
if (cp->string == NULL &&
!(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
/* Now that the interfaces are installed, re-enable LPM. */
usb_unlocked_enable_lpm(dev);
/* Enable LTM if it was turned off by usb_disable_device. */
usb_enable_ltm(dev);
/* Now that all the interfaces are set up, register them
* to trigger binding of drivers to interfaces. probe()
* routines may install different altsettings and may
* claim() any interfaces not yet bound. Many class drivers
* need that: CDC, audio, video, etc.
*/
for (i = 0; i < nintf; ++i) {
struct usb_interface *intf = cp->interface[i];
dev_dbg(&dev->dev,
"adding %s (config #%d, interface %d)\n",
dev_name(&intf->dev), configuration,
intf->cur_altsetting->desc.bInterfaceNumber);
device_enable_async_suspend(&intf->dev);
ret = device_add(&intf->dev);
if (ret != 0) {
dev_err(&dev->dev, "device_add(%s) --> %d\n",
dev_name(&intf->dev), ret);
continue;
}
create_intf_ep_devs(intf);
}
usb_autosuspend_device(dev);
return 0;
}
EXPORT_SYMBOL_GPL(usb_set_configuration);
static LIST_HEAD(set_config_list);
static DEFINE_SPINLOCK(set_config_lock);
struct set_config_request {
struct usb_device *udev;
int config;
struct work_struct work;
struct list_head node;
};
/* Worker routine for usb_driver_set_configuration() */
static void driver_set_config_work(struct work_struct *work)
{
struct set_config_request *req =
container_of(work, struct set_config_request, work);
struct usb_device *udev = req->udev;
usb_lock_device(udev);
spin_lock(&set_config_lock);
list_del(&req->node);
spin_unlock(&set_config_lock);
if (req->config >= -1) /* Is req still valid? */
usb_set_configuration(udev, req->config);
usb_unlock_device(udev);
usb_put_dev(udev);
kfree(req);
}
/* Cancel pending Set-Config requests for a device whose configuration
* was just changed
*/
static void cancel_async_set_config(struct usb_device *udev)
{
struct set_config_request *req;
spin_lock(&set_config_lock);
list_for_each_entry(req, &set_config_list, node) {
if (req->udev == udev)
req->config = -999; /* Mark as cancelled */
}
spin_unlock(&set_config_lock);
}
/**
* usb_driver_set_configuration - Provide a way for drivers to change device configurations
* @udev: the device whose configuration is being updated
* @config: the configuration being chosen.
* Context: In process context, must be able to sleep
*
* Device interface drivers are not allowed to change device configurations.
* This is because changing configurations will destroy the interface the
* driver is bound to and create new ones; it would be like a floppy-disk
* driver telling the computer to replace the floppy-disk drive with a
* tape drive!
*
* Still, in certain specialized circumstances the need may arise. This
* routine gets around the normal restrictions by using a work thread to
* submit the change-config request.
*
* Return: 0 if the request was successfully queued, error code otherwise.
* The caller has no way to know whether the queued request will eventually
* succeed.
*/
int usb_driver_set_configuration(struct usb_device *udev, int config)
{
struct set_config_request *req;
req = kmalloc(sizeof(*req), GFP_KERNEL);
if (!req)
return -ENOMEM;
req->udev = udev;
req->config = config;
INIT_WORK(&req->work, driver_set_config_work);
spin_lock(&set_config_lock);
list_add(&req->node, &set_config_list);
spin_unlock(&set_config_lock);
usb_get_dev(udev);
schedule_work(&req->work);
return 0;
}
EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
/**
* cdc_parse_cdc_header - parse the extra headers present in CDC devices
* @hdr: the place to put the results of the parsing
* @intf: the interface for which parsing is requested
* @buffer: pointer to the extra headers to be parsed
* @buflen: length of the extra headers
*
* This evaluates the extra headers present in CDC devices which
* bind the interfaces for data and control and provide details
* about the capabilities of the device.
*
* Return: number of descriptors parsed or -EINVAL
* if the header is contradictory beyond salvage
*/
int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr,
struct usb_interface *intf,
u8 *buffer,
int buflen)
{
/* duplicates are ignored */
struct usb_cdc_union_desc *union_header = NULL;
/* duplicates are not tolerated */
struct usb_cdc_header_desc *header = NULL;
struct usb_cdc_ether_desc *ether = NULL;
struct usb_cdc_mdlm_detail_desc *detail = NULL;
struct usb_cdc_mdlm_desc *desc = NULL;
unsigned int elength;
int cnt = 0;
memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header));
hdr->phonet_magic_present = false;
while (buflen > 0) {
elength = buffer[0];
if (!elength) {
dev_err(&intf->dev, "skipping garbage byte\n");
elength = 1;
goto next_desc;
}
if (buffer[1] != USB_DT_CS_INTERFACE) {
dev_err(&intf->dev, "skipping garbage\n");
goto next_desc;
}
switch (buffer[2]) {
case USB_CDC_UNION_TYPE: /* we've found it */
if (elength < sizeof(struct usb_cdc_union_desc))
goto next_desc;
if (union_header) {
dev_err(&intf->dev, "More than one union descriptor, skipping ...\n");
goto next_desc;
}
union_header = (struct usb_cdc_union_desc *)buffer;
break;
case USB_CDC_COUNTRY_TYPE:
if (elength < sizeof(struct usb_cdc_country_functional_desc))
goto next_desc;
hdr->usb_cdc_country_functional_desc =
(struct usb_cdc_country_functional_desc *)buffer;
break;
case USB_CDC_HEADER_TYPE:
if (elength != sizeof(struct usb_cdc_header_desc))
goto next_desc;
if (header)
return -EINVAL;
header = (struct usb_cdc_header_desc *)buffer;
break;
case USB_CDC_ACM_TYPE:
if (elength < sizeof(struct usb_cdc_acm_descriptor))
goto next_desc;
hdr->usb_cdc_acm_descriptor =
(struct usb_cdc_acm_descriptor *)buffer;
break;
case USB_CDC_ETHERNET_TYPE:
if (elength != sizeof(struct usb_cdc_ether_desc))
goto next_desc;
if (ether)
return -EINVAL;
ether = (struct usb_cdc_ether_desc *)buffer;
break;
case USB_CDC_CALL_MANAGEMENT_TYPE:
if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor))
goto next_desc;
hdr->usb_cdc_call_mgmt_descriptor =
(struct usb_cdc_call_mgmt_descriptor *)buffer;
break;
case USB_CDC_DMM_TYPE:
if (elength < sizeof(struct usb_cdc_dmm_desc))
goto next_desc;
hdr->usb_cdc_dmm_desc =
(struct usb_cdc_dmm_desc *)buffer;
break;
case USB_CDC_MDLM_TYPE:
if (elength < sizeof(struct usb_cdc_mdlm_desc *))
goto next_desc;
if (desc)
return -EINVAL;
desc = (struct usb_cdc_mdlm_desc *)buffer;
break;
case USB_CDC_MDLM_DETAIL_TYPE:
if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *))
goto next_desc;
if (detail)
return -EINVAL;
detail = (struct usb_cdc_mdlm_detail_desc *)buffer;
break;
case USB_CDC_NCM_TYPE:
if (elength < sizeof(struct usb_cdc_ncm_desc))
goto next_desc;
hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer;
break;
case USB_CDC_MBIM_TYPE:
if (elength < sizeof(struct usb_cdc_mbim_desc))
goto next_desc;
hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer;
break;
case USB_CDC_MBIM_EXTENDED_TYPE:
if (elength < sizeof(struct usb_cdc_mbim_extended_desc))
break;
hdr->usb_cdc_mbim_extended_desc =
(struct usb_cdc_mbim_extended_desc *)buffer;
break;
case CDC_PHONET_MAGIC_NUMBER:
hdr->phonet_magic_present = true;
break;
default:
/*
* there are LOTS more CDC descriptors that
* could legitimately be found here.
*/
dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n",
buffer[2], elength);
goto next_desc;
}
cnt++;
next_desc:
buflen -= elength;
buffer += elength;
}
hdr->usb_cdc_union_desc = union_header;
hdr->usb_cdc_header_desc = header;
hdr->usb_cdc_mdlm_detail_desc = detail;
hdr->usb_cdc_mdlm_desc = desc;
hdr->usb_cdc_ether_desc = ether;
return cnt;
}
EXPORT_SYMBOL(cdc_parse_cdc_header);
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2915_0 |
crossvul-cpp_data_bad_4359_0 | /* pb_decode.c -- decode a protobuf using minimal resources
*
* 2011 Petteri Aimonen <jpa@kapsi.fi>
*/
/* Use the GCC warn_unused_result attribute to check that all return values
* are propagated correctly. On other compilers and gcc before 3.4.0 just
* ignore the annotation.
*/
#if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
#define checkreturn
#else
#define checkreturn __attribute__((warn_unused_result))
#endif
#include "pb.h"
#include "pb_decode.h"
#include "pb_common.h"
/**************************************
* Declarations internal to this file *
**************************************/
typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn;
static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count);
static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size);
static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension);
static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type);
static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter);
static bool checkreturn find_extension_field(pb_field_iter_t *iter);
static void pb_field_set_to_default(pb_field_iter_t *iter);
static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct);
static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof);
static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_skip_varint(pb_istream_t *stream);
static bool checkreturn pb_skip_string(pb_istream_t *stream);
#ifdef PB_ENABLE_MALLOC
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size);
static bool checkreturn pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter);
static void pb_release_single_field(const pb_field_iter_t *iter);
#endif
#ifdef PB_WITHOUT_64BIT
#define pb_int64_t int32_t
#define pb_uint64_t uint32_t
#else
#define pb_int64_t int64_t
#define pb_uint64_t uint64_t
#endif
/* --- Function pointers to field decoders ---
* Order in the array must match pb_action_t LTYPE numbering.
*/
static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = {
&pb_dec_bool,
&pb_dec_varint,
&pb_dec_uvarint,
&pb_dec_svarint,
&pb_dec_fixed32,
&pb_dec_fixed64,
&pb_dec_bytes,
&pb_dec_string,
&pb_dec_submessage,
NULL, /* extensions */
&pb_dec_fixed_length_bytes
};
/*******************************
* pb_istream_t implementation *
*******************************/
static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count)
{
size_t i;
const pb_byte_t *source = (const pb_byte_t*)stream->state;
stream->state = (pb_byte_t*)stream->state + count;
if (buf != NULL)
{
for (i = 0; i < count; i++)
buf[i] = source[i];
}
return true;
}
bool checkreturn pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count)
{
if (count == 0)
return true;
#ifndef PB_BUFFER_ONLY
if (buf == NULL && stream->callback != buf_read)
{
/* Skip input bytes */
pb_byte_t tmp[16];
while (count > 16)
{
if (!pb_read(stream, tmp, 16))
return false;
count -= 16;
}
return pb_read(stream, tmp, count);
}
#endif
if (stream->bytes_left < count)
PB_RETURN_ERROR(stream, "end-of-stream");
#ifndef PB_BUFFER_ONLY
if (!stream->callback(stream, buf, count))
PB_RETURN_ERROR(stream, "io error");
#else
if (!buf_read(stream, buf, count))
return false;
#endif
stream->bytes_left -= count;
return true;
}
/* Read a single byte from input stream. buf may not be NULL.
* This is an optimization for the varint decoding. */
static bool checkreturn pb_readbyte(pb_istream_t *stream, pb_byte_t *buf)
{
if (stream->bytes_left == 0)
PB_RETURN_ERROR(stream, "end-of-stream");
#ifndef PB_BUFFER_ONLY
if (!stream->callback(stream, buf, 1))
PB_RETURN_ERROR(stream, "io error");
#else
*buf = *(const pb_byte_t*)stream->state;
stream->state = (pb_byte_t*)stream->state + 1;
#endif
stream->bytes_left--;
return true;
}
pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize)
{
pb_istream_t stream;
/* Cast away the const from buf without a compiler error. We are
* careful to use it only in a const manner in the callbacks.
*/
union {
void *state;
const void *c_state;
} state;
#ifdef PB_BUFFER_ONLY
stream.callback = NULL;
#else
stream.callback = &buf_read;
#endif
state.c_state = buf;
stream.state = state.state;
stream.bytes_left = bufsize;
#ifndef PB_NO_ERRMSG
stream.errmsg = NULL;
#endif
return stream;
}
/********************
* Helper functions *
********************/
static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof)
{
pb_byte_t byte;
uint32_t result;
if (!pb_readbyte(stream, &byte))
{
if (stream->bytes_left == 0)
{
if (eof)
{
*eof = true;
}
}
return false;
}
if ((byte & 0x80) == 0)
{
/* Quick case, 1 byte value */
result = byte;
}
else
{
/* Multibyte case */
uint_fast8_t bitpos = 7;
result = byte & 0x7F;
do
{
if (!pb_readbyte(stream, &byte))
return false;
if (bitpos >= 32)
{
/* Note: The varint could have trailing 0x80 bytes, or 0xFF for negative. */
uint8_t sign_extension = (bitpos < 63) ? 0xFF : 0x01;
if ((byte & 0x7F) != 0x00 && ((result >> 31) == 0 || byte != sign_extension))
{
PB_RETURN_ERROR(stream, "varint overflow");
}
}
else
{
result |= (uint32_t)(byte & 0x7F) << bitpos;
}
bitpos = (uint_fast8_t)(bitpos + 7);
} while (byte & 0x80);
if (bitpos == 35 && (byte & 0x70) != 0)
{
/* The last byte was at bitpos=28, so only bottom 4 bits fit. */
PB_RETURN_ERROR(stream, "varint overflow");
}
}
*dest = result;
return true;
}
bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest)
{
return pb_decode_varint32_eof(stream, dest, NULL);
}
#ifndef PB_WITHOUT_64BIT
bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)
{
pb_byte_t byte;
uint_fast8_t bitpos = 0;
uint64_t result = 0;
do
{
if (bitpos >= 64)
PB_RETURN_ERROR(stream, "varint overflow");
if (!pb_readbyte(stream, &byte))
return false;
result |= (uint64_t)(byte & 0x7F) << bitpos;
bitpos = (uint_fast8_t)(bitpos + 7);
} while (byte & 0x80);
*dest = result;
return true;
}
#endif
bool checkreturn pb_skip_varint(pb_istream_t *stream)
{
pb_byte_t byte;
do
{
if (!pb_read(stream, &byte, 1))
return false;
} while (byte & 0x80);
return true;
}
bool checkreturn pb_skip_string(pb_istream_t *stream)
{
uint32_t length;
if (!pb_decode_varint32(stream, &length))
return false;
return pb_read(stream, NULL, length);
}
bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof)
{
uint32_t temp;
*eof = false;
*wire_type = (pb_wire_type_t) 0;
*tag = 0;
if (!pb_decode_varint32_eof(stream, &temp, eof))
{
return false;
}
if (temp == 0)
{
*eof = true; /* Special feature: allow 0-terminated messages. */
return false;
}
*tag = temp >> 3;
*wire_type = (pb_wire_type_t)(temp & 7);
return true;
}
bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type)
{
switch (wire_type)
{
case PB_WT_VARINT: return pb_skip_varint(stream);
case PB_WT_64BIT: return pb_read(stream, NULL, 8);
case PB_WT_STRING: return pb_skip_string(stream);
case PB_WT_32BIT: return pb_read(stream, NULL, 4);
default: PB_RETURN_ERROR(stream, "invalid wire_type");
}
}
/* Read a raw value to buffer, for the purpose of passing it to callback as
* a substream. Size is maximum size on call, and actual size on return.
*/
static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size)
{
size_t max_size = *size;
switch (wire_type)
{
case PB_WT_VARINT:
*size = 0;
do
{
(*size)++;
if (*size > max_size) return false;
if (!pb_read(stream, buf, 1)) return false;
} while (*buf++ & 0x80);
return true;
case PB_WT_64BIT:
*size = 8;
return pb_read(stream, buf, 8);
case PB_WT_32BIT:
*size = 4;
return pb_read(stream, buf, 4);
case PB_WT_STRING:
/* Calling read_raw_value with a PB_WT_STRING is an error.
* Explicitly handle this case and fallthrough to default to avoid
* compiler warnings.
*/
default: PB_RETURN_ERROR(stream, "invalid wire_type");
}
}
/* Decode string length from stream and return a substream with limited length.
* Remember to close the substream using pb_close_string_substream().
*/
bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream)
{
uint32_t size;
if (!pb_decode_varint32(stream, &size))
return false;
*substream = *stream;
if (substream->bytes_left < size)
PB_RETURN_ERROR(stream, "parent stream too short");
substream->bytes_left = size;
stream->bytes_left -= size;
return true;
}
bool checkreturn pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream)
{
if (substream->bytes_left) {
if (!pb_read(substream, NULL, substream->bytes_left))
return false;
}
stream->state = substream->state;
#ifndef PB_NO_ERRMSG
stream->errmsg = substream->errmsg;
#endif
return true;
}
/*************************
* Decode a single field *
*************************/
static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
{
pb_type_t type;
pb_decoder_t func;
type = iter->pos->type;
func = PB_DECODERS[PB_LTYPE(type)];
switch (PB_HTYPE(type))
{
case PB_HTYPE_REQUIRED:
return func(stream, iter->pos, iter->pData);
case PB_HTYPE_OPTIONAL:
if (iter->pSize != iter->pData)
*(bool*)iter->pSize = true;
return func(stream, iter->pos, iter->pData);
case PB_HTYPE_REPEATED:
if (wire_type == PB_WT_STRING
&& PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
{
/* Packed array */
bool status = true;
pb_size_t *size = (pb_size_t*)iter->pSize;
pb_istream_t substream;
if (!pb_make_string_substream(stream, &substream))
return false;
while (substream.bytes_left > 0 && *size < iter->pos->array_size)
{
void *pItem = (char*)iter->pData + iter->pos->data_size * (*size);
if (!func(&substream, iter->pos, pItem))
{
status = false;
break;
}
(*size)++;
}
if (substream.bytes_left != 0)
PB_RETURN_ERROR(stream, "array overflow");
if (!pb_close_string_substream(stream, &substream))
return false;
return status;
}
else
{
/* Repeated field */
pb_size_t *size = (pb_size_t*)iter->pSize;
char *pItem = (char*)iter->pData + iter->pos->data_size * (*size);
if ((*size)++ >= iter->pos->array_size)
PB_RETURN_ERROR(stream, "array overflow");
return func(stream, iter->pos, pItem);
}
case PB_HTYPE_ONEOF:
*(pb_size_t*)iter->pSize = iter->pos->tag;
if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
{
/* We memset to zero so that any callbacks are set to NULL.
* Then set any default values. */
memset(iter->pData, 0, iter->pos->data_size);
pb_message_set_to_defaults((const pb_field_t*)iter->pos->ptr, iter->pData);
}
return func(stream, iter->pos, iter->pData);
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
}
#ifdef PB_ENABLE_MALLOC
/* Allocate storage for the field and store the pointer at iter->pData.
* array_size is the number of entries to reserve in an array.
* Zero size is not allowed, use pb_free() for releasing.
*/
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size)
{
void *ptr = *(void**)pData;
if (data_size == 0 || array_size == 0)
PB_RETURN_ERROR(stream, "invalid size");
#ifdef __AVR__
/* Workaround for AVR libc bug 53284: http://savannah.nongnu.org/bugs/?53284
* Realloc to size of 1 byte can cause corruption of the malloc structures.
*/
if (data_size == 1 && array_size == 1)
{
data_size = 2;
}
#endif
/* Check for multiplication overflows.
* This code avoids the costly division if the sizes are small enough.
* Multiplication is safe as long as only half of bits are set
* in either multiplicand.
*/
{
const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4);
if (data_size >= check_limit || array_size >= check_limit)
{
const size_t size_max = (size_t)-1;
if (size_max / array_size < data_size)
{
PB_RETURN_ERROR(stream, "size too large");
}
}
}
/* Allocate new or expand previous allocation */
/* Note: on failure the old pointer will remain in the structure,
* the message must be freed by caller also on error return. */
ptr = pb_realloc(ptr, array_size * data_size);
if (ptr == NULL)
PB_RETURN_ERROR(stream, "realloc failed");
*(void**)pData = ptr;
return true;
}
/* Clear a newly allocated item in case it contains a pointer, or is a submessage. */
static void initialize_pointer_field(void *pItem, pb_field_iter_t *iter)
{
if (PB_LTYPE(iter->pos->type) == PB_LTYPE_STRING ||
PB_LTYPE(iter->pos->type) == PB_LTYPE_BYTES)
{
*(void**)pItem = NULL;
}
else if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)
{
/* We memset to zero so that any callbacks are set to NULL.
* Then set any default values. */
memset(pItem, 0, iter->pos->data_size);
pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, pItem);
}
}
#endif
static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
{
#ifndef PB_ENABLE_MALLOC
PB_UNUSED(wire_type);
PB_UNUSED(iter);
PB_RETURN_ERROR(stream, "no malloc support");
#else
pb_type_t type;
pb_decoder_t func;
type = iter->pos->type;
func = PB_DECODERS[PB_LTYPE(type)];
switch (PB_HTYPE(type))
{
case PB_HTYPE_REQUIRED:
case PB_HTYPE_OPTIONAL:
case PB_HTYPE_ONEOF:
if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&
*(void**)iter->pData != NULL)
{
/* Duplicate field, have to release the old allocation first. */
pb_release_single_field(iter);
}
if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
{
*(pb_size_t*)iter->pSize = iter->pos->tag;
}
if (PB_LTYPE(type) == PB_LTYPE_STRING ||
PB_LTYPE(type) == PB_LTYPE_BYTES)
{
return func(stream, iter->pos, iter->pData);
}
else
{
if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))
return false;
initialize_pointer_field(*(void**)iter->pData, iter);
return func(stream, iter->pos, *(void**)iter->pData);
}
case PB_HTYPE_REPEATED:
if (wire_type == PB_WT_STRING
&& PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
{
/* Packed array, multiple items come in at once. */
bool status = true;
pb_size_t *size = (pb_size_t*)iter->pSize;
size_t allocated_size = *size;
void *pItem;
pb_istream_t substream;
if (!pb_make_string_substream(stream, &substream))
return false;
while (substream.bytes_left)
{
if (*size == PB_SIZE_MAX)
{
#ifndef PB_NO_ERRMSG
stream->errmsg = "too many array entries";
#endif
status = false;
break;
}
if ((size_t)*size + 1 > allocated_size)
{
/* Allocate more storage. This tries to guess the
* number of remaining entries. Round the division
* upwards. */
size_t remain = (substream.bytes_left - 1) / iter->pos->data_size + 1;
if (remain < PB_SIZE_MAX - allocated_size)
allocated_size += remain;
else
allocated_size += 1;
if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))
{
status = false;
break;
}
}
/* Decode the array entry */
pItem = *(char**)iter->pData + iter->pos->data_size * (*size);
initialize_pointer_field(pItem, iter);
if (!func(&substream, iter->pos, pItem))
{
status = false;
break;
}
(*size)++;
}
if (!pb_close_string_substream(stream, &substream))
return false;
return status;
}
else
{
/* Normal repeated field, i.e. only one item at a time. */
pb_size_t *size = (pb_size_t*)iter->pSize;
void *pItem;
if (*size == PB_SIZE_MAX)
PB_RETURN_ERROR(stream, "too many array entries");
if (!allocate_field(stream, iter->pData, iter->pos->data_size, (size_t)(*size + 1)))
return false;
pItem = *(char**)iter->pData + iter->pos->data_size * (*size);
(*size)++;
initialize_pointer_field(pItem, iter);
return func(stream, iter->pos, pItem);
}
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
#endif
}
static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
{
pb_callback_t *pCallback = (pb_callback_t*)iter->pData;
#ifdef PB_OLD_CALLBACK_STYLE
void *arg;
#else
void **arg;
#endif
if (pCallback == NULL || pCallback->funcs.decode == NULL)
return pb_skip_field(stream, wire_type);
#ifdef PB_OLD_CALLBACK_STYLE
arg = pCallback->arg;
#else
arg = &(pCallback->arg);
#endif
if (wire_type == PB_WT_STRING)
{
pb_istream_t substream;
if (!pb_make_string_substream(stream, &substream))
return false;
do
{
if (!pCallback->funcs.decode(&substream, iter->pos, arg))
PB_RETURN_ERROR(stream, "callback failed");
} while (substream.bytes_left);
if (!pb_close_string_substream(stream, &substream))
return false;
return true;
}
else
{
/* Copy the single scalar value to stack.
* This is required so that we can limit the stream length,
* which in turn allows to use same callback for packed and
* not-packed fields. */
pb_istream_t substream;
pb_byte_t buffer[10];
size_t size = sizeof(buffer);
if (!read_raw_value(stream, wire_type, buffer, &size))
return false;
substream = pb_istream_from_buffer(buffer, size);
return pCallback->funcs.decode(&substream, iter->pos, arg);
}
}
static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
{
#ifdef PB_ENABLE_MALLOC
/* When decoding an oneof field, check if there is old data that must be
* released first. */
if (PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF)
{
if (!pb_release_union_field(stream, iter))
return false;
}
#endif
switch (PB_ATYPE(iter->pos->type))
{
case PB_ATYPE_STATIC:
return decode_static_field(stream, wire_type, iter);
case PB_ATYPE_POINTER:
return decode_pointer_field(stream, wire_type, iter);
case PB_ATYPE_CALLBACK:
return decode_callback_field(stream, wire_type, iter);
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
}
static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension)
{
/* Fake a field iterator for the extension field.
* It is not actually safe to advance this iterator, but decode_field
* will not even try to. */
const pb_field_t *field = (const pb_field_t*)extension->type->arg;
(void)pb_field_iter_begin(iter, field, extension->dest);
iter->pData = extension->dest;
iter->pSize = &extension->found;
if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
{
/* For pointer extensions, the pointer is stored directly
* in the extension structure. This avoids having an extra
* indirection. */
iter->pData = &extension->dest;
}
}
/* Default handler for extension fields. Expects a pb_field_t structure
* in extension->type->arg. */
static bool checkreturn default_extension_decoder(pb_istream_t *stream,
pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type)
{
const pb_field_t *field = (const pb_field_t*)extension->type->arg;
pb_field_iter_t iter;
if (field->tag != tag)
return true;
iter_from_extension(&iter, extension);
extension->found = true;
return decode_field(stream, wire_type, &iter);
}
/* Try to decode an unknown field as an extension field. Tries each extension
* decoder in turn, until one of them handles the field or loop ends. */
static bool checkreturn decode_extension(pb_istream_t *stream,
uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter)
{
pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;
size_t pos = stream->bytes_left;
while (extension != NULL && pos == stream->bytes_left)
{
bool status;
if (extension->type->decode)
status = extension->type->decode(stream, extension, tag, wire_type);
else
status = default_extension_decoder(stream, extension, tag, wire_type);
if (!status)
return false;
extension = extension->next;
}
return true;
}
/* Step through the iterator until an extension field is found or until all
* entries have been checked. There can be only one extension field per
* message. Returns false if no extension field is found. */
static bool checkreturn find_extension_field(pb_field_iter_t *iter)
{
const pb_field_t *start = iter->pos;
do {
if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION)
return true;
(void)pb_field_iter_next(iter);
} while (iter->pos != start);
return false;
}
/* Initialize message fields to default values, recursively */
static void pb_field_set_to_default(pb_field_iter_t *iter)
{
pb_type_t type;
type = iter->pos->type;
if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
{
pb_extension_t *ext = *(pb_extension_t* const *)iter->pData;
while (ext != NULL)
{
pb_field_iter_t ext_iter;
ext->found = false;
iter_from_extension(&ext_iter, ext);
pb_field_set_to_default(&ext_iter);
ext = ext->next;
}
}
else if (PB_ATYPE(type) == PB_ATYPE_STATIC)
{
bool init_data = true;
if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && iter->pSize != iter->pData)
{
/* Set has_field to false. Still initialize the optional field
* itself also. */
*(bool*)iter->pSize = false;
}
else if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||
PB_HTYPE(type) == PB_HTYPE_ONEOF)
{
/* REPEATED: Set array count to 0, no need to initialize contents.
ONEOF: Set which_field to 0. */
*(pb_size_t*)iter->pSize = 0;
init_data = false;
}
if (init_data)
{
if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)
{
/* Initialize submessage to defaults */
pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, iter->pData);
}
else if (iter->pos->ptr != NULL)
{
/* Initialize to default value */
memcpy(iter->pData, iter->pos->ptr, iter->pos->data_size);
}
else
{
/* Initialize to zeros */
memset(iter->pData, 0, iter->pos->data_size);
}
}
}
else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
{
/* Initialize the pointer to NULL. */
*(void**)iter->pData = NULL;
/* Initialize array count to 0. */
if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||
PB_HTYPE(type) == PB_HTYPE_ONEOF)
{
*(pb_size_t*)iter->pSize = 0;
}
}
else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
{
/* Don't overwrite callback */
}
}
static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
{
pb_field_iter_t iter;
if (!pb_field_iter_begin(&iter, fields, dest_struct))
return; /* Empty message type */
do
{
pb_field_set_to_default(&iter);
} while (pb_field_iter_next(&iter));
}
/*********************
* Decode all fields *
*********************/
bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
uint32_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 31) / 32] = {0, 0};
const uint32_t allbits = ~(uint32_t)0;
uint32_t extension_range_start = 0;
pb_field_iter_t iter;
/* 'fixed_count_field' and 'fixed_count_size' track position of a repeated fixed
* count field. This can only handle _one_ repeated fixed count field that
* is unpacked and unordered among other (non repeated fixed count) fields.
*/
const pb_field_t *fixed_count_field = NULL;
pb_size_t fixed_count_size = 0;
/* Return value ignored, as empty message types will be correctly handled by
* pb_field_iter_find() anyway. */
(void)pb_field_iter_begin(&iter, fields, dest_struct);
while (stream->bytes_left)
{
uint32_t tag;
pb_wire_type_t wire_type;
bool eof;
if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
{
if (eof)
break;
else
return false;
}
if (!pb_field_iter_find(&iter, tag))
{
/* No match found, check if it matches an extension. */
if (tag >= extension_range_start)
{
if (!find_extension_field(&iter))
extension_range_start = (uint32_t)-1;
else
extension_range_start = iter.pos->tag;
if (tag >= extension_range_start)
{
size_t pos = stream->bytes_left;
if (!decode_extension(stream, tag, wire_type, &iter))
return false;
if (pos != stream->bytes_left)
{
/* The field was handled */
continue;
}
}
}
/* No match found, skip data */
if (!pb_skip_field(stream, wire_type))
return false;
continue;
}
/* If a repeated fixed count field was found, get size from
* 'fixed_count_field' as there is no counter contained in the struct.
*/
if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REPEATED
&& iter.pSize == iter.pData)
{
if (fixed_count_field != iter.pos) {
/* If the new fixed count field does not match the previous one,
* check that the previous one is NULL or that it finished
* receiving all the expected data.
*/
if (fixed_count_field != NULL &&
fixed_count_size != fixed_count_field->array_size)
{
PB_RETURN_ERROR(stream, "wrong size for fixed count field");
}
fixed_count_field = iter.pos;
fixed_count_size = 0;
}
iter.pSize = &fixed_count_size;
}
if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED
&& iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
{
uint32_t tmp = ((uint32_t)1 << (iter.required_field_index & 31));
fields_seen[iter.required_field_index >> 5] |= tmp;
}
if (!decode_field(stream, wire_type, &iter))
return false;
}
/* Check that all elements of the last decoded fixed count field were present. */
if (fixed_count_field != NULL &&
fixed_count_size != fixed_count_field->array_size)
{
PB_RETURN_ERROR(stream, "wrong size for fixed count field");
}
/* Check that all required fields were present. */
{
/* First figure out the number of required fields by
* seeking to the end of the field array. Usually we
* are already close to end after decoding.
*/
unsigned req_field_count;
pb_type_t last_type;
unsigned i;
do {
req_field_count = iter.required_field_index;
last_type = iter.pos->type;
} while (pb_field_iter_next(&iter));
/* Fixup if last field was also required. */
if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0)
req_field_count++;
if (req_field_count > PB_MAX_REQUIRED_FIELDS)
req_field_count = PB_MAX_REQUIRED_FIELDS;
if (req_field_count > 0)
{
/* Check the whole words */
for (i = 0; i < (req_field_count >> 5); i++)
{
if (fields_seen[i] != allbits)
PB_RETURN_ERROR(stream, "missing required field");
}
/* Check the remaining bits (if any) */
if ((req_field_count & 31) != 0)
{
if (fields_seen[req_field_count >> 5] !=
(allbits >> (32 - (req_field_count & 31))))
{
PB_RETURN_ERROR(stream, "missing required field");
}
}
}
}
return true;
}
bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
bool status;
pb_message_set_to_defaults(fields, dest_struct);
status = pb_decode_noinit(stream, fields, dest_struct);
#ifdef PB_ENABLE_MALLOC
if (!status)
pb_release(fields, dest_struct);
#endif
return status;
}
bool pb_decode_delimited_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
pb_istream_t substream;
bool status;
if (!pb_make_string_substream(stream, &substream))
return false;
status = pb_decode_noinit(&substream, fields, dest_struct);
if (!pb_close_string_substream(stream, &substream))
return false;
return status;
}
bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
pb_istream_t substream;
bool status;
if (!pb_make_string_substream(stream, &substream))
return false;
status = pb_decode(&substream, fields, dest_struct);
if (!pb_close_string_substream(stream, &substream))
return false;
return status;
}
bool pb_decode_nullterminated(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
/* This behaviour will be separated in nanopb-0.4.0, see issue #278. */
return pb_decode(stream, fields, dest_struct);
}
#ifdef PB_ENABLE_MALLOC
/* Given an oneof field, if there has already been a field inside this oneof,
* release it before overwriting with a different one. */
static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter)
{
pb_size_t old_tag = *(pb_size_t*)iter->pSize; /* Previous which_ value */
pb_size_t new_tag = iter->pos->tag; /* New which_ value */
if (old_tag == 0)
return true; /* Ok, no old data in union */
if (old_tag == new_tag)
return true; /* Ok, old data is of same type => merge */
/* Release old data. The find can fail if the message struct contains
* invalid data. */
if (!pb_field_iter_find(iter, old_tag))
PB_RETURN_ERROR(stream, "invalid union tag");
pb_release_single_field(iter);
/* Restore iterator to where it should be.
* This shouldn't fail unless the pb_field_t structure is corrupted. */
if (!pb_field_iter_find(iter, new_tag))
PB_RETURN_ERROR(stream, "iterator error");
return true;
}
static void pb_release_single_field(const pb_field_iter_t *iter)
{
pb_type_t type;
type = iter->pos->type;
if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
{
if (*(pb_size_t*)iter->pSize != iter->pos->tag)
return; /* This is not the current field in the union */
}
/* Release anything contained inside an extension or submsg.
* This has to be done even if the submsg itself is statically
* allocated. */
if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
{
/* Release fields from all extensions in the linked list */
pb_extension_t *ext = *(pb_extension_t**)iter->pData;
while (ext != NULL)
{
pb_field_iter_t ext_iter;
iter_from_extension(&ext_iter, ext);
pb_release_single_field(&ext_iter);
ext = ext->next;
}
}
else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE && PB_ATYPE(type) != PB_ATYPE_CALLBACK)
{
/* Release fields in submessage or submsg array */
void *pItem = iter->pData;
pb_size_t count = 1;
if (PB_ATYPE(type) == PB_ATYPE_POINTER)
{
pItem = *(void**)iter->pData;
}
if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
{
if (PB_ATYPE(type) == PB_ATYPE_STATIC && iter->pSize == iter->pData) {
/* No _count field so use size of the array */
count = iter->pos->array_size;
} else {
count = *(pb_size_t*)iter->pSize;
}
if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > iter->pos->array_size)
{
/* Protect against corrupted _count fields */
count = iter->pos->array_size;
}
}
if (pItem)
{
while (count--)
{
pb_release((const pb_field_t*)iter->pos->ptr, pItem);
pItem = (char*)pItem + iter->pos->data_size;
}
}
}
if (PB_ATYPE(type) == PB_ATYPE_POINTER)
{
if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
(PB_LTYPE(type) == PB_LTYPE_STRING ||
PB_LTYPE(type) == PB_LTYPE_BYTES))
{
/* Release entries in repeated string or bytes array */
void **pItem = *(void***)iter->pData;
pb_size_t count = *(pb_size_t*)iter->pSize;
while (count--)
{
pb_free(*pItem);
*pItem++ = NULL;
}
}
if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
{
/* We are going to release the array, so set the size to 0 */
*(pb_size_t*)iter->pSize = 0;
}
/* Release main item */
pb_free(*(void**)iter->pData);
*(void**)iter->pData = NULL;
}
}
void pb_release(const pb_field_t fields[], void *dest_struct)
{
pb_field_iter_t iter;
if (!dest_struct)
return; /* Ignore NULL pointers, similar to free() */
if (!pb_field_iter_begin(&iter, fields, dest_struct))
return; /* Empty message type */
do
{
pb_release_single_field(&iter);
} while (pb_field_iter_next(&iter));
}
#endif
/* Field decoders */
bool pb_decode_bool(pb_istream_t *stream, bool *dest)
{
return pb_dec_bool(stream, NULL, (void*)dest);
}
bool pb_decode_svarint(pb_istream_t *stream, pb_int64_t *dest)
{
pb_uint64_t value;
if (!pb_decode_varint(stream, &value))
return false;
if (value & 1)
*dest = (pb_int64_t)(~(value >> 1));
else
*dest = (pb_int64_t)(value >> 1);
return true;
}
bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
{
pb_byte_t bytes[4];
if (!pb_read(stream, bytes, 4))
return false;
*(uint32_t*)dest = ((uint32_t)bytes[0] << 0) |
((uint32_t)bytes[1] << 8) |
((uint32_t)bytes[2] << 16) |
((uint32_t)bytes[3] << 24);
return true;
}
#ifndef PB_WITHOUT_64BIT
bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
{
pb_byte_t bytes[8];
if (!pb_read(stream, bytes, 8))
return false;
*(uint64_t*)dest = ((uint64_t)bytes[0] << 0) |
((uint64_t)bytes[1] << 8) |
((uint64_t)bytes[2] << 16) |
((uint64_t)bytes[3] << 24) |
((uint64_t)bytes[4] << 32) |
((uint64_t)bytes[5] << 40) |
((uint64_t)bytes[6] << 48) |
((uint64_t)bytes[7] << 56);
return true;
}
#endif
static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
uint32_t value;
PB_UNUSED(field);
if (!pb_decode_varint32(stream, &value))
return false;
*(bool*)dest = (value != 0);
return true;
}
static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
pb_uint64_t value;
pb_int64_t svalue;
pb_int64_t clamped;
if (!pb_decode_varint(stream, &value))
return false;
/* See issue 97: Google's C++ protobuf allows negative varint values to
* be cast as int32_t, instead of the int64_t that should be used when
* encoding. Previous nanopb versions had a bug in encoding. In order to
* not break decoding of such messages, we cast <=32 bit fields to
* int32_t first to get the sign correct.
*/
if (field->data_size == sizeof(pb_int64_t))
svalue = (pb_int64_t)value;
else
svalue = (int32_t)value;
/* Cast to the proper field size, while checking for overflows */
if (field->data_size == sizeof(pb_int64_t))
clamped = *(pb_int64_t*)dest = svalue;
else if (field->data_size == sizeof(int32_t))
clamped = *(int32_t*)dest = (int32_t)svalue;
else if (field->data_size == sizeof(int_least16_t))
clamped = *(int_least16_t*)dest = (int_least16_t)svalue;
else if (field->data_size == sizeof(int_least8_t))
clamped = *(int_least8_t*)dest = (int_least8_t)svalue;
else
PB_RETURN_ERROR(stream, "invalid data_size");
if (clamped != svalue)
PB_RETURN_ERROR(stream, "integer too large");
return true;
}
static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
pb_uint64_t value, clamped;
if (!pb_decode_varint(stream, &value))
return false;
/* Cast to the proper field size, while checking for overflows */
if (field->data_size == sizeof(pb_uint64_t))
clamped = *(pb_uint64_t*)dest = value;
else if (field->data_size == sizeof(uint32_t))
clamped = *(uint32_t*)dest = (uint32_t)value;
else if (field->data_size == sizeof(uint_least16_t))
clamped = *(uint_least16_t*)dest = (uint_least16_t)value;
else if (field->data_size == sizeof(uint_least8_t))
clamped = *(uint_least8_t*)dest = (uint_least8_t)value;
else
PB_RETURN_ERROR(stream, "invalid data_size");
if (clamped != value)
PB_RETURN_ERROR(stream, "integer too large");
return true;
}
static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
pb_int64_t value, clamped;
if (!pb_decode_svarint(stream, &value))
return false;
/* Cast to the proper field size, while checking for overflows */
if (field->data_size == sizeof(pb_int64_t))
clamped = *(pb_int64_t*)dest = value;
else if (field->data_size == sizeof(int32_t))
clamped = *(int32_t*)dest = (int32_t)value;
else if (field->data_size == sizeof(int_least16_t))
clamped = *(int_least16_t*)dest = (int_least16_t)value;
else if (field->data_size == sizeof(int_least8_t))
clamped = *(int_least8_t*)dest = (int_least8_t)value;
else
PB_RETURN_ERROR(stream, "invalid data_size");
if (clamped != value)
PB_RETURN_ERROR(stream, "integer too large");
return true;
}
static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
PB_UNUSED(field);
return pb_decode_fixed32(stream, dest);
}
static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
PB_UNUSED(field);
#ifndef PB_WITHOUT_64BIT
return pb_decode_fixed64(stream, dest);
#else
PB_UNUSED(dest);
PB_RETURN_ERROR(stream, "no 64bit support");
#endif
}
static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
uint32_t size;
size_t alloc_size;
pb_bytes_array_t *bdest;
if (!pb_decode_varint32(stream, &size))
return false;
if (size > PB_SIZE_MAX)
PB_RETURN_ERROR(stream, "bytes overflow");
alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size);
if (size > alloc_size)
PB_RETURN_ERROR(stream, "size too large");
if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
{
#ifndef PB_ENABLE_MALLOC
PB_RETURN_ERROR(stream, "no malloc support");
#else
if (!allocate_field(stream, dest, alloc_size, 1))
return false;
bdest = *(pb_bytes_array_t**)dest;
#endif
}
else
{
if (alloc_size > field->data_size)
PB_RETURN_ERROR(stream, "bytes overflow");
bdest = (pb_bytes_array_t*)dest;
}
bdest->size = (pb_size_t)size;
return pb_read(stream, bdest->bytes, size);
}
static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
uint32_t size;
size_t alloc_size;
bool status;
if (!pb_decode_varint32(stream, &size))
return false;
/* Space for null terminator */
alloc_size = size + 1;
if (alloc_size < size)
PB_RETURN_ERROR(stream, "size too large");
if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
{
#ifndef PB_ENABLE_MALLOC
PB_RETURN_ERROR(stream, "no malloc support");
#else
if (!allocate_field(stream, dest, alloc_size, 1))
return false;
dest = *(void**)dest;
#endif
}
else
{
if (alloc_size > field->data_size)
PB_RETURN_ERROR(stream, "string overflow");
}
status = pb_read(stream, (pb_byte_t*)dest, size);
*((pb_byte_t*)dest + size) = 0;
return status;
}
static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
bool status;
pb_istream_t substream;
const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
if (!pb_make_string_substream(stream, &substream))
return false;
if (field->ptr == NULL)
PB_RETURN_ERROR(stream, "invalid field descriptor");
/* New array entries need to be initialized, while required and optional
* submessages have already been initialized in the top-level pb_decode. */
if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
status = pb_decode(&substream, submsg_fields, dest);
else
status = pb_decode_noinit(&substream, submsg_fields, dest);
if (!pb_close_string_substream(stream, &substream))
return false;
return status;
}
static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
uint32_t size;
if (!pb_decode_varint32(stream, &size))
return false;
if (size > PB_SIZE_MAX)
PB_RETURN_ERROR(stream, "bytes overflow");
if (size == 0)
{
/* As a special case, treat empty bytes string as all zeros for fixed_length_bytes. */
memset(dest, 0, field->data_size);
return true;
}
if (size != field->data_size)
PB_RETURN_ERROR(stream, "incorrect fixed length bytes size");
return pb_read(stream, (pb_byte_t*)dest, field->data_size);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4359_0 |
crossvul-cpp_data_bad_345_1 | /*
* Support for ePass2003 smart cards
*
* Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com>
* Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef ENABLE_SM /* empty file without SM enabled */
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include "internal.h"
#include "asn1.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table epass2003_atrs[] = {
/* This is a FIPS certified card using SCP01 security messaging. */
{"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e",
"FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00",
"FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL },
{NULL, NULL, NULL, 0, 0, NULL}
};
static struct sc_card_operations *iso_ops = NULL;
static struct sc_card_operations epass2003_ops;
static struct sc_card_driver epass2003_drv = {
"epass2003",
"epass2003",
&epass2003_ops,
NULL, 0, NULL
};
#define KEY_TYPE_AES 0x01 /* FIPS mode */
#define KEY_TYPE_DES 0x02 /* Non-FIPS mode */
#define KEY_LEN_AES 16
#define KEY_LEN_DES 8
#define KEY_LEN_DES3 24
#define HASH_LEN 24
static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID };
/*0x00:plain; 0x01:scp01 sm*/
#define SM_PLAIN 0x00
#define SM_SCP01 0x01
static unsigned char g_init_key_enc[16] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10
};
static unsigned char g_init_key_mac[16] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10
};
static unsigned char g_random[8] = {
0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40
};
typedef struct epass2003_exdata_st {
unsigned char sm; /* SM_PLAIN or SM_SCP01 */
unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */
unsigned char sk_enc[16]; /* encrypt session key */
unsigned char sk_mac[16]; /* mac session key */
unsigned char icv_mac[16]; /* instruction counter vector(for sm) */
unsigned char currAlg; /* current Alg */
unsigned int ecAlgFlags; /* Ec Alg mechanism type*/
} epass2003_exdata;
#define REVERSE_ORDER4(x) ( \
((unsigned long)x & 0xFF000000)>> 24 | \
((unsigned long)x & 0x00FF0000)>> 8 | \
((unsigned long)x & 0x0000FF00)<< 8 | \
((unsigned long)x & 0x000000FF)<< 24)
static const struct sc_card_error epass2003_errors[] = {
{ 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" },
{ 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" },
{ 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" },
{ 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" },
{ 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" },
{ 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"},
{ 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"},
{ 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" },
{ 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" },
{ 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" },
{ 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" },
{ 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" },
{ 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" },
{ 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" },
{ 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" },
{ 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" },
{ 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" },
{ 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" },
{ 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" },
{ 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" },
{ 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" },
{ 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" },
{ 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" },
{ 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" },
{ 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" },
{ 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" },
{ 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" },
{ 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" },
{ 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" },
{ 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" },
{ 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" },
{ 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" },
{ 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"},
{ 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"},
{ 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" },
{ 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" },
{ 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" },
{ 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" },
{ 0x9000,SC_SUCCESS, NULL }
};
static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu);
static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out);
int epass2003_refresh(struct sc_card *card);
static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType);
static int
epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)
{
const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]);
int i;
/* Handle special cases here */
if (sw1 == 0x6C) {
sc_log(card->ctx, "Wrong length; correct length is %d", sw2);
return SC_ERROR_WRONG_LENGTH;
}
for (i = 0; i < err_count; i++) {
if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) {
sc_log(card->ctx, "%s", epass2003_errors[i].errorstr);
return epass2003_errors[i].errorno;
}
}
sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2);
return SC_ERROR_CARD_CMD_FAILED;
}
static int
sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu)
{
int r = sc_transmit_apdu(card, apdu);
if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2)))
{
epass2003_refresh(card);
r = sc_transmit_apdu(card, apdu);
}
return r;
}
static int
openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv,
const unsigned char *input, size_t length, unsigned char *output)
{
int r = SC_ERROR_INTERNAL;
EVP_CIPHER_CTX * ctx = NULL;
int outl = 0;
int outl_tmp = 0;
unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 };
memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
goto out;
EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp);
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_EncryptUpdate(ctx, output, &outl, input, length))
goto out;
if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp))
goto out;
r = SC_SUCCESS;
out:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
return r;
}
static int
openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv,
const unsigned char *input, size_t length, unsigned char *output)
{
int r = SC_ERROR_INTERNAL;
EVP_CIPHER_CTX * ctx = NULL;
int outl = 0;
int outl_tmp = 0;
unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 };
memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
goto out;
EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp);
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_DecryptUpdate(ctx, output, &outl, input, length))
goto out;
if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp))
goto out;
r = SC_SUCCESS;
out:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
return r;
}
static int
aes128_encrypt_ecb(const unsigned char *key, int keysize,
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output);
}
static int
aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output);
}
static int
aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output);
}
static int
des3_encrypt_ecb(const unsigned char *key, int keysize,
const unsigned char *input, int length, unsigned char *output)
{
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output);
}
static int
des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output);
}
static int
des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output);
}
static int
des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_enc(EVP_des_cbc(), key, iv, input, length, output);
}
static int
des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dec(EVP_des_cbc(), key, iv, input, length, output);
}
static int
openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length,
unsigned char *output)
{
int r = 0;
EVP_MD_CTX *ctx = NULL;
unsigned outl = 0;
ctx = EVP_MD_CTX_create();
if (ctx == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
EVP_MD_CTX_init(ctx);
EVP_DigestInit_ex(ctx, digest, NULL);
if (!EVP_DigestUpdate(ctx, input, length)) {
r = SC_ERROR_INTERNAL;
goto err;
}
if (!EVP_DigestFinal_ex(ctx, output, &outl)) {
r = SC_ERROR_INTERNAL;
goto err;
}
r = SC_SUCCESS;
err:
if (ctx)
EVP_MD_CTX_destroy(ctx);
return r;
}
static int
sha1_digest(const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dig(EVP_sha1(), input, length, output);
}
static int
sha256_digest(const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dig(EVP_sha256(), input, length, output);
}
static int
gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac,
unsigned char *result, unsigned char key_type)
{
int r;
struct sc_apdu apdu;
unsigned char data[256] = { 0 };
unsigned char tmp_sm;
unsigned long blocksize = 0;
unsigned char cryptogram[256] = { 0 }; /* host cryptogram */
unsigned char iv[16] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = sizeof(g_random);
apdu.data = g_random; /* host random */
apdu.le = apdu.resplen = 28;
apdu.resp = result; /* card random is result[12~19] */
tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = epass2003_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "gen_init_key failed");
/* Step 1 - Generate Derivation data */
memcpy(data, &result[16], 4);
memcpy(&data[4], g_random, 4);
memcpy(&data[8], &result[12], 4);
memcpy(&data[12], &g_random[4], 4);
/* Step 2,3 - Create S-ENC/S-MAC Session Key */
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc);
aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac);
}
else {
des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc);
des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac);
}
memcpy(data, g_random, 8);
memcpy(&data[8], &result[12], 8);
data[16] = 0x80;
blocksize = (key_type == KEY_TYPE_AES ? 16 : 8);
memset(&data[17], 0x00, blocksize - 1);
/* calculate host cryptogram */
if (KEY_TYPE_AES == key_type)
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram);
else
des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram);
/* verify card cryptogram */
if (0 != memcmp(&cryptogram[16], &result[20], 8))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type)
{
int r;
struct sc_apdu apdu;
unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8);
unsigned char data[256] = { 0 };
unsigned char cryptogram[256] = { 0 }; /* host cryptogram */
unsigned char iv[16] = { 0 };
unsigned char mac[256] = { 0 };
unsigned long i;
unsigned char tmp_sm;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
memcpy(data, ran_key, 8);
memcpy(&data[8], g_random, 8);
data[16] = 0x80;
memset(&data[17], 0x00, blocksize - 1);
memset(iv, 0, 16);
/* calculate host cryptogram */
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize,
cryptogram);
} else {
des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize,
cryptogram);
}
memset(data, 0, sizeof(data));
memcpy(data, "\x84\x82\x03\x00\x10", 5);
memcpy(&data[5], &cryptogram[16], 8);
memcpy(&data[13], "\x80\x00\x00", 3);
/* calculate mac icv */
memset(iv, 0x00, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac);
i = 0;
} else {
des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac);
i = 8;
}
/* save mac icv */
memset(exdata->icv_mac, 0x00, 16);
memcpy(exdata->icv_mac, &mac[i], 8);
/* verify host cryptogram */
memcpy(data, &cryptogram[16], 8);
memcpy(&data[8], &mac[i], 8);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00);
apdu.cla = 0x84;
apdu.lc = apdu.datalen = 16;
apdu.data = data;
tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = epass2003_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
LOG_TEST_RET(card->ctx, r,
"APDU verify_init_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r,
"verify_init_key failed");
return r;
}
static int
mutual_auth(struct sc_card *card, unsigned char *key_enc,
unsigned char *key_mac)
{
struct sc_context *ctx = card->ctx;
int r;
unsigned char result[256] = { 0 };
unsigned char ran_key[8] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(ctx);
r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype);
LOG_TEST_RET(ctx, r, "gen_init_key failed");
memcpy(ran_key, &result[12], 8);
r = verify_init_key(card, ran_key, exdata->smtype);
LOG_TEST_RET(ctx, r, "verify_init_key failed");
LOG_FUNC_RETURN(ctx, r);
}
int
epass2003_refresh(struct sc_card *card)
{
int r = SC_SUCCESS;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (exdata->sm) {
card->sm_ctx.sm_mode = 0;
r = mutual_auth(card, g_init_key_enc, g_init_key_mac);
card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
LOG_TEST_RET(card->ctx, r, "mutual_auth failed");
}
return r;
}
/* Data(TLV)=0x87|L|0x01+Cipher */
static int
construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf,
unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char pad[4096] = { 0 };
size_t pad_len;
size_t tlv_more; /* increased tlv length */
unsigned char iv[16] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* padding */
apdu_buf[block_size] = 0x87;
memcpy(pad, apdu->data, apdu->lc);
pad[apdu->lc] = 0x80;
if ((apdu->lc + 1) % block_size)
pad_len = ((apdu->lc + 1) / block_size + 1) * block_size;
else
pad_len = apdu->lc + 1;
/* encode Lc' */
if (pad_len > 0x7E) {
/* Lc' > 0x7E, use extended APDU */
apdu_buf[block_size + 1] = 0x82;
apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100);
apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100);
apdu_buf[block_size + 4] = 0x01;
tlv_more = 5;
}
else {
apdu_buf[block_size + 1] = (unsigned char)pad_len + 1;
apdu_buf[block_size + 2] = 0x01;
tlv_more = 3;
}
memcpy(data_tlv, &apdu_buf[block_size], tlv_more);
/* encrypt Data */
if (KEY_TYPE_AES == key_type)
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more);
else
des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more);
memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len);
*data_tlv_len = tlv_more + pad_len;
return 0;
}
/* Le(TLV)=0x97|L|Le */
static int
construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len,
unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
*(apdu_buf + block_size + data_tlv_len) = 0x97;
if (apdu->le > 0x7F) {
/* Le' > 0x7E, use extended APDU */
*(apdu_buf + block_size + data_tlv_len + 1) = 2;
*(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100);
*(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100);
memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4);
*le_tlv_len = 4;
}
else {
*(apdu_buf + block_size + data_tlv_len + 1) = 1;
*(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le;
memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3);
*le_tlv_len = 3;
}
return 0;
}
/* MAC(TLV)=0x8e|0x08|MAC */
static int
construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len,
unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char mac[4096] = { 0 };
size_t mac_len;
unsigned char icv[16] = { 0 };
int i = (KEY_TYPE_AES == key_type ? 15 : 7);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (0 == data_tlv_len && 0 == le_tlv_len) {
mac_len = block_size;
}
else {
/* padding */
*(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80;
if ((data_tlv_len + le_tlv_len + 1) % block_size)
mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) +
1) * block_size + block_size;
else
mac_len = data_tlv_len + le_tlv_len + 1 + block_size;
memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1),
0, (mac_len - (data_tlv_len + le_tlv_len + 1)));
}
/* increase icv */
for (; i >= 0; i--) {
if (exdata->icv_mac[i] == 0xff) {
exdata->icv_mac[i] = 0;
}
else {
exdata->icv_mac[i]++;
break;
}
}
/* calculate MAC */
memset(icv, 0, sizeof(icv));
memcpy(icv, exdata->icv_mac, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac);
memcpy(mac_tlv + 2, &mac[mac_len - 16], 8);
}
else {
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char tmp[8] = { 0 };
des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac);
des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp);
memset(iv, 0x00, sizeof iv);
des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2);
}
*mac_tlv_len = 2 + 8;
return 0;
}
/* According to GlobalPlatform Card Specification's SCP01
* encode APDU from
* CLA INS P1 P2 [Lc] Data [Le]
* to
* CLA INS P1 P2 Lc' Data' [Le]
* where
* Data'=Data(TLV)+Le(TLV)+MAC(TLV) */
static int
encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm,
unsigned char *apdu_buf, size_t * apdu_buf_len)
{
size_t block_size = 0;
unsigned char dataTLV[4096] = { 0 };
size_t data_tlv_len = 0;
unsigned char le_tlv[256] = { 0 };
size_t le_tlv_len = 0;
size_t mac_tlv_len = 10;
size_t tmp_lc = 0;
size_t tmp_le = 0;
unsigned char mac_tlv[256] = { 0 };
epass2003_exdata *exdata = NULL;
mac_tlv[0] = 0x8E;
mac_tlv[1] = 8;
/* size_t plain_le = 0; */
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata*)card->drv_data;
block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8);
sm->cse = SC_APDU_CASE_4_SHORT;
apdu_buf[0] = (unsigned char)plain->cla;
apdu_buf[1] = (unsigned char)plain->ins;
apdu_buf[2] = (unsigned char)plain->p1;
apdu_buf[3] = (unsigned char)plain->p2;
/* plain_le = plain->le; */
/* padding */
apdu_buf[4] = 0x80;
memset(&apdu_buf[5], 0x00, block_size - 5);
/* Data -> Data' */
if (plain->lc != 0)
if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype))
return -1;
if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0))
if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv,
&le_tlv_len, exdata->smtype))
return -1;
if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype))
return -1;
memset(apdu_buf + 4, 0, *apdu_buf_len - 4);
sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len;
if (sm->lc > 0xFF) {
sm->cse = SC_APDU_CASE_4_EXT;
apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000);
apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100);
apdu_buf[6] = (unsigned char)((sm->lc) % 0x100);
tmp_lc = 3;
}
else {
apdu_buf[4] = (unsigned char)sm->lc;
tmp_lc = 1;
}
memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len);
memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len);
memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len);
memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen);
*apdu_buf_len = 0;
if (4 == le_tlv_len) {
sm->cse = SC_APDU_CASE_4_EXT;
*(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100);
*(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100);
tmp_le = 2;
}
else if (3 == le_tlv_len) {
*(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le;
tmp_le = 1;
}
*apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le;
/* sm->le = calc_le(plain_le); */
return 0;
}
static int
epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm)
{
unsigned char buf[4096] = { 0 }; /* APDU buffer */
size_t buf_len = sizeof(buf);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
if (exdata->sm)
plain->cla |= 0x0C;
sm->cse = plain->cse;
sm->cla = plain->cla;
sm->ins = plain->ins;
sm->p1 = plain->p1;
sm->p2 = plain->p2;
sm->lc = plain->lc;
sm->le = plain->le;
sm->control = plain->control;
sm->flags = plain->flags;
switch (sm->cla & 0x0C) {
case 0x00:
case 0x04:
sm->datalen = plain->datalen;
memcpy((void *)sm->data, plain->data, plain->datalen);
sm->resplen = plain->resplen;
memcpy(sm->resp, plain->resp, plain->resplen);
break;
case 0x0C:
memset(buf, 0, sizeof(buf));
if (0 != encode_apdu(card, plain, sm, buf, &buf_len))
return SC_ERROR_CARD_CMD_FAILED;
break;
default:
return SC_ERROR_INCORRECT_PARAMETERS;
}
return SC_SUCCESS;
}
/* According to GlobalPlatform Card Specification's SCP01
* decrypt APDU response from
* ResponseData' SW1 SW2
* to
* ResponseData SW1 SW2
* where
* ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV)
* where
* Data(TLV)=0x87|L|Cipher
* SW12(TLV)=0x99|0x02|SW1+SW2
* MAC(TLV)=0x8e|0x08|MAC */
static int
decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len)
{
size_t cipher_len;
size_t i;
unsigned char iv[16] = { 0 };
unsigned char plaintext[4096] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* no cipher */
if (in[0] == 0x99)
return 0;
/* parse cipher length */
if (0x01 == in[2] && 0x82 != in[1]) {
cipher_len = in[1];
i = 3;
}
else if (0x01 == in[3] && 0x81 == in[1]) {
cipher_len = in[2];
i = 4;
}
else if (0x01 == in[4] && 0x82 == in[1]) {
cipher_len = in[2] * 0x100;
cipher_len += in[3];
i = 5;
}
else {
return -1;
}
if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext)
return -1;
/* decrypt */
if (KEY_TYPE_AES == exdata->smtype)
aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
else
des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
/* unpadding */
while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))
cipher_len--;
if (2 == cipher_len)
return -1;
memcpy(out, plaintext, cipher_len - 2);
*out_len = cipher_len - 2;
return 0;
}
static int
epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_sm_free_wrapped_apdu(struct sc_card *card,
struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
int rv = SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
if (!sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
if (!(*sm_apdu))
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
if (plain)
rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain);
if ((*sm_apdu)->data) {
unsigned char * p = (unsigned char *)((*sm_apdu)->data);
free(p);
}
if ((*sm_apdu)->resp) {
free((*sm_apdu)->resp);
}
free(*sm_apdu);
*sm_apdu = NULL;
LOG_FUNC_RETURN(ctx, rv);
}
static int
epass2003_sm_get_wrapped_apdu(struct sc_card *card,
struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu *apdu = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (!plain || !sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
*sm_apdu = NULL;
//construct new SM apdu from original apdu
apdu = calloc(1, sizeof(struct sc_apdu));
if (!apdu) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE);
if (!apdu->data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE);
if (!apdu->resp) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE;
apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE;
rv = epass2003_sm_wrap_apdu(card, plain, apdu);
if (rv) {
rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu);
if (rv < 0)
goto err;
}
*sm_apdu = apdu;
apdu = NULL;
err:
if (apdu) {
free((unsigned char *) apdu->data);
free(apdu->resp);
free(apdu);
apdu = NULL;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = sc_transmit_apdu_t(card, apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return r;
}
static int
get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen)
{
int r;
struct sc_apdu apdu;
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
size_t resplen = SC_MAX_APDU_BUFFER_SIZE;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type);
apdu.resp = resp;
apdu.le = 0;
apdu.resplen = resplen;
if (0x86 == type) {
/* No SM temporarily */
unsigned char tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = sc_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
}
else {
r = sc_transmit_apdu_t(card, &apdu);
}
LOG_TEST_RET(card->ctx, r, "APDU get_data failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "get_data failed");
memcpy(data, resp, datalen);
return r;
}
/* card driver functions */
static int epass2003_match_card(struct sc_card *card)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = _sc_match_atr(card, epass2003_atrs, &card->type);
if (r < 0)
return 0;
return 1;
}
static int
epass2003_init(struct sc_card *card)
{
unsigned int flags;
unsigned int ext_flags;
unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
size_t datalen = SC_MAX_APDU_BUFFER_SIZE;
epass2003_exdata *exdata = NULL;
LOG_FUNC_CALLED(card->ctx);
card->name = "epass2003";
card->cla = 0x00;
exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata));
if (!exdata)
return SC_ERROR_OUT_OF_MEMORY;
card->drv_data = exdata;
exdata->sm = SM_SCP01;
/* decide FIPS/Non-FIPS mode */
if (SC_SUCCESS != get_data(card, 0x86, data, datalen))
return SC_ERROR_INVALID_CARD;
if (0x01 == data[2])
exdata->smtype = KEY_TYPE_AES;
else
exdata->smtype = KEY_TYPE_DES;
if (0x84 == data[14]) {
if (0x00 == data[16]) {
exdata->sm = SM_PLAIN;
}
}
/* mutual authentication */
card->max_recv_size = 0xD8;
card->max_send_size = 0xE8;
card->sm_ctx.ops.open = epass2003_refresh;
card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu;
card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu;
/* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */
epass2003_refresh(card);
card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
//set EC Alg Flags
flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW;
ext_flags = 0;
_sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL);
card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_finish(sc_card_t *card)
{
epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data;
if (exdata)
free(exdata);
return SC_SUCCESS;
}
/* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the
* same DF, so use hook functions to increase/decrease FID by 0x20 */
static int
epass2003_hook_path(struct sc_path *path, int inc)
{
u8 fid_h = path->value[path->len - 2];
u8 fid_l = path->value[path->len - 1];
switch (fid_h) {
case 0x29:
case 0x30:
case 0x31:
case 0x32:
case 0x33:
case 0x34:
if (inc)
fid_l = fid_l * FID_STEP;
else
fid_l = fid_l / FID_STEP;
path->value[path->len - 1] = fid_l;
return 1;
default:
break;
}
return 0;
}
static void
epass2003_hook_file(struct sc_file *file, int inc)
{
int fidl = file->id & 0xff;
int fidh = file->id & 0xff00;
if (epass2003_hook_path(&file->path, inc)) {
if (inc)
file->id = fidh + fidl * FID_STEP;
else
file->id = fidh + fidl / FID_STEP;
}
}
static int
epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out)
{
struct sc_apdu apdu;
u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
int r, pathlen;
sc_file_t *file = NULL;
epass2003_hook_path(in_path, 1);
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
apdu.p1 = 0;
if (pathlen != 2)
return SC_ERROR_INVALID_ARGUMENTS;
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.p2 = 0; /* first record, return FCI */
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 0;
}
else {
apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */
/* Not allowed to select private key file, so fake fci. */
/* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */
apdu.resplen = 0x18;
memcpy(apdu.resp,
"\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff",
apdu.resplen);
apdu.resp[9] = path[1];
apdu.sw1 = 0x90;
apdu.sw2 = 0x00;
}
else {
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
}
if (file_out == NULL) {
if (apdu.sw1 == 0x61)
LOG_FUNC_RETURN(card->ctx, 0);
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(card->ctx, r);
if (apdu.resplen < 2)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
switch (apdu.resp[0]) {
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
if (card->ops->process_fci == NULL) {
sc_file_free(file);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
if ((size_t) apdu.resp[1] + 2 <= apdu.resplen)
card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]);
epass2003_hook_file(file, 0);
*file_out = file;
break;
case 0x00: /* proprietary coding */
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
return 0;
}
static int
epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo,
sc_file_t ** file_out)
{
int r;
sc_file_t *file = 0;
sc_path_t path;
memset(&path, 0, sizeof(path));
path.type = SC_PATH_TYPE_FILE_ID;
path.value[0] = id_hi;
path.value[1] = id_lo;
path.len = 2;
r = epass2003_select_fid_(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
/* update cache */
if (file && file->type == SC_FILE_TYPE_DF) {
card->cache.current_path.type = SC_PATH_TYPE_PATH;
card->cache.current_path.value[0] = 0x3f;
card->cache.current_path.value[1] = 0x00;
if (id_hi == 0x3f && id_lo == 0x00) {
card->cache.current_path.len = 2;
}
else {
card->cache.current_path.len = 4;
card->cache.current_path.value[2] = id_hi;
card->cache.current_path.value[3] = id_lo;
}
}
if (file_out)
*file_out = file;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out)
{
int r = 0;
if (card->cache.valid
&& card->cache.current_path.type == SC_PATH_TYPE_DF_NAME
&& card->cache.current_path.len == in_path->len
&& memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) {
if (file_out) {
*file_out = sc_file_new();
if (!file_out)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
}
else {
r = iso_ops->select_file(card, in_path, file_out);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
/* update cache */
card->cache.current_path.type = SC_PATH_TYPE_DF_NAME;
card->cache.current_path.len = in_path->len;
memcpy(card->cache.current_path.value, in_path->value, in_path->len);
}
if (file_out) {
sc_file_t *file = *file_out;
file->type = SC_FILE_TYPE_DF;
file->ef_structure = SC_FILE_EF_UNKNOWN;
file->path.len = 0;
file->size = 0;
/* AID */
memcpy(file->name, in_path->value, in_path->len);
file->namelen = in_path->len;
file->id = 0x0000;
}
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len,
sc_file_t ** file_out)
{
u8 n_pathbuf[SC_MAX_PATH_SIZE];
const u8 *path = pathbuf;
size_t pathlen = len;
int bMatch = -1;
unsigned int i;
int r;
if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
/* if pathlen == 6 then the first FID must be MF (== 3F00) */
if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
/* unify path (the first FID should be MF) */
if (path[0] != 0x3f || path[1] != 0x00) {
n_pathbuf[0] = 0x3f;
n_pathbuf[1] = 0x00;
for (i = 0; i < pathlen; i++)
n_pathbuf[i + 2] = pathbuf[i];
path = n_pathbuf;
pathlen += 2;
}
/* check current working directory */
if (card->cache.valid
&& card->cache.current_path.type == SC_PATH_TYPE_PATH
&& card->cache.current_path.len >= 2
&& card->cache.current_path.len <= pathlen) {
bMatch = 0;
for (i = 0; i < card->cache.current_path.len; i += 2)
if (card->cache.current_path.value[i] == path[i]
&& card->cache.current_path.value[i + 1] == path[i + 1])
bMatch += 2;
}
if (card->cache.valid && bMatch > 2) {
if (pathlen - bMatch == 2) {
/* we are in the right directory */
return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out);
}
else if (pathlen - bMatch > 2) {
/* two more steps to go */
sc_path_t new_path;
/* first step: change directory */
r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL);
LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed");
new_path.type = SC_PATH_TYPE_PATH;
new_path.len = pathlen - bMatch - 2;
memcpy(new_path.value, &(path[bMatch + 2]), new_path.len);
/* final step: select file */
return epass2003_select_file(card, &new_path, file_out);
}
else { /* if (bMatch - pathlen == 0) */
/* done: we are already in the
* requested directory */
sc_log(card->ctx, "cache hit\n");
/* copy file info (if necessary) */
if (file_out) {
sc_file_t *file = sc_file_new();
if (!file)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
file->id = (path[pathlen - 2] << 8) + path[pathlen - 1];
file->path = card->cache.current_path;
file->type = SC_FILE_TYPE_DF;
file->ef_structure = SC_FILE_EF_UNKNOWN;
file->size = 0;
file->namelen = 0;
file->magic = SC_FILE_MAGIC;
*file_out = file;
}
/* nothing left to do */
return SC_SUCCESS;
}
}
else {
/* no usable cache */
for (i = 0; i < pathlen - 2; i += 2) {
r = epass2003_select_fid(card, path[i], path[i + 1], NULL);
LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed");
}
return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out);
}
}
static int
epass2003_select_file(struct sc_card *card, const sc_path_t * in_path,
sc_file_t ** file_out)
{
int r;
char pbuf[SC_MAX_PATH_STRING_SIZE];
LOG_FUNC_CALLED(card->ctx);
r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path);
if (r != SC_SUCCESS)
pbuf[0] = '\0';
sc_log(card->ctx,
"current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n",
card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ?
"aid" : "path",
card->cache.valid ? "valid" : "invalid", pbuf,
card->cache.current_path.len);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (in_path->len != 2)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out);
case SC_PATH_TYPE_DF_NAME:
return epass2003_select_aid(card, in_path, file_out);
case SC_PATH_TYPE_PATH:
return epass2003_select_path(card, in_path->value, in_path->len, file_out);
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
}
static int
epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num)
{
struct sc_apdu apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 *p;
unsigned short fid = 0;
int r, locked = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0);
p = sbuf;
*p++ = 0x80; /* algorithm reference */
*p++ = 0x01;
*p++ = 0x84;
*p++ = 0x81;
*p++ = 0x02;
fid = 0x2900;
fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff));
*p++ = fid >> 8;
*p++ = fid & 0xff;
r = p - sbuf;
apdu.lc = r;
apdu.datalen = r;
apdu.data = sbuf;
if (env->algorithm == SC_ALGORITHM_EC)
{
apdu.p2 = 0xB6;
exdata->currAlg = SC_ALGORITHM_EC;
if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
sbuf[2] = 0x91;
exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1;
}
else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
sbuf[2] = 0x92;
exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256;
}
else
{
sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags);
goto err;
}
}
else if(env->algorithm == SC_ALGORITHM_RSA)
{
exdata->currAlg = SC_ALGORITHM_RSA;
apdu.p2 = 0xB8;
sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags);
}
else
{
sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm);
}
if (se_num > 0) {
r = sc_lock(card);
LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
locked = 1;
}
if (apdu.datalen != 0) {
r = sc_transmit_apdu_t(card, &apdu);
if (r) {
sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r));
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r) {
sc_log(card->ctx, "%s: Card returned error", sc_strerror(r));
goto err;
}
}
if (se_num <= 0)
return 0;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num);
r = sc_transmit_apdu_t(card, &apdu);
sc_unlock(card);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
err:
if (locked)
sc_unlock(card);
return r;
}
static int
epass2003_restore_security_env(struct sc_card *card, int se_num)
{
LOG_FUNC_CALLED(card->ctx);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
int r;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
epass2003_exdata *exdata = NULL;
LOG_FUNC_CALLED(card->ctx);
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if(exdata->currAlg == SC_ALGORITHM_EC)
{
if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash_data failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A);
apdu.data = sbuf;
apdu.lc = 0x14;
apdu.datalen = 0x14;
}
else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256);
LOG_TEST_RET(card->ctx, r, "hash_data failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A);
apdu.data = sbuf;
apdu.lc = 0x20;
apdu.datalen = 0x20;
}
else
{
return SC_ERROR_NOT_SUPPORTED;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
size_t len = apdu.resplen > outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
LOG_FUNC_RETURN(card->ctx, len);
}
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
else if(exdata->currAlg == SC_ALGORITHM_RSA)
{
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0;
memcpy(sbuf, data, datalen);
apdu.data = sbuf;
apdu.lc = datalen;
apdu.datalen = datalen;
}
else
{
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
memcpy(sbuf, data, datalen);
apdu.data = sbuf;
apdu.lc = datalen;
apdu.datalen = datalen;
}
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
size_t len = apdu.resplen > outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
LOG_FUNC_RETURN(card->ctx, len);
}
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int
acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e)
{
if (e == NULL)
return SC_ERROR_OBJECT_NOT_FOUND;
switch (e->method) {
case SC_AC_NONE:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE);
case SC_AC_NEVER:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE);
default:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER);
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
}
static int
epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen)
{
sc_context_t *ctx = card->ctx;
size_t taglen, len = buflen;
const u8 *tag = NULL, *p = buf;
sc_log(ctx, "processing FCI bytes");
tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen);
if (tag != NULL && taglen == 2) {
file->id = (tag[0] << 8) | tag[1];
sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]);
}
tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen);
if (tag != NULL && taglen > 0 && taglen < 3) {
file->size = tag[0];
if (taglen == 2)
file->size = (file->size << 8) + tag[1];
sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u",
file->size);
}
if (tag == NULL) {
tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen);
if (tag != NULL && taglen >= 2) {
int bytes = (tag[0] << 8) + tag[1];
sc_log(ctx, " bytes in file: %d", bytes);
file->size = bytes;
}
}
tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen);
if (tag != NULL) {
if (taglen > 0) {
unsigned char byte = tag[0];
const char *type;
if (byte == 0x38) {
type = "DF";
file->type = SC_FILE_TYPE_DF;
}
else if (0x01 <= byte && byte <= 0x07) {
type = "working EF";
file->type = SC_FILE_TYPE_WORKING_EF;
switch (byte) {
case 0x01:
file->ef_structure = SC_FILE_EF_TRANSPARENT;
break;
case 0x02:
file->ef_structure = SC_FILE_EF_LINEAR_FIXED;
break;
case 0x04:
file->ef_structure = SC_FILE_EF_LINEAR_FIXED;
break;
case 0x03:
case 0x05:
case 0x06:
case 0x07:
break;
default:
break;
}
}
else if (0x10 == byte) {
type = "BSO";
file->type = SC_FILE_TYPE_BSO;
}
else if (0x11 <= byte) {
type = "internal EF";
file->type = SC_FILE_TYPE_INTERNAL_EF;
switch (byte) {
case 0x11:
break;
case 0x12:
break;
default:
break;
}
}
else {
type = "unknown";
file->type = SC_FILE_TYPE_INTERNAL_EF;
}
sc_log(ctx, "type %s, EF structure %d", type, byte);
}
}
tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen);
if (tag != NULL && taglen > 0 && taglen <= 16) {
memcpy(file->name, tag, taglen);
file->namelen = taglen;
sc_log_hex(ctx, "File name", file->name, file->namelen);
if (!file->type)
file->type = SC_FILE_TYPE_DF;
}
tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen);
if (tag != NULL && taglen)
sc_file_set_prop_attr(file, tag, taglen);
else
file->prop_attr_len = 0;
tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen);
if (tag != NULL && taglen)
sc_file_set_prop_attr(file, tag, taglen);
tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen);
if (tag != NULL && taglen)
sc_file_set_sec_attr(file, tag, taglen);
tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen);
if (tag != NULL && taglen == 1) {
if (tag[0] == 0x01)
file->status = SC_FILE_STATUS_CREATION;
else if (tag[0] == 0x07 || tag[0] == 0x05)
file->status = SC_FILE_STATUS_ACTIVATED;
else if (tag[0] == 0x06 || tag[0] == 0x04)
file->status = SC_FILE_STATUS_INVALIDATED;
}
file->magic = SC_FILE_MAGIC;
return 0;
}
static int
epass2003_construct_fci(struct sc_card *card, const sc_file_t * file,
u8 * out, size_t * outlen)
{
u8 *p = out;
u8 buf[64];
unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
int rv;
unsigned ii;
if (*outlen < 2)
return SC_ERROR_BUFFER_TOO_SMALL;
*p++ = 0x62;
p++;
if (file->type == SC_FILE_TYPE_WORKING_EF) {
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p);
}
}
if (file->type == SC_FILE_TYPE_DF) {
buf[0] = 0x38;
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
buf[0] = file->ef_structure & 7;
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED
|| file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) {
buf[1] = 0x00;
buf[2] = 0x00;
buf[3] = 0x40; /* record length */
buf[4] = 0x00; /* record count */
sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p);
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) {
buf[0] = 0x11;
buf[1] = 0x00;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
buf[0] = 0x12;
buf[1] = 0x00;
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_BSO) {
buf[0] = 0x10;
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p);
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen != 0) {
sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p);
}
else {
return SC_ERROR_INVALID_ARGUMENTS;
}
}
if (file->type == SC_FILE_TYPE_DF) {
unsigned char data[2] = {0x00, 0x7F};
/* 127 files at most */
sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_BSO) {
buf[0] = file->size & 0xff;
sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p);
}
}
if (file->sec_attr_len) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p);
}
else {
sc_log(card->ctx, "SC_FILE_ACL");
if (file->type == SC_FILE_TYPE_DF) {
ops[0] = SC_AC_OP_LIST_FILES;
ops[1] = SC_AC_OP_CREATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED
|| file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_WRITE;
ops[3] = SC_AC_OP_DELETE;
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
}
else if (file->type == SC_FILE_TYPE_BSO) {
ops[0] = SC_AC_OP_UPDATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) {
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_CRYPTO;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_CRYPTO;
ops[3] = SC_AC_OP_DELETE;
}
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
for (ii = 0; ii < sizeof(ops); ii++) {
const struct sc_acl_entry *entry;
buf[ii] = 0xFF;
if (ops[ii] == 0xFF)
continue;
entry = sc_file_get_acl_entry(file, ops[ii]);
rv = acl_to_ac_byte(card, entry);
LOG_TEST_RET(card->ctx, rv, "Invalid ACL");
buf[ii] = rv;
}
sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p);
if(file->size == 256)
{
out[4]= 0x13;
}
}
/* VT ??? */
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
unsigned char data[2] = {0x00, 0x66};
sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p);
if(file->size == 256)
{
out[4]= 0x14;
}
}
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int
epass2003_create_file(struct sc_card *card, sc_file_t * file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
struct sc_apdu apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
epass2003_hook_file(file, 1);
if (card->ops->construct_fci == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
r = epass2003_construct_fci(card, file, sbuf, &len);
LOG_TEST_RET(card->ctx, r, "construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong");
epass2003_hook_file(file, 0);
return r;
}
static int
epass2003_delete_file(struct sc_card *card, const sc_path_t * path)
{
int r;
u8 sbuf[2];
struct sc_apdu apdu;
LOG_FUNC_CALLED(card->ctx);
r = sc_select_file(card, path, NULL);
epass2003_hook_path((struct sc_path *)path, 1);
if (r == SC_SUCCESS) {
sbuf[0] = path->value[path->len - 2];
sbuf[1] = path->value[path->len - 1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
}
else {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Delete file failed");
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen)
{
struct sc_apdu apdu;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00);
apdu.cla = 0x80;
apdu.le = 0;
apdu.resplen = sizeof(rbuf);
apdu.resp = rbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Card returned error");
if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0)
LOG_FUNC_RETURN(card->ctx, 0);
buflen = buflen < apdu.resplen ? buflen : apdu.resplen;
memcpy(buf, rbuf, buflen);
LOG_FUNC_RETURN(card->ctx, buflen);
}
static int
internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor,
sc_pkcs15_bignum_t data)
{
int r;
struct sc_apdu apdu;
u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
LOG_FUNC_CALLED(card->ctx);
sbuff[0] = ((fid & 0xff00) >> 8);
sbuff[1] = (fid & 0x00ff);
memcpy(&sbuff[2], data.data, data.len);
// sc_mem_reverse(&sbuff[2], data.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 2 + data.len;
apdu.data = sbuff;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus);
LOG_TEST_RET(card->ctx, r, "write n failed");
r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d);
LOG_TEST_RET(card->ctx, r, "write d failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType)
{
if ((NULL == data) || (NULL == hash))
return SC_ERROR_INVALID_ARGUMENTS;
if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
unsigned char data_hash[24] = { 0 };
size_t len = 0;
sha1_digest(data, datalen, data_hash);
len = REVERSE_ORDER4(datalen);
memcpy(&data_hash[20], &len, 4);
memcpy(hash, data_hash, 24);
}
else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
unsigned char data_hash[36] = { 0 };
size_t len = 0;
sha256_digest(data, datalen, data_hash);
len = REVERSE_ORDER4(datalen);
memcpy(&data_hash[32], &len, 4);
memcpy(hash, data_hash, 36);
}
else
{
return SC_ERROR_NOT_SUPPORTED;
}
return SC_SUCCESS;
}
static int
install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid,
unsigned char useac, unsigned char modifyac, unsigned char EC,
unsigned char *data, unsigned long dataLen)
{
int r;
struct sc_apdu apdu;
unsigned char isapp = 0x00; /* appendable */
unsigned char tmp_data[256] = { 0 };
tmp_data[0] = ktype;
tmp_data[1] = kid;
tmp_data[2] = useac;
tmp_data[3] = modifyac;
tmp_data[8] = 0xFF;
if (0x04 == ktype || 0x06 == ktype) {
tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO;
tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO;
tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO);
tmp_data[9] = (EC << 4) | EC;
}
memcpy(&tmp_data[10], data, dataLen);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 10 + dataLen;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "install_secret_key failed");
return r;
}
static int
internal_install_pre(struct sc_card *card)
{
int r;
/* init key for enc */
r = install_secret_key(card, 0x01, 0x00,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
0, g_init_key_enc, 16);
LOG_TEST_RET(card->ctx, r, "Install init key failed");
/* init key for mac */
r = install_secret_key(card, 0x02, 0x00,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
0, g_init_key_mac, 16);
LOG_TEST_RET(card->ctx, r, "Install init key failed");
return r;
}
/* use external auth secret as pin */
static int
internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin)
{
int r;
unsigned char hash[HASH_LEN] = { 0 };
r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid,
pin->key_data.es_secret.ac[0],
pin->key_data.es_secret.ac[1],
pin->key_data.es_secret.EC, hash, HASH_LEN);
LOG_TEST_RET(card->ctx, r, "Install failed");
return r;
}
static int
epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data)
{
LOG_FUNC_CALLED(card->ctx);
if (data->type & SC_EPASS2003_KEY) {
if (data->type == SC_EPASS2003_KEY_RSA)
return internal_write_rsa_key(card, data->key_data.es_key.fid,
data->key_data.es_key.rsa);
else
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
} else if (data->type & SC_EPASS2003_SECRET) {
if (data->type == SC_EPASS2003_SECRET_PRE)
return internal_install_pre(card);
else if (data->type == SC_EPASS2003_SECRET_PIN)
return internal_install_pin(card, data);
else
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
else {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data)
{
int r;
size_t len = data->key_length;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
LOG_FUNC_CALLED(card->ctx);
if(len == 256)
{
sbuf[0] = 0x02;
}
else
{
sbuf[0] = 0x01;
}
sbuf[1] = (u8) ((len >> 8) & 0xff);
sbuf[2] = (u8) (len & 0xff);
sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF);
sbuf[4] = (u8) ((data->prkey_id) & 0xFF);
sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF);
sbuf[6] = (u8) ((data->pukey_id) & 0xFF);
/* generate key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00);
apdu.lc = apdu.datalen = 7;
apdu.data = sbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "generate keypair failed");
/* read public key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00);
if(len == 256)
{
apdu.p1 = 0x00;
}
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 2;
apdu.data = &sbuf[5];
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x00;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "get pukey failed");
if (len < apdu.resplen)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
data->modulus = (u8 *) malloc(len);
if (!data->modulus)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(data->modulus, rbuf, len);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_erase_card(struct sc_card *card)
{
int r;
LOG_FUNC_CALLED(card->ctx);
sc_invalidate_cache(card);
r = sc_delete_file(card, sc_get_mf_path());
LOG_TEST_RET(card->ctx, r, "delete MF failed");
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial)
{
u8 rbuf[8];
size_t rbuf_len = sizeof(rbuf);
LOG_FUNC_CALLED(card->ctx);
if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len))
return SC_ERROR_CARD_CMD_FAILED;
card->serialnr.len = serial->len = 8;
memcpy(card->serialnr.value, rbuf, 8);
memcpy(serial->value, rbuf, 8);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr)
{
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "cmd is %0lx", cmd);
switch (cmd) {
case SC_CARDCTL_ENTERSAFE_WRITE_KEY:
return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr);
case SC_CARDCTL_ENTERSAFE_GENERATE_KEY:
return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr);
case SC_CARDCTL_ERASE_CARD:
return epass2003_erase_card(card);
case SC_CARDCTL_GET_SERIALNR:
return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static void
internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num)
{
pin->encoding = SC_PIN_ENCODING_ASCII;
pin->min_length = 4;
pin->max_length = 16;
pin->pad_length = 16;
pin->offset = 5 + num * 16;
pin->pad_char = 0x00;
}
static int
get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries)
{
unsigned char maxcounter[2] = { 0 };
static const sc_path_t file_path = {
{0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6,
0,
0,
SC_PATH_TYPE_PATH,
{{0}, 0}
};
int ret;
ret = sc_select_file(card, &file_path, NULL);
LOG_TEST_RET(card->ctx, ret, "select max counter file failed");
ret = sc_read_binary(card, 0, maxcounter, 2, 0);
LOG_TEST_RET(card->ctx, ret, "read max counter file failed");
*maxtries = maxcounter[0];
return SC_SUCCESS;
}
static int
get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries)
{
int r;
struct sc_apdu apdu;
unsigned char random[16] = { 0 };
r = sc_get_challenge(card, random, 8);
LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid);
apdu.resp = NULL;
apdu.resplen = 0;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed");
if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) {
*retries = (apdu.sw2 & 0x0f);
r = SC_SUCCESS;
}
else {
LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed");
r = SC_ERROR_CARD_CMD_FAILED;
}
return r;
}
static int
epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
u8 rbuf[16];
size_t out_len;
int r;
LOG_FUNC_CALLED(card->ctx);
r = iso_ops->get_challenge(card, rbuf, sizeof rbuf);
LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed");
if (len < (size_t) r) {
out_len = len;
} else {
out_len = (size_t) r;
}
memcpy(rnd, rbuf, out_len);
LOG_FUNC_RETURN(card->ctx, (int) out_len);
}
static int
external_key_auth(struct sc_card *card, unsigned char kid,
unsigned char *data, size_t datalen)
{
int r;
struct sc_apdu apdu;
unsigned char random[16] = { 0 };
unsigned char tmp_data[16] = { 0 };
unsigned char hash[HASH_LEN] = { 0 };
unsigned char iv[16] = { 0 };
r = sc_get_challenge(card, random, 8);
LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed");
r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid);
apdu.lc = apdu.datalen = 8;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "external_key_auth failed");
return r;
}
static int
update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid,
const unsigned char *data, unsigned long datalen)
{
int r;
struct sc_apdu apdu;
unsigned char hash[HASH_LEN] = { 0 };
unsigned char tmp_data[256] = { 0 };
unsigned char maxtries = 0;
r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
r = get_external_key_maxtries(card, &maxtries);
LOG_TEST_RET(card->ctx, r, "get max counter failed");
tmp_data[0] = (maxtries << 4) | maxtries;
memcpy(&tmp_data[1], hash, HASH_LEN);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 1 + HASH_LEN;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "update_secret_key failed");
return r;
}
/* use external auth secret as pin */
static int
epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
int r;
u8 kid;
u8 retries = 0;
u8 pin_low = 3;
unsigned char maxtries = 0;
LOG_FUNC_CALLED(card->ctx);
internal_sanitize_pin_info(&data->pin1, 0);
internal_sanitize_pin_info(&data->pin2, 1);
data->flags |= SC_PIN_CMD_NEED_PADDING;
kid = data->pin_reference;
/* get pin retries */
if (data->cmd == SC_PIN_CMD_GET_INFO) {
r = get_external_key_retries(card, 0x80 | kid, &retries);
if (r == SC_SUCCESS) {
data->pin1.tries_left = retries;
if (tries_left)
*tries_left = retries;
r = get_external_key_maxtries(card, &maxtries);
LOG_TEST_RET(card->ctx, r, "get max counter failed");
data->pin1.max_tries = maxtries;
}
//remove below code, because the old implement only return PIN retries, now modify the code and return PIN status
// return r;
}
else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */
r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data,
data->pin1.len);
LOG_TEST_RET(card->ctx, r, "verify pin failed");
}
else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */
r = update_secret_key(card, 0x04, kid, data->pin2.data,
(unsigned long)data->pin2.len);
LOG_TEST_RET(card->ctx, r, "verify pin failed");
}
else {
r = external_key_auth(card, kid, (unsigned char *)data->pin1.data,
data->pin1.len);
get_external_key_retries(card, 0x80 | kid, &retries);
if (retries < pin_low)
sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries);
}
LOG_TEST_RET(card->ctx, r, "verify pin failed");
if (r == SC_SUCCESS)
{
data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN;
}
return r;
}
static struct sc_card_driver *sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
epass2003_ops = *iso_ops;
epass2003_ops.match_card = epass2003_match_card;
epass2003_ops.init = epass2003_init;
epass2003_ops.finish = epass2003_finish;
epass2003_ops.write_binary = NULL;
epass2003_ops.write_record = NULL;
epass2003_ops.select_file = epass2003_select_file;
epass2003_ops.get_response = NULL;
epass2003_ops.restore_security_env = epass2003_restore_security_env;
epass2003_ops.set_security_env = epass2003_set_security_env;
epass2003_ops.decipher = epass2003_decipher;
epass2003_ops.compute_signature = epass2003_decipher;
epass2003_ops.create_file = epass2003_create_file;
epass2003_ops.delete_file = epass2003_delete_file;
epass2003_ops.list_files = epass2003_list_files;
epass2003_ops.card_ctl = epass2003_card_ctl;
epass2003_ops.process_fci = epass2003_process_fci;
epass2003_ops.construct_fci = epass2003_construct_fci;
epass2003_ops.pin_cmd = epass2003_pin_cmd;
epass2003_ops.check_sw = epass2003_check_sw;
epass2003_ops.get_challenge = epass2003_get_challenge;
return &epass2003_drv;
}
struct sc_card_driver *sc_get_epass2003_driver(void)
{
return sc_get_driver();
}
#endif /* #ifdef ENABLE_OPENSSL */
#endif /* #ifdef ENABLE_SM */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_345_1 |
crossvul-cpp_data_bad_4907_0 | /**
* eCryptfs: Linux filesystem encryption layer
*
* Copyright (C) 2008 International Business Machines Corp.
* Author(s): Michael A. Halcrow <mahalcro@us.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/slab.h>
#include <linux/wait.h>
#include <linux/mount.h>
#include "ecryptfs_kernel.h"
struct ecryptfs_open_req {
struct file **lower_file;
struct path path;
struct completion done;
struct list_head kthread_ctl_list;
};
static struct ecryptfs_kthread_ctl {
#define ECRYPTFS_KTHREAD_ZOMBIE 0x00000001
u32 flags;
struct mutex mux;
struct list_head req_list;
wait_queue_head_t wait;
} ecryptfs_kthread_ctl;
static struct task_struct *ecryptfs_kthread;
/**
* ecryptfs_threadfn
* @ignored: ignored
*
* The eCryptfs kernel thread that has the responsibility of getting
* the lower file with RW permissions.
*
* Returns zero on success; non-zero otherwise
*/
static int ecryptfs_threadfn(void *ignored)
{
set_freezable();
while (1) {
struct ecryptfs_open_req *req;
wait_event_freezable(
ecryptfs_kthread_ctl.wait,
(!list_empty(&ecryptfs_kthread_ctl.req_list)
|| kthread_should_stop()));
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
mutex_unlock(&ecryptfs_kthread_ctl.mux);
goto out;
}
while (!list_empty(&ecryptfs_kthread_ctl.req_list)) {
req = list_first_entry(&ecryptfs_kthread_ctl.req_list,
struct ecryptfs_open_req,
kthread_ctl_list);
list_del(&req->kthread_ctl_list);
*req->lower_file = dentry_open(&req->path,
(O_RDWR | O_LARGEFILE), current_cred());
complete(&req->done);
}
mutex_unlock(&ecryptfs_kthread_ctl.mux);
}
out:
return 0;
}
int __init ecryptfs_init_kthread(void)
{
int rc = 0;
mutex_init(&ecryptfs_kthread_ctl.mux);
init_waitqueue_head(&ecryptfs_kthread_ctl.wait);
INIT_LIST_HEAD(&ecryptfs_kthread_ctl.req_list);
ecryptfs_kthread = kthread_run(&ecryptfs_threadfn, NULL,
"ecryptfs-kthread");
if (IS_ERR(ecryptfs_kthread)) {
rc = PTR_ERR(ecryptfs_kthread);
printk(KERN_ERR "%s: Failed to create kernel thread; rc = [%d]"
"\n", __func__, rc);
}
return rc;
}
void ecryptfs_destroy_kthread(void)
{
struct ecryptfs_open_req *req, *tmp;
mutex_lock(&ecryptfs_kthread_ctl.mux);
ecryptfs_kthread_ctl.flags |= ECRYPTFS_KTHREAD_ZOMBIE;
list_for_each_entry_safe(req, tmp, &ecryptfs_kthread_ctl.req_list,
kthread_ctl_list) {
list_del(&req->kthread_ctl_list);
*req->lower_file = ERR_PTR(-EIO);
complete(&req->done);
}
mutex_unlock(&ecryptfs_kthread_ctl.mux);
kthread_stop(ecryptfs_kthread);
wake_up(&ecryptfs_kthread_ctl.wait);
}
/**
* ecryptfs_privileged_open
* @lower_file: Result of dentry_open by root on lower dentry
* @lower_dentry: Lower dentry for file to open
* @lower_mnt: Lower vfsmount for file to open
*
* This function gets a r/w file opened againt the lower dentry.
*
* Returns zero on success; non-zero otherwise
*/
int ecryptfs_privileged_open(struct file **lower_file,
struct dentry *lower_dentry,
struct vfsmount *lower_mnt,
const struct cred *cred)
{
struct ecryptfs_open_req req;
int flags = O_LARGEFILE;
int rc = 0;
init_completion(&req.done);
req.lower_file = lower_file;
req.path.dentry = lower_dentry;
req.path.mnt = lower_mnt;
/* Corresponding dput() and mntput() are done when the
* lower file is fput() when all eCryptfs files for the inode are
* released. */
flags |= IS_RDONLY(d_inode(lower_dentry)) ? O_RDONLY : O_RDWR;
(*lower_file) = dentry_open(&req.path, flags, cred);
if (!IS_ERR(*lower_file))
goto out;
if ((flags & O_ACCMODE) == O_RDONLY) {
rc = PTR_ERR((*lower_file));
goto out;
}
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
rc = -EIO;
mutex_unlock(&ecryptfs_kthread_ctl.mux);
printk(KERN_ERR "%s: We are in the middle of shutting down; "
"aborting privileged request to open lower file\n",
__func__);
goto out;
}
list_add_tail(&req.kthread_ctl_list, &ecryptfs_kthread_ctl.req_list);
mutex_unlock(&ecryptfs_kthread_ctl.mux);
wake_up(&ecryptfs_kthread_ctl.wait);
wait_for_completion(&req.done);
if (IS_ERR(*lower_file))
rc = PTR_ERR(*lower_file);
out:
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4907_0 |
crossvul-cpp_data_bad_4787_4 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% BBBB GGGG RRRR %
% B B G R R %
% BBBB G GG RRRR %
% B B G G R R %
% BBBB GGG R R %
% %
% %
% Read/Write Raw BGR Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/channel.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/utility.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteBGRImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d B G R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadBGRImage() reads an image of raw BGR, or BGRA samples and returns
% it. It allocates the memory necessary for the new Image structure and
% returns a pointer to the new image.
%
% The format of the ReadBGRImage method is:
%
% Image *ReadBGRImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadBGRImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*canvas_image,
*image;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
if (image_info->interlace != PartitionInterlace)
{
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
/*
Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]).
*/
canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse,
exception);
(void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod);
quantum_info=AcquireQuantumInfo(image_info,canvas_image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
quantum_type=BGRQuantum;
if (LocaleCompare(image_info->magick,"BGRA") == 0)
{
quantum_type=BGRAQuantum;
image->matte=MagickTrue;
}
if (image_info->number_scenes != 0)
while (image->scene < image_info->scene)
{
/*
Skip to next image.
*/
image->scene++;
length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
}
count=0;
length=0;
scene=0;
do
{
/*
Read pixels to virtual canvas image then push to image.
*/
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
switch (image_info->interlace)
{
case NoInterlace:
default:
{
/*
No interlacing: BGRBGRBGRBGRBGRBGR...
*/
if (scene == 0)
{
length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);
count=ReadBlob(image,length,pixels);
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,quantum_type,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=QueueAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
SetPixelGreen(q,GetPixelGreen(p));
SetPixelBlue(q,GetPixelBlue(p));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelOpacity(q,GetPixelOpacity(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
break;
}
case LineInterlace:
{
static QuantumType
quantum_types[4] =
{
BlueQuantum,
GreenQuantum,
RedQuantum,
AlphaQuantum
};
/*
Line interlacing: BBB...GGG...RRR...RRR...GGG...BBB...
*/
if (scene == 0)
{
length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum);
count=ReadBlob(image,length,pixels);
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
for (i=0; i < (ssize_t) (image->matte != MagickFalse ? 4 : 3); i++)
{
quantum_type=quantum_types[i];
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,quantum_type,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch (quantum_type)
{
case RedQuantum:
{
SetPixelRed(q,GetPixelRed(p));
break;
}
case GreenQuantum:
{
SetPixelGreen(q,GetPixelGreen(p));
break;
}
case BlueQuantum:
{
SetPixelBlue(q,GetPixelBlue(p));
break;
}
case OpacityQuantum:
{
SetPixelOpacity(q,GetPixelOpacity(p));
break;
}
case AlphaQuantum:
{
SetPixelAlpha(q,GetPixelAlpha(p));
break;
}
default:
break;
}
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
if (scene == 0)
{
length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum);
count=ReadBlob(image,length,pixels);
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,RedQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,1,6);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,GreenQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGreen(q,GetPixelGreen(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,2,6);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,BlueQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(q,GetPixelBlue(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,3,6);
if (status == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,4,6);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
{
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,
canvas_image->extract_info.x,0,canvas_image->columns,1,
exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelOpacity(q,GetPixelOpacity(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,5,6);
if (status == MagickFalse)
break;
}
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,6,6);
if (status == MagickFalse)
break;
}
break;
}
case PartitionInterlace:
{
/*
Partition interlacing: BBBBBB..., GGGGGG..., RRRRRR...
*/
AppendImageFormat("B",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
canvas_image=DestroyImageList(canvas_image);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum);
for (i=0; i < (ssize_t) scene; i++)
for (y=0; y < (ssize_t) image->extract_info.height; y++)
if (ReadBlob(image,length,pixels) != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
count=ReadBlob(image,length,pixels);
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,BlueQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,1,5);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
AppendImageFormat("G",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
canvas_image=DestroyImageList(canvas_image);
image=DestroyImageList(image);
return((Image *) NULL);
}
length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum);
for (i=0; i < (ssize_t) scene; i++)
for (y=0; y < (ssize_t) image->extract_info.height; y++)
if (ReadBlob(image,length,pixels) != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
count=ReadBlob(image,length,pixels);
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,GreenQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGreen(q,GetPixelGreen(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,2,5);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
AppendImageFormat("R",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
canvas_image=DestroyImageList(canvas_image);
image=DestroyImageList(image);
return((Image *) NULL);
}
length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum);
for (i=0; i < (ssize_t) scene; i++)
for (y=0; y < (ssize_t) image->extract_info.height; y++)
if (ReadBlob(image,length,pixels) != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
count=ReadBlob(image,length,pixels);
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,RedQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(q,GetPixelBlue(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,3,5);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
{
(void) CloseBlob(image);
AppendImageFormat("A",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
canvas_image=DestroyImageList(canvas_image);
image=DestroyImageList(image);
return((Image *) NULL);
}
length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum);
for (i=0; i < (ssize_t) scene; i++)
for (y=0; y < (ssize_t) image->extract_info.height; y++)
if (ReadBlob(image,length,pixels) != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
count=ReadBlob(image,length,pixels);
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,BlueQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,
0,canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelOpacity(q,GetPixelOpacity(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,4,5);
if (status == MagickFalse)
break;
}
}
(void) CloseBlob(image);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,5,5);
if (status == MagickFalse)
break;
}
break;
}
}
SetQuantumImageType(image,quantum_type);
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (count == (ssize_t) length)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
scene++;
} while (count == (ssize_t) length);
quantum_info=DestroyQuantumInfo(quantum_info);
InheritException(&image->exception,&canvas_image->exception);
canvas_image=DestroyImage(canvas_image);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r B G R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterBGRImage() adds attributes for the BGR image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterBGRImage method is:
%
% size_t RegisterBGRImage(void)
%
*/
ModuleExport size_t RegisterBGRImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("BGR");
entry->decoder=(DecodeImageHandler *) ReadBGRImage;
entry->encoder=(EncodeImageHandler *) WriteBGRImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Raw blue, green, and red samples");
entry->module=ConstantString("BGR");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("BGRA");
entry->decoder=(DecodeImageHandler *) ReadBGRImage;
entry->encoder=(EncodeImageHandler *) WriteBGRImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Raw blue, green, red, and alpha samples");
entry->module=ConstantString("BGR");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r B G R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterBGRImage() removes format registrations made by the BGR module
% from the list of supported formats.
%
% The format of the UnregisterBGRImage method is:
%
% UnregisterBGRImage(void)
%
*/
ModuleExport void UnregisterBGRImage(void)
{
(void) UnregisterMagickInfo("BGRA");
(void) UnregisterMagickInfo("BGR");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e B G R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteBGRImage() writes an image to a file in the BGR or BGRA
% rasterfile format.
%
% The format of the WriteBGRImage method is:
%
% MagickBooleanType WriteBGRImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteBGRImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Allocate memory for pixels.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image_info->interlace != PartitionInterlace)
{
/*
Open output image file.
*/
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
}
quantum_type=BGRQuantum;
if (LocaleCompare(image_info->magick,"BGRA") == 0)
{
quantum_type=BGRAQuantum;
image->matte=MagickTrue;
}
scene=0;
do
{
/*
Convert MIFF to BGR raster pixels.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if ((LocaleCompare(image_info->magick,"BGRA") == 0) &&
(image->matte == MagickFalse))
(void) SetImageAlphaChannel(image,ResetAlphaChannel);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
switch (image_info->interlace)
{
case NoInterlace:
default:
{
/*
No interlacing: BGRBGRBGRBGRBGRBGR...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case LineInterlace:
{
/*
Line interlacing: BBB...GGG...RRR...RRR...GGG...BBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
if (quantum_type == BGRAQuantum)
{
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,1,6);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,2,6);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,3,6);
if (status == MagickFalse)
break;
}
if (quantum_type == BGRAQuantum)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,5,6);
if (status == MagickFalse)
break;
}
}
if (image_info->interlace == PartitionInterlace)
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,6,6);
if (status == MagickFalse)
break;
}
break;
}
case PartitionInterlace:
{
/*
Partition interlacing: BBBBBB..., GGGGGG..., RRRRRR...
*/
AppendImageFormat("B",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,1,6);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
AppendImageFormat("G",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,2,6);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
AppendImageFormat("R",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,3,6);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
if (quantum_type == BGRAQuantum)
{
(void) CloseBlob(image);
AppendImageFormat("A",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,5,6);
if (status == MagickFalse)
break;
}
}
(void) CloseBlob(image);
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,6,6);
if (status == MagickFalse)
break;
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4787_4 |
crossvul-cpp_data_good_4999_1 | /*
* Packet matching code.
*
* Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
* Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org>
* Copyright (C) 2006-2010 Patrick McHardy <kaber@trash.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/cache.h>
#include <linux/capability.h>
#include <linux/skbuff.h>
#include <linux/kmod.h>
#include <linux/vmalloc.h>
#include <linux/netdevice.h>
#include <linux/module.h>
#include <linux/icmp.h>
#include <net/ip.h>
#include <net/compat.h>
#include <asm/uaccess.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/err.h>
#include <linux/cpumask.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <net/netfilter/nf_log.h>
#include "../../netfilter/xt_repldata.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>");
MODULE_DESCRIPTION("IPv4 packet filter");
/*#define DEBUG_IP_FIREWALL*/
/*#define DEBUG_ALLOW_ALL*/ /* Useful for remote debugging */
/*#define DEBUG_IP_FIREWALL_USER*/
#ifdef DEBUG_IP_FIREWALL
#define dprintf(format, args...) pr_info(format , ## args)
#else
#define dprintf(format, args...)
#endif
#ifdef DEBUG_IP_FIREWALL_USER
#define duprintf(format, args...) pr_info(format , ## args)
#else
#define duprintf(format, args...)
#endif
#ifdef CONFIG_NETFILTER_DEBUG
#define IP_NF_ASSERT(x) WARN_ON(!(x))
#else
#define IP_NF_ASSERT(x)
#endif
#if 0
/* All the better to debug you with... */
#define static
#define inline
#endif
void *ipt_alloc_initial_table(const struct xt_table *info)
{
return xt_alloc_initial_table(ipt, IPT);
}
EXPORT_SYMBOL_GPL(ipt_alloc_initial_table);
/* Returns whether matches rule or not. */
/* Performance critical - called for every packet */
static inline bool
ip_packet_match(const struct iphdr *ip,
const char *indev,
const char *outdev,
const struct ipt_ip *ipinfo,
int isfrag)
{
unsigned long ret;
#define FWINV(bool, invflg) ((bool) ^ !!(ipinfo->invflags & (invflg)))
if (FWINV((ip->saddr&ipinfo->smsk.s_addr) != ipinfo->src.s_addr,
IPT_INV_SRCIP) ||
FWINV((ip->daddr&ipinfo->dmsk.s_addr) != ipinfo->dst.s_addr,
IPT_INV_DSTIP)) {
dprintf("Source or dest mismatch.\n");
dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n",
&ip->saddr, &ipinfo->smsk.s_addr, &ipinfo->src.s_addr,
ipinfo->invflags & IPT_INV_SRCIP ? " (INV)" : "");
dprintf("DST: %pI4 Mask: %pI4 Target: %pI4.%s\n",
&ip->daddr, &ipinfo->dmsk.s_addr, &ipinfo->dst.s_addr,
ipinfo->invflags & IPT_INV_DSTIP ? " (INV)" : "");
return false;
}
ret = ifname_compare_aligned(indev, ipinfo->iniface, ipinfo->iniface_mask);
if (FWINV(ret != 0, IPT_INV_VIA_IN)) {
dprintf("VIA in mismatch (%s vs %s).%s\n",
indev, ipinfo->iniface,
ipinfo->invflags & IPT_INV_VIA_IN ? " (INV)" : "");
return false;
}
ret = ifname_compare_aligned(outdev, ipinfo->outiface, ipinfo->outiface_mask);
if (FWINV(ret != 0, IPT_INV_VIA_OUT)) {
dprintf("VIA out mismatch (%s vs %s).%s\n",
outdev, ipinfo->outiface,
ipinfo->invflags & IPT_INV_VIA_OUT ? " (INV)" : "");
return false;
}
/* Check specific protocol */
if (ipinfo->proto &&
FWINV(ip->protocol != ipinfo->proto, IPT_INV_PROTO)) {
dprintf("Packet protocol %hi does not match %hi.%s\n",
ip->protocol, ipinfo->proto,
ipinfo->invflags & IPT_INV_PROTO ? " (INV)" : "");
return false;
}
/* If we have a fragment rule but the packet is not a fragment
* then we return zero */
if (FWINV((ipinfo->flags&IPT_F_FRAG) && !isfrag, IPT_INV_FRAG)) {
dprintf("Fragment rule but not fragment.%s\n",
ipinfo->invflags & IPT_INV_FRAG ? " (INV)" : "");
return false;
}
return true;
}
static bool
ip_checkentry(const struct ipt_ip *ip)
{
if (ip->flags & ~IPT_F_MASK) {
duprintf("Unknown flag bits set: %08X\n",
ip->flags & ~IPT_F_MASK);
return false;
}
if (ip->invflags & ~IPT_INV_MASK) {
duprintf("Unknown invflag bits set: %08X\n",
ip->invflags & ~IPT_INV_MASK);
return false;
}
return true;
}
static unsigned int
ipt_error(struct sk_buff *skb, const struct xt_action_param *par)
{
net_info_ratelimited("error: `%s'\n", (const char *)par->targinfo);
return NF_DROP;
}
/* Performance critical */
static inline struct ipt_entry *
get_entry(const void *base, unsigned int offset)
{
return (struct ipt_entry *)(base + offset);
}
/* All zeroes == unconditional rule. */
/* Mildly perf critical (only if packet tracing is on) */
static inline bool unconditional(const struct ipt_entry *e)
{
static const struct ipt_ip uncond;
return e->target_offset == sizeof(struct ipt_entry) &&
memcmp(&e->ip, &uncond, sizeof(uncond)) == 0;
#undef FWINV
}
/* for const-correctness */
static inline const struct xt_entry_target *
ipt_get_target_c(const struct ipt_entry *e)
{
return ipt_get_target((struct ipt_entry *)e);
}
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
static const char *const hooknames[] = {
[NF_INET_PRE_ROUTING] = "PREROUTING",
[NF_INET_LOCAL_IN] = "INPUT",
[NF_INET_FORWARD] = "FORWARD",
[NF_INET_LOCAL_OUT] = "OUTPUT",
[NF_INET_POST_ROUTING] = "POSTROUTING",
};
enum nf_ip_trace_comments {
NF_IP_TRACE_COMMENT_RULE,
NF_IP_TRACE_COMMENT_RETURN,
NF_IP_TRACE_COMMENT_POLICY,
};
static const char *const comments[] = {
[NF_IP_TRACE_COMMENT_RULE] = "rule",
[NF_IP_TRACE_COMMENT_RETURN] = "return",
[NF_IP_TRACE_COMMENT_POLICY] = "policy",
};
static struct nf_loginfo trace_loginfo = {
.type = NF_LOG_TYPE_LOG,
.u = {
.log = {
.level = 4,
.logflags = NF_LOG_MASK,
},
},
};
/* Mildly perf critical (only if packet tracing is on) */
static inline int
get_chainname_rulenum(const struct ipt_entry *s, const struct ipt_entry *e,
const char *hookname, const char **chainname,
const char **comment, unsigned int *rulenum)
{
const struct xt_standard_target *t = (void *)ipt_get_target_c(s);
if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) {
/* Head of user chain: ERROR target with chainname */
*chainname = t->target.data;
(*rulenum) = 0;
} else if (s == e) {
(*rulenum)++;
if (unconditional(s) &&
strcmp(t->target.u.kernel.target->name,
XT_STANDARD_TARGET) == 0 &&
t->verdict < 0) {
/* Tail of chains: STANDARD target (return/policy) */
*comment = *chainname == hookname
? comments[NF_IP_TRACE_COMMENT_POLICY]
: comments[NF_IP_TRACE_COMMENT_RETURN];
}
return 1;
} else
(*rulenum)++;
return 0;
}
static void trace_packet(struct net *net,
const struct sk_buff *skb,
unsigned int hook,
const struct net_device *in,
const struct net_device *out,
const char *tablename,
const struct xt_table_info *private,
const struct ipt_entry *e)
{
const struct ipt_entry *root;
const char *hookname, *chainname, *comment;
const struct ipt_entry *iter;
unsigned int rulenum = 0;
root = get_entry(private->entries, private->hook_entry[hook]);
hookname = chainname = hooknames[hook];
comment = comments[NF_IP_TRACE_COMMENT_RULE];
xt_entry_foreach(iter, root, private->size - private->hook_entry[hook])
if (get_chainname_rulenum(iter, e, hookname,
&chainname, &comment, &rulenum) != 0)
break;
nf_log_trace(net, AF_INET, hook, skb, in, out, &trace_loginfo,
"TRACE: %s:%s:%s:%u ",
tablename, chainname, comment, rulenum);
}
#endif
static inline
struct ipt_entry *ipt_next_entry(const struct ipt_entry *entry)
{
return (void *)entry + entry->next_offset;
}
/* Returns one of the generic firewall policies, like NF_ACCEPT. */
unsigned int
ipt_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct xt_table *table)
{
unsigned int hook = state->hook;
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
const struct iphdr *ip;
/* Initializing verdict to NF_DROP keeps gcc happy. */
unsigned int verdict = NF_DROP;
const char *indev, *outdev;
const void *table_base;
struct ipt_entry *e, **jumpstack;
unsigned int stackidx, cpu;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
/* Initialization */
stackidx = 0;
ip = ip_hdr(skb);
indev = state->in ? state->in->name : nulldevname;
outdev = state->out ? state->out->name : nulldevname;
/* We handle fragments by dealing with the first fragment as
* if it was a normal packet. All other fragments are treated
* normally, except that they will NEVER match rules that ask
* things we don't know, ie. tcp syn flag or ports). If the
* rule is also a fragment-specific rule, non-fragments won't
* match it. */
acpar.fragoff = ntohs(ip->frag_off) & IP_OFFSET;
acpar.thoff = ip_hdrlen(skb);
acpar.hotdrop = false;
acpar.net = state->net;
acpar.in = state->in;
acpar.out = state->out;
acpar.family = NFPROTO_IPV4;
acpar.hooknum = hook;
IP_NF_ASSERT(table->valid_hooks & (1 << hook));
local_bh_disable();
addend = xt_write_recseq_begin();
private = table->private;
cpu = smp_processor_id();
/*
* Ensure we load private-> members after we've fetched the base
* pointer.
*/
smp_read_barrier_depends();
table_base = private->entries;
jumpstack = (struct ipt_entry **)private->jumpstack[cpu];
/* Switch to alternate jumpstack if we're being invoked via TEE.
* TEE issues XT_CONTINUE verdict on original skb so we must not
* clobber the jumpstack.
*
* For recursion via REJECT or SYNPROXY the stack will be clobbered
* but it is no problem since absolute verdict is issued by these.
*/
if (static_key_false(&xt_tee_enabled))
jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated);
e = get_entry(table_base, private->hook_entry[hook]);
pr_debug("Entering %s(hook %u), UF %p\n",
table->name, hook,
get_entry(table_base, private->underflow[hook]));
do {
const struct xt_entry_target *t;
const struct xt_entry_match *ematch;
struct xt_counters *counter;
IP_NF_ASSERT(e);
if (!ip_packet_match(ip, indev, outdev,
&e->ip, acpar.fragoff)) {
no_match:
e = ipt_next_entry(e);
continue;
}
xt_ematch_foreach(ematch, e) {
acpar.match = ematch->u.kernel.match;
acpar.matchinfo = ematch->data;
if (!acpar.match->match(skb, &acpar))
goto no_match;
}
counter = xt_get_this_cpu_counter(&e->counters);
ADD_COUNTER(*counter, skb->len, 1);
t = ipt_get_target(e);
IP_NF_ASSERT(t->u.kernel.target);
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
/* The packet is traced: log it */
if (unlikely(skb->nf_trace))
trace_packet(state->net, skb, hook, state->in,
state->out, table->name, private, e);
#endif
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned int)(-v) - 1;
break;
}
if (stackidx == 0) {
e = get_entry(table_base,
private->underflow[hook]);
pr_debug("Underflow (this is normal) "
"to %p\n", e);
} else {
e = jumpstack[--stackidx];
pr_debug("Pulled %p out from pos %u\n",
e, stackidx);
e = ipt_next_entry(e);
}
continue;
}
if (table_base + v != ipt_next_entry(e) &&
!(e->ip.flags & IPT_F_GOTO)) {
jumpstack[stackidx++] = e;
pr_debug("Pushed %p into pos %u\n",
e, stackidx - 1);
}
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
/* Target might have changed stuff. */
ip = ip_hdr(skb);
if (verdict == XT_CONTINUE)
e = ipt_next_entry(e);
else
/* Verdict */
break;
} while (!acpar.hotdrop);
pr_debug("Exiting %s; sp at %u\n", __func__, stackidx);
xt_write_recseq_end(addend);
local_bh_enable();
#ifdef DEBUG_ALLOW_ALL
return NF_ACCEPT;
#else
if (acpar.hotdrop)
return NF_DROP;
else return verdict;
#endif
}
/* Figures out from what hook each rule can be called: returns 0 if
there are loops. Puts hook bitmask in comefrom. */
static int
mark_source_chains(const struct xt_table_info *newinfo,
unsigned int valid_hooks, void *entry0)
{
unsigned int hook;
/* No recursion; use packet counter to save back ptrs (reset
to 0 as we leave), and comefrom to save source hook bitmask */
for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) {
unsigned int pos = newinfo->hook_entry[hook];
struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos);
if (!(valid_hooks & (1 << hook)))
continue;
/* Set initial back pointer. */
e->counters.pcnt = pos;
for (;;) {
const struct xt_standard_target *t
= (void *)ipt_get_target_c(e);
int visited = e->comefrom & (1 << hook);
if (e->comefrom & (1 << NF_INET_NUMHOOKS)) {
pr_err("iptables: loop hook %u pos %u %08X.\n",
hook, pos, e->comefrom);
return 0;
}
e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS));
/* Unconditional return/END. */
if ((unconditional(e) &&
(strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < 0) || visited) {
unsigned int oldpos, size;
if ((strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < -NF_MAX_VERDICT - 1) {
duprintf("mark_source_chains: bad "
"negative verdict (%i)\n",
t->verdict);
return 0;
}
/* Return: backtrack through the last
big jump. */
do {
e->comefrom ^= (1<<NF_INET_NUMHOOKS);
#ifdef DEBUG_IP_FIREWALL_USER
if (e->comefrom
& (1 << NF_INET_NUMHOOKS)) {
duprintf("Back unset "
"on hook %u "
"rule %u\n",
hook, pos);
}
#endif
oldpos = pos;
pos = e->counters.pcnt;
e->counters.pcnt = 0;
/* We're at the start. */
if (pos == oldpos)
goto next;
e = (struct ipt_entry *)
(entry0 + pos);
} while (oldpos == pos + e->next_offset);
/* Move along one */
size = e->next_offset;
e = (struct ipt_entry *)
(entry0 + pos + size);
e->counters.pcnt = pos;
pos += size;
} else {
int newpos = t->verdict;
if (strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0 &&
newpos >= 0) {
if (newpos > newinfo->size -
sizeof(struct ipt_entry)) {
duprintf("mark_source_chains: "
"bad verdict (%i)\n",
newpos);
return 0;
}
/* This a jump; chase it. */
duprintf("Jump rule %u -> %u\n",
pos, newpos);
} else {
/* ... this is a fallthru */
newpos = pos + e->next_offset;
}
e = (struct ipt_entry *)
(entry0 + newpos);
e->counters.pcnt = pos;
pos = newpos;
}
}
next:
duprintf("Finished chain %u\n", hook);
}
return 1;
}
static void cleanup_match(struct xt_entry_match *m, struct net *net)
{
struct xt_mtdtor_param par;
par.net = net;
par.match = m->u.kernel.match;
par.matchinfo = m->data;
par.family = NFPROTO_IPV4;
if (par.match->destroy != NULL)
par.match->destroy(&par);
module_put(par.match->me);
}
static int
check_entry(const struct ipt_entry *e)
{
const struct xt_entry_target *t;
if (!ip_checkentry(&e->ip))
return -EINVAL;
if (e->target_offset + sizeof(struct xt_entry_target) >
e->next_offset)
return -EINVAL;
t = ipt_get_target_c(e);
if (e->target_offset + t->u.target_size > e->next_offset)
return -EINVAL;
return 0;
}
static int
check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
{
const struct ipt_ip *ip = par->entryinfo;
int ret;
par->match = m->u.kernel.match;
par->matchinfo = m->data;
ret = xt_check_match(par, m->u.match_size - sizeof(*m),
ip->proto, ip->invflags & IPT_INV_PROTO);
if (ret < 0) {
duprintf("check failed for `%s'.\n", par->match->name);
return ret;
}
return 0;
}
static int
find_check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
{
struct xt_match *match;
int ret;
match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name,
m->u.user.revision);
if (IS_ERR(match)) {
duprintf("find_check_match: `%s' not found\n", m->u.user.name);
return PTR_ERR(match);
}
m->u.kernel.match = match;
ret = check_match(m, par);
if (ret)
goto err;
return 0;
err:
module_put(m->u.kernel.match->me);
return ret;
}
static int check_target(struct ipt_entry *e, struct net *net, const char *name)
{
struct xt_entry_target *t = ipt_get_target(e);
struct xt_tgchk_param par = {
.net = net,
.table = name,
.entryinfo = e,
.target = t->u.kernel.target,
.targinfo = t->data,
.hook_mask = e->comefrom,
.family = NFPROTO_IPV4,
};
int ret;
ret = xt_check_target(&par, t->u.target_size - sizeof(*t),
e->ip.proto, e->ip.invflags & IPT_INV_PROTO);
if (ret < 0) {
duprintf("check failed for `%s'.\n",
t->u.kernel.target->name);
return ret;
}
return 0;
}
static int
find_check_entry(struct ipt_entry *e, struct net *net, const char *name,
unsigned int size)
{
struct xt_entry_target *t;
struct xt_target *target;
int ret;
unsigned int j;
struct xt_mtchk_param mtpar;
struct xt_entry_match *ematch;
e->counters.pcnt = xt_percpu_counter_alloc();
if (IS_ERR_VALUE(e->counters.pcnt))
return -ENOMEM;
j = 0;
mtpar.net = net;
mtpar.table = name;
mtpar.entryinfo = &e->ip;
mtpar.hook_mask = e->comefrom;
mtpar.family = NFPROTO_IPV4;
xt_ematch_foreach(ematch, e) {
ret = find_check_match(ematch, &mtpar);
if (ret != 0)
goto cleanup_matches;
++j;
}
t = ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("find_check_entry: `%s' not found\n", t->u.user.name);
ret = PTR_ERR(target);
goto cleanup_matches;
}
t->u.kernel.target = target;
ret = check_target(e, net, name);
if (ret)
goto err;
return 0;
err:
module_put(t->u.kernel.target->me);
cleanup_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
cleanup_match(ematch, net);
}
xt_percpu_counter_free(e->counters.pcnt);
return ret;
}
static bool check_underflow(const struct ipt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(e))
return false;
t = ipt_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
static int
check_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_debug("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
static void
cleanup_entry(struct ipt_entry *e, struct net *net)
{
struct xt_tgdtor_param par;
struct xt_entry_target *t;
struct xt_entry_match *ematch;
/* Cleanup all matches */
xt_ematch_foreach(ematch, e)
cleanup_match(ematch, net);
t = ipt_get_target(e);
par.net = net;
par.target = t->u.kernel.target;
par.targinfo = t->data;
par.family = NFPROTO_IPV4;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
xt_percpu_counter_free(e->counters.pcnt);
}
/* Checks and translates the user-supplied table segment (held in
newinfo) */
static int
translate_table(struct net *net, struct xt_table_info *newinfo, void *entry0,
const struct ipt_replace *repl)
{
struct ipt_entry *iter;
unsigned int i;
int ret = 0;
newinfo->size = repl->size;
newinfo->number = repl->num_entries;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
newinfo->hook_entry[i] = 0xFFFFFFFF;
newinfo->underflow[i] = 0xFFFFFFFF;
}
duprintf("translate_table: size %u\n", newinfo->size);
i = 0;
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = check_entry_size_and_hooks(iter, newinfo, entry0,
entry0 + repl->size,
repl->hook_entry,
repl->underflow,
repl->valid_hooks);
if (ret != 0)
return ret;
++i;
if (strcmp(ipt_get_target(iter)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
if (i != repl->num_entries) {
duprintf("translate_table: %u not %u entries\n",
i, repl->num_entries);
return -EINVAL;
}
/* Check hooks all assigned */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
/* Only hooks which are valid */
if (!(repl->valid_hooks & (1 << i)))
continue;
if (newinfo->hook_entry[i] == 0xFFFFFFFF) {
duprintf("Invalid hook entry %u %u\n",
i, repl->hook_entry[i]);
return -EINVAL;
}
if (newinfo->underflow[i] == 0xFFFFFFFF) {
duprintf("Invalid underflow %u %u\n",
i, repl->underflow[i]);
return -EINVAL;
}
}
if (!mark_source_chains(newinfo, repl->valid_hooks, entry0))
return -ELOOP;
/* Finally, each sanity check must pass */
i = 0;
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = find_check_entry(iter, net, repl->name, repl->size);
if (ret != 0)
break;
++i;
}
if (ret != 0) {
xt_entry_foreach(iter, entry0, newinfo->size) {
if (i-- == 0)
break;
cleanup_entry(iter, net);
}
return ret;
}
return ret;
}
static void
get_counters(const struct xt_table_info *t,
struct xt_counters counters[])
{
struct ipt_entry *iter;
unsigned int cpu;
unsigned int i;
for_each_possible_cpu(cpu) {
seqcount_t *s = &per_cpu(xt_recseq, cpu);
i = 0;
xt_entry_foreach(iter, t->entries, t->size) {
struct xt_counters *tmp;
u64 bcnt, pcnt;
unsigned int start;
tmp = xt_get_per_cpu_counter(&iter->counters, cpu);
do {
start = read_seqcount_begin(s);
bcnt = tmp->bcnt;
pcnt = tmp->pcnt;
} while (read_seqcount_retry(s, start));
ADD_COUNTER(counters[i], bcnt, pcnt);
++i; /* macro does multi eval of i */
}
}
}
static struct xt_counters *alloc_counters(const struct xt_table *table)
{
unsigned int countersize;
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
/* We need atomic snapshot of counters: rest doesn't change
(other than comefrom, which userspace doesn't care
about). */
countersize = sizeof(struct xt_counters) * private->number;
counters = vzalloc(countersize);
if (counters == NULL)
return ERR_PTR(-ENOMEM);
get_counters(private, counters);
return counters;
}
static int
copy_entries_to_user(unsigned int total_size,
const struct xt_table *table,
void __user *userptr)
{
unsigned int off, num;
const struct ipt_entry *e;
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
int ret = 0;
const void *loc_cpu_entry;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
loc_cpu_entry = private->entries;
if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) {
ret = -EFAULT;
goto free_counters;
}
/* FIXME: use iterator macros --RR */
/* ... then go back and fix counters and names */
for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){
unsigned int i;
const struct xt_entry_match *m;
const struct xt_entry_target *t;
e = (struct ipt_entry *)(loc_cpu_entry + off);
if (copy_to_user(userptr + off
+ offsetof(struct ipt_entry, counters),
&counters[num],
sizeof(counters[num])) != 0) {
ret = -EFAULT;
goto free_counters;
}
for (i = sizeof(struct ipt_entry);
i < e->target_offset;
i += m->u.match_size) {
m = (void *)e + i;
if (copy_to_user(userptr + off + i
+ offsetof(struct xt_entry_match,
u.user.name),
m->u.kernel.match->name,
strlen(m->u.kernel.match->name)+1)
!= 0) {
ret = -EFAULT;
goto free_counters;
}
}
t = ipt_get_target_c(e);
if (copy_to_user(userptr + off + e->target_offset
+ offsetof(struct xt_entry_target,
u.user.name),
t->u.kernel.target->name,
strlen(t->u.kernel.target->name)+1) != 0) {
ret = -EFAULT;
goto free_counters;
}
}
free_counters:
vfree(counters);
return ret;
}
#ifdef CONFIG_COMPAT
static void compat_standard_from_user(void *dst, const void *src)
{
int v = *(compat_int_t *)src;
if (v > 0)
v += xt_compat_calc_jump(AF_INET, v);
memcpy(dst, &v, sizeof(v));
}
static int compat_standard_to_user(void __user *dst, const void *src)
{
compat_int_t cv = *(int *)src;
if (cv > 0)
cv -= xt_compat_calc_jump(AF_INET, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
static int compat_calc_entry(const struct ipt_entry *e,
const struct xt_table_info *info,
const void *base, struct xt_table_info *newinfo)
{
const struct xt_entry_match *ematch;
const struct xt_entry_target *t;
unsigned int entry_offset;
int off, i, ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - base;
xt_ematch_foreach(ematch, e)
off += xt_compat_match_offset(ematch->u.kernel.match);
t = ipt_get_target_c(e);
off += xt_compat_target_offset(t->u.kernel.target);
newinfo->size -= off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
if (info->hook_entry[i] &&
(e < (struct ipt_entry *)(base + info->hook_entry[i])))
newinfo->hook_entry[i] -= off;
if (info->underflow[i] &&
(e < (struct ipt_entry *)(base + info->underflow[i])))
newinfo->underflow[i] -= off;
}
return 0;
}
static int compat_table_info(const struct xt_table_info *info,
struct xt_table_info *newinfo)
{
struct ipt_entry *iter;
const void *loc_cpu_entry;
int ret;
if (!newinfo || !info)
return -EINVAL;
/* we dont care about newinfo->entries */
memcpy(newinfo, info, offsetof(struct xt_table_info, entries));
newinfo->initial_entries = 0;
loc_cpu_entry = info->entries;
xt_compat_init_offsets(AF_INET, info->number);
xt_entry_foreach(iter, loc_cpu_entry, info->size) {
ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo);
if (ret != 0)
return ret;
}
return 0;
}
#endif
static int get_info(struct net *net, void __user *user,
const int *len, int compat)
{
char name[XT_TABLE_MAXNAMELEN];
struct xt_table *t;
int ret;
if (*len != sizeof(struct ipt_getinfo)) {
duprintf("length %u != %zu\n", *len,
sizeof(struct ipt_getinfo));
return -EINVAL;
}
if (copy_from_user(name, user, sizeof(name)) != 0)
return -EFAULT;
name[XT_TABLE_MAXNAMELEN-1] = '\0';
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_lock(AF_INET);
#endif
t = try_then_request_module(xt_find_table_lock(net, AF_INET, name),
"iptable_%s", name);
if (!IS_ERR_OR_NULL(t)) {
struct ipt_getinfo info;
const struct xt_table_info *private = t->private;
#ifdef CONFIG_COMPAT
struct xt_table_info tmp;
if (compat) {
ret = compat_table_info(private, &tmp);
xt_compat_flush_offsets(AF_INET);
private = &tmp;
}
#endif
memset(&info, 0, sizeof(info));
info.valid_hooks = t->valid_hooks;
memcpy(info.hook_entry, private->hook_entry,
sizeof(info.hook_entry));
memcpy(info.underflow, private->underflow,
sizeof(info.underflow));
info.num_entries = private->number;
info.size = private->size;
strcpy(info.name, name);
if (copy_to_user(user, &info, *len) != 0)
ret = -EFAULT;
else
ret = 0;
xt_table_unlock(t);
module_put(t->me);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_unlock(AF_INET);
#endif
return ret;
}
static int
get_entries(struct net *net, struct ipt_get_entries __user *uptr,
const int *len)
{
int ret;
struct ipt_get_entries get;
struct xt_table *t;
if (*len < sizeof(get)) {
duprintf("get_entries: %u < %zu\n", *len, sizeof(get));
return -EINVAL;
}
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct ipt_get_entries) + get.size) {
duprintf("get_entries: %u != %zu\n",
*len, sizeof(get) + get.size);
return -EINVAL;
}
t = xt_find_table_lock(net, AF_INET, get.name);
if (!IS_ERR_OR_NULL(t)) {
const struct xt_table_info *private = t->private;
duprintf("t->private->number = %u\n", private->number);
if (get.size == private->size)
ret = copy_entries_to_user(private->size,
t, uptr->entrytable);
else {
duprintf("get_entries: I've got %u not %u!\n",
private->size, get.size);
ret = -EAGAIN;
}
module_put(t->me);
xt_table_unlock(t);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
return ret;
}
static int
__do_replace(struct net *net, const char *name, unsigned int valid_hooks,
struct xt_table_info *newinfo, unsigned int num_counters,
void __user *counters_ptr)
{
int ret;
struct xt_table *t;
struct xt_table_info *oldinfo;
struct xt_counters *counters;
struct ipt_entry *iter;
ret = 0;
counters = vzalloc(num_counters * sizeof(struct xt_counters));
if (!counters) {
ret = -ENOMEM;
goto out;
}
t = try_then_request_module(xt_find_table_lock(net, AF_INET, name),
"iptable_%s", name);
if (IS_ERR_OR_NULL(t)) {
ret = t ? PTR_ERR(t) : -ENOENT;
goto free_newinfo_counters_untrans;
}
/* You lied! */
if (valid_hooks != t->valid_hooks) {
duprintf("Valid hook crap: %08X vs %08X\n",
valid_hooks, t->valid_hooks);
ret = -EINVAL;
goto put_module;
}
oldinfo = xt_replace_table(t, num_counters, newinfo, &ret);
if (!oldinfo)
goto put_module;
/* Update module usage count based on number of rules */
duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n",
oldinfo->number, oldinfo->initial_entries, newinfo->number);
if ((oldinfo->number > oldinfo->initial_entries) ||
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
if ((oldinfo->number > oldinfo->initial_entries) &&
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
/* Get the old counters, and synchronize with replace */
get_counters(oldinfo, counters);
/* Decrease module usage counts and free resource */
xt_entry_foreach(iter, oldinfo->entries, oldinfo->size)
cleanup_entry(iter, net);
xt_free_table_info(oldinfo);
if (copy_to_user(counters_ptr, counters,
sizeof(struct xt_counters) * num_counters) != 0) {
/* Silent error, can't fail, new table is already in place */
net_warn_ratelimited("iptables: counters copy to user failed while replacing table\n");
}
vfree(counters);
xt_table_unlock(t);
return ret;
put_module:
module_put(t->me);
xt_table_unlock(t);
free_newinfo_counters_untrans:
vfree(counters);
out:
return ret;
}
static int
do_replace(struct net *net, const void __user *user, unsigned int len)
{
int ret;
struct ipt_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct ipt_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
if (tmp.num_counters == 0)
return -EINVAL;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_table(net, newinfo, loc_cpu_entry, &tmp);
if (ret != 0)
goto free_newinfo;
duprintf("Translated table\n");
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, tmp.counters);
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter, net);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int
do_add_counters(struct net *net, const void __user *user,
unsigned int len, int compat)
{
unsigned int i;
struct xt_counters_info tmp;
struct xt_counters *paddc;
unsigned int num_counters;
const char *name;
int size;
void *ptmp;
struct xt_table *t;
const struct xt_table_info *private;
int ret = 0;
struct ipt_entry *iter;
unsigned int addend;
#ifdef CONFIG_COMPAT
struct compat_xt_counters_info compat_tmp;
if (compat) {
ptmp = &compat_tmp;
size = sizeof(struct compat_xt_counters_info);
} else
#endif
{
ptmp = &tmp;
size = sizeof(struct xt_counters_info);
}
if (copy_from_user(ptmp, user, size) != 0)
return -EFAULT;
#ifdef CONFIG_COMPAT
if (compat) {
num_counters = compat_tmp.num_counters;
name = compat_tmp.name;
} else
#endif
{
num_counters = tmp.num_counters;
name = tmp.name;
}
if (len != size + num_counters * sizeof(struct xt_counters))
return -EINVAL;
paddc = vmalloc(len - size);
if (!paddc)
return -ENOMEM;
if (copy_from_user(paddc, user + size, len - size) != 0) {
ret = -EFAULT;
goto free;
}
t = xt_find_table_lock(net, AF_INET, name);
if (IS_ERR_OR_NULL(t)) {
ret = t ? PTR_ERR(t) : -ENOENT;
goto free;
}
local_bh_disable();
private = t->private;
if (private->number != num_counters) {
ret = -EINVAL;
goto unlock_up_free;
}
i = 0;
addend = xt_write_recseq_begin();
xt_entry_foreach(iter, private->entries, private->size) {
struct xt_counters *tmp;
tmp = xt_get_this_cpu_counter(&iter->counters);
ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt);
++i;
}
xt_write_recseq_end(addend);
unlock_up_free:
local_bh_enable();
xt_table_unlock(t);
module_put(t->me);
free:
vfree(paddc);
return ret;
}
#ifdef CONFIG_COMPAT
struct compat_ipt_replace {
char name[XT_TABLE_MAXNAMELEN];
u32 valid_hooks;
u32 num_entries;
u32 size;
u32 hook_entry[NF_INET_NUMHOOKS];
u32 underflow[NF_INET_NUMHOOKS];
u32 num_counters;
compat_uptr_t counters; /* struct xt_counters * */
struct compat_ipt_entry entries[0];
};
static int
compat_copy_entry_to_user(struct ipt_entry *e, void __user **dstptr,
unsigned int *size, struct xt_counters *counters,
unsigned int i)
{
struct xt_entry_target *t;
struct compat_ipt_entry __user *ce;
u_int16_t target_offset, next_offset;
compat_uint_t origsize;
const struct xt_entry_match *ematch;
int ret = 0;
origsize = *size;
ce = (struct compat_ipt_entry __user *)*dstptr;
if (copy_to_user(ce, e, sizeof(struct ipt_entry)) != 0 ||
copy_to_user(&ce->counters, &counters[i],
sizeof(counters[i])) != 0)
return -EFAULT;
*dstptr += sizeof(struct compat_ipt_entry);
*size -= sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
xt_ematch_foreach(ematch, e) {
ret = xt_compat_match_to_user(ematch, dstptr, size);
if (ret != 0)
return ret;
}
target_offset = e->target_offset - (origsize - *size);
t = ipt_get_target(e);
ret = xt_compat_target_to_user(t, dstptr, size);
if (ret)
return ret;
next_offset = e->next_offset - (origsize - *size);
if (put_user(target_offset, &ce->target_offset) != 0 ||
put_user(next_offset, &ce->next_offset) != 0)
return -EFAULT;
return 0;
}
static int
compat_find_calc_match(struct xt_entry_match *m,
const char *name,
const struct ipt_ip *ip,
int *size)
{
struct xt_match *match;
match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name,
m->u.user.revision);
if (IS_ERR(match)) {
duprintf("compat_check_calc_match: `%s' not found\n",
m->u.user.name);
return PTR_ERR(match);
}
m->u.kernel.match = match;
*size += xt_compat_match_offset(match);
return 0;
}
static void compat_release_entry(struct compat_ipt_entry *e)
{
struct xt_entry_target *t;
struct xt_entry_match *ematch;
/* Cleanup all matches */
xt_ematch_foreach(ematch, e)
module_put(ematch->u.kernel.match->me);
t = compat_ipt_get_target(e);
module_put(t->u.kernel.target->me);
}
static int
check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ipt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ipt_entry *)e);
if (ret)
return ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ip, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
static int
compat_copy_entry_from_user(struct compat_ipt_entry *e, void **dstptr,
unsigned int *size, const char *name,
struct xt_table_info *newinfo, unsigned char *base)
{
struct xt_entry_target *t;
struct xt_target *target;
struct ipt_entry *de;
unsigned int origsize;
int ret, h;
struct xt_entry_match *ematch;
ret = 0;
origsize = *size;
de = (struct ipt_entry *)*dstptr;
memcpy(de, e, sizeof(struct ipt_entry));
memcpy(&de->counters, &e->counters, sizeof(e->counters));
*dstptr += sizeof(struct ipt_entry);
*size += sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
xt_ematch_foreach(ematch, e) {
ret = xt_compat_match_from_user(ematch, dstptr, size);
if (ret != 0)
return ret;
}
de->target_offset = e->target_offset - (origsize - *size);
t = compat_ipt_get_target(e);
target = t->u.kernel.target;
xt_compat_target_from_user(t, dstptr, size);
de->next_offset = e->next_offset - (origsize - *size);
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)de - base < newinfo->hook_entry[h])
newinfo->hook_entry[h] -= origsize - *size;
if ((unsigned char *)de - base < newinfo->underflow[h])
newinfo->underflow[h] -= origsize - *size;
}
return ret;
}
static int
compat_check_entry(struct ipt_entry *e, struct net *net, const char *name)
{
struct xt_entry_match *ematch;
struct xt_mtchk_param mtpar;
unsigned int j;
int ret = 0;
e->counters.pcnt = xt_percpu_counter_alloc();
if (IS_ERR_VALUE(e->counters.pcnt))
return -ENOMEM;
j = 0;
mtpar.net = net;
mtpar.table = name;
mtpar.entryinfo = &e->ip;
mtpar.hook_mask = e->comefrom;
mtpar.family = NFPROTO_IPV4;
xt_ematch_foreach(ematch, e) {
ret = check_match(ematch, &mtpar);
if (ret != 0)
goto cleanup_matches;
++j;
}
ret = check_target(e, net, name);
if (ret)
goto cleanup_matches;
return 0;
cleanup_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
cleanup_match(ematch, net);
}
xt_percpu_counter_free(e->counters.pcnt);
return ret;
}
static int
translate_compat_table(struct net *net,
const char *name,
unsigned int valid_hooks,
struct xt_table_info **pinfo,
void **pentry0,
unsigned int total_size,
unsigned int number,
unsigned int *hook_entries,
unsigned int *underflows)
{
unsigned int i, j;
struct xt_table_info *newinfo, *info;
void *pos, *entry0, *entry1;
struct compat_ipt_entry *iter0;
struct ipt_entry *iter1;
unsigned int size;
int ret;
info = *pinfo;
entry0 = *pentry0;
size = total_size;
info->number = number;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
info->hook_entry[i] = 0xFFFFFFFF;
info->underflow[i] = 0xFFFFFFFF;
}
duprintf("translate_compat_table: size %u\n", info->size);
j = 0;
xt_compat_lock(AF_INET);
xt_compat_init_offsets(AF_INET, number);
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter0, entry0, total_size) {
ret = check_compat_entry_size_and_hooks(iter0, info, &size,
entry0,
entry0 + total_size,
hook_entries,
underflows,
name);
if (ret != 0)
goto out_unlock;
++j;
}
ret = -EINVAL;
if (j != number) {
duprintf("translate_compat_table: %u not %u entries\n",
j, number);
goto out_unlock;
}
/* Check hooks all assigned */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
/* Only hooks which are valid */
if (!(valid_hooks & (1 << i)))
continue;
if (info->hook_entry[i] == 0xFFFFFFFF) {
duprintf("Invalid hook entry %u %u\n",
i, hook_entries[i]);
goto out_unlock;
}
if (info->underflow[i] == 0xFFFFFFFF) {
duprintf("Invalid underflow %u %u\n",
i, underflows[i]);
goto out_unlock;
}
}
ret = -ENOMEM;
newinfo = xt_alloc_table_info(size);
if (!newinfo)
goto out_unlock;
newinfo->number = number;
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
newinfo->hook_entry[i] = info->hook_entry[i];
newinfo->underflow[i] = info->underflow[i];
}
entry1 = newinfo->entries;
pos = entry1;
size = total_size;
xt_entry_foreach(iter0, entry0, total_size) {
ret = compat_copy_entry_from_user(iter0, &pos, &size,
name, newinfo, entry1);
if (ret != 0)
break;
}
xt_compat_flush_offsets(AF_INET);
xt_compat_unlock(AF_INET);
if (ret)
goto free_newinfo;
ret = -ELOOP;
if (!mark_source_chains(newinfo, valid_hooks, entry1))
goto free_newinfo;
i = 0;
xt_entry_foreach(iter1, entry1, newinfo->size) {
ret = compat_check_entry(iter1, net, name);
if (ret != 0)
break;
++i;
if (strcmp(ipt_get_target(iter1)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
if (ret) {
/*
* The first i matches need cleanup_entry (calls ->destroy)
* because they had called ->check already. The other j-i
* entries need only release.
*/
int skip = i;
j -= i;
xt_entry_foreach(iter0, entry0, newinfo->size) {
if (skip-- > 0)
continue;
if (j-- == 0)
break;
compat_release_entry(iter0);
}
xt_entry_foreach(iter1, entry1, newinfo->size) {
if (i-- == 0)
break;
cleanup_entry(iter1, net);
}
xt_free_table_info(newinfo);
return ret;
}
*pinfo = newinfo;
*pentry0 = entry1;
xt_free_table_info(info);
return 0;
free_newinfo:
xt_free_table_info(newinfo);
out:
xt_entry_foreach(iter0, entry0, total_size) {
if (j-- == 0)
break;
compat_release_entry(iter0);
}
return ret;
out_unlock:
xt_compat_flush_offsets(AF_INET);
xt_compat_unlock(AF_INET);
goto out;
}
static int
compat_do_replace(struct net *net, void __user *user, unsigned int len)
{
int ret;
struct compat_ipt_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct ipt_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.size >= INT_MAX / num_possible_cpus())
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
if (tmp.num_counters == 0)
return -EINVAL;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_compat_table(net, tmp.name, tmp.valid_hooks,
&newinfo, &loc_cpu_entry, tmp.size,
tmp.num_entries, tmp.hook_entry,
tmp.underflow);
if (ret != 0)
goto free_newinfo;
duprintf("compat_do_replace: Translated table\n");
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, compat_ptr(tmp.counters));
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter, net);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int
compat_do_ipt_set_ctl(struct sock *sk, int cmd, void __user *user,
unsigned int len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IPT_SO_SET_REPLACE:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case IPT_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 1);
break;
default:
duprintf("do_ipt_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
struct compat_ipt_get_entries {
char name[XT_TABLE_MAXNAMELEN];
compat_uint_t size;
struct compat_ipt_entry entrytable[0];
};
static int
compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table,
void __user *userptr)
{
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
void __user *pos;
unsigned int size;
int ret = 0;
unsigned int i = 0;
struct ipt_entry *iter;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
pos = userptr;
size = total_size;
xt_entry_foreach(iter, private->entries, total_size) {
ret = compat_copy_entry_to_user(iter, &pos,
&size, counters, i++);
if (ret != 0)
break;
}
vfree(counters);
return ret;
}
static int
compat_get_entries(struct net *net, struct compat_ipt_get_entries __user *uptr,
int *len)
{
int ret;
struct compat_ipt_get_entries get;
struct xt_table *t;
if (*len < sizeof(get)) {
duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get));
return -EINVAL;
}
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct compat_ipt_get_entries) + get.size) {
duprintf("compat_get_entries: %u != %zu\n",
*len, sizeof(get) + get.size);
return -EINVAL;
}
xt_compat_lock(AF_INET);
t = xt_find_table_lock(net, AF_INET, get.name);
if (!IS_ERR_OR_NULL(t)) {
const struct xt_table_info *private = t->private;
struct xt_table_info info;
duprintf("t->private->number = %u\n", private->number);
ret = compat_table_info(private, &info);
if (!ret && get.size == info.size) {
ret = compat_copy_entries_to_user(private->size,
t, uptr->entrytable);
} else if (!ret) {
duprintf("compat_get_entries: I've got %u not %u!\n",
private->size, get.size);
ret = -EAGAIN;
}
xt_compat_flush_offsets(AF_INET);
module_put(t->me);
xt_table_unlock(t);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
xt_compat_unlock(AF_INET);
return ret;
}
static int do_ipt_get_ctl(struct sock *, int, void __user *, int *);
static int
compat_do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IPT_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 1);
break;
case IPT_SO_GET_ENTRIES:
ret = compat_get_entries(sock_net(sk), user, len);
break;
default:
ret = do_ipt_get_ctl(sk, cmd, user, len);
}
return ret;
}
#endif
static int
do_ipt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IPT_SO_SET_REPLACE:
ret = do_replace(sock_net(sk), user, len);
break;
case IPT_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 0);
break;
default:
duprintf("do_ipt_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static int
do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IPT_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 0);
break;
case IPT_SO_GET_ENTRIES:
ret = get_entries(sock_net(sk), user, len);
break;
case IPT_SO_GET_REVISION_MATCH:
case IPT_SO_GET_REVISION_TARGET: {
struct xt_get_revision rev;
int target;
if (*len != sizeof(rev)) {
ret = -EINVAL;
break;
}
if (copy_from_user(&rev, user, sizeof(rev)) != 0) {
ret = -EFAULT;
break;
}
rev.name[sizeof(rev.name)-1] = 0;
if (cmd == IPT_SO_GET_REVISION_TARGET)
target = 1;
else
target = 0;
try_then_request_module(xt_find_revision(AF_INET, rev.name,
rev.revision,
target, &ret),
"ipt_%s", rev.name);
break;
}
default:
duprintf("do_ipt_get_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static void __ipt_unregister_table(struct net *net, struct xt_table *table)
{
struct xt_table_info *private;
void *loc_cpu_entry;
struct module *table_owner = table->me;
struct ipt_entry *iter;
private = xt_unregister_table(table);
/* Decrease module usage counts and free resources */
loc_cpu_entry = private->entries;
xt_entry_foreach(iter, loc_cpu_entry, private->size)
cleanup_entry(iter, net);
if (private->number > private->initial_entries)
module_put(table_owner);
xt_free_table_info(private);
}
int ipt_register_table(struct net *net, const struct xt_table *table,
const struct ipt_replace *repl,
const struct nf_hook_ops *ops, struct xt_table **res)
{
int ret;
struct xt_table_info *newinfo;
struct xt_table_info bootstrap = {0};
void *loc_cpu_entry;
struct xt_table *new_table;
newinfo = xt_alloc_table_info(repl->size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
memcpy(loc_cpu_entry, repl->entries, repl->size);
ret = translate_table(net, newinfo, loc_cpu_entry, repl);
if (ret != 0)
goto out_free;
new_table = xt_register_table(net, table, &bootstrap, newinfo);
if (IS_ERR(new_table)) {
ret = PTR_ERR(new_table);
goto out_free;
}
/* set res now, will see skbs right after nf_register_net_hooks */
WRITE_ONCE(*res, new_table);
ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks));
if (ret != 0) {
__ipt_unregister_table(net, new_table);
*res = NULL;
}
return ret;
out_free:
xt_free_table_info(newinfo);
return ret;
}
void ipt_unregister_table(struct net *net, struct xt_table *table,
const struct nf_hook_ops *ops)
{
nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks));
__ipt_unregister_table(net, table);
}
/* Returns 1 if the type and code is matched by the range, 0 otherwise */
static inline bool
icmp_type_code_match(u_int8_t test_type, u_int8_t min_code, u_int8_t max_code,
u_int8_t type, u_int8_t code,
bool invert)
{
return ((test_type == 0xFF) ||
(type == test_type && code >= min_code && code <= max_code))
^ invert;
}
static bool
icmp_match(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct icmphdr *ic;
struct icmphdr _icmph;
const struct ipt_icmp *icmpinfo = par->matchinfo;
/* Must not be a fragment. */
if (par->fragoff != 0)
return false;
ic = skb_header_pointer(skb, par->thoff, sizeof(_icmph), &_icmph);
if (ic == NULL) {
/* We've been asked to examine this packet, and we
* can't. Hence, no choice but to drop.
*/
duprintf("Dropping evil ICMP tinygram.\n");
par->hotdrop = true;
return false;
}
return icmp_type_code_match(icmpinfo->type,
icmpinfo->code[0],
icmpinfo->code[1],
ic->type, ic->code,
!!(icmpinfo->invflags&IPT_ICMP_INV));
}
static int icmp_checkentry(const struct xt_mtchk_param *par)
{
const struct ipt_icmp *icmpinfo = par->matchinfo;
/* Must specify no unknown invflags */
return (icmpinfo->invflags & ~IPT_ICMP_INV) ? -EINVAL : 0;
}
static struct xt_target ipt_builtin_tg[] __read_mostly = {
{
.name = XT_STANDARD_TARGET,
.targetsize = sizeof(int),
.family = NFPROTO_IPV4,
#ifdef CONFIG_COMPAT
.compatsize = sizeof(compat_int_t),
.compat_from_user = compat_standard_from_user,
.compat_to_user = compat_standard_to_user,
#endif
},
{
.name = XT_ERROR_TARGET,
.target = ipt_error,
.targetsize = XT_FUNCTION_MAXNAMELEN,
.family = NFPROTO_IPV4,
},
};
static struct nf_sockopt_ops ipt_sockopts = {
.pf = PF_INET,
.set_optmin = IPT_BASE_CTL,
.set_optmax = IPT_SO_SET_MAX+1,
.set = do_ipt_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_ipt_set_ctl,
#endif
.get_optmin = IPT_BASE_CTL,
.get_optmax = IPT_SO_GET_MAX+1,
.get = do_ipt_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_ipt_get_ctl,
#endif
.owner = THIS_MODULE,
};
static struct xt_match ipt_builtin_mt[] __read_mostly = {
{
.name = "icmp",
.match = icmp_match,
.matchsize = sizeof(struct ipt_icmp),
.checkentry = icmp_checkentry,
.proto = IPPROTO_ICMP,
.family = NFPROTO_IPV4,
},
};
static int __net_init ip_tables_net_init(struct net *net)
{
return xt_proto_init(net, NFPROTO_IPV4);
}
static void __net_exit ip_tables_net_exit(struct net *net)
{
xt_proto_fini(net, NFPROTO_IPV4);
}
static struct pernet_operations ip_tables_net_ops = {
.init = ip_tables_net_init,
.exit = ip_tables_net_exit,
};
static int __init ip_tables_init(void)
{
int ret;
ret = register_pernet_subsys(&ip_tables_net_ops);
if (ret < 0)
goto err1;
/* No one else will be downing sem now, so we won't sleep */
ret = xt_register_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
if (ret < 0)
goto err2;
ret = xt_register_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
if (ret < 0)
goto err4;
/* Register setsockopt */
ret = nf_register_sockopt(&ipt_sockopts);
if (ret < 0)
goto err5;
pr_info("(C) 2000-2006 Netfilter Core Team\n");
return 0;
err5:
xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
err4:
xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
err2:
unregister_pernet_subsys(&ip_tables_net_ops);
err1:
return ret;
}
static void __exit ip_tables_fini(void)
{
nf_unregister_sockopt(&ipt_sockopts);
xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
unregister_pernet_subsys(&ip_tables_net_ops);
}
EXPORT_SYMBOL(ipt_register_table);
EXPORT_SYMBOL(ipt_unregister_table);
EXPORT_SYMBOL(ipt_do_table);
module_init(ip_tables_init);
module_exit(ip_tables_fini);
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4999_1 |
crossvul-cpp_data_bad_4781_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT IIIII FFFFF FFFFF %
% T I F F %
% T I FFF FFF %
% T I F F %
% T IIIII F F %
% %
% %
% Read/Write TIFF Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/splay-tree.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread_.h"
#include "magick/token.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_TIFF_DELEGATE)
# if defined(MAGICKCORE_HAVE_TIFFCONF_H)
# include "tiffconf.h"
# endif
# include "tiff.h"
# include "tiffio.h"
# if !defined(COMPRESSION_ADOBE_DEFLATE)
# define COMPRESSION_ADOBE_DEFLATE 8
# endif
# if !defined(PREDICTOR_HORIZONTAL)
# define PREDICTOR_HORIZONTAL 2
# endif
# if !defined(TIFFTAG_COPYRIGHT)
# define TIFFTAG_COPYRIGHT 33432
# endif
# if !defined(TIFFTAG_OPIIMAGEID)
# define TIFFTAG_OPIIMAGEID 32781
# endif
#include "psd-private.h"
/*
Typedef declarations.
*/
typedef enum
{
ReadSingleSampleMethod,
ReadRGBAMethod,
ReadCMYKAMethod,
ReadYCCKMethod,
ReadStripMethod,
ReadTileMethod,
ReadGenericMethod
} TIFFMethodType;
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
typedef struct _ExifInfo
{
unsigned int
tag,
type,
variable_length;
const char
*property;
} ExifInfo;
static const ExifInfo
exif_info[] = {
{ EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" },
{ EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" },
{ EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" },
{ EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" },
{ EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" },
{ EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" },
{ EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" },
{ EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" },
{ EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" },
{ EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" },
{ EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" },
{ EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" },
{ EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" },
{ EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" },
{ EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" },
{ EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" },
{ EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" },
{ EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" },
{ EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" },
{ EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" },
{ EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" },
{ EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" },
{ EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" },
{ EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" },
{ EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" },
{ EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" },
{ EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" },
{ EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" },
{ EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" },
{ EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" },
{ EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" },
{ EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" },
{ EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" },
{ EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" },
{ EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" },
{ EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" },
{ EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" },
{ EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" },
{ EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" },
{ EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" },
{ EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" },
{ EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" },
{ EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" },
{ EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" },
{ EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" },
{ EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" },
{ EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" },
{ EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" },
{ EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" },
{ EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" },
{ EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" },
{ EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" },
{ EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" },
{ EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" },
{ EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" },
{ 0, 0, 0, (char *) NULL }
};
#endif
#endif /* MAGICKCORE_TIFF_DELEGATE */
/*
Global declarations.
*/
static MagickThreadKey
tiff_exception;
static SemaphoreInfo
*tiff_semaphore = (SemaphoreInfo *) NULL;
static TIFFErrorHandler
error_handler,
warning_handler;
static volatile MagickBooleanType
instantiate_key = MagickFalse;
/*
Forward declarations.
*/
#if defined(MAGICKCORE_TIFF_DELEGATE)
static Image *
ReadTIFFImage(const ImageInfo *,ExceptionInfo *);
static MagickBooleanType
WriteGROUP4Image(const ImageInfo *,Image *),
WritePTIFImage(const ImageInfo *,Image *),
WriteTIFFImage(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T I F F %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTIFF() returns MagickTrue if the image format type, identified by the
% magick string, is TIFF.
%
% The format of the IsTIFF method is:
%
% MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\052",4) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\052\000",4) == 0)
return(MagickTrue);
#if defined(TIFF_VERSION_BIG)
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
return(MagickTrue);
#endif
return(MagickFalse);
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadGROUP4Image method is:
%
% Image *ReadGROUP4Image(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline size_t WriteLSBLong(FILE *file,const size_t value)
{
unsigned char
buffer[4];
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
buffer[2]=(unsigned char) (value >> 16);
buffer[3]=(unsigned char) (value >> 24);
return(fwrite(buffer,1,4,file));
}
static Image *ReadGROUP4Image(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MaxTextExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
size_t
length;
ssize_t
offset,
strip_offset;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Write raw CCITT Group 4 wrapped as a TIFF image file.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->columns);
length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
strip_offset=10+(12*14)+4+8;
length=WriteLSBLong(file,(size_t) strip_offset);
length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) image_info->orientation);
length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
offset=(ssize_t) ftell(file)-4;
length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
length=fwrite("\000\000\000\000",1,4,file);
length=WriteLSBLong(file,(size_t) (image->x_resolution+0.5));
length=WriteLSBLong(file,1);
for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
(void) fputc(c,file);
offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
length=WriteLSBLong(file,(unsigned int) length);
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Read TIFF image.
*/
read_info=CloneImageInfo((ImageInfo *) NULL);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename);
image=ReadTIFFImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MaxTextExtent);
(void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent);
}
(void) RelinquishUniqueFileResource(filename);
return(image);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTIFFImage() reads a Tagged image file and returns it. It allocates the
% memory necessary for the new Image structure and returns a pointer to the
% new image.
%
% The format of the ReadTIFFImage method is:
%
% Image *ReadTIFFImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline unsigned char ClampYCC(double value)
{
value=255.0-value;
if (value < 0.0)
return((unsigned char)0);
if (value > 255.0)
return((unsigned char)255);
return((unsigned char)(value));
}
static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(q)+0.5;
if (a > 1.0)
a-=1.0;
b=QuantumScale*GetPixelb(q)+0.5;
if (b > 1.0)
b-=1.0;
SetPixela(q,QuantumRange*a);
SetPixelb(q,QuantumRange*b);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType ReadProfile(Image *image,const char *name,
const unsigned char *datum,ssize_t length)
{
MagickBooleanType
status;
StringInfo
*profile;
if (length < 4)
return(MagickFalse);
profile=BlobToStringInfo(datum,(size_t) length);
if (profile == (StringInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=SetImageProfile(image,name,profile);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
return(MagickTrue);
}
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int TIFFCloseBlob(thandle_t image)
{
(void) CloseBlob((Image *) image);
return(0);
}
static void TIFFErrors(const char *module,const char *format,va_list error)
{
char
message[MaxTextExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MaxTextExtent,format,error);
#else
(void) vsprintf(message,format,error);
#endif
(void) ConcatenateMagickString(message,".",MaxTextExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
"`%s'",module);
}
static toff_t TIFFGetBlobSize(thandle_t image)
{
return((toff_t) GetBlobSize((Image *) image));
}
static void TIFFGetProfiles(TIFF *tiff,Image *image,MagickBooleanType ping)
{
uint32
length;
unsigned char
*profile;
length=0;
if (ping == MagickFalse)
{
#if defined(TIFFTAG_ICCPROFILE)
if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"icc",profile,(ssize_t) length);
#endif
#if defined(TIFFTAG_PHOTOSHOP)
if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"8bim",profile,(ssize_t) length);
#endif
#if defined(TIFFTAG_RICHTIFFIPTC)
if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
{
if (TIFFIsByteSwapped(tiff) != 0)
TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
(void) ReadProfile(image,"iptc",profile,4L*length);
}
#endif
#if defined(TIFFTAG_XMLPACKET)
if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"xmp",profile,(ssize_t) length);
#endif
if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length);
}
if ((TIFFGetField(tiff,37724,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length);
}
static void TIFFGetProperties(TIFF *tiff,Image *image)
{
char
message[MaxTextExtent],
*text;
uint32
count,
length,
type;
unsigned long
*tietz;
if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1)
(void) SetImageProperty(image,"tiff:artist",text);
if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1)
(void) SetImageProperty(image,"tiff:copyright",text);
if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1)
(void) SetImageProperty(image,"tiff:timestamp",text);
if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1)
(void) SetImageProperty(image,"tiff:document",text);
if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1)
(void) SetImageProperty(image,"tiff:hostcomputer",text);
if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1)
(void) SetImageProperty(image,"comment",text);
if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1)
(void) SetImageProperty(image,"tiff:make",text);
if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1)
(void) SetImageProperty(image,"tiff:model",text);
if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1)
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:image-id",message);
}
if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1)
(void) SetImageProperty(image,"label",text);
if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1)
(void) SetImageProperty(image,"tiff:software",text);
if (TIFFGetField(tiff,33423,&count,&text) == 1)
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-33423",message);
}
if (TIFFGetField(tiff,36867,&count,&text) == 1)
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-36867",message);
}
if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1)
switch (type)
{
case 0x01:
{
(void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE");
break;
}
case 0x02:
{
(void) SetImageProperty(image,"tiff:subfiletype","PAGE");
break;
}
case 0x04:
{
(void) SetImageProperty(image,"tiff:subfiletype","MASK");
break;
}
default:
break;
}
if (TIFFGetField(tiff,37706,&length,&tietz) == 1)
{
(void) FormatLocaleString(message,MaxTextExtent,"%lu",tietz[0]);
(void) SetImageProperty(image,"tiff:tietz_offset",message);
}
}
static void TIFFGetEXIFProperties(TIFF *tiff,Image *image)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
char
value[MaxTextExtent];
register ssize_t
i;
tdir_t
directory;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
offset;
void
*sans;
/*
Read EXIF properties.
*/
offset=0;
if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1)
return;
directory=TIFFCurrentDirectory(tiff);
if (TIFFReadEXIFDirectory(tiff,offset) != 1)
{
TIFFSetDirectory(tiff,directory);
return;
}
sans=NULL;
for (i=0; exif_info[i].tag != 0; i++)
{
*value='\0';
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
char
*ascii;
ascii=(char *) NULL;
if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) &&
(ascii != (char *) NULL) && (*ascii != '\0'))
(void) CopyMagickString(value,ascii,MaxTextExtent);
break;
}
case TIFF_SHORT:
{
if (exif_info[i].variable_length == 0)
{
uint16
shorty;
shorty=0;
if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",shorty);
}
else
{
int
tiff_status;
uint16
*shorty;
uint16
shorty_num;
tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty,
&sans,&sans);
if (tiff_status == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",
shorty_num != 0 ? shorty[0] : 0);
}
break;
}
case TIFF_LONG:
{
uint32
longy;
longy=0;
if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",longy);
break;
}
#if defined(TIFF_VERSION_BIG)
case TIFF_LONG8:
{
uint64
long8y;
long8y=0;
if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
((MagickOffsetType) long8y));
break;
}
#endif
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
case TIFF_FLOAT:
{
float
floaty;
floaty=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty);
break;
}
case TIFF_DOUBLE:
{
double
doubley;
doubley=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%g",doubley);
break;
}
default:
break;
}
if (*value != '\0')
(void) SetImageProperty(image,exif_info[i].property,value);
}
TIFFSetDirectory(tiff,directory);
#else
(void) tiff;
(void) image;
#endif
}
static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
{
*base=(tdata_t *) GetBlobStreamData((Image *) image);
if (*base != (tdata_t *) NULL)
*size=(toff_t) GetBlobSize((Image *) image);
if (*base != (tdata_t *) NULL)
return(1);
return(0);
}
static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample,
tsample_t sample,ssize_t row,tdata_t scanline)
{
int32
status;
(void) bits_per_sample;
status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
return(status);
}
static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
{
return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
}
static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
{
(void) image;
(void) base;
(void) size;
}
static void TIFFWarnings(const char *module,const char *format,va_list warning)
{
char
message[MaxTextExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MaxTextExtent,format,warning);
#else
(void) vsprintf(message,format,warning);
#endif
(void) ConcatenateMagickString(message,".",MaxTextExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'",module);
}
static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric,
uint16 bits_per_sample,uint16 samples_per_pixel)
{
#define BUFFER_SIZE 2048
MagickOffsetType
position,
offset;
register size_t
i;
TIFFMethodType
method;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
**value;
unsigned char
buffer[BUFFER_SIZE+32];
unsigned short
length;
/* only support 8 bit for now */
if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) ||
(samples_per_pixel != 4))
return(ReadGenericMethod);
/* Search for Adobe APP14 JPEG Marker */
if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value))
return(ReadRGBAMethod);
position=TellBlob(image);
offset=(MagickOffsetType) (value[0]);
if (SeekBlob(image,offset,SEEK_SET) != offset)
return(ReadRGBAMethod);
method=ReadRGBAMethod;
if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE)
{
for (i=0; i < BUFFER_SIZE; i++)
{
while (i < BUFFER_SIZE)
{
if (buffer[i++] == 255)
break;
}
while (i < BUFFER_SIZE)
{
if (buffer[++i] != 255)
break;
}
if (buffer[i++] == 216) /* JPEG_MARKER_SOI */
continue;
length=(unsigned short) (((unsigned int) (buffer[i] << 8) |
(unsigned int) buffer[i+1]) & 0xffff);
if (i+(size_t) length >= BUFFER_SIZE)
break;
if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */
{
if (length != 14)
break;
/* 0 == CMYK, 1 == YCbCr, 2 = YCCK */
if (buffer[i+13] == 2)
method=ReadYCCKMethod;
break;
}
i+=(size_t) length;
}
}
(void) SeekBlob(image,position,SEEK_SET);
return(method);
}
static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
const StringInfo
*layer_info;
Image
*layers;
PSDInfo
info;
register ssize_t
i;
if (GetImageListLength(image) != 1)
return;
if ((image_info->number_scenes == 1) && (image_info->scene == 0))
return;
option=GetImageOption(image_info,"tiff:ignore-layers");
if (option != (const char * ) NULL)
return;
layer_info=GetImageProfile(image,"tiff:37724");
if (layer_info == (const StringInfo *) NULL)
return;
for (i=0; i < (ssize_t) layer_info->length-8; i++)
{
if (LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0)
continue;
i+=4;
if ((LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0))
break;
}
i+=4;
if (i >= (ssize_t) (layer_info->length-8))
return;
layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
(void) DeleteImageProfile(layers,"tiff:37724");
AttachBlob(layers->blob,layer_info->datum,layer_info->length);
SeekBlob(layers,(MagickOffsetType) i,SEEK_SET);
info.version=1;
info.columns=layers->columns;
info.rows=layers->rows;
/* Setting the mode to a value that won't change the colorspace */
info.mode=10;
if (IsGrayImage(image,&image->exception) != MagickFalse)
info.channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
if (image->storage_class == PseudoClass)
info.channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
{
if (image->colorspace != CMYKColorspace)
info.channels=(image->matte != MagickFalse ? 4UL : 3UL);
else
info.channels=(image->matte != MagickFalse ? 5UL : 4UL);
}
(void) ReadPSDLayers(layers,image_info,&info,MagickFalse,exception);
InheritException(exception,&layers->exception);
DeleteImageFromList(&layers);
if (layers != (Image *) NULL)
{
SetImageArtifact(image,"tiff:has-layers","true");
AppendImageToList(&image,layers);
while (layers != (Image *) NULL)
{
SetImageArtifact(layers,"tiff:has-layers","true");
DetachBlob(layers->blob);
layers=GetNextImageInList(layers);
}
}
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static Image *ReadTIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
float
*chromaticity,
x_position,
y_position,
x_resolution,
y_resolution;
Image
*image;
int
tiff_status;
MagickBooleanType
status;
MagickSizeType
number_pixels;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
pad;
ssize_t
y;
TIFF
*tiff;
TIFFMethodType
method;
uint16
compress_tag,
bits_per_sample,
endian,
extra_samples,
interlace,
max_sample_value,
min_sample_value,
orientation,
pages,
photometric,
*sample_info,
sample_format,
samples_per_pixel,
units,
value;
uint32
height,
rows_per_strip,
width;
unsigned char
*pixels;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SetMagickThreadValue(tiff_exception,exception);
tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image_info->number_scenes != 0)
{
/*
Generate blank images for subimage specification (e.g. image.tif[4].
We need to check the number of directores because it is possible that
the subimage(s) are stored in the photoshop profile.
*/
if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff))
{
for (i=0; i < (ssize_t) image_info->scene; i++)
{
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status == MagickFalse)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
}
}
}
do
{
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
TIFFPrintDirectory(tiff,stdout,MagickFalse);
RestoreMSCWarning
if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||
(TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (sample_format == SAMPLEFORMAT_IEEEFP)
(void) SetImageProperty(image,"quantum:format","floating-point");
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-black");
break;
}
case PHOTOMETRIC_MINISWHITE:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-white");
break;
}
case PHOTOMETRIC_PALETTE:
{
(void) SetImageProperty(image,"tiff:photometric","palette");
break;
}
case PHOTOMETRIC_RGB:
{
(void) SetImageProperty(image,"tiff:photometric","RGB");
break;
}
case PHOTOMETRIC_CIELAB:
{
(void) SetImageProperty(image,"tiff:photometric","CIELAB");
break;
}
case PHOTOMETRIC_LOGL:
{
(void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)");
break;
}
case PHOTOMETRIC_LOGLUV:
{
(void) SetImageProperty(image,"tiff:photometric","LOGLUV");
break;
}
#if defined(PHOTOMETRIC_MASK)
case PHOTOMETRIC_MASK:
{
(void) SetImageProperty(image,"tiff:photometric","MASK");
break;
}
#endif
case PHOTOMETRIC_SEPARATED:
{
(void) SetImageProperty(image,"tiff:photometric","separated");
break;
}
case PHOTOMETRIC_YCBCR:
{
(void) SetImageProperty(image,"tiff:photometric","YCBCR");
break;
}
default:
{
(void) SetImageProperty(image,"tiff:photometric","unknown");
break;
}
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
(unsigned int) width,(unsigned int) height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
interlace);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Bits per sample: %u",bits_per_sample);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Min sample value: %u",min_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Max sample value: %u",max_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
"interpretation: %s",GetImageProperty(image,"tiff:photometric"));
}
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=(size_t) bits_per_sample;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
(double) image->depth);
image->endian=MSBEndian;
if (endian == FILLORDER_LSB2MSB)
image->endian=LSBEndian;
#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
if (TIFFIsBigEndian(tiff) == 0)
{
(void) SetImageProperty(image,"tiff:endian","lsb");
image->endian=LSBEndian;
}
else
{
(void) SetImageProperty(image,"tiff:endian","msb");
image->endian=MSBEndian;
}
#endif
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
SetImageColorspace(image,GRAYColorspace);
if (photometric == PHOTOMETRIC_SEPARATED)
SetImageColorspace(image,CMYKColorspace);
if (photometric == PHOTOMETRIC_CIELAB)
SetImageColorspace(image,LabColorspace);
TIFFGetProfiles(tiff,image,image_info->ping);
TIFFGetProperties(tiff,image);
option=GetImageOption(image_info,"tiff:exif-properties");
if ((option == (const char *) NULL) ||
(IsMagickTrue(option) != MagickFalse))
TIFFGetEXIFProperties(tiff,image);
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))
{
image->x_resolution=x_resolution;
image->y_resolution=y_resolution;
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)
{
if (units == RESUNIT_INCH)
image->units=PixelsPerInchResolution;
if (units == RESUNIT_CENTIMETER)
image->units=PixelsPerCentimeterResolution;
}
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))
{
image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5);
image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5);
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)
image->orientation=(OrientationType) orientation;
if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.white_point.x=chromaticity[0];
image->chromaticity.white_point.y=chromaticity[1];
}
}
if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"CompressNotSupported");
}
#endif
switch (compress_tag)
{
case COMPRESSION_NONE: image->compression=NoCompression; break;
case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
case COMPRESSION_JPEG:
{
image->compression=JPEGCompression;
#if defined(JPEG_SUPPORT)
{
char
sampling_factor[MaxTextExtent];
int
tiff_status;
uint16
horizontal,
vertical;
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,
&horizontal,&vertical);
if (tiff_status == 1)
{
(void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
horizontal,vertical);
(void) SetImageProperty(image,"jpeg:sampling-factor",
sampling_factor);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling Factors: %s",sampling_factor);
}
}
#endif
break;
}
case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
#if defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA: image->compression=LZMACompression; break;
#endif
case COMPRESSION_LZW: image->compression=LZWCompression; break;
case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
default: image->compression=RLECompression; break;
}
/*
Allocate memory for the image and pixel buffer.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (sample_format == SAMPLEFORMAT_UINT)
status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_INT)
status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_IEEEFP)
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
{
TIFFClose(tiff);
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
status=MagickTrue;
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
quantum_info->min_is_white=MagickFalse;
break;
}
case PHOTOMETRIC_MINISWHITE:
{
quantum_info->min_is_white=MagickTrue;
break;
}
default:
break;
}
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
&sample_info);
if (tiff_status == 1)
{
(void) SetImageProperty(image,"tiff:alpha","unspecified");
if (extra_samples == 0)
{
if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
image->matte=MagickTrue;
}
else
for (i=0; i < extra_samples; i++)
{
image->matte=MagickTrue;
if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
{
SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
(void) SetImageProperty(image,"tiff:alpha","associated");
}
else
if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)
(void) SetImageProperty(image,"tiff:alpha","unassociated");
}
}
if ((photometric == PHOTOMETRIC_PALETTE) &&
(pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
{
size_t
colors;
colors=(size_t) GetQuantumRange(bits_per_sample)+1;
if (AcquireImageColormap(image,colors) == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)
image->scene=value;
if (image->storage_class == PseudoClass)
{
int
tiff_status;
size_t
range;
uint16
*blue_colormap,
*green_colormap,
*red_colormap;
/*
Initialize colormap.
*/
tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
&green_colormap,&blue_colormap);
if (tiff_status == 1)
{
if ((red_colormap != (uint16 *) NULL) &&
(green_colormap != (uint16 *) NULL) &&
(blue_colormap != (uint16 *) NULL))
{
range=255; /* might be old style 8-bit colormap */
for (i=0; i < (ssize_t) image->colors; i++)
if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
(blue_colormap[i] >= 256))
{
range=65535;
break;
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ClampToQuantum(((double)
QuantumRange*red_colormap[i])/range);
image->colormap[i].green=ClampToQuantum(((double)
QuantumRange*green_colormap[i])/range);
image->colormap[i].blue=ClampToQuantum(((double)
QuantumRange*blue_colormap[i])/range);
}
}
}
if (image->matte == MagickFalse)
image->depth=GetImageDepth(image,exception);
}
if (image_info->ping != MagickFalse)
{
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
{
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
goto next_tiff_frame;
}
method=ReadGenericMethod;
if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)
{
char
value[MaxTextExtent];
method=ReadStripMethod;
(void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int)
rows_per_strip);
(void) SetImageProperty(image,"tiff:rows-per-strip",value);
}
if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))
method=ReadRGBAMethod;
if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))
method=ReadCMYKAMethod;
if ((photometric != PHOTOMETRIC_RGB) &&
(photometric != PHOTOMETRIC_CIELAB) &&
(photometric != PHOTOMETRIC_SEPARATED))
method=ReadGenericMethod;
if (image->storage_class == PseudoClass)
method=ReadSingleSampleMethod;
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
method=ReadSingleSampleMethod;
if ((photometric != PHOTOMETRIC_SEPARATED) &&
(interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
method=ReadGenericMethod;
if (image->compression == JPEGCompression)
method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,
samples_per_pixel);
if (compress_tag == COMPRESSION_JBIG)
method=ReadStripMethod;
if (TIFFIsTiled(tiff) != MagickFalse)
method=ReadTileMethod;
quantum_info->endian=LSBEndian;
quantum_type=RGBQuantum;
pixels=GetQuantumPixels(quantum_info);
switch (method)
{
case ReadSingleSampleMethod:
{
/*
Convert TIFF image to PseudoClass MIFF image.
*/
quantum_type=IndexQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
if (image->matte != MagickFalse)
{
if (image->storage_class != PseudoClass)
{
quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
GrayAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
else
{
quantum_type=IndexAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
}
else
if (image->storage_class != PseudoClass)
{
quantum_type=GrayQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register PixelPacket
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadRGBAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
{
quantum_type=RGBAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
}
if (image->colorspace == CMYKColorspace)
{
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
{
quantum_type=CMYKAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
}
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register PixelPacket
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadCMYKAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
int
status;
status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
pixels);
if (status == -1)
break;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (image->colorspace != CMYKColorspace)
switch (i)
{
case 0: quantum_type=RedQuantum; break;
case 1: quantum_type=GreenQuantum; break;
case 2: quantum_type=BlueQuantum; break;
case 3: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
else
switch (i)
{
case 0: quantum_type=CyanQuantum; break;
case 1: quantum_type=MagentaQuantum; break;
case 2: quantum_type=YellowQuantum; break;
case 3: quantum_type=BlackQuantum; break;
case 4: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadYCCKMethod:
{
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register IndexPacket
*indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
unsigned char
*p;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+
(1.402*(double) *(p+2))-179.456)));
SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p-
(0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+
135.45984)));
SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+
(1.772*(double) *(p+1))-226.816)));
SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3)));
q++;
p+=4;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadStripMethod:
{
register uint32
*p;
/*
Convert stripped TIFF image to DirectClass MIFF image.
*/
i=0;
p=(uint32 *) NULL;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (i == 0)
{
if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
break;
i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
image->rows-y);
}
i--;
p=((uint32 *) pixels)+image->columns*i;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(TIFFGetR(*p))));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
(TIFFGetG(*p))));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
(TIFFGetB(*p))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,ScaleCharToQuantum((unsigned char)
(TIFFGetA(*p))));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadTileMethod:
{
register uint32
*p;
uint32
*tile_pixels,
columns,
rows;
size_t
number_pixels;
/*
Convert tiled TIFF image to DirectClass MIFF image.
*/
if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||
(TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"ImageIsNotTiled");
}
(void) SetImageStorageClass(image,DirectClass);
number_pixels=columns*rows;
tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels,
sizeof(*tile_pixels));
if (tile_pixels == (uint32 *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y+=rows)
{
PixelPacket
*tile;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
size_t
columns_remaining,
rows_remaining;
rows_remaining=image->rows-y;
if ((ssize_t) (y+rows) < (ssize_t) image->rows)
rows_remaining=rows;
tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
exception);
if (tile == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x+=columns)
{
size_t
column,
row;
if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
break;
columns_remaining=image->columns-x;
if ((ssize_t) (x+columns) < (ssize_t) image->columns)
columns_remaining=columns;
p=tile_pixels+(rows-rows_remaining)*columns;
q=tile+(image->columns*(rows_remaining-1)+x);
for (row=rows_remaining; row > 0; row--)
{
if (image->matte != MagickFalse)
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
TIFFGetA(*p)));
q++;
p++;
}
else
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)));
q++;
p++;
}
p+=columns-columns_remaining;
q-=(image->columns+columns_remaining);
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
break;
}
case ReadGenericMethod:
default:
{
MemoryInfo
*pixel_info;
register uint32
*p;
uint32
*pixels;
/*
Convert TIFF image to DirectClass MIFF image.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
(number_pixels*sizeof(uint32))))
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(uint32));
if (pixel_info == (MemoryInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
(void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)
image->rows,(uint32 *) pixels,0);
/*
Convert image to DirectClass pixel packets.
*/
p=pixels+number_pixels-1;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
q+=image->columns-1;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)));
p--;
q--;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
break;
}
}
SetQuantumImageType(image,quantum_type);
next_tiff_frame:
quantum_info=DestroyQuantumInfo(quantum_info);
if (photometric == PHOTOMETRIC_CIELAB)
DecodeLabImage(image,exception);
if ((photometric == PHOTOMETRIC_LOGL) ||
(photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
{
image->type=GrayscaleType;
if (bits_per_sample == 1)
image->type=BilevelType;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,image->scene-1,
image->scene);
if (status == MagickFalse)
break;
}
} while (status != MagickFalse);
TIFFClose(tiff);
TIFFReadPhotoshopLayers(image,image_info,exception);
if (image_info->number_scenes != 0)
{
if (image_info->scene >= GetImageListLength(image))
{
/* Subimage was not found in the Photoshop layer */
image = DestroyImageList(image);
return((Image *)NULL);
}
}
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTIFFImage() adds properties for the TIFF image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterTIFFImage method is:
%
% size_t RegisterTIFFImage(void)
%
*/
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
static TIFFExtendProc
tag_extender = (TIFFExtendProc) NULL;
static void TIFFIgnoreTags(TIFF *tiff)
{
char
*q;
const char
*p,
*tags;
Image
*image;
register ssize_t
i;
size_t
count;
TIFFFieldInfo
*ignore;
if (TIFFGetReadProc(tiff) != TIFFReadBlob)
return;
image=(Image *)TIFFClientdata(tiff);
tags=GetImageArtifact(image,"tiff:ignore-tags");
if (tags == (const char *) NULL)
return;
count=0;
p=tags;
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
(void) strtol(p,&q,10);
if (p == q)
return;
p=q;
count++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
if (count == 0)
return;
i=0;
p=tags;
ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore));
/* This also sets field_bit to 0 (FIELD_IGNORE) */
ResetMagickMemory(ignore,0,count*sizeof(*ignore));
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
ignore[i].field_tag=(ttag_t) strtol(p,&q,10);
p=q;
i++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
(void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count);
ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore);
}
static void TIFFTagExtender(TIFF *tiff)
{
static const TIFFFieldInfo
TIFFExtensions[] =
{
{ 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "PhotoshopLayerData" },
{ 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "Microscope" }
};
TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
sizeof(*TIFFExtensions));
if (tag_extender != (TIFFExtendProc) NULL)
(*tag_extender)(tiff);
TIFFIgnoreTags(tiff);
}
#endif
ModuleExport size_t RegisterTIFFImage(void)
{
#define TIFFDescription "Tagged Image File Format"
char
version[MaxTextExtent];
MagickInfo
*entry;
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key == MagickFalse)
{
if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
error_handler=TIFFSetErrorHandler(TIFFErrors);
warning_handler=TIFFSetWarningHandler(TIFFWarnings);
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
tag_extender=TIFFSetTagExtender(TIFFTagExtender);
#endif
instantiate_key=MagickTrue;
}
UnlockSemaphoreInfo(tiff_semaphore);
*version='\0';
#if defined(TIFF_VERSION)
(void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION);
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
{
const char
*p;
register ssize_t
i;
p=TIFFGetVersion();
for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++)
version[i]=(*p++);
version[i]='\0';
}
#endif
entry=SetMagickInfo("GROUP4");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
#endif
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->adjoin=MagickFalse;
entry->format_type=ImplicitFormatType;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Raw CCITT Group4");
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PTIF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WritePTIFImage;
#endif
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Pyramid encoded TIFF");
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->stealth=MagickTrue;
entry->description=ConstantString(TIFFDescription);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIFF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->magick=(IsImageFormatHandler *) IsTIFF;
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString(TIFFDescription);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIFF64");
#if defined(TIFF_VERSION_BIG)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->adjoin=MagickFalse;
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Tagged Image File Format (64-bit)");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTIFFImage() removes format registrations made by the TIFF module
% from the list of supported formats.
%
% The format of the UnregisterTIFFImage method is:
%
% UnregisterTIFFImage(void)
%
*/
ModuleExport void UnregisterTIFFImage(void)
{
(void) UnregisterMagickInfo("TIFF64");
(void) UnregisterMagickInfo("TIFF");
(void) UnregisterMagickInfo("TIF");
(void) UnregisterMagickInfo("PTIF");
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key != MagickFalse)
{
if (DeleteMagickThreadKey(tiff_exception) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
(void) TIFFSetTagExtender(tag_extender);
#endif
(void) TIFFSetWarningHandler(warning_handler);
(void) TIFFSetErrorHandler(error_handler);
instantiate_key=MagickFalse;
}
UnlockSemaphoreInfo(tiff_semaphore);
DestroySemaphoreInfo(&tiff_semaphore);
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
%
% The format of the WriteGROUP4Image method is:
%
% MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
Image *image)
{
char
filename[MaxTextExtent];
FILE
*file;
Image
*huffman_image;
ImageInfo
*write_info;
int
unique_file;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count;
TIFF
*tiff;
toff_t
*byte_count,
strip_size;
unsigned char
*buffer;
/*
Write image as CCITT Group4 TIFF image to a temporary file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
huffman_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (huffman_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
huffman_image->endian=MSBEndian;
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
ThrowFileException(&image->exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
return(MagickFalse);
}
(void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s",
filename);
(void) SetImageType(huffman_image,BilevelType);
write_info=CloneImageInfo((ImageInfo *) NULL);
SetImageInfoFile(write_info,file);
(void) SetImageType(image,BilevelType);
(void) SetImageDepth(image,1);
write_info->compression=Group4Compression;
write_info->type=BilevelType;
(void) SetImageOption(write_info,"quantum:polarity","min-is-white");
status=WriteTIFFImage(write_info,huffman_image);
(void) fflush(file);
write_info=DestroyImageInfo(write_info);
if (status == MagickFalse)
{
InheritException(&image->exception,&huffman_image->exception);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
tiff=TIFFOpen(filename,"rb");
if (tiff == (TIFF *) NULL)
{
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile",
image_info->filename);
return(MagickFalse);
}
/*
Allocate raw strip buffer.
*/
if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
strip_size=byte_count[0];
for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
if (byte_count[i] > strip_size)
strip_size=byte_count[i];
buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image_info->filename);
}
/*
Compress runlength encoded to 2D Huffman pixels.
*/
for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
{
count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
if (WriteBlob(image,(size_t) count,buffer) != count)
status=MagickFalse;
}
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
(void) CloseBlob(image);
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P T I F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
% format.
%
% The format of the WritePTIFImage method is:
%
% MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
Image *image)
{
ExceptionInfo
*exception;
Image
*images,
*next,
*pyramid_image;
ImageInfo
*write_info;
MagickBooleanType
status;
PointInfo
resolution;
size_t
columns,
rows;
/*
Create pyramid-encoded TIFF image.
*/
exception=(&image->exception);
images=NewImageList();
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
{
Image
*clone_image;
clone_image=CloneImage(next,0,0,MagickFalse,exception);
if (clone_image == (Image *) NULL)
break;
clone_image->previous=NewImageList();
clone_image->next=NewImageList();
(void) SetImageProperty(clone_image,"tiff:subfiletype","none");
AppendImageToList(&images,clone_image);
columns=next->columns;
rows=next->rows;
resolution.x=next->x_resolution;
resolution.y=next->y_resolution;
while ((columns > 64) && (rows > 64))
{
columns/=2;
rows/=2;
resolution.x/=2.0;
resolution.y/=2.0;
pyramid_image=ResizeImage(next,columns,rows,image->filter,image->blur,
exception);
if (pyramid_image == (Image *) NULL)
break;
pyramid_image->x_resolution=resolution.x;
pyramid_image->y_resolution=resolution.y;
(void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE");
AppendImageToList(&images,pyramid_image);
}
}
/*
Write pyramid-encoded TIFF image.
*/
write_info=CloneImageInfo(image_info);
write_info->adjoin=MagickTrue;
status=WriteTIFFImage(write_info,GetFirstImageInList(images));
images=DestroyImageList(images);
write_info=DestroyImageInfo(write_info);
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W r i t e T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTIFFImage() writes an image in the Tagged image file format.
%
% The format of the WriteTIFFImage method is:
%
% MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
typedef struct _TIFFInfo
{
RectangleInfo
tile_geometry;
unsigned char
*scanline,
*scanlines,
*pixels;
} TIFFInfo;
static void DestroyTIFFInfo(TIFFInfo *tiff_info)
{
assert(tiff_info != (TIFFInfo *) NULL);
if (tiff_info->scanlines != (unsigned char *) NULL)
tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
tiff_info->scanlines);
if (tiff_info->pixels != (unsigned char *) NULL)
tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
tiff_info->pixels);
}
static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(q)-0.5;
if (a < 0.0)
a+=1.0;
b=QuantumScale*GetPixelb(q)-0.5;
if (b < 0.0)
b+=1.0;
SetPixela(q,QuantumRange*a);
SetPixelb(q,QuantumRange*b);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff,
TIFFInfo *tiff_info)
{
const char
*option;
MagickStatusType
flags;
uint32
tile_columns,
tile_rows;
assert(tiff_info != (TIFFInfo *) NULL);
(void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
option=GetImageOption(image_info,"tiff:tile-geometry");
if (option == (const char *) NULL)
return(MagickTrue);
flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
if ((flags & HeightValue) == 0)
tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
tile_columns=(uint32) tiff_info->tile_geometry.width;
tile_rows=(uint32) tiff_info->tile_geometry.height;
TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
(void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
(void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
tiff_info->tile_geometry.width=tile_columns;
tiff_info->tile_geometry.height=tile_rows;
tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
if ((tiff_info->scanlines == (unsigned char *) NULL) ||
(tiff_info->pixels == (unsigned char *) NULL))
{
DestroyTIFFInfo(tiff_info);
return(MagickFalse);
}
return(MagickTrue);
}
static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
tsample_t sample,Image *image)
{
int32
status;
register ssize_t
i;
register unsigned char
*p,
*q;
size_t
number_tiles,
tile_width;
ssize_t
bytes_per_pixel,
j,
k,
l;
if (TIFFIsTiled(tiff) == 0)
return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
/*
Fill scanlines to tile height.
*/
i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
(void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
(size_t) TIFFScanlineSize(tiff));
if (((size_t) (row % tiff_info->tile_geometry.height) !=
(tiff_info->tile_geometry.height-1)) &&
(row != (ssize_t) (image->rows-1)))
return(0);
/*
Write tile to TIFF image.
*/
status=0;
bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (tiff_info->tile_geometry.height*
tiff_info->tile_geometry.width);
number_tiles=(image->columns+tiff_info->tile_geometry.width)/
tiff_info->tile_geometry.width;
for (i=0; i < (ssize_t) number_tiles; i++)
{
tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
for (k=0; k < (ssize_t) tile_width; k++)
{
if (bytes_per_pixel == 0)
{
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)/8);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
*q++=(*p++);
continue;
}
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)*bytes_per_pixel);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
for (l=0; l < bytes_per_pixel; l++)
*q++=(*p++);
}
if ((i*tiff_info->tile_geometry.width) != image->columns)
status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
tiff_info->tile_geometry.width),(uint32) ((row/
tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
sample);
if (status < 0)
break;
}
return(status);
}
static void TIFFSetProfiles(TIFF *tiff,Image *image)
{
const char
*name;
const StringInfo
*profile;
if (image->profiles == (void *) NULL)
return;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (GetStringInfoLength(profile) == 0)
{
name=GetNextImageProfile(image);
continue;
}
#if defined(TIFFTAG_XMLPACKET)
if (LocaleCompare(name,"xmp") == 0)
(void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
#if defined(TIFFTAG_ICCPROFILE)
if (LocaleCompare(name,"icc") == 0)
(void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"iptc") == 0)
{
size_t
length;
StringInfo
*iptc_profile;
iptc_profile=CloneStringInfo(profile);
length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
0x03);
SetStringInfoLength(iptc_profile,length);
if (TIFFIsByteSwapped(tiff))
TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
(unsigned long) (length/4));
(void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
iptc_profile=DestroyStringInfo(iptc_profile);
}
#if defined(TIFFTAG_PHOTOSHOP)
if (LocaleCompare(name,"8bim") == 0)
(void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
GetStringInfoLength(profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"tiff:37724") == 0)
(void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
if (LocaleCompare(name,"tiff:34118") == 0)
(void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
name=GetNextImageProfile(image);
}
}
static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info,
Image *image)
{
const char
*value;
value=GetImageArtifact(image,"tiff:document");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value);
value=GetImageArtifact(image,"tiff:hostcomputer");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
value=GetImageArtifact(image,"tiff:artist");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
value=GetImageArtifact(image,"tiff:timestamp");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
value=GetImageArtifact(image,"tiff:make");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
value=GetImageArtifact(image,"tiff:model");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
value=GetImageArtifact(image,"tiff:software");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
value=GetImageArtifact(image,"tiff:copyright");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
value=GetImageArtifact(image,"kodak-33423");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,33423,value);
value=GetImageArtifact(image,"kodak-36867");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,36867,value);
value=GetImageProperty(image,"label");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
value=GetImageArtifact(image,"tiff:subfiletype");
if (value != (const char *) NULL)
{
if (LocaleCompare(value,"REDUCEDIMAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
else
if (LocaleCompare(value,"PAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
else
if (LocaleCompare(value,"MASK") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK);
}
else
{
uint16
page,
pages;
page=(uint16) image->scene;
pages=(uint16) GetImageListLength(image);
if ((image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
}
static void TIFFSetEXIFProperties(TIFF *tiff,Image *image)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
const char
*value;
register ssize_t
i;
uint32
offset;
/*
Write EXIF properties.
*/
offset=0;
(void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
for (i=0; exif_info[i].tag != 0; i++)
{
value=GetImageProperty(image,exif_info[i].property);
if (value == (const char *) NULL)
continue;
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
(void) TIFFSetField(tiff,exif_info[i].tag,value);
break;
}
case TIFF_SHORT:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_LONG:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
{
float
field;
field=StringToDouble(value,(char **) NULL);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
default:
break;
}
}
/* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
#else
(void) tiff;
(void) image;
#endif
}
static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image)
{
#if !defined(TIFFDefaultStripSize)
#define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff))
#endif
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric;
uint32
rows_per_strip;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) SetMagickThreadValue(tiff_exception,&image->exception);
endian_type=UndefinedEndian;
option=GetImageOption(image_info,"tiff:endian");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian_type=MSBEndian;
if (LocaleNCompare(option,"lsb",3) == 0)
endian_type=LSBEndian;;
}
switch (endian_type)
{
case LSBEndian: mode="wl"; break;
case MSBEndian: mode="wb"; break;
default: mode="w"; break;
}
#if defined(TIFF_VERSION_BIG)
if (LocaleCompare(image_info->magick,"TIFF64") == 0)
switch (endian_type)
{
case LSBEndian: mode="wl8"; break;
case MSBEndian: mode="wb8"; break;
default: mode="w8"; break;
}
#endif
tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
return(MagickFalse);
scene=0;
debug=IsEventLogging();
(void) debug;
do
{
/*
Initialize TIFF fields.
*/
if ((image_info->type != UndefinedType) &&
(image_info->type != OptimizeType))
(void) SetImageType(image,image_info->type);
compression=UndefinedCompression;
if (image->compression != JPEGCompression)
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
(void) SetImageType(image,BilevelType);
(void) SetImageDepth(image,1);
break;
}
case JPEGCompression:
{
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
break;
}
default:
break;
}
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
(quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))
{
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
(GetPreviousImageInList(image) != (Image *) NULL))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
if ((image->columns != (uint32) image->columns) ||
(image->rows != (uint32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
(void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
switch (compression)
{
case FaxCompression:
{
compress_tag=COMPRESSION_CCITTFAX3;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
#if defined(COMPRESSION_JBIG)
case JBIG1Compression:
{
compress_tag=COMPRESSION_JBIG;
break;
}
#endif
case JPEGCompression:
{
compress_tag=COMPRESSION_JPEG;
break;
}
#if defined(COMPRESSION_LZMA)
case LZMACompression:
{
compress_tag=COMPRESSION_LZMA;
break;
}
#endif
case LZWCompression:
{
compress_tag=COMPRESSION_LZW;
break;
}
case RLECompression:
{
compress_tag=COMPRESSION_PACKBITS;
break;
}
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
case NoCompression:
default:
{
compress_tag=COMPRESSION_NONE;
break;
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
}
#else
switch (compress_tag)
{
#if defined(CCITT_SUPPORT)
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
#endif
#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
case COMPRESSION_JPEG:
#endif
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
#endif
#if defined(LZW_SUPPORT)
case COMPRESSION_LZW:
#endif
#if defined(PACKBITS_SUPPORT)
case COMPRESSION_PACKBITS:
#endif
#if defined(ZIP_SUPPORT)
case COMPRESSION_ADOBE_DEFLATE:
#endif
case COMPRESSION_NONE:
break;
default:
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
break;
}
}
#endif
if (image->colorspace == CMYKColorspace)
{
photometric=PHOTOMETRIC_SEPARATED;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
(void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
}
else
{
/*
Full color TIFF raster.
*/
if (image->colorspace == LabColorspace)
{
photometric=PHOTOMETRIC_CIELAB;
EncodeLabImage(image,&image->exception);
}
else
if (image->colorspace == YCbCrColorspace)
{
photometric=PHOTOMETRIC_YCBCR;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
}
else
photometric=PHOTOMETRIC_RGB;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorMatteType))
{
if ((image_info->type != PaletteType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
photometric=(uint16) (quantum_info->min_is_white !=
MagickFalse ? PHOTOMETRIC_MINISWHITE :
PHOTOMETRIC_MINISBLACK);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
if ((image->depth == 1) && (image->matte == MagickFalse))
SetImageMonochrome(image,&image->exception);
}
else
if (image->storage_class == PseudoClass)
{
size_t
depth;
/*
Colormapped TIFF raster.
*/
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
photometric=PHOTOMETRIC_PALETTE;
depth=1;
while ((GetQuantumRange(depth)+1) < image->colors)
depth<<=1;
status=SetQuantumDepth(image,quantum_info,depth);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
if ((compress_tag == COMPRESSION_CCITTFAX3) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
else
if ((compress_tag == COMPRESSION_CCITTFAX4) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
option=GetImageOption(image_info,"tiff:fill-order");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian=FILLORDER_MSB2LSB;
if (LocaleNCompare(option,"lsb",3) == 0)
endian=FILLORDER_LSB2MSB;
}
(void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
(void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
(void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
if (image->matte != MagickFalse)
{
uint16
extra_samples,
sample_info[1],
samples_per_pixel;
/*
TIFF has a matte channel.
*/
extra_samples=1;
sample_info[0]=EXTRASAMPLE_UNASSALPHA;
option=GetImageOption(image_info,"tiff:alpha");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"associated") == 0)
sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
else
if (LocaleCompare(option,"unspecified") == 0)
sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
(void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
&sample_info);
if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
}
(void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
switch (quantum_info->format)
{
case FloatingPointQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
(void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
(void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
break;
}
case SignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
break;
}
case UnsignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
break;
}
default:
break;
}
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
if (photometric == PHOTOMETRIC_RGB)
if ((image_info->interlace == PlaneInterlace) ||
(image_info->interlace == PartitionInterlace))
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
rows_per_strip=TIFFDefaultStripSize(tiff,0);
option=GetImageOption(image_info,"tiff:rows-per-strip");
if (option != (const char *) NULL)
rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
rows_per_strip+=(16-(rows_per_strip % 16));
if (image_info->quality != UndefinedCompressionQuality)
(void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
{
const char
*value;
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
sampling_factor=(const char *) NULL;
value=GetImageProperty(image,"jpeg:sampling-factor");
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor != (const char *) NULL)
{
flags=ParseGeometry(sampling_factor,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
if (image->colorspace == YCbCrColorspace)
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
geometry_info.rho,(uint16) geometry_info.sigma);
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (bits_per_sample == 12)
(void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
#endif
break;
}
case COMPRESSION_ADOBE_DEFLATE:
{
rows_per_strip=(uint32) image->rows;
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
case COMPRESSION_CCITTFAX3:
{
/*
Byte-aligned EOL.
*/
rows_per_strip=(uint32) image->rows;
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
{
rows_per_strip=(uint32) image->rows;
break;
}
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
#endif
case COMPRESSION_LZW:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
break;
}
default:
break;
}
if (rows_per_strip < 1)
rows_per_strip=1;
if ((image->rows/rows_per_strip) >= (1UL << 15))
rows_per_strip=(uint32) (image->rows >> 15);
(void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
{
unsigned short
units;
/*
Set image resolution.
*/
units=RESUNIT_NONE;
if (image->units == PixelsPerInchResolution)
units=RESUNIT_INCH;
if (image->units == PixelsPerCentimeterResolution)
units=RESUNIT_CENTIMETER;
(void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
(void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution);
(void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution);
if ((image->page.x < 0) || (image->page.y < 0))
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"TIFF: negative image positions unsupported","%s",
image->filename);
if ((image->page.x > 0) && (image->x_resolution > 0.0))
{
/*
Set horizontal image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
image->x_resolution);
}
if ((image->page.y > 0) && (image->y_resolution > 0.0))
{
/*
Set vertical image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
image->y_resolution);
}
}
if (image->chromaticity.white_point.x != 0.0)
{
float
chromaticity[6];
/*
Set image chromaticity.
*/
chromaticity[0]=(float) image->chromaticity.red_primary.x;
chromaticity[1]=(float) image->chromaticity.red_primary.y;
chromaticity[2]=(float) image->chromaticity.green_primary.x;
chromaticity[3]=(float) image->chromaticity.green_primary.y;
chromaticity[4]=(float) image->chromaticity.blue_primary.x;
chromaticity[5]=(float) image->chromaticity.blue_primary.y;
(void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
chromaticity[0]=(float) image->chromaticity.white_point.x;
chromaticity[1]=(float) image->chromaticity.white_point.y;
(void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
}
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
GetImageListLength(image));
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) GetImageListLength(image);
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
(void) TIFFSetProperties(tiff,image_info,image);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
(void) TIFFSetEXIFProperties(tiff,image);
/*
Write image scanlines.
*/
if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->endian=LSBEndian;
pixels=GetQuantumPixels(quantum_info);
tiff_info.scanline=GetQuantumPixels(quantum_info);
switch (photometric)
{
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_RGB:
{
/*
RGB TIFF image.
*/
switch (image_info->interlace)
{
case NoInterlace:
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
case PartitionInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,100,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,200,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,300,400);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,400,400);
if (status == MagickFalse)
break;
}
break;
}
}
break;
}
case PHOTOMETRIC_SEPARATED:
{
/*
CMYK TIFF image.
*/
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
quantum_type=CMYKAQuantum;
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PHOTOMETRIC_PALETTE:
{
uint16
*blue,
*green,
*red;
/*
Colormapped TIFF image.
*/
red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
(blue == (uint16 *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize TIFF colormap.
*/
(void) ResetMagickMemory(red,0,65536*sizeof(*red));
(void) ResetMagickMemory(green,0,65536*sizeof(*green));
(void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
for (i=0; i < (ssize_t) image->colors; i++)
{
red[i]=ScaleQuantumToShort(image->colormap[i].red);
green[i]=ScaleQuantumToShort(image->colormap[i].green);
blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
}
(void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
red=(uint16 *) RelinquishMagickMemory(red);
green=(uint16 *) RelinquishMagickMemory(green);
blue=(uint16 *) RelinquishMagickMemory(blue);
}
default:
{
/*
Convert PseudoClass packets to contiguous grayscale scanlines.
*/
quantum_type=IndexQuantum;
if (image->matte != MagickFalse)
{
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayAlphaQuantum;
else
quantum_type=IndexAlphaQuantum;
}
else
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->colorspace == LabColorspace)
DecodeLabImage(image,&image->exception);
DestroyTIFFInfo(&tiff_info);
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
RestoreMSCWarning
TIFFPrintDirectory(tiff,stdout,MagickFalse);
(void) TIFFWriteDirectory(tiff);
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4781_1 |
crossvul-cpp_data_good_339_4 | /*
* PKCS15 emulation layer for EstEID card.
*
* Copyright (C) 2004, Martin Paljak <martin@martinpaljak.net>
* Copyright (C) 2004, Bud P. Bruegger <bud@comune.grosseto.it>
* Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it>
* Copyright (C) 2003, Olaf Kirch <okir@suse.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#include "internal.h"
#include "opensc.h"
#include "pkcs15.h"
#include "esteid.h"
int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *);
static void
set_string (char **strp, const char *value)
{
if (*strp)
free (*strp);
*strp = value ? strdup (value) : NULL;
}
int
select_esteid_df (sc_card_t * card)
{
int r;
sc_path_t tmppath;
sc_format_path ("3F00EEEE", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "esteid select DF failed");
return r;
}
static int
sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
unsigned char buff[128];
int r, i;
size_t field_length = 0, modulus_length = 0;
sc_path_t tmppath;
set_string (&p15card->tokeninfo->label, "ID-kaart");
set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus");
/* Select application directory */
sc_format_path ("3f00eeee5044", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed");
/* read the serial (document number) */
r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed");
buff[MIN((size_t) r, (sizeof buff)-1)] = '\0';
set_string (&p15card->tokeninfo->serial_number, (const char *) buff);
p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION
| SC_PKCS15_TOKEN_EID_COMPLIANT
| SC_PKCS15_TOKEN_READONLY;
/* add certificates */
for (i = 0; i < 2; i++) {
static const char *esteid_cert_names[2] = {
"Isikutuvastus",
"Allkirjastamine"};
static char const *esteid_cert_paths[2] = {
"3f00eeeeaace",
"3f00eeeeddce"};
static int esteid_cert_ids[2] = {1, 2};
struct sc_pkcs15_cert_info cert_info;
struct sc_pkcs15_object cert_obj;
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id.value[0] = esteid_cert_ids[i];
cert_info.id.len = 1;
sc_format_path(esteid_cert_paths[i], &cert_info.path);
strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
if (r < 0)
return SC_ERROR_INTERNAL;
if (i == 0) {
sc_pkcs15_cert_t *cert = NULL;
r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert);
if (r < 0)
return SC_ERROR_INTERNAL;
if (cert->key->algorithm == SC_ALGORITHM_EC)
field_length = cert->key->u.ec.params.field_length;
else
modulus_length = cert->key->u.rsa.modulus.len * 8;
if (r == SC_SUCCESS) {
static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }};
u8 *cn_name = NULL;
size_t cn_len = 0;
sc_pkcs15_get_name_from_dn(card->ctx, cert->subject,
cert->subject_len, &cn_oid, &cn_name, &cn_len);
if (cn_len > 0) {
char *token_name = malloc(cn_len+1);
if (token_name) {
memcpy(token_name, cn_name, cn_len);
token_name[cn_len] = '\0';
set_string(&p15card->tokeninfo->label, (const char*)token_name);
free(token_name);
}
}
free(cn_name);
sc_pkcs15_free_certificate(cert);
}
}
}
/* the file with key pin info (tries left) */
sc_format_path ("3f000016", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
if (r < 0)
return SC_ERROR_INTERNAL;
/* add pins */
for (i = 0; i < 3; i++) {
unsigned char tries_left;
static const char *esteid_pin_names[3] = {
"PIN1",
"PIN2",
"PUK" };
static const int esteid_pin_min[3] = {4, 5, 8};
static const int esteid_pin_ref[3] = {1, 2, 0};
static const int esteid_pin_authid[3] = {1, 2, 3};
static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN};
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
/* read the number of tries left for the PIN */
r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
if (r < 0)
return SC_ERROR_INTERNAL;
tries_left = buff[5];
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = esteid_pin_authid[i];
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = esteid_pin_ref[i];
pin_info.attrs.pin.flags = esteid_pin_flags[i];
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = esteid_pin_min[i];
pin_info.attrs.pin.stored_length = 12;
pin_info.attrs.pin.max_length = 12;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = (int)tries_left;
pin_info.max_tries = 3;
strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label));
pin_obj.flags = esteid_pin_flags[i];
/* Link normal PINs with PUK */
if (i < 2) {
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 3;
}
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
/* add private keys */
for (i = 0; i < 2; i++) {
static int prkey_pin[2] = {1, 2};
static const char *prkey_name[2] = {
"Isikutuvastus",
"Allkirjastamine"};
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
memset(&prkey_info, 0, sizeof(prkey_info));
memset(&prkey_obj, 0, sizeof(prkey_obj));
prkey_info.id.len = 1;
prkey_info.id.value[0] = prkey_pin[i];
prkey_info.native = 1;
prkey_info.key_reference = i + 1;
prkey_info.field_length = field_length;
prkey_info.modulus_length = modulus_length;
if (i == 1)
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
else if(field_length > 0) // ECC has sign and derive usage
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE;
else
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT;
strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label));
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = prkey_pin[i];
prkey_obj.user_consent = 0;
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
if(field_length > 0)
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info);
else
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
return SC_SUCCESS;
}
static int esteid_detect_card(sc_pkcs15_card_t *p15card)
{
if (is_esteid_card(p15card->card))
return SC_SUCCESS;
else
return SC_ERROR_WRONG_CARD;
}
int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)
return sc_pkcs15emu_esteid_init(p15card);
else {
int r = esteid_detect_card(p15card);
if (r)
return SC_ERROR_WRONG_CARD;
return sc_pkcs15emu_esteid_init(p15card);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_339_4 |
crossvul-cpp_data_good_4837_0 | /*
* Copyright (c) 2000, 2001, 2002 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* multiple format streaming server based on the FFmpeg libraries
*/
#include "config.h"
#if !HAVE_CLOSESOCKET
#define closesocket close
#endif
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "libavformat/avformat.h"
/* FIXME: those are internal headers, ffserver _really_ shouldn't use them */
#include "libavformat/rtpproto.h"
#include "libavformat/rtsp.h"
#include "libavformat/avio_internal.h"
#include "libavformat/internal.h"
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/lfg.h"
#include "libavutil/dict.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/mathematics.h"
#include "libavutil/random_seed.h"
#include "libavutil/rational.h"
#include "libavutil/parseutils.h"
#include "libavutil/opt.h"
#include "libavutil/time.h"
#include <stdarg.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <fcntl.h>
#include <sys/ioctl.h>
#if HAVE_POLL_H
#include <poll.h>
#endif
#include <errno.h>
#include <time.h>
#include <sys/wait.h>
#include <signal.h>
#include "cmdutils.h"
#include "ffserver_config.h"
#define PATH_LENGTH 1024
const char program_name[] = "ffserver";
const int program_birth_year = 2000;
static const OptionDef options[];
enum HTTPState {
HTTPSTATE_WAIT_REQUEST,
HTTPSTATE_SEND_HEADER,
HTTPSTATE_SEND_DATA_HEADER,
HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
HTTPSTATE_SEND_DATA_TRAILER,
HTTPSTATE_RECEIVE_DATA,
HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
HTTPSTATE_READY,
RTSPSTATE_WAIT_REQUEST,
RTSPSTATE_SEND_REPLY,
RTSPSTATE_SEND_PACKET,
};
static const char * const http_state[] = {
"HTTP_WAIT_REQUEST",
"HTTP_SEND_HEADER",
"SEND_DATA_HEADER",
"SEND_DATA",
"SEND_DATA_TRAILER",
"RECEIVE_DATA",
"WAIT_FEED",
"READY",
"RTSP_WAIT_REQUEST",
"RTSP_SEND_REPLY",
"RTSP_SEND_PACKET",
};
#define IOBUFFER_INIT_SIZE 8192
/* timeouts are in ms */
#define HTTP_REQUEST_TIMEOUT (15 * 1000)
#define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
#define SYNC_TIMEOUT (10 * 1000)
typedef struct RTSPActionServerSetup {
uint32_t ipaddr;
char transport_option[512];
} RTSPActionServerSetup;
typedef struct {
int64_t count1, count2;
int64_t time1, time2;
} DataRateData;
/* context associated with one connection */
typedef struct HTTPContext {
enum HTTPState state;
int fd; /* socket file descriptor */
struct sockaddr_in from_addr; /* origin */
struct pollfd *poll_entry; /* used when polling */
int64_t timeout;
uint8_t *buffer_ptr, *buffer_end;
int http_error;
int post;
int chunked_encoding;
int chunk_size; /* 0 if it needs to be read */
struct HTTPContext *next;
int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
int64_t data_count;
/* feed input */
int feed_fd;
/* input format handling */
AVFormatContext *fmt_in;
int64_t start_time; /* In milliseconds - this wraps fairly often */
int64_t first_pts; /* initial pts value */
int64_t cur_pts; /* current pts value from the stream in us */
int64_t cur_frame_duration; /* duration of the current frame in us */
int cur_frame_bytes; /* output frame size, needed to compute
the time at which we send each
packet */
int pts_stream_index; /* stream we choose as clock reference */
int64_t cur_clock; /* current clock reference value in us */
/* output format handling */
struct FFServerStream *stream;
/* -1 is invalid stream */
int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
int switch_pending;
AVFormatContext *pfmt_ctx; /* instance of FFServerStream for one user */
int last_packet_sent; /* true if last data packet was sent */
int suppress_log;
DataRateData datarate;
int wmp_client_id;
char protocol[16];
char method[16];
char url[128];
char clean_url[128*7];
int buffer_size;
uint8_t *buffer;
int is_packetized; /* if true, the stream is packetized */
int packet_stream_index; /* current stream for output in state machine */
/* RTSP state specific */
uint8_t *pb_buffer; /* XXX: use that in all the code */
AVIOContext *pb;
int seq; /* RTSP sequence number */
/* RTP state specific */
enum RTSPLowerTransport rtp_protocol;
char session_id[32]; /* session id */
AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
/* RTP/UDP specific */
URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
/* RTP/TCP specific */
struct HTTPContext *rtsp_c;
uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
} HTTPContext;
static HTTPContext *first_http_ctx;
static FFServerConfig config = {
.nb_max_http_connections = 2000,
.nb_max_connections = 5,
.max_bandwidth = 1000,
.use_defaults = 1,
};
static void new_connection(int server_fd, int is_rtsp);
static void close_connection(HTTPContext *c);
/* HTTP handling */
static int handle_connection(HTTPContext *c);
static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
static void compute_status(HTTPContext *c);
static int open_input_stream(HTTPContext *c, const char *info);
static int http_parse_request(HTTPContext *c);
static int http_send_data(HTTPContext *c);
static int http_start_receive_data(HTTPContext *c);
static int http_receive_data(HTTPContext *c);
/* RTSP handling */
static int rtsp_parse_request(HTTPContext *c);
static void rtsp_cmd_describe(HTTPContext *c, const char *url);
static void rtsp_cmd_options(HTTPContext *c, const char *url);
static void rtsp_cmd_setup(HTTPContext *c, const char *url,
RTSPMessageHeader *h);
static void rtsp_cmd_play(HTTPContext *c, const char *url,
RTSPMessageHeader *h);
static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
RTSPMessageHeader *h, int pause_only);
/* SDP handling */
static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
struct in_addr my_ip);
/* RTP handling */
static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
FFServerStream *stream,
const char *session_id,
enum RTSPLowerTransport rtp_protocol);
static int rtp_new_av_stream(HTTPContext *c,
int stream_index, struct sockaddr_in *dest_addr,
HTTPContext *rtsp_c);
/* utils */
static size_t htmlencode (const char *src, char **dest);
static inline void cp_html_entity (char *buffer, const char *entity);
static inline int check_codec_match(LayeredAVStream *ccf, AVStream *ccs, int stream);
static const char *my_program_name;
static int no_launch;
static int need_to_start_children;
/* maximum number of simultaneous HTTP connections */
static unsigned int nb_connections;
static uint64_t current_bandwidth;
/* Making this global saves on passing it around everywhere */
static int64_t cur_time;
static AVLFG random_state;
static FILE *logfile = NULL;
static void unlayer_stream(AVStream *st, LayeredAVStream *lst)
{
avcodec_free_context(&st->codec);
avcodec_parameters_free(&st->codecpar);
#define COPY(a) st->a = lst->a;
COPY(index)
COPY(id)
COPY(codec)
COPY(codecpar)
COPY(time_base)
COPY(pts_wrap_bits)
COPY(sample_aspect_ratio)
COPY(recommended_encoder_configuration)
}
static inline void cp_html_entity (char *buffer, const char *entity) {
if (!buffer || !entity)
return;
while (*entity)
*buffer++ = *entity++;
}
/**
* Substitutes known conflicting chars on a text string with
* their corresponding HTML entities.
*
* Returns the number of bytes in the 'encoded' representation
* not including the terminating NUL.
*/
static size_t htmlencode (const char *src, char **dest) {
const char *amp = "&";
const char *lt = "<";
const char *gt = ">";
const char *start;
char *tmp;
size_t final_size = 0;
if (!src)
return 0;
start = src;
/* Compute needed dest size */
while (*src != '\0') {
switch(*src) {
case 38: /* & */
final_size += 5;
break;
case 60: /* < */
case 62: /* > */
final_size += 4;
break;
default:
final_size++;
}
src++;
}
src = start;
*dest = av_mallocz(final_size + 1);
if (!*dest)
return 0;
/* Build dest */
tmp = *dest;
while (*src != '\0') {
switch(*src) {
case 38: /* & */
cp_html_entity (tmp, amp);
tmp += 5;
break;
case 60: /* < */
cp_html_entity (tmp, lt);
tmp += 4;
break;
case 62: /* > */
cp_html_entity (tmp, gt);
tmp += 4;
break;
default:
*tmp = *src;
tmp += 1;
}
src++;
}
*tmp = '\0';
return final_size;
}
static int64_t ffm_read_write_index(int fd)
{
uint8_t buf[8];
if (lseek(fd, 8, SEEK_SET) < 0)
return AVERROR(EIO);
if (read(fd, buf, 8) != 8)
return AVERROR(EIO);
return AV_RB64(buf);
}
static int ffm_write_write_index(int fd, int64_t pos)
{
uint8_t buf[8];
int i;
for(i=0;i<8;i++)
buf[i] = (pos >> (56 - i * 8)) & 0xff;
if (lseek(fd, 8, SEEK_SET) < 0)
goto bail_eio;
if (write(fd, buf, 8) != 8)
goto bail_eio;
return 8;
bail_eio:
return AVERROR(EIO);
}
static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
int64_t file_size)
{
av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN);
av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN);
av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN);
}
static char *ctime1(char *buf2, size_t buf_size)
{
time_t ti;
char *p;
ti = time(NULL);
p = ctime(&ti);
if (!p || !*p) {
*buf2 = '\0';
return buf2;
}
av_strlcpy(buf2, p, buf_size);
p = buf2 + strlen(buf2) - 1;
if (*p == '\n')
*p = '\0';
return buf2;
}
static void http_vlog(const char *fmt, va_list vargs)
{
static int print_prefix = 1;
char buf[32];
if (!logfile)
return;
if (print_prefix) {
ctime1(buf, sizeof(buf));
fprintf(logfile, "%s ", buf);
}
print_prefix = strstr(fmt, "\n") != NULL;
vfprintf(logfile, fmt, vargs);
fflush(logfile);
}
#ifdef __GNUC__
__attribute__ ((format (printf, 1, 2)))
#endif
static void http_log(const char *fmt, ...)
{
va_list vargs;
va_start(vargs, fmt);
http_vlog(fmt, vargs);
va_end(vargs);
}
static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
{
static int print_prefix = 1;
AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
if (level > av_log_get_level())
return;
if (print_prefix && avc)
http_log("[%s @ %p]", avc->item_name(ptr), ptr);
print_prefix = strstr(fmt, "\n") != NULL;
http_vlog(fmt, vargs);
}
static void log_connection(HTTPContext *c)
{
if (c->suppress_log)
return;
http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
}
static void update_datarate(DataRateData *drd, int64_t count)
{
if (!drd->time1 && !drd->count1) {
drd->time1 = drd->time2 = cur_time;
drd->count1 = drd->count2 = count;
} else if (cur_time - drd->time2 > 5000) {
drd->time1 = drd->time2;
drd->count1 = drd->count2;
drd->time2 = cur_time;
drd->count2 = count;
}
}
/* In bytes per second */
static int compute_datarate(DataRateData *drd, int64_t count)
{
if (cur_time == drd->time1)
return 0;
return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
}
static void start_children(FFServerStream *feed)
{
char *pathname;
char *slash;
int i;
size_t cmd_length;
if (no_launch)
return;
cmd_length = strlen(my_program_name);
/**
* FIXME: WIP Safeguard. Remove after clearing all harcoded
* '1024' path lengths
*/
if (cmd_length > PATH_LENGTH - 1) {
http_log("Could not start children. Command line: '%s' exceeds "
"path length limit (%d)\n", my_program_name, PATH_LENGTH);
return;
}
pathname = av_strdup (my_program_name);
if (!pathname) {
http_log("Could not allocate memory for children cmd line\n");
return;
}
/* replace "ffserver" with "ffmpeg" in the path of current
* program. Ignore user provided path */
slash = strrchr(pathname, '/');
if (!slash)
slash = pathname;
else
slash++;
strcpy(slash, "ffmpeg");
for (; feed; feed = feed->next) {
if (!feed->child_argv || feed->pid)
continue;
feed->pid_start = time(0);
feed->pid = fork();
if (feed->pid < 0) {
http_log("Unable to create children: %s\n", strerror(errno));
av_free (pathname);
exit(EXIT_FAILURE);
}
if (feed->pid)
continue;
/* In child */
http_log("Launch command line: ");
http_log("%s ", pathname);
for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
http_log("%s ", feed->child_argv[i]);
http_log("\n");
for (i = 3; i < 256; i++)
close(i);
if (!config.debug) {
if (!freopen("/dev/null", "r", stdin))
http_log("failed to redirect STDIN to /dev/null\n;");
if (!freopen("/dev/null", "w", stdout))
http_log("failed to redirect STDOUT to /dev/null\n;");
if (!freopen("/dev/null", "w", stderr))
http_log("failed to redirect STDERR to /dev/null\n;");
}
signal(SIGPIPE, SIG_DFL);
execvp(pathname, feed->child_argv);
av_free (pathname);
_exit(1);
}
av_free (pathname);
}
/* open a listening socket */
static int socket_open_listen(struct sockaddr_in *my_addr)
{
int server_fd, tmp;
server_fd = socket(AF_INET,SOCK_STREAM,0);
if (server_fd < 0) {
perror ("socket");
return -1;
}
tmp = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
my_addr->sin_family = AF_INET;
if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
char bindmsg[32];
snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
ntohs(my_addr->sin_port));
perror (bindmsg);
goto fail;
}
if (listen (server_fd, 5) < 0) {
perror ("listen");
goto fail;
}
if (ff_socket_nonblock(server_fd, 1) < 0)
av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
return server_fd;
fail:
closesocket(server_fd);
return -1;
}
/* start all multicast streams */
static void start_multicast(void)
{
FFServerStream *stream;
char session_id[32];
HTTPContext *rtp_c;
struct sockaddr_in dest_addr = {0};
int default_port, stream_index;
unsigned int random0, random1;
default_port = 6000;
for(stream = config.first_stream; stream; stream = stream->next) {
if (!stream->is_multicast)
continue;
random0 = av_lfg_get(&random_state);
random1 = av_lfg_get(&random_state);
/* open the RTP connection */
snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
/* choose a port if none given */
if (stream->multicast_port == 0) {
stream->multicast_port = default_port;
default_port += 100;
}
dest_addr.sin_family = AF_INET;
dest_addr.sin_addr = stream->multicast_ip;
dest_addr.sin_port = htons(stream->multicast_port);
rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
if (!rtp_c)
continue;
if (open_input_stream(rtp_c, "") < 0) {
http_log("Could not open input stream for stream '%s'\n",
stream->filename);
continue;
}
/* open each RTP stream */
for(stream_index = 0; stream_index < stream->nb_streams;
stream_index++) {
dest_addr.sin_port = htons(stream->multicast_port +
2 * stream_index);
if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
continue;
http_log("Could not open output stream '%s/streamid=%d'\n",
stream->filename, stream_index);
exit(1);
}
rtp_c->state = HTTPSTATE_SEND_DATA;
}
}
/* main loop of the HTTP server */
static int http_server(void)
{
int server_fd = 0, rtsp_server_fd = 0;
int ret, delay;
struct pollfd *poll_table, *poll_entry;
HTTPContext *c, *c_next;
poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
sizeof(*poll_table));
if(!poll_table) {
http_log("Impossible to allocate a poll table handling %d "
"connections.\n", config.nb_max_http_connections);
return -1;
}
if (config.http_addr.sin_port) {
server_fd = socket_open_listen(&config.http_addr);
if (server_fd < 0)
goto quit;
}
if (config.rtsp_addr.sin_port) {
rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
if (rtsp_server_fd < 0) {
closesocket(server_fd);
goto quit;
}
}
if (!rtsp_server_fd && !server_fd) {
http_log("HTTP and RTSP disabled.\n");
goto quit;
}
http_log("FFserver started.\n");
start_children(config.first_feed);
start_multicast();
for(;;) {
poll_entry = poll_table;
if (server_fd) {
poll_entry->fd = server_fd;
poll_entry->events = POLLIN;
poll_entry++;
}
if (rtsp_server_fd) {
poll_entry->fd = rtsp_server_fd;
poll_entry->events = POLLIN;
poll_entry++;
}
/* wait for events on each HTTP handle */
c = first_http_ctx;
delay = 1000;
while (c) {
int fd;
fd = c->fd;
switch(c->state) {
case HTTPSTATE_SEND_HEADER:
case RTSPSTATE_SEND_REPLY:
case RTSPSTATE_SEND_PACKET:
c->poll_entry = poll_entry;
poll_entry->fd = fd;
poll_entry->events = POLLOUT;
poll_entry++;
break;
case HTTPSTATE_SEND_DATA_HEADER:
case HTTPSTATE_SEND_DATA:
case HTTPSTATE_SEND_DATA_TRAILER:
if (!c->is_packetized) {
/* for TCP, we output as much as we can
* (may need to put a limit) */
c->poll_entry = poll_entry;
poll_entry->fd = fd;
poll_entry->events = POLLOUT;
poll_entry++;
} else {
/* when ffserver is doing the timing, we work by
* looking at which packet needs to be sent every
* 10 ms (one tick wait XXX: 10 ms assumed) */
if (delay > 10)
delay = 10;
}
break;
case HTTPSTATE_WAIT_REQUEST:
case HTTPSTATE_RECEIVE_DATA:
case HTTPSTATE_WAIT_FEED:
case RTSPSTATE_WAIT_REQUEST:
/* need to catch errors */
c->poll_entry = poll_entry;
poll_entry->fd = fd;
poll_entry->events = POLLIN;/* Maybe this will work */
poll_entry++;
break;
default:
c->poll_entry = NULL;
break;
}
c = c->next;
}
/* wait for an event on one connection. We poll at least every
* second to handle timeouts */
do {
ret = poll(poll_table, poll_entry - poll_table, delay);
if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR)) {
goto quit;
}
} while (ret < 0);
cur_time = av_gettime() / 1000;
if (need_to_start_children) {
need_to_start_children = 0;
start_children(config.first_feed);
}
/* now handle the events */
for(c = first_http_ctx; c; c = c_next) {
c_next = c->next;
if (handle_connection(c) < 0) {
log_connection(c);
/* close and free the connection */
close_connection(c);
}
}
poll_entry = poll_table;
if (server_fd) {
/* new HTTP connection request ? */
if (poll_entry->revents & POLLIN)
new_connection(server_fd, 0);
poll_entry++;
}
if (rtsp_server_fd) {
/* new RTSP connection request ? */
if (poll_entry->revents & POLLIN)
new_connection(rtsp_server_fd, 1);
}
}
quit:
av_free(poll_table);
return -1;
}
/* start waiting for a new HTTP/RTSP request */
static void start_wait_request(HTTPContext *c, int is_rtsp)
{
c->buffer_ptr = c->buffer;
c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
c->timeout = cur_time +
(is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
}
static void http_send_too_busy_reply(int fd)
{
char buffer[400];
int len = snprintf(buffer, sizeof(buffer),
"HTTP/1.0 503 Server too busy\r\n"
"Content-type: text/html\r\n"
"\r\n"
"<!DOCTYPE html>\n"
"<html><head><title>Too busy</title></head><body>\r\n"
"<p>The server is too busy to serve your request at "
"this time.</p>\r\n"
"<p>The number of current connections is %u, and this "
"exceeds the limit of %u.</p>\r\n"
"</body></html>\r\n",
nb_connections, config.nb_max_connections);
av_assert0(len < sizeof(buffer));
if (send(fd, buffer, len, 0) < len)
av_log(NULL, AV_LOG_WARNING,
"Could not send too-busy reply, send() failed\n");
}
static void new_connection(int server_fd, int is_rtsp)
{
struct sockaddr_in from_addr;
socklen_t len;
int fd;
HTTPContext *c = NULL;
len = sizeof(from_addr);
fd = accept(server_fd, (struct sockaddr *)&from_addr,
&len);
if (fd < 0) {
http_log("error during accept %s\n", strerror(errno));
return;
}
if (ff_socket_nonblock(fd, 1) < 0)
av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
if (nb_connections >= config.nb_max_connections) {
http_send_too_busy_reply(fd);
goto fail;
}
/* add a new connection */
c = av_mallocz(sizeof(HTTPContext));
if (!c)
goto fail;
c->fd = fd;
c->poll_entry = NULL;
c->from_addr = from_addr;
c->buffer_size = IOBUFFER_INIT_SIZE;
c->buffer = av_malloc(c->buffer_size);
if (!c->buffer)
goto fail;
c->next = first_http_ctx;
first_http_ctx = c;
nb_connections++;
start_wait_request(c, is_rtsp);
return;
fail:
if (c) {
av_freep(&c->buffer);
av_free(c);
}
closesocket(fd);
}
static void close_connection(HTTPContext *c)
{
HTTPContext **cp, *c1;
int i, nb_streams;
AVFormatContext *ctx;
AVStream *st;
/* remove connection from list */
cp = &first_http_ctx;
while (*cp) {
c1 = *cp;
if (c1 == c)
*cp = c->next;
else
cp = &c1->next;
}
/* remove references, if any (XXX: do it faster) */
for(c1 = first_http_ctx; c1; c1 = c1->next) {
if (c1->rtsp_c == c)
c1->rtsp_c = NULL;
}
/* remove connection associated resources */
if (c->fd >= 0)
closesocket(c->fd);
if (c->fmt_in) {
/* close each frame parser */
for(i=0;i<c->fmt_in->nb_streams;i++) {
st = c->fmt_in->streams[i];
if (st->codec->codec)
avcodec_close(st->codec);
}
avformat_close_input(&c->fmt_in);
}
/* free RTP output streams if any */
nb_streams = 0;
if (c->stream)
nb_streams = c->stream->nb_streams;
for(i=0;i<nb_streams;i++) {
ctx = c->rtp_ctx[i];
if (ctx) {
av_write_trailer(ctx);
av_dict_free(&ctx->metadata);
av_freep(&ctx->streams[0]);
av_freep(&ctx);
}
ffurl_close(c->rtp_handles[i]);
}
ctx = c->pfmt_ctx;
if (ctx) {
if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
/* prepare header */
if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
av_write_trailer(ctx);
av_freep(&c->pb_buffer);
avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
}
}
for(i=0; i<ctx->nb_streams; i++)
av_freep(&ctx->streams[i]);
av_freep(&ctx->streams);
av_freep(&ctx->priv_data);
}
if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
current_bandwidth -= c->stream->bandwidth;
/* signal that there is no feed if we are the feeder socket */
if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
c->stream->feed_opened = 0;
close(c->feed_fd);
}
av_freep(&c->pb_buffer);
av_freep(&c->packet_buffer);
av_freep(&c->buffer);
av_free(c);
nb_connections--;
}
static int handle_connection(HTTPContext *c)
{
int len, ret;
uint8_t *ptr;
switch(c->state) {
case HTTPSTATE_WAIT_REQUEST:
case RTSPSTATE_WAIT_REQUEST:
/* timeout ? */
if ((c->timeout - cur_time) < 0)
return -1;
if (c->poll_entry->revents & (POLLERR | POLLHUP))
return -1;
/* no need to read if no events */
if (!(c->poll_entry->revents & POLLIN))
return 0;
/* read the data */
read_loop:
if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
return -1;
if (len < 0) {
if (ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR))
return -1;
break;
}
/* search for end of request. */
c->buffer_ptr += len;
ptr = c->buffer_ptr;
if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
(ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
/* request found : parse it and reply */
if (c->state == HTTPSTATE_WAIT_REQUEST)
ret = http_parse_request(c);
else
ret = rtsp_parse_request(c);
if (ret < 0)
return -1;
} else if (ptr >= c->buffer_end) {
/* request too long: cannot do anything */
return -1;
} else goto read_loop;
break;
case HTTPSTATE_SEND_HEADER:
if (c->poll_entry->revents & (POLLERR | POLLHUP))
return -1;
/* no need to write if no events */
if (!(c->poll_entry->revents & POLLOUT))
return 0;
len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
if (len < 0) {
if (ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR)) {
goto close_connection;
}
break;
}
c->buffer_ptr += len;
if (c->stream)
c->stream->bytes_served += len;
c->data_count += len;
if (c->buffer_ptr >= c->buffer_end) {
av_freep(&c->pb_buffer);
/* if error, exit */
if (c->http_error)
return -1;
/* all the buffer was sent : synchronize to the incoming
* stream */
c->state = HTTPSTATE_SEND_DATA_HEADER;
c->buffer_ptr = c->buffer_end = c->buffer;
}
break;
case HTTPSTATE_SEND_DATA:
case HTTPSTATE_SEND_DATA_HEADER:
case HTTPSTATE_SEND_DATA_TRAILER:
/* for packetized output, we consider we can always write (the
* input streams set the speed). It may be better to verify
* that we do not rely too much on the kernel queues */
if (!c->is_packetized) {
if (c->poll_entry->revents & (POLLERR | POLLHUP))
return -1;
/* no need to read if no events */
if (!(c->poll_entry->revents & POLLOUT))
return 0;
}
if (http_send_data(c) < 0)
return -1;
/* close connection if trailer sent */
if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
return -1;
/* Check if it is a single jpeg frame 123 */
if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
close_connection(c);
}
break;
case HTTPSTATE_RECEIVE_DATA:
/* no need to read if no events */
if (c->poll_entry->revents & (POLLERR | POLLHUP))
return -1;
if (!(c->poll_entry->revents & POLLIN))
return 0;
if (http_receive_data(c) < 0)
return -1;
break;
case HTTPSTATE_WAIT_FEED:
/* no need to read if no events */
if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
return -1;
/* nothing to do, we'll be waken up by incoming feed packets */
break;
case RTSPSTATE_SEND_REPLY:
if (c->poll_entry->revents & (POLLERR | POLLHUP))
goto close_connection;
/* no need to write if no events */
if (!(c->poll_entry->revents & POLLOUT))
return 0;
len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
if (len < 0) {
if (ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR)) {
goto close_connection;
}
break;
}
c->buffer_ptr += len;
c->data_count += len;
if (c->buffer_ptr >= c->buffer_end) {
/* all the buffer was sent : wait for a new request */
av_freep(&c->pb_buffer);
start_wait_request(c, 1);
}
break;
case RTSPSTATE_SEND_PACKET:
if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
av_freep(&c->packet_buffer);
return -1;
}
/* no need to write if no events */
if (!(c->poll_entry->revents & POLLOUT))
return 0;
len = send(c->fd, c->packet_buffer_ptr,
c->packet_buffer_end - c->packet_buffer_ptr, 0);
if (len < 0) {
if (ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR)) {
/* error : close connection */
av_freep(&c->packet_buffer);
return -1;
}
break;
}
c->packet_buffer_ptr += len;
if (c->packet_buffer_ptr >= c->packet_buffer_end) {
/* all the buffer was sent : wait for a new request */
av_freep(&c->packet_buffer);
c->state = RTSPSTATE_WAIT_REQUEST;
}
break;
case HTTPSTATE_READY:
/* nothing to do */
break;
default:
return -1;
}
return 0;
close_connection:
av_freep(&c->pb_buffer);
return -1;
}
static int extract_rates(char *rates, int ratelen, const char *request)
{
const char *p;
for (p = request; *p && *p != '\r' && *p != '\n'; ) {
if (av_strncasecmp(p, "Pragma:", 7) == 0) {
const char *q = p + 7;
while (*q && *q != '\n' && av_isspace(*q))
q++;
if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
int stream_no;
int rate_no;
q += 20;
memset(rates, 0xff, ratelen);
while (1) {
while (*q && *q != '\n' && *q != ':')
q++;
if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
break;
stream_no--;
if (stream_no < ratelen && stream_no >= 0)
rates[stream_no] = rate_no;
while (*q && *q != '\n' && !av_isspace(*q))
q++;
}
return 1;
}
}
p = strchr(p, '\n');
if (!p)
break;
p++;
}
return 0;
}
static int find_stream_in_feed(FFServerStream *feed, AVCodecParameters *codec,
int bit_rate)
{
int i;
int best_bitrate = 100000000;
int best = -1;
for (i = 0; i < feed->nb_streams; i++) {
AVCodecParameters *feed_codec = feed->streams[i]->codecpar;
if (feed_codec->codec_id != codec->codec_id ||
feed_codec->sample_rate != codec->sample_rate ||
feed_codec->width != codec->width ||
feed_codec->height != codec->height)
continue;
/* Potential stream */
/* We want the fastest stream less than bit_rate, or the slowest
* faster than bit_rate
*/
if (feed_codec->bit_rate <= bit_rate) {
if (best_bitrate > bit_rate ||
feed_codec->bit_rate > best_bitrate) {
best_bitrate = feed_codec->bit_rate;
best = i;
}
continue;
}
if (feed_codec->bit_rate < best_bitrate) {
best_bitrate = feed_codec->bit_rate;
best = i;
}
}
return best;
}
static int modify_current_stream(HTTPContext *c, char *rates)
{
int i;
FFServerStream *req = c->stream;
int action_required = 0;
/* Not much we can do for a feed */
if (!req->feed)
return 0;
for (i = 0; i < req->nb_streams; i++) {
AVCodecParameters *codec = req->streams[i]->codecpar;
switch(rates[i]) {
case 0:
c->switch_feed_streams[i] = req->feed_streams[i];
break;
case 1:
c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
break;
case 2:
/* Wants off or slow */
c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
#ifdef WANTS_OFF
/* This doesn't work well when it turns off the only stream! */
c->switch_feed_streams[i] = -2;
c->feed_streams[i] = -2;
#endif
break;
}
if (c->switch_feed_streams[i] >= 0 &&
c->switch_feed_streams[i] != c->feed_streams[i]) {
action_required = 1;
}
}
return action_required;
}
static void get_word(char *buf, int buf_size, const char **pp)
{
const char *p;
char *q;
#define SPACE_CHARS " \t\r\n"
p = *pp;
p += strspn(p, SPACE_CHARS);
q = buf;
while (!av_isspace(*p) && *p != '\0') {
if ((q - buf) < buf_size - 1)
*q++ = *p;
p++;
}
if (buf_size > 0)
*q = '\0';
*pp = p;
}
static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
HTTPContext *c)
{
FILE* f;
char line[1024];
char cmd[1024];
FFServerIPAddressACL *acl = NULL;
int line_num = 0;
const char *p;
f = fopen(stream->dynamic_acl, "r");
if (!f) {
perror(stream->dynamic_acl);
return NULL;
}
acl = av_mallocz(sizeof(FFServerIPAddressACL));
if (!acl) {
fclose(f);
return NULL;
}
/* Build ACL */
while (fgets(line, sizeof(line), f)) {
line_num++;
p = line;
while (av_isspace(*p))
p++;
if (*p == '\0' || *p == '#')
continue;
ffserver_get_arg(cmd, sizeof(cmd), &p);
if (!av_strcasecmp(cmd, "ACL"))
ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
line_num);
}
fclose(f);
return acl;
}
static void free_acl_list(FFServerIPAddressACL *in_acl)
{
FFServerIPAddressACL *pacl, *pacl2;
pacl = in_acl;
while(pacl) {
pacl2 = pacl;
pacl = pacl->next;
av_freep(pacl2);
}
}
static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
{
enum FFServerIPAddressAction last_action = IP_DENY;
FFServerIPAddressACL *acl;
struct in_addr *src = &c->from_addr.sin_addr;
unsigned long src_addr = src->s_addr;
for (acl = in_acl; acl; acl = acl->next) {
if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
return (acl->action == IP_ALLOW) ? 1 : 0;
last_action = acl->action;
}
/* Nothing matched, so return not the last action */
return (last_action == IP_DENY) ? 1 : 0;
}
static int validate_acl(FFServerStream *stream, HTTPContext *c)
{
int ret = 0;
FFServerIPAddressACL *acl;
/* if stream->acl is null validate_acl_list will return 1 */
ret = validate_acl_list(stream->acl, c);
if (stream->dynamic_acl[0]) {
acl = parse_dynamic_acl(stream, c);
ret = validate_acl_list(acl, c);
free_acl_list(acl);
}
return ret;
}
/**
* compute the real filename of a file by matching it without its
* extensions to all the stream's filenames
*/
static void compute_real_filename(char *filename, int max_size)
{
char file1[1024];
char file2[1024];
char *p;
FFServerStream *stream;
av_strlcpy(file1, filename, sizeof(file1));
p = strrchr(file1, '.');
if (p)
*p = '\0';
for(stream = config.first_stream; stream; stream = stream->next) {
av_strlcpy(file2, stream->filename, sizeof(file2));
p = strrchr(file2, '.');
if (p)
*p = '\0';
if (!strcmp(file1, file2)) {
av_strlcpy(filename, stream->filename, max_size);
break;
}
}
}
enum RedirType {
REDIR_NONE,
REDIR_ASX,
REDIR_RAM,
REDIR_ASF,
REDIR_RTSP,
REDIR_SDP,
};
/* parse HTTP request and prepare header */
static int http_parse_request(HTTPContext *c)
{
const char *p;
char *p1;
enum RedirType redir_type;
char cmd[32];
char info[1024], filename[1024];
char url[1024], *q;
char protocol[32];
char msg[1024];
char *encoded_msg = NULL;
const char *mime_type;
FFServerStream *stream;
int i;
char ratebuf[32];
const char *useragent = 0;
p = c->buffer;
get_word(cmd, sizeof(cmd), &p);
av_strlcpy(c->method, cmd, sizeof(c->method));
if (!strcmp(cmd, "GET"))
c->post = 0;
else if (!strcmp(cmd, "POST"))
c->post = 1;
else
return -1;
get_word(url, sizeof(url), &p);
av_strlcpy(c->url, url, sizeof(c->url));
get_word(protocol, sizeof(protocol), (const char **)&p);
if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
return -1;
av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
if (config.debug)
http_log("%s - - New connection: %s %s\n",
inet_ntoa(c->from_addr.sin_addr), cmd, url);
/* find the filename and the optional info string in the request */
p1 = strchr(url, '?');
if (p1) {
av_strlcpy(info, p1, sizeof(info));
*p1 = '\0';
} else
info[0] = '\0';
av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
useragent = p + 11;
if (*useragent && *useragent != '\n' && av_isspace(*useragent))
useragent++;
break;
}
p = strchr(p, '\n');
if (!p)
break;
p++;
}
redir_type = REDIR_NONE;
if (av_match_ext(filename, "asx")) {
redir_type = REDIR_ASX;
filename[strlen(filename)-1] = 'f';
} else if (av_match_ext(filename, "asf") &&
(!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
/* if this isn't WMP or lookalike, return the redirector file */
redir_type = REDIR_ASF;
} else if (av_match_ext(filename, "rpm,ram")) {
redir_type = REDIR_RAM;
strcpy(filename + strlen(filename)-2, "m");
} else if (av_match_ext(filename, "rtsp")) {
redir_type = REDIR_RTSP;
compute_real_filename(filename, sizeof(filename) - 1);
} else if (av_match_ext(filename, "sdp")) {
redir_type = REDIR_SDP;
compute_real_filename(filename, sizeof(filename) - 1);
}
/* "redirect" request to index.html */
if (!strlen(filename))
av_strlcpy(filename, "index.html", sizeof(filename) - 1);
stream = config.first_stream;
while (stream) {
if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
break;
stream = stream->next;
}
if (!stream) {
snprintf(msg, sizeof(msg), "File '%s' not found", url);
http_log("File '%s' not found\n", url);
goto send_error;
}
c->stream = stream;
memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
if (stream->stream_type == STREAM_TYPE_REDIRECT) {
c->http_error = 301;
q = c->buffer;
snprintf(q, c->buffer_size,
"HTTP/1.0 301 Moved\r\n"
"Location: %s\r\n"
"Content-type: text/html\r\n"
"\r\n"
"<!DOCTYPE html>\n"
"<html><head><title>Moved</title></head><body>\r\n"
"You should be <a href=\"%s\">redirected</a>.\r\n"
"</body></html>\r\n",
stream->feed_filename, stream->feed_filename);
q += strlen(q);
/* prepare output buffer */
c->buffer_ptr = c->buffer;
c->buffer_end = q;
c->state = HTTPSTATE_SEND_HEADER;
return 0;
}
/* If this is WMP, get the rate information */
if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
if (modify_current_stream(c, ratebuf)) {
for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
if (c->switch_feed_streams[i] >= 0)
c->switch_feed_streams[i] = -1;
}
}
}
if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
current_bandwidth += stream->bandwidth;
/* If already streaming this feed, do not let another feeder start */
if (stream->feed_opened) {
snprintf(msg, sizeof(msg), "This feed is already being received.");
http_log("Feed '%s' already being received\n", stream->feed_filename);
goto send_error;
}
if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
c->http_error = 503;
q = c->buffer;
snprintf(q, c->buffer_size,
"HTTP/1.0 503 Server too busy\r\n"
"Content-type: text/html\r\n"
"\r\n"
"<!DOCTYPE html>\n"
"<html><head><title>Too busy</title></head><body>\r\n"
"<p>The server is too busy to serve your request at "
"this time.</p>\r\n"
"<p>The bandwidth being served (including your stream) "
"is %"PRIu64"kbit/s, and this exceeds the limit of "
"%"PRIu64"kbit/s.</p>\r\n"
"</body></html>\r\n",
current_bandwidth, config.max_bandwidth);
q += strlen(q);
/* prepare output buffer */
c->buffer_ptr = c->buffer;
c->buffer_end = q;
c->state = HTTPSTATE_SEND_HEADER;
return 0;
}
if (redir_type != REDIR_NONE) {
const char *hostinfo = 0;
for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
if (av_strncasecmp(p, "Host:", 5) == 0) {
hostinfo = p + 5;
break;
}
p = strchr(p, '\n');
if (!p)
break;
p++;
}
if (hostinfo) {
char *eoh;
char hostbuf[260];
while (av_isspace(*hostinfo))
hostinfo++;
eoh = strchr(hostinfo, '\n');
if (eoh) {
if (eoh[-1] == '\r')
eoh--;
if (eoh - hostinfo < sizeof(hostbuf) - 1) {
memcpy(hostbuf, hostinfo, eoh - hostinfo);
hostbuf[eoh - hostinfo] = 0;
c->http_error = 200;
q = c->buffer;
switch(redir_type) {
case REDIR_ASX:
snprintf(q, c->buffer_size,
"HTTP/1.0 200 ASX Follows\r\n"
"Content-type: video/x-ms-asf\r\n"
"\r\n"
"<ASX Version=\"3\">\r\n"
//"<!-- Autogenerated by ffserver -->\r\n"
"<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
"</ASX>\r\n", hostbuf, filename, info);
q += strlen(q);
break;
case REDIR_RAM:
snprintf(q, c->buffer_size,
"HTTP/1.0 200 RAM Follows\r\n"
"Content-type: audio/x-pn-realaudio\r\n"
"\r\n"
"# Autogenerated by ffserver\r\n"
"http://%s/%s%s\r\n", hostbuf, filename, info);
q += strlen(q);
break;
case REDIR_ASF:
snprintf(q, c->buffer_size,
"HTTP/1.0 200 ASF Redirect follows\r\n"
"Content-type: video/x-ms-asf\r\n"
"\r\n"
"[Reference]\r\n"
"Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
q += strlen(q);
break;
case REDIR_RTSP:
{
char hostname[256], *p;
/* extract only hostname */
av_strlcpy(hostname, hostbuf, sizeof(hostname));
p = strrchr(hostname, ':');
if (p)
*p = '\0';
snprintf(q, c->buffer_size,
"HTTP/1.0 200 RTSP Redirect follows\r\n"
/* XXX: incorrect MIME type ? */
"Content-type: application/x-rtsp\r\n"
"\r\n"
"rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
q += strlen(q);
}
break;
case REDIR_SDP:
{
uint8_t *sdp_data;
int sdp_data_size;
socklen_t len;
struct sockaddr_in my_addr;
snprintf(q, c->buffer_size,
"HTTP/1.0 200 OK\r\n"
"Content-type: application/sdp\r\n"
"\r\n");
q += strlen(q);
len = sizeof(my_addr);
/* XXX: Should probably fail? */
if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
http_log("getsockname() failed\n");
/* XXX: should use a dynamic buffer */
sdp_data_size = prepare_sdp_description(stream,
&sdp_data,
my_addr.sin_addr);
if (sdp_data_size > 0) {
memcpy(q, sdp_data, sdp_data_size);
q += sdp_data_size;
*q = '\0';
av_freep(&sdp_data);
}
}
break;
default:
abort();
break;
}
/* prepare output buffer */
c->buffer_ptr = c->buffer;
c->buffer_end = q;
c->state = HTTPSTATE_SEND_HEADER;
return 0;
}
}
}
snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
goto send_error;
}
stream->conns_served++;
/* XXX: add there authenticate and IP match */
if (c->post) {
/* if post, it means a feed is being sent */
if (!stream->is_feed) {
/* However it might be a status report from WMP! Let us log the
* data as it might come handy one day. */
const char *logline = 0;
int client_id = 0;
for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
logline = p;
break;
}
if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
client_id = strtol(p + 18, 0, 10);
p = strchr(p, '\n');
if (!p)
break;
p++;
}
if (logline) {
char *eol = strchr(logline, '\n');
logline += 17;
if (eol) {
if (eol[-1] == '\r')
eol--;
http_log("%.*s\n", (int) (eol - logline), logline);
c->suppress_log = 1;
}
}
#ifdef DEBUG
http_log("\nGot request:\n%s\n", c->buffer);
#endif
if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
HTTPContext *wmpc;
/* Now we have to find the client_id */
for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
if (wmpc->wmp_client_id == client_id)
break;
}
if (wmpc && modify_current_stream(wmpc, ratebuf))
wmpc->switch_pending = 1;
}
snprintf(msg, sizeof(msg), "POST command not handled");
c->stream = 0;
goto send_error;
}
if (http_start_receive_data(c) < 0) {
snprintf(msg, sizeof(msg), "could not open feed");
goto send_error;
}
c->http_error = 0;
c->state = HTTPSTATE_RECEIVE_DATA;
return 0;
}
#ifdef DEBUG
if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
http_log("\nGot request:\n%s\n", c->buffer);
#endif
if (c->stream->stream_type == STREAM_TYPE_STATUS)
goto send_status;
/* open input stream */
if (open_input_stream(c, info) < 0) {
snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
goto send_error;
}
/* prepare HTTP header */
c->buffer[0] = 0;
av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
mime_type = c->stream->fmt->mime_type;
if (!mime_type)
mime_type = "application/x-octet-stream";
av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
/* for asf, we need extra headers */
if (!strcmp(c->stream->fmt->name,"asf_stream")) {
/* Need to allocate a client id */
c->wmp_client_id = av_lfg_get(&random_state);
av_strlcatf(c->buffer, c->buffer_size, "Server: Cougar 4.1.0.3923\r\nCache-Control: no-cache\r\nPragma: client-id=%d\r\nPragma: features=\"broadcast\"\r\n", c->wmp_client_id);
}
av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
av_strlcatf(c->buffer, c->buffer_size, "\r\n");
q = c->buffer + strlen(c->buffer);
/* prepare output buffer */
c->http_error = 0;
c->buffer_ptr = c->buffer;
c->buffer_end = q;
c->state = HTTPSTATE_SEND_HEADER;
return 0;
send_error:
c->http_error = 404;
q = c->buffer;
if (!htmlencode(msg, &encoded_msg)) {
http_log("Could not encode filename '%s' as HTML\n", msg);
}
snprintf(q, c->buffer_size,
"HTTP/1.0 404 Not Found\r\n"
"Content-type: text/html\r\n"
"\r\n"
"<!DOCTYPE html>\n"
"<html>\n"
"<head>\n"
"<meta charset=\"UTF-8\">\n"
"<title>404 Not Found</title>\n"
"</head>\n"
"<body>%s</body>\n"
"</html>\n", encoded_msg? encoded_msg : "File not found");
q += strlen(q);
/* prepare output buffer */
c->buffer_ptr = c->buffer;
c->buffer_end = q;
c->state = HTTPSTATE_SEND_HEADER;
av_freep(&encoded_msg);
return 0;
send_status:
compute_status(c);
/* horrible: we use this value to avoid
* going to the send data state */
c->http_error = 200;
c->state = HTTPSTATE_SEND_HEADER;
return 0;
}
static void fmt_bytecount(AVIOContext *pb, int64_t count)
{
static const char suffix[] = " kMGTP";
const char *s;
for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
avio_printf(pb, "%"PRId64"%c", count, *s);
}
static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
{
int i, stream_no;
const char *type = "unknown";
char parameters[64];
LayeredAVStream *st;
AVCodec *codec;
stream_no = stream->nb_streams;
avio_printf(pb, "<table><tr><th>Stream<th>"
"type<th>kbit/s<th>codec<th>"
"Parameters\n");
for (i = 0; i < stream_no; i++) {
st = stream->streams[i];
codec = avcodec_find_encoder(st->codecpar->codec_id);
parameters[0] = 0;
switch(st->codecpar->codec_type) {
case AVMEDIA_TYPE_AUDIO:
type = "audio";
snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
st->codecpar->channels, st->codecpar->sample_rate);
break;
case AVMEDIA_TYPE_VIDEO:
type = "video";
snprintf(parameters, sizeof(parameters),
"%dx%d, q=%d-%d, fps=%d", st->codecpar->width,
st->codecpar->height, st->codec->qmin, st->codec->qmax,
st->time_base.den / st->time_base.num);
break;
default:
abort();
}
avio_printf(pb, "<tr><td>%d<td>%s<td>%"PRId64
"<td>%s<td>%s\n",
i, type, (int64_t)st->codecpar->bit_rate/1000,
codec ? codec->name : "", parameters);
}
avio_printf(pb, "</table>\n");
}
static void clean_html(char *clean, int clean_len, char *dirty)
{
int i, o;
for (o = i = 0; o+10 < clean_len && dirty[i];) {
int len = strspn(dirty+i, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$-_.+!*(),?/ :;%");
if (len) {
if (o + len >= clean_len)
break;
memcpy(clean + o, dirty + i, len);
i += len;
o += len;
} else {
int c = dirty[i++];
switch (c) {
case '&': av_strlcat(clean+o, "&" , clean_len - o); break;
case '<': av_strlcat(clean+o, "<" , clean_len - o); break;
case '>': av_strlcat(clean+o, ">" , clean_len - o); break;
case '\'': av_strlcat(clean+o, "'" , clean_len - o); break;
case '\"': av_strlcat(clean+o, """ , clean_len - o); break;
default: av_strlcat(clean+o, "☹", clean_len - o); break;
}
o += strlen(clean+o);
}
}
clean[o] = 0;
}
static void compute_status(HTTPContext *c)
{
HTTPContext *c1;
FFServerStream *stream;
char *p;
time_t ti;
int i, len;
AVIOContext *pb;
if (avio_open_dyn_buf(&pb) < 0) {
/* XXX: return an error ? */
c->buffer_ptr = c->buffer;
c->buffer_end = c->buffer;
return;
}
avio_printf(pb, "HTTP/1.0 200 OK\r\n");
avio_printf(pb, "Content-type: text/html\r\n");
avio_printf(pb, "Pragma: no-cache\r\n");
avio_printf(pb, "\r\n");
avio_printf(pb, "<!DOCTYPE html>\n");
avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
if (c->stream->feed_filename[0])
avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
c->stream->feed_filename);
avio_printf(pb, "</head>\n<body>");
avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
/* format status */
avio_printf(pb, "<h2>Available Streams</h2>\n");
avio_printf(pb, "<table>\n");
avio_printf(pb, "<tr><th>Path<th>Served<br>Conns<th><br>bytes<th>Format<th>Bit rate<br>kbit/s<th>Video<br>kbit/s<th><br>Codec<th>Audio<br>kbit/s<th><br>Codec<th>Feed\n");
stream = config.first_stream;
while (stream) {
char sfilename[1024];
char *eosf;
if (stream->feed == stream) {
stream = stream->next;
continue;
}
av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
eosf = sfilename + strlen(sfilename);
if (eosf - sfilename >= 4) {
if (strcmp(eosf - 4, ".asf") == 0)
strcpy(eosf - 4, ".asx");
else if (strcmp(eosf - 3, ".rm") == 0)
strcpy(eosf - 3, ".ram");
else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
/* generate a sample RTSP director if
* unicast. Generate an SDP redirector if
* multicast */
eosf = strrchr(sfilename, '.');
if (!eosf)
eosf = sfilename + strlen(sfilename);
if (stream->is_multicast)
strcpy(eosf, ".sdp");
else
strcpy(eosf, ".rtsp");
}
}
avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
sfilename, stream->filename);
avio_printf(pb, "<td> %d <td> ",
stream->conns_served);
// TODO: Investigate if we can make http bitexact so it always produces the same count of bytes
if (!config.bitexact)
fmt_bytecount(pb, stream->bytes_served);
switch(stream->stream_type) {
case STREAM_TYPE_LIVE: {
int audio_bit_rate = 0;
int video_bit_rate = 0;
const char *audio_codec_name = "";
const char *video_codec_name = "";
const char *audio_codec_name_extra = "";
const char *video_codec_name_extra = "";
for(i=0;i<stream->nb_streams;i++) {
LayeredAVStream *st = stream->streams[i];
AVCodec *codec = avcodec_find_encoder(st->codecpar->codec_id);
switch(st->codecpar->codec_type) {
case AVMEDIA_TYPE_AUDIO:
audio_bit_rate += st->codecpar->bit_rate;
if (codec) {
if (*audio_codec_name)
audio_codec_name_extra = "...";
audio_codec_name = codec->name;
}
break;
case AVMEDIA_TYPE_VIDEO:
video_bit_rate += st->codecpar->bit_rate;
if (codec) {
if (*video_codec_name)
video_codec_name_extra = "...";
video_codec_name = codec->name;
}
break;
case AVMEDIA_TYPE_DATA:
video_bit_rate += st->codecpar->bit_rate;
break;
default:
abort();
}
}
avio_printf(pb, "<td> %s <td> %d <td> %d <td> %s %s <td> "
"%d <td> %s %s",
stream->fmt->name, stream->bandwidth,
video_bit_rate / 1000, video_codec_name,
video_codec_name_extra, audio_bit_rate / 1000,
audio_codec_name, audio_codec_name_extra);
if (stream->feed)
avio_printf(pb, "<td>%s", stream->feed->filename);
else
avio_printf(pb, "<td>%s", stream->feed_filename);
avio_printf(pb, "\n");
}
break;
default:
avio_printf(pb, "<td> - <td> - "
"<td> - <td><td> - <td>\n");
break;
}
stream = stream->next;
}
avio_printf(pb, "</table>\n");
stream = config.first_stream;
while (stream) {
if (stream->feed != stream) {
stream = stream->next;
continue;
}
avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
if (stream->pid) {
avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid);
#if defined(linux)
{
FILE *pid_stat;
char ps_cmd[64];
/* This is somewhat linux specific I guess */
snprintf(ps_cmd, sizeof(ps_cmd),
"ps -o \"%%cpu,cputime\" --no-headers %"PRId64"",
(int64_t) stream->pid);
pid_stat = popen(ps_cmd, "r");
if (pid_stat) {
char cpuperc[10];
char cpuused[64];
if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
avio_printf(pb, "Currently using %s%% of the cpu. "
"Total time used %s.\n",
cpuperc, cpuused);
}
fclose(pid_stat);
}
}
#endif
avio_printf(pb, "<p>");
}
print_stream_params(pb, stream);
stream = stream->next;
}
/* connection status */
avio_printf(pb, "<h2>Connection Status</h2>\n");
avio_printf(pb, "Number of connections: %d / %d<br>\n",
nb_connections, config.nb_max_connections);
avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
current_bandwidth, config.max_bandwidth);
avio_printf(pb, "<table>\n");
avio_printf(pb, "<tr><th>#<th>File<th>IP<th>URL<th>Proto<th>State<th>Target "
"bit/s<th>Actual bit/s<th>Bytes transferred\n");
c1 = first_http_ctx;
i = 0;
while (c1) {
int bitrate;
int j;
bitrate = 0;
if (c1->stream) {
for (j = 0; j < c1->stream->nb_streams; j++) {
if (!c1->stream->feed)
bitrate += c1->stream->streams[j]->codecpar->bit_rate;
else if (c1->feed_streams[j] >= 0)
bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codecpar->bit_rate;
}
}
i++;
p = inet_ntoa(c1->from_addr.sin_addr);
clean_html(c1->clean_url, sizeof(c1->clean_url), c1->url);
avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td>%s"
"<td>",
i, c1->stream ? c1->stream->filename : "",
c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
p,
c1->clean_url,
c1->protocol, http_state[c1->state]);
fmt_bytecount(pb, bitrate);
avio_printf(pb, "<td>");
fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
avio_printf(pb, "<td>");
fmt_bytecount(pb, c1->data_count);
avio_printf(pb, "\n");
c1 = c1->next;
}
avio_printf(pb, "</table>\n");
if (!config.bitexact) {
/* date */
ti = time(NULL);
p = ctime(&ti);
avio_printf(pb, "<hr>Generated at %s", p);
}
avio_printf(pb, "</body>\n</html>\n");
len = avio_close_dyn_buf(pb, &c->pb_buffer);
c->buffer_ptr = c->pb_buffer;
c->buffer_end = c->pb_buffer + len;
}
static int open_input_stream(HTTPContext *c, const char *info)
{
char buf[128];
char input_filename[1024];
AVFormatContext *s = NULL;
int buf_size, i, ret;
int64_t stream_pos;
/* find file name */
if (c->stream->feed) {
strcpy(input_filename, c->stream->feed->feed_filename);
buf_size = FFM_PACKET_SIZE;
/* compute position (absolute time) */
if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
http_log("Invalid date specification '%s' for stream\n", buf);
return ret;
}
} else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
int prebuffer = strtol(buf, 0, 10);
stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
} else
stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
} else {
strcpy(input_filename, c->stream->feed_filename);
buf_size = 0;
/* compute position (relative time) */
if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
http_log("Invalid date specification '%s' for stream\n", buf);
return ret;
}
} else
stream_pos = 0;
}
if (!input_filename[0]) {
http_log("No filename was specified for stream\n");
return AVERROR(EINVAL);
}
/* open stream */
ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
&c->stream->in_opts);
if (ret < 0) {
http_log("Could not open input '%s': %s\n",
input_filename, av_err2str(ret));
return ret;
}
/* set buffer size */
if (buf_size > 0) {
ret = ffio_set_buf_size(s->pb, buf_size);
if (ret < 0) {
http_log("Failed to set buffer size\n");
return ret;
}
}
s->flags |= AVFMT_FLAG_GENPTS;
c->fmt_in = s;
if (strcmp(s->iformat->name, "ffm") &&
(ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
http_log("Could not find stream info for input '%s'\n", input_filename);
avformat_close_input(&s);
return ret;
}
/* choose stream as clock source (we favor the video stream if
* present) for packet sending */
c->pts_stream_index = 0;
for(i=0;i<c->stream->nb_streams;i++) {
if (c->pts_stream_index == 0 &&
c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
c->pts_stream_index = i;
}
}
if (c->fmt_in->iformat->read_seek)
av_seek_frame(c->fmt_in, -1, stream_pos, 0);
/* set the start time (needed for maxtime and RTP packet timing) */
c->start_time = cur_time;
c->first_pts = AV_NOPTS_VALUE;
return 0;
}
/* return the server clock (in us) */
static int64_t get_server_clock(HTTPContext *c)
{
/* compute current pts value from system time */
return (cur_time - c->start_time) * 1000;
}
/* return the estimated time (in us) at which the current packet must be sent */
static int64_t get_packet_send_clock(HTTPContext *c)
{
int bytes_left, bytes_sent, frame_bytes;
frame_bytes = c->cur_frame_bytes;
if (frame_bytes <= 0)
return c->cur_pts;
bytes_left = c->buffer_end - c->buffer_ptr;
bytes_sent = frame_bytes - bytes_left;
return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
}
static int http_prepare_data(HTTPContext *c)
{
int i, len, ret;
AVFormatContext *ctx;
av_freep(&c->pb_buffer);
switch(c->state) {
case HTTPSTATE_SEND_DATA_HEADER:
ctx = avformat_alloc_context();
if (!ctx)
return AVERROR(ENOMEM);
c->pfmt_ctx = ctx;
av_dict_copy(&(c->pfmt_ctx->metadata), c->stream->metadata, 0);
for(i=0;i<c->stream->nb_streams;i++) {
LayeredAVStream *src;
AVStream *st = avformat_new_stream(c->pfmt_ctx, NULL);
if (!st)
return AVERROR(ENOMEM);
/* if file or feed, then just take streams from FFServerStream
* struct */
if (!c->stream->feed ||
c->stream->feed == c->stream)
src = c->stream->streams[i];
else
src = c->stream->feed->streams[c->stream->feed_streams[i]];
unlayer_stream(c->pfmt_ctx->streams[i], src); //TODO we no longer copy st->internal, does this matter?
av_assert0(!c->pfmt_ctx->streams[i]->priv_data);
if (src->codec->flags & AV_CODEC_FLAG_BITEXACT)
c->pfmt_ctx->flags |= AVFMT_FLAG_BITEXACT;
}
/* set output format parameters */
c->pfmt_ctx->oformat = c->stream->fmt;
av_assert0(c->pfmt_ctx->nb_streams == c->stream->nb_streams);
c->got_key_frame = 0;
/* prepare header and save header data in a stream */
if (avio_open_dyn_buf(&c->pfmt_ctx->pb) < 0) {
/* XXX: potential leak */
return -1;
}
c->pfmt_ctx->pb->seekable = 0;
/*
* HACK to avoid MPEG-PS muxer to spit many underflow errors
* Default value from FFmpeg
* Try to set it using configuration option
*/
c->pfmt_ctx->max_delay = (int)(0.7*AV_TIME_BASE);
if ((ret = avformat_write_header(c->pfmt_ctx, NULL)) < 0) {
http_log("Error writing output header for stream '%s': %s\n",
c->stream->filename, av_err2str(ret));
return ret;
}
av_dict_free(&c->pfmt_ctx->metadata);
len = avio_close_dyn_buf(c->pfmt_ctx->pb, &c->pb_buffer);
c->buffer_ptr = c->pb_buffer;
c->buffer_end = c->pb_buffer + len;
c->state = HTTPSTATE_SEND_DATA;
c->last_packet_sent = 0;
break;
case HTTPSTATE_SEND_DATA:
/* find a new packet */
/* read a packet from the input stream */
if (c->stream->feed)
ffm_set_write_index(c->fmt_in,
c->stream->feed->feed_write_index,
c->stream->feed->feed_size);
if (c->stream->max_time &&
c->stream->max_time + c->start_time - cur_time < 0)
/* We have timed out */
c->state = HTTPSTATE_SEND_DATA_TRAILER;
else {
AVPacket pkt;
redo:
ret = av_read_frame(c->fmt_in, &pkt);
if (ret < 0) {
if (c->stream->feed) {
/* if coming from feed, it means we reached the end of the
* ffm file, so must wait for more data */
c->state = HTTPSTATE_WAIT_FEED;
return 1; /* state changed */
}
if (ret == AVERROR(EAGAIN)) {
/* input not ready, come back later */
return 0;
}
if (c->stream->loop) {
avformat_close_input(&c->fmt_in);
if (open_input_stream(c, "") < 0)
goto no_loop;
goto redo;
} else {
no_loop:
/* must send trailer now because EOF or error */
c->state = HTTPSTATE_SEND_DATA_TRAILER;
}
} else {
int source_index = pkt.stream_index;
/* update first pts if needed */
if (c->first_pts == AV_NOPTS_VALUE && pkt.dts != AV_NOPTS_VALUE) {
c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
c->start_time = cur_time;
}
/* send it to the appropriate stream */
if (c->stream->feed) {
/* if coming from a feed, select the right stream */
if (c->switch_pending) {
c->switch_pending = 0;
for(i=0;i<c->stream->nb_streams;i++) {
if (c->switch_feed_streams[i] == pkt.stream_index)
if (pkt.flags & AV_PKT_FLAG_KEY)
c->switch_feed_streams[i] = -1;
if (c->switch_feed_streams[i] >= 0)
c->switch_pending = 1;
}
}
for(i=0;i<c->stream->nb_streams;i++) {
if (c->stream->feed_streams[i] == pkt.stream_index) {
AVStream *st = c->fmt_in->streams[source_index];
pkt.stream_index = i;
if (pkt.flags & AV_PKT_FLAG_KEY &&
(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
c->stream->nb_streams == 1))
c->got_key_frame = 1;
if (!c->stream->send_on_key || c->got_key_frame)
goto send_it;
}
}
} else {
AVStream *ist, *ost;
send_it:
ist = c->fmt_in->streams[source_index];
/* specific handling for RTP: we use several
* output streams (one for each RTP connection).
* XXX: need more abstract handling */
if (c->is_packetized) {
/* compute send time and duration */
if (pkt.dts != AV_NOPTS_VALUE) {
c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
c->cur_pts -= c->first_pts;
}
c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
/* find RTP context */
c->packet_stream_index = pkt.stream_index;
ctx = c->rtp_ctx[c->packet_stream_index];
if(!ctx) {
av_packet_unref(&pkt);
break;
}
/* only one stream per RTP connection */
pkt.stream_index = 0;
} else {
ctx = c->pfmt_ctx;
/* Fudge here */
}
if (c->is_packetized) {
int max_packet_size;
if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
else
max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
ret = ffio_open_dyn_packet_buf(&ctx->pb,
max_packet_size);
} else
ret = avio_open_dyn_buf(&ctx->pb);
if (ret < 0) {
/* XXX: potential leak */
return -1;
}
ost = ctx->streams[pkt.stream_index];
ctx->pb->seekable = 0;
if (pkt.dts != AV_NOPTS_VALUE)
pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
ost->time_base);
if (pkt.pts != AV_NOPTS_VALUE)
pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
ost->time_base);
pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
ost->time_base);
if ((ret = av_write_frame(ctx, &pkt)) < 0) {
http_log("Error writing frame to output for stream '%s': %s\n",
c->stream->filename, av_err2str(ret));
c->state = HTTPSTATE_SEND_DATA_TRAILER;
}
av_freep(&c->pb_buffer);
len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
ctx->pb = NULL;
c->cur_frame_bytes = len;
c->buffer_ptr = c->pb_buffer;
c->buffer_end = c->pb_buffer + len;
if (len == 0) {
av_packet_unref(&pkt);
goto redo;
}
}
av_packet_unref(&pkt);
}
}
break;
default:
case HTTPSTATE_SEND_DATA_TRAILER:
/* last packet test ? */
if (c->last_packet_sent || c->is_packetized)
return -1;
ctx = c->pfmt_ctx;
/* prepare header */
if (avio_open_dyn_buf(&ctx->pb) < 0) {
/* XXX: potential leak */
return -1;
}
c->pfmt_ctx->pb->seekable = 0;
av_write_trailer(ctx);
len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
c->buffer_ptr = c->pb_buffer;
c->buffer_end = c->pb_buffer + len;
c->last_packet_sent = 1;
break;
}
return 0;
}
/* should convert the format at the same time */
/* send data starting at c->buffer_ptr to the output connection
* (either UDP or TCP)
*/
static int http_send_data(HTTPContext *c)
{
int len, ret;
for(;;) {
if (c->buffer_ptr >= c->buffer_end) {
ret = http_prepare_data(c);
if (ret < 0)
return -1;
else if (ret)
/* state change requested */
break;
} else {
if (c->is_packetized) {
/* RTP data output */
len = c->buffer_end - c->buffer_ptr;
if (len < 4) {
/* fail safe - should never happen */
fail1:
c->buffer_ptr = c->buffer_end;
return 0;
}
len = (c->buffer_ptr[0] << 24) |
(c->buffer_ptr[1] << 16) |
(c->buffer_ptr[2] << 8) |
(c->buffer_ptr[3]);
if (len > (c->buffer_end - c->buffer_ptr))
goto fail1;
if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
/* nothing to send yet: we can wait */
return 0;
}
c->data_count += len;
update_datarate(&c->datarate, c->data_count);
if (c->stream)
c->stream->bytes_served += len;
if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
/* RTP packets are sent inside the RTSP TCP connection */
AVIOContext *pb;
int interleaved_index, size;
uint8_t header[4];
HTTPContext *rtsp_c;
rtsp_c = c->rtsp_c;
/* if no RTSP connection left, error */
if (!rtsp_c)
return -1;
/* if already sending something, then wait. */
if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
break;
if (avio_open_dyn_buf(&pb) < 0)
goto fail1;
interleaved_index = c->packet_stream_index * 2;
/* RTCP packets are sent at odd indexes */
if (c->buffer_ptr[1] == 200)
interleaved_index++;
/* write RTSP TCP header */
header[0] = '$';
header[1] = interleaved_index;
header[2] = len >> 8;
header[3] = len;
avio_write(pb, header, 4);
/* write RTP packet data */
c->buffer_ptr += 4;
avio_write(pb, c->buffer_ptr, len);
size = avio_close_dyn_buf(pb, &c->packet_buffer);
/* prepare asynchronous TCP sending */
rtsp_c->packet_buffer_ptr = c->packet_buffer;
rtsp_c->packet_buffer_end = c->packet_buffer + size;
c->buffer_ptr += len;
/* send everything we can NOW */
len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
if (len > 0)
rtsp_c->packet_buffer_ptr += len;
if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
/* if we could not send all the data, we will
* send it later, so a new state is needed to
* "lock" the RTSP TCP connection */
rtsp_c->state = RTSPSTATE_SEND_PACKET;
break;
} else
/* all data has been sent */
av_freep(&c->packet_buffer);
} else {
/* send RTP packet directly in UDP */
c->buffer_ptr += 4;
ffurl_write(c->rtp_handles[c->packet_stream_index],
c->buffer_ptr, len);
c->buffer_ptr += len;
/* here we continue as we can send several packets
* per 10 ms slot */
}
} else {
/* TCP data output */
len = send(c->fd, c->buffer_ptr,
c->buffer_end - c->buffer_ptr, 0);
if (len < 0) {
if (ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR))
/* error : close connection */
return -1;
else
return 0;
}
c->buffer_ptr += len;
c->data_count += len;
update_datarate(&c->datarate, c->data_count);
if (c->stream)
c->stream->bytes_served += len;
break;
}
}
} /* for(;;) */
return 0;
}
static int http_start_receive_data(HTTPContext *c)
{
int fd;
int ret;
int64_t ret64;
if (c->stream->feed_opened) {
http_log("Stream feed '%s' was not opened\n",
c->stream->feed_filename);
return AVERROR(EINVAL);
}
/* Don't permit writing to this one */
if (c->stream->readonly) {
http_log("Cannot write to read-only file '%s'\n",
c->stream->feed_filename);
return AVERROR(EINVAL);
}
/* open feed */
fd = open(c->stream->feed_filename, O_RDWR);
if (fd < 0) {
ret = AVERROR(errno);
http_log("Could not open feed file '%s': %s\n",
c->stream->feed_filename, strerror(errno));
return ret;
}
c->feed_fd = fd;
if (c->stream->truncate) {
/* truncate feed file */
ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
ret = AVERROR(errno);
http_log("Error truncating feed file '%s': %s\n",
c->stream->feed_filename, strerror(errno));
return ret;
}
} else {
ret64 = ffm_read_write_index(fd);
if (ret64 < 0) {
http_log("Error reading write index from feed file '%s': %s\n",
c->stream->feed_filename, strerror(errno));
return ret64;
}
c->stream->feed_write_index = ret64;
}
c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
FFM_PACKET_SIZE);
c->stream->feed_size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
/* init buffer input */
c->buffer_ptr = c->buffer;
c->buffer_end = c->buffer + FFM_PACKET_SIZE;
c->stream->feed_opened = 1;
c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
return 0;
}
static int http_receive_data(HTTPContext *c)
{
HTTPContext *c1;
int len, loop_run = 0;
while (c->chunked_encoding && !c->chunk_size &&
c->buffer_end > c->buffer_ptr) {
/* read chunk header, if present */
len = recv(c->fd, c->buffer_ptr, 1, 0);
if (len < 0) {
if (ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR))
/* error : close connection */
goto fail;
return 0;
} else if (len == 0) {
/* end of connection : close it */
goto fail;
} else if (c->buffer_ptr - c->buffer >= 2 &&
!memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
c->chunk_size = strtol(c->buffer, 0, 16);
if (c->chunk_size <= 0) { // end of stream or invalid chunk size
c->chunk_size = 0;
goto fail;
}
c->buffer_ptr = c->buffer;
break;
} else if (++loop_run > 10)
/* no chunk header, abort */
goto fail;
else
c->buffer_ptr++;
}
if (c->buffer_end > c->buffer_ptr) {
len = recv(c->fd, c->buffer_ptr,
FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
if (len < 0) {
if (ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR))
/* error : close connection */
goto fail;
} else if (len == 0)
/* end of connection : close it */
goto fail;
else {
av_assert0(len <= c->chunk_size);
c->chunk_size -= len;
c->buffer_ptr += len;
c->data_count += len;
update_datarate(&c->datarate, c->data_count);
}
}
if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
if (c->buffer[0] != 'f' ||
c->buffer[1] != 'm') {
http_log("Feed stream has become desynchronized -- disconnecting\n");
goto fail;
}
}
if (c->buffer_ptr >= c->buffer_end) {
FFServerStream *feed = c->stream;
/* a packet has been received : write it in the store, except
* if header */
if (c->data_count > FFM_PACKET_SIZE) {
/* XXX: use llseek or url_seek
* XXX: Should probably fail? */
if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
http_log("Error writing to feed file: %s\n", strerror(errno));
goto fail;
}
feed->feed_write_index += FFM_PACKET_SIZE;
/* update file size */
if (feed->feed_write_index > c->stream->feed_size)
feed->feed_size = feed->feed_write_index;
/* handle wrap around if max file size reached */
if (c->stream->feed_max_size &&
feed->feed_write_index >= c->stream->feed_max_size)
feed->feed_write_index = FFM_PACKET_SIZE;
/* write index */
if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
http_log("Error writing index to feed file: %s\n",
strerror(errno));
goto fail;
}
/* wake up any waiting connections */
for(c1 = first_http_ctx; c1; c1 = c1->next) {
if (c1->state == HTTPSTATE_WAIT_FEED &&
c1->stream->feed == c->stream->feed)
c1->state = HTTPSTATE_SEND_DATA;
}
} else {
/* We have a header in our hands that contains useful data */
AVFormatContext *s = avformat_alloc_context();
AVIOContext *pb;
AVInputFormat *fmt_in;
int i;
if (!s)
goto fail;
/* use feed output format name to find corresponding input format */
fmt_in = av_find_input_format(feed->fmt->name);
if (!fmt_in)
goto fail;
pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
0, NULL, NULL, NULL, NULL);
if (!pb)
goto fail;
pb->seekable = 0;
s->pb = pb;
if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
av_freep(&pb);
goto fail;
}
/* Now we have the actual streams */
if (s->nb_streams != feed->nb_streams) {
avformat_close_input(&s);
av_freep(&pb);
http_log("Feed '%s' stream number does not match registered feed\n",
c->stream->feed_filename);
goto fail;
}
for (i = 0; i < s->nb_streams; i++) {
LayeredAVStream *fst = feed->streams[i];
AVStream *st = s->streams[i];
avcodec_parameters_to_context(fst->codec, st->codecpar);
avcodec_parameters_from_context(fst->codecpar, fst->codec);
}
avformat_close_input(&s);
av_freep(&pb);
}
c->buffer_ptr = c->buffer;
}
return 0;
fail:
c->stream->feed_opened = 0;
close(c->feed_fd);
/* wake up any waiting connections to stop waiting for feed */
for(c1 = first_http_ctx; c1; c1 = c1->next) {
if (c1->state == HTTPSTATE_WAIT_FEED &&
c1->stream->feed == c->stream->feed)
c1->state = HTTPSTATE_SEND_DATA_TRAILER;
}
return -1;
}
/********************************************************************/
/* RTSP handling */
static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
{
const char *str;
time_t ti;
struct tm *tm;
char buf2[32];
str = RTSP_STATUS_CODE2STRING(error_number);
if (!str)
str = "Unknown Error";
avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
/* output GMT time */
ti = time(NULL);
tm = gmtime(&ti);
strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
}
static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
{
rtsp_reply_header(c, error_number);
avio_printf(c->pb, "\r\n");
}
static int rtsp_parse_request(HTTPContext *c)
{
const char *p, *p1, *p2;
char cmd[32];
char url[1024];
char protocol[32];
char line[1024];
int len;
RTSPMessageHeader header1 = { 0 }, *header = &header1;
c->buffer_ptr[0] = '\0';
p = c->buffer;
get_word(cmd, sizeof(cmd), &p);
get_word(url, sizeof(url), &p);
get_word(protocol, sizeof(protocol), &p);
av_strlcpy(c->method, cmd, sizeof(c->method));
av_strlcpy(c->url, url, sizeof(c->url));
av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
if (avio_open_dyn_buf(&c->pb) < 0) {
/* XXX: cannot do more */
c->pb = NULL; /* safety */
return -1;
}
/* check version name */
if (strcmp(protocol, "RTSP/1.0")) {
rtsp_reply_error(c, RTSP_STATUS_VERSION);
goto the_end;
}
/* parse each header line */
/* skip to next line */
while (*p != '\n' && *p != '\0')
p++;
if (*p == '\n')
p++;
while (*p != '\0') {
p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
if (!p1)
break;
p2 = p1;
if (p2 > p && p2[-1] == '\r')
p2--;
/* skip empty line */
if (p2 == p)
break;
len = p2 - p;
if (len > sizeof(line) - 1)
len = sizeof(line) - 1;
memcpy(line, p, len);
line[len] = '\0';
ff_rtsp_parse_line(NULL, header, line, NULL, NULL);
p = p1 + 1;
}
/* handle sequence number */
c->seq = header->seq;
if (!strcmp(cmd, "DESCRIBE"))
rtsp_cmd_describe(c, url);
else if (!strcmp(cmd, "OPTIONS"))
rtsp_cmd_options(c, url);
else if (!strcmp(cmd, "SETUP"))
rtsp_cmd_setup(c, url, header);
else if (!strcmp(cmd, "PLAY"))
rtsp_cmd_play(c, url, header);
else if (!strcmp(cmd, "PAUSE"))
rtsp_cmd_interrupt(c, url, header, 1);
else if (!strcmp(cmd, "TEARDOWN"))
rtsp_cmd_interrupt(c, url, header, 0);
else
rtsp_reply_error(c, RTSP_STATUS_METHOD);
the_end:
len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
c->pb = NULL; /* safety */
if (len < 0)
/* XXX: cannot do more */
return -1;
c->buffer_ptr = c->pb_buffer;
c->buffer_end = c->pb_buffer + len;
c->state = RTSPSTATE_SEND_REPLY;
return 0;
}
static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
struct in_addr my_ip)
{
AVFormatContext *avc;
AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
int i;
*pbuffer = NULL;
avc = avformat_alloc_context();
if (!avc || !rtp_format)
return -1;
avc->oformat = rtp_format;
av_dict_set(&avc->metadata, "title",
entry ? entry->value : "No Title", 0);
if (stream->is_multicast) {
snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
inet_ntoa(stream->multicast_ip),
stream->multicast_port, stream->multicast_ttl);
} else
snprintf(avc->filename, 1024, "rtp://0.0.0.0");
for(i = 0; i < stream->nb_streams; i++) {
AVStream *st = avformat_new_stream(avc, NULL);
if (!st)
goto sdp_done;
avcodec_parameters_from_context(stream->streams[i]->codecpar, stream->streams[i]->codec);
unlayer_stream(st, stream->streams[i]);
}
#define PBUFFER_SIZE 2048
*pbuffer = av_mallocz(PBUFFER_SIZE);
if (!*pbuffer)
goto sdp_done;
av_sdp_create(&avc, 1, *pbuffer, PBUFFER_SIZE);
sdp_done:
av_freep(&avc->streams);
av_dict_free(&avc->metadata);
av_free(avc);
return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
}
static void rtsp_cmd_options(HTTPContext *c, const char *url)
{
/* rtsp_reply_header(c, RTSP_STATUS_OK); */
avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
avio_printf(c->pb, "Public: %s\r\n",
"OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
avio_printf(c->pb, "\r\n");
}
static void rtsp_cmd_describe(HTTPContext *c, const char *url)
{
FFServerStream *stream;
char path1[1024];
const char *path;
uint8_t *content;
int content_length;
socklen_t len;
struct sockaddr_in my_addr;
/* find which URL is asked */
av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
path = path1;
if (*path == '/')
path++;
for(stream = config.first_stream; stream; stream = stream->next) {
if (!stream->is_feed &&
stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
!strcmp(path, stream->filename)) {
goto found;
}
}
/* no stream found */
rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
return;
found:
/* prepare the media description in SDP format */
/* get the host IP */
len = sizeof(my_addr);
getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
content_length = prepare_sdp_description(stream, &content,
my_addr.sin_addr);
if (content_length < 0) {
rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
return;
}
rtsp_reply_header(c, RTSP_STATUS_OK);
avio_printf(c->pb, "Content-Base: %s/\r\n", url);
avio_printf(c->pb, "Content-Type: application/sdp\r\n");
avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
avio_printf(c->pb, "\r\n");
avio_write(c->pb, content, content_length);
av_free(content);
}
static HTTPContext *find_rtp_session(const char *session_id)
{
HTTPContext *c;
if (session_id[0] == '\0')
return NULL;
for(c = first_http_ctx; c; c = c->next) {
if (!strcmp(c->session_id, session_id))
return c;
}
return NULL;
}
static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
{
RTSPTransportField *th;
int i;
for(i=0;i<h->nb_transports;i++) {
th = &h->transports[i];
if (th->lower_transport == lower_transport)
return th;
}
return NULL;
}
static void rtsp_cmd_setup(HTTPContext *c, const char *url,
RTSPMessageHeader *h)
{
FFServerStream *stream;
int stream_index, rtp_port, rtcp_port;
char buf[1024];
char path1[1024];
const char *path;
HTTPContext *rtp_c;
RTSPTransportField *th;
struct sockaddr_in dest_addr;
RTSPActionServerSetup setup;
/* find which URL is asked */
av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
path = path1;
if (*path == '/')
path++;
/* now check each stream */
for(stream = config.first_stream; stream; stream = stream->next) {
if (stream->is_feed || !stream->fmt ||
strcmp(stream->fmt->name, "rtp")) {
continue;
}
/* accept aggregate filenames only if single stream */
if (!strcmp(path, stream->filename)) {
if (stream->nb_streams != 1) {
rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
return;
}
stream_index = 0;
goto found;
}
for(stream_index = 0; stream_index < stream->nb_streams;
stream_index++) {
snprintf(buf, sizeof(buf), "%s/streamid=%d",
stream->filename, stream_index);
if (!strcmp(path, buf))
goto found;
}
}
/* no stream found */
rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
return;
found:
/* generate session id if needed */
if (h->session_id[0] == '\0') {
unsigned random0 = av_lfg_get(&random_state);
unsigned random1 = av_lfg_get(&random_state);
snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
random0, random1);
}
/* find RTP session, and create it if none found */
rtp_c = find_rtp_session(h->session_id);
if (!rtp_c) {
/* always prefer UDP */
th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
if (!th) {
th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
if (!th) {
rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
return;
}
}
rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
th->lower_transport);
if (!rtp_c) {
rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
return;
}
/* open input stream */
if (open_input_stream(rtp_c, "") < 0) {
rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
return;
}
}
/* test if stream is OK (test needed because several SETUP needs
* to be done for a given file) */
if (rtp_c->stream != stream) {
rtsp_reply_error(c, RTSP_STATUS_SERVICE);
return;
}
/* test if stream is already set up */
if (rtp_c->rtp_ctx[stream_index]) {
rtsp_reply_error(c, RTSP_STATUS_STATE);
return;
}
/* check transport */
th = find_transport(h, rtp_c->rtp_protocol);
if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
th->client_port_min <= 0)) {
rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
return;
}
/* setup default options */
setup.transport_option[0] = '\0';
dest_addr = rtp_c->from_addr;
dest_addr.sin_port = htons(th->client_port_min);
/* setup stream */
if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
return;
}
/* now everything is OK, so we can send the connection parameters */
rtsp_reply_header(c, RTSP_STATUS_OK);
/* session ID */
avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
switch(rtp_c->rtp_protocol) {
case RTSP_LOWER_TRANSPORT_UDP:
rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
"client_port=%d-%d;server_port=%d-%d",
th->client_port_min, th->client_port_max,
rtp_port, rtcp_port);
break;
case RTSP_LOWER_TRANSPORT_TCP:
avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
stream_index * 2, stream_index * 2 + 1);
break;
default:
break;
}
if (setup.transport_option[0] != '\0')
avio_printf(c->pb, ";%s", setup.transport_option);
avio_printf(c->pb, "\r\n");
avio_printf(c->pb, "\r\n");
}
/**
* find an RTP connection by using the session ID. Check consistency
* with filename
*/
static HTTPContext *find_rtp_session_with_url(const char *url,
const char *session_id)
{
HTTPContext *rtp_c;
char path1[1024];
const char *path;
char buf[1024];
int s, len;
rtp_c = find_rtp_session(session_id);
if (!rtp_c)
return NULL;
/* find which URL is asked */
av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
path = path1;
if (*path == '/')
path++;
if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
for(s=0; s<rtp_c->stream->nb_streams; ++s) {
snprintf(buf, sizeof(buf), "%s/streamid=%d",
rtp_c->stream->filename, s);
if(!strncmp(path, buf, sizeof(buf)))
/* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
* if nb_streams>1? */
return rtp_c;
}
len = strlen(path);
if (len > 0 && path[len - 1] == '/' &&
!strncmp(path, rtp_c->stream->filename, len - 1))
return rtp_c;
return NULL;
}
static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
{
HTTPContext *rtp_c;
rtp_c = find_rtp_session_with_url(url, h->session_id);
if (!rtp_c) {
rtsp_reply_error(c, RTSP_STATUS_SESSION);
return;
}
if (rtp_c->state != HTTPSTATE_SEND_DATA &&
rtp_c->state != HTTPSTATE_WAIT_FEED &&
rtp_c->state != HTTPSTATE_READY) {
rtsp_reply_error(c, RTSP_STATUS_STATE);
return;
}
rtp_c->state = HTTPSTATE_SEND_DATA;
/* now everything is OK, so we can send the connection parameters */
rtsp_reply_header(c, RTSP_STATUS_OK);
/* session ID */
avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
avio_printf(c->pb, "\r\n");
}
static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
RTSPMessageHeader *h, int pause_only)
{
HTTPContext *rtp_c;
rtp_c = find_rtp_session_with_url(url, h->session_id);
if (!rtp_c) {
rtsp_reply_error(c, RTSP_STATUS_SESSION);
return;
}
if (pause_only) {
if (rtp_c->state != HTTPSTATE_SEND_DATA &&
rtp_c->state != HTTPSTATE_WAIT_FEED) {
rtsp_reply_error(c, RTSP_STATUS_STATE);
return;
}
rtp_c->state = HTTPSTATE_READY;
rtp_c->first_pts = AV_NOPTS_VALUE;
}
/* now everything is OK, so we can send the connection parameters */
rtsp_reply_header(c, RTSP_STATUS_OK);
/* session ID */
avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
avio_printf(c->pb, "\r\n");
if (!pause_only)
close_connection(rtp_c);
}
/********************************************************************/
/* RTP handling */
static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
FFServerStream *stream,
const char *session_id,
enum RTSPLowerTransport rtp_protocol)
{
HTTPContext *c = NULL;
const char *proto_str;
/* XXX: should output a warning page when coming
* close to the connection limit */
if (nb_connections >= config.nb_max_connections)
goto fail;
/* add a new connection */
c = av_mallocz(sizeof(HTTPContext));
if (!c)
goto fail;
c->fd = -1;
c->poll_entry = NULL;
c->from_addr = *from_addr;
c->buffer_size = IOBUFFER_INIT_SIZE;
c->buffer = av_malloc(c->buffer_size);
if (!c->buffer)
goto fail;
nb_connections++;
c->stream = stream;
av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
c->state = HTTPSTATE_READY;
c->is_packetized = 1;
c->rtp_protocol = rtp_protocol;
/* protocol is shown in statistics */
switch(c->rtp_protocol) {
case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
proto_str = "MCAST";
break;
case RTSP_LOWER_TRANSPORT_UDP:
proto_str = "UDP";
break;
case RTSP_LOWER_TRANSPORT_TCP:
proto_str = "TCP";
break;
default:
proto_str = "???";
break;
}
av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
current_bandwidth += stream->bandwidth;
c->next = first_http_ctx;
first_http_ctx = c;
return c;
fail:
if (c) {
av_freep(&c->buffer);
av_free(c);
}
return NULL;
}
/**
* add a new RTP stream in an RTP connection (used in RTSP SETUP
* command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
* used.
*/
static int rtp_new_av_stream(HTTPContext *c,
int stream_index, struct sockaddr_in *dest_addr,
HTTPContext *rtsp_c)
{
AVFormatContext *ctx;
AVStream *st;
char *ipaddr;
URLContext *h = NULL;
uint8_t *dummy_buf;
int max_packet_size;
void *st_internal;
/* now we can open the relevant output stream */
ctx = avformat_alloc_context();
if (!ctx)
return -1;
ctx->oformat = av_guess_format("rtp", NULL, NULL);
st = avformat_new_stream(ctx, NULL);
if (!st)
goto fail;
st_internal = st->internal;
if (!c->stream->feed ||
c->stream->feed == c->stream)
unlayer_stream(st, c->stream->streams[stream_index]);
else
unlayer_stream(st,
c->stream->feed->streams[c->stream->feed_streams[stream_index]]);
av_assert0(st->priv_data == NULL);
av_assert0(st->internal == st_internal);
/* build destination RTP address */
ipaddr = inet_ntoa(dest_addr->sin_addr);
switch(c->rtp_protocol) {
case RTSP_LOWER_TRANSPORT_UDP:
case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
/* RTP/UDP case */
/* XXX: also pass as parameter to function ? */
if (c->stream->is_multicast) {
int ttl;
ttl = c->stream->multicast_ttl;
if (!ttl)
ttl = 16;
snprintf(ctx->filename, sizeof(ctx->filename),
"rtp://%s:%d?multicast=1&ttl=%d",
ipaddr, ntohs(dest_addr->sin_port), ttl);
} else {
snprintf(ctx->filename, sizeof(ctx->filename),
"rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
}
if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
goto fail;
c->rtp_handles[stream_index] = h;
max_packet_size = h->max_packet_size;
break;
case RTSP_LOWER_TRANSPORT_TCP:
/* RTP/TCP case */
c->rtsp_c = rtsp_c;
max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
break;
default:
goto fail;
}
http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
ipaddr, ntohs(dest_addr->sin_port),
c->stream->filename, stream_index, c->protocol);
/* normally, no packets should be output here, but the packet size may
* be checked */
if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
/* XXX: close stream */
goto fail;
if (avformat_write_header(ctx, NULL) < 0) {
fail:
if (h)
ffurl_close(h);
av_free(st);
av_free(ctx);
return -1;
}
avio_close_dyn_buf(ctx->pb, &dummy_buf);
ctx->pb = NULL;
av_free(dummy_buf);
c->rtp_ctx[stream_index] = ctx;
return 0;
}
/********************************************************************/
/* ffserver initialization */
/* FIXME: This code should use avformat_new_stream() */
static LayeredAVStream *add_av_stream1(FFServerStream *stream,
AVCodecContext *codec, int copy)
{
LayeredAVStream *fst;
if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
return NULL;
fst = av_mallocz(sizeof(*fst));
if (!fst)
return NULL;
if (copy) {
fst->codec = avcodec_alloc_context3(codec->codec);
if (!fst->codec) {
av_free(fst);
return NULL;
}
avcodec_copy_context(fst->codec, codec);
} else
/* live streams must use the actual feed's codec since it may be
* updated later to carry extradata needed by them.
*/
fst->codec = codec;
//NOTE we previously allocated internal & internal->avctx, these seemed uneeded though
fst->codecpar = avcodec_parameters_alloc();
fst->index = stream->nb_streams;
fst->time_base = codec->time_base;
fst->pts_wrap_bits = 33;
fst->sample_aspect_ratio = codec->sample_aspect_ratio;
stream->streams[stream->nb_streams++] = fst;
return fst;
}
/* return the stream number in the feed */
static int add_av_stream(FFServerStream *feed, LayeredAVStream *st)
{
LayeredAVStream *fst;
AVCodecContext *av, *av1;
int i;
av = st->codec;
for(i=0;i<feed->nb_streams;i++) {
av1 = feed->streams[i]->codec;
if (av1->codec_id == av->codec_id &&
av1->codec_type == av->codec_type &&
av1->bit_rate == av->bit_rate) {
switch(av->codec_type) {
case AVMEDIA_TYPE_AUDIO:
if (av1->channels == av->channels &&
av1->sample_rate == av->sample_rate)
return i;
break;
case AVMEDIA_TYPE_VIDEO:
if (av1->width == av->width &&
av1->height == av->height &&
av1->time_base.den == av->time_base.den &&
av1->time_base.num == av->time_base.num &&
av1->gop_size == av->gop_size)
return i;
break;
default:
abort();
}
}
}
fst = add_av_stream1(feed, av, 0);
if (!fst)
return -1;
if (st->recommended_encoder_configuration)
fst->recommended_encoder_configuration =
av_strdup(st->recommended_encoder_configuration);
return feed->nb_streams - 1;
}
static void remove_stream(FFServerStream *stream)
{
FFServerStream **ps;
ps = &config.first_stream;
while (*ps) {
if (*ps == stream)
*ps = (*ps)->next;
else
ps = &(*ps)->next;
}
}
/* compute the needed AVStream for each file */
static void build_file_streams(void)
{
FFServerStream *stream;
AVFormatContext *infile;
int i, ret;
/* gather all streams */
for(stream = config.first_stream; stream; stream = stream->next) {
infile = NULL;
if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
continue;
/* the stream comes from a file */
/* try to open the file */
/* open stream */
/* specific case: if transport stream output to RTP,
* we use a raw transport stream reader */
if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
if (!stream->feed_filename[0]) {
http_log("Unspecified feed file for stream '%s'\n",
stream->filename);
goto fail;
}
http_log("Opening feed file '%s' for stream '%s'\n",
stream->feed_filename, stream->filename);
ret = avformat_open_input(&infile, stream->feed_filename,
stream->ifmt, &stream->in_opts);
if (ret < 0) {
http_log("Could not open '%s': %s\n", stream->feed_filename,
av_err2str(ret));
/* remove stream (no need to spend more time on it) */
fail:
remove_stream(stream);
} else {
/* find all the AVStreams inside and reference them in
* 'stream' */
if (avformat_find_stream_info(infile, NULL) < 0) {
http_log("Could not find codec parameters from '%s'\n",
stream->feed_filename);
avformat_close_input(&infile);
goto fail;
}
for(i=0;i<infile->nb_streams;i++)
add_av_stream1(stream, infile->streams[i]->codec, 1);
avformat_close_input(&infile);
}
}
}
static inline
int check_codec_match(LayeredAVStream *ccf, AVStream *ccs, int stream)
{
int matches = 1;
/* FIXME: Missed check on AVCodecContext.flags */
#define CHECK_CODEC(x) (ccf->codecpar->x != ccs->codecpar->x)
if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
http_log("Codecs do not match for stream %d\n", stream);
matches = 0;
} else if (CHECK_CODEC(bit_rate)) {
http_log("Codec bitrates do not match for stream %d\n", stream);
matches = 0;
} else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
if (av_cmp_q(ccf->time_base, ccs->time_base) ||
CHECK_CODEC(width) || CHECK_CODEC(height)) {
http_log("Codec width, height or framerate do not match for stream %d\n", stream);
matches = 0;
}
} else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
if (CHECK_CODEC(sample_rate) ||
CHECK_CODEC(channels) ||
CHECK_CODEC(frame_size)) {
http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);
matches = 0;
}
} else {
http_log("Unknown codec type for stream %d\n", stream);
matches = 0;
}
return matches;
}
/* compute the needed AVStream for each feed */
static int build_feed_streams(void)
{
FFServerStream *stream, *feed;
int i, fd;
/* gather all streams */
for(stream = config.first_stream; stream; stream = stream->next) {
feed = stream->feed;
if (!feed)
continue;
if (stream->is_feed) {
for(i=0;i<stream->nb_streams;i++)
stream->feed_streams[i] = i;
continue;
}
/* we handle a stream coming from a feed */
for(i=0;i<stream->nb_streams;i++)
stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
}
/* create feed files if needed */
for(feed = config.first_feed; feed; feed = feed->next_feed) {
if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
AVFormatContext *s = NULL;
int matches = 0;
/* See if it matches */
if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) {
http_log("Deleting feed file '%s' as it appears "
"to be corrupt\n",
feed->feed_filename);
goto drop;
}
/* set buffer size */
if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) {
http_log("Failed to set buffer size\n");
avformat_close_input(&s);
goto bail;
}
/* Now see if it matches */
if (s->nb_streams != feed->nb_streams) {
http_log("Deleting feed file '%s' as stream counts "
"differ (%d != %d)\n",
feed->feed_filename, s->nb_streams, feed->nb_streams);
goto drop;
}
matches = 1;
for(i=0;i<s->nb_streams;i++) {
AVStream *ss;
LayeredAVStream *sf;
sf = feed->streams[i];
ss = s->streams[i];
if (sf->index != ss->index || sf->id != ss->id) {
http_log("Index & Id do not match for stream %d (%s)\n",
i, feed->feed_filename);
matches = 0;
break;
}
matches = check_codec_match (sf, ss, i);
if (!matches)
break;
}
drop:
if (s)
avformat_close_input(&s);
if (!matches) {
if (feed->readonly) {
http_log("Unable to delete read-only feed file '%s'\n",
feed->feed_filename);
goto bail;
}
unlink(feed->feed_filename);
}
}
if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
AVFormatContext *s = avformat_alloc_context();
if (!s) {
http_log("Failed to allocate context\n");
goto bail;
}
if (feed->readonly) {
http_log("Unable to create feed file '%s' as it is "
"marked readonly\n",
feed->feed_filename);
avformat_free_context(s);
goto bail;
}
/* only write the header of the ffm file */
if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
http_log("Could not open output feed file '%s'\n",
feed->feed_filename);
avformat_free_context(s);
goto bail;
}
s->oformat = feed->fmt;
for (i = 0; i<feed->nb_streams; i++) {
AVStream *st = avformat_new_stream(s, NULL); // FIXME free this
if (!st) {
http_log("Failed to allocate stream\n");
goto bail;
}
unlayer_stream(st, feed->streams[i]);
}
if (avformat_write_header(s, NULL) < 0) {
http_log("Container doesn't support the required parameters\n");
avio_closep(&s->pb);
s->streams = NULL;
s->nb_streams = 0;
avformat_free_context(s);
goto bail;
}
/* XXX: need better API */
av_freep(&s->priv_data);
avio_closep(&s->pb);
s->streams = NULL;
s->nb_streams = 0;
avformat_free_context(s);
}
/* get feed size and write index */
fd = open(feed->feed_filename, O_RDONLY);
if (fd < 0) {
http_log("Could not open output feed file '%s'\n",
feed->feed_filename);
goto bail;
}
feed->feed_write_index = FFMAX(ffm_read_write_index(fd),
FFM_PACKET_SIZE);
feed->feed_size = lseek(fd, 0, SEEK_END);
/* ensure that we do not wrap before the end of file */
if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
feed->feed_max_size = feed->feed_size;
close(fd);
}
return 0;
bail:
return -1;
}
/* compute the bandwidth used by each stream */
static void compute_bandwidth(void)
{
unsigned bandwidth;
int i;
FFServerStream *stream;
for(stream = config.first_stream; stream; stream = stream->next) {
bandwidth = 0;
for(i=0;i<stream->nb_streams;i++) {
LayeredAVStream *st = stream->streams[i];
switch(st->codec->codec_type) {
case AVMEDIA_TYPE_AUDIO:
case AVMEDIA_TYPE_VIDEO:
bandwidth += st->codec->bit_rate;
break;
default:
break;
}
}
stream->bandwidth = (bandwidth + 999) / 1000;
}
}
static void handle_child_exit(int sig)
{
pid_t pid;
int status;
time_t uptime;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
FFServerStream *feed;
for (feed = config.first_feed; feed; feed = feed->next) {
if (feed->pid != pid)
continue;
uptime = time(0) - feed->pid_start;
feed->pid = 0;
fprintf(stderr,
"%s: Pid %"PRId64" exited with status %d after %"PRId64" "
"seconds\n",
feed->filename, (int64_t) pid, status, (int64_t)uptime);
if (uptime < 30)
/* Turn off any more restarts */
ffserver_free_child_args(&feed->child_argv);
}
}
need_to_start_children = 1;
}
static void opt_debug(void)
{
config.debug = 1;
snprintf(config.logfilename, sizeof(config.logfilename), "-");
}
void show_help_default(const char *opt, const char *arg)
{
printf("usage: ffserver [options]\n"
"Hyper fast multi format Audio/Video streaming server\n");
printf("\n");
show_help_options(options, "Main options:", 0, 0, 0);
}
static const OptionDef options[] = {
#include "cmdutils_common_opts.h"
{ "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
{ "d", 0, {(void*)opt_debug}, "enable debug mode" },
{ "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
{ NULL },
};
int main(int argc, char **argv)
{
struct sigaction sigact = { { 0 } };
int cfg_parsed;
int ret = EXIT_FAILURE;
init_dynload();
config.filename = av_strdup("/etc/ffserver.conf");
parse_loglevel(argc, argv, options);
av_register_all();
avformat_network_init();
show_banner(argc, argv, options);
my_program_name = argv[0];
parse_options(NULL, argc, argv, options, NULL);
unsetenv("http_proxy"); /* Kill the http_proxy */
av_lfg_init(&random_state, av_get_random_seed());
sigact.sa_handler = handle_child_exit;
sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
sigaction(SIGCHLD, &sigact, 0);
if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
fprintf(stderr, "Error reading configuration file '%s': %s\n",
config.filename, av_err2str(cfg_parsed));
goto bail;
}
/* open log file if needed */
if (config.logfilename[0] != '\0') {
if (!strcmp(config.logfilename, "-"))
logfile = stdout;
else
logfile = fopen(config.logfilename, "a");
av_log_set_callback(http_av_log);
}
build_file_streams();
if (build_feed_streams() < 0) {
http_log("Could not setup feed streams\n");
goto bail;
}
compute_bandwidth();
/* signal init */
signal(SIGPIPE, SIG_IGN);
if (http_server() < 0) {
http_log("Could not start server\n");
goto bail;
}
ret=EXIT_SUCCESS;
bail:
av_freep (&config.filename);
avformat_network_deinit();
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4837_0 |
crossvul-cpp_data_good_5280_0 | /*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| Copyright (c) 1998-2016 Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@zend.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andi Gutmans <andi@zend.com> |
| Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "zend.h"
#include "zend_globals.h"
#include "zend_variables.h"
#include "zend_API.h"
#include "zend_objects_API.h"
#define ZEND_DEBUG_OBJECTS 0
ZEND_API void zend_objects_store_init(zend_objects_store *objects, zend_uint init_size)
{
objects->object_buckets = (zend_object_store_bucket *) emalloc(init_size * sizeof(zend_object_store_bucket));
objects->top = 1; /* Skip 0 so that handles are true */
objects->size = init_size;
objects->free_list_head = -1;
memset(&objects->object_buckets[0], 0, sizeof(zend_object_store_bucket));
}
ZEND_API void zend_objects_store_destroy(zend_objects_store *objects)
{
efree(objects->object_buckets);
objects->object_buckets = NULL;
}
ZEND_API void zend_objects_store_call_destructors(zend_objects_store *objects TSRMLS_DC)
{
zend_uint i = 1;
for (i = 1; i < objects->top ; i++) {
if (objects->object_buckets[i].valid) {
struct _store_object *obj = &objects->object_buckets[i].bucket.obj;
if (!objects->object_buckets[i].destructor_called) {
objects->object_buckets[i].destructor_called = 1;
if (obj->dtor && obj->object) {
obj->refcount++;
obj->dtor(obj->object, i TSRMLS_CC);
obj = &objects->object_buckets[i].bucket.obj;
obj->refcount--;
if (obj->refcount == 0) {
/* in case gc_collect_cycle is triggered before free_storage */
GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
}
}
}
}
}
}
ZEND_API void zend_objects_store_mark_destructed(zend_objects_store *objects TSRMLS_DC)
{
zend_uint i;
if (!objects->object_buckets) {
return;
}
for (i = 1; i < objects->top ; i++) {
if (objects->object_buckets[i].valid) {
objects->object_buckets[i].destructor_called = 1;
}
}
}
ZEND_API void zend_objects_store_free_object_storage(zend_objects_store *objects TSRMLS_DC)
{
zend_uint i = 1;
for (i = 1; i < objects->top ; i++) {
if (objects->object_buckets[i].valid) {
struct _store_object *obj = &objects->object_buckets[i].bucket.obj;
GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
objects->object_buckets[i].valid = 0;
if (obj->free_storage) {
obj->free_storage(obj->object TSRMLS_CC);
}
/* Not adding to free list as we are shutting down anyway */
}
}
}
/* Store objects API */
ZEND_API zend_object_handle zend_objects_store_put(void *object, zend_objects_store_dtor_t dtor, zend_objects_free_object_storage_t free_storage, zend_objects_store_clone_t clone TSRMLS_DC)
{
zend_object_handle handle;
struct _store_object *obj;
if (EG(objects_store).free_list_head != -1) {
handle = EG(objects_store).free_list_head;
EG(objects_store).free_list_head = EG(objects_store).object_buckets[handle].bucket.free_list.next;
} else {
if (EG(objects_store).top == EG(objects_store).size) {
EG(objects_store).size <<= 1;
EG(objects_store).object_buckets = (zend_object_store_bucket *) erealloc(EG(objects_store).object_buckets, EG(objects_store).size * sizeof(zend_object_store_bucket));
}
handle = EG(objects_store).top++;
}
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
EG(objects_store).object_buckets[handle].destructor_called = 0;
EG(objects_store).object_buckets[handle].valid = 1;
EG(objects_store).object_buckets[handle].apply_count = 0;
obj->refcount = 1;
GC_OBJ_INIT(obj);
obj->object = object;
obj->dtor = dtor?dtor:(zend_objects_store_dtor_t)zend_objects_destroy_object;
obj->free_storage = free_storage;
obj->clone = clone;
obj->handlers = NULL;
#if ZEND_DEBUG_OBJECTS
fprintf(stderr, "Allocated object id #%d\n", handle);
#endif
return handle;
}
ZEND_API zend_uint zend_objects_store_get_refcount(zval *object TSRMLS_DC)
{
zend_object_handle handle = Z_OBJ_HANDLE_P(object);
return EG(objects_store).object_buckets[handle].bucket.obj.refcount;
}
ZEND_API void zend_objects_store_add_ref(zval *object TSRMLS_DC)
{
zend_object_handle handle = Z_OBJ_HANDLE_P(object);
EG(objects_store).object_buckets[handle].bucket.obj.refcount++;
#if ZEND_DEBUG_OBJECTS
fprintf(stderr, "Increased refcount of object id #%d\n", handle);
#endif
}
/*
* Add a reference to an objects store entry given the object handle.
*/
ZEND_API void zend_objects_store_add_ref_by_handle(zend_object_handle handle TSRMLS_DC)
{
EG(objects_store).object_buckets[handle].bucket.obj.refcount++;
}
#define ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST() \
EG(objects_store).object_buckets[handle].bucket.free_list.next = EG(objects_store).free_list_head; \
EG(objects_store).free_list_head = handle; \
EG(objects_store).object_buckets[handle].valid = 0;
ZEND_API void zend_objects_store_del_ref(zval *zobject TSRMLS_DC)
{
zend_object_handle handle;
handle = Z_OBJ_HANDLE_P(zobject);
Z_ADDREF_P(zobject);
zend_objects_store_del_ref_by_handle_ex(handle, Z_OBJ_HT_P(zobject) TSRMLS_CC);
Z_DELREF_P(zobject);
GC_ZOBJ_CHECK_POSSIBLE_ROOT(zobject);
}
/*
* Delete a reference to an objects store entry given the object handle.
*/
ZEND_API void zend_objects_store_del_ref_by_handle_ex(zend_object_handle handle, const zend_object_handlers *handlers TSRMLS_DC) /* {{{ */
{
struct _store_object *obj;
int failure = 0;
if (!EG(objects_store).object_buckets) {
return;
}
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
/* Make sure we hold a reference count during the destructor call
otherwise, when the destructor ends the storage might be freed
when the refcount reaches 0 a second time
*/
if (EG(objects_store).object_buckets[handle].valid) {
if (obj->refcount == 1) {
if (!EG(objects_store).object_buckets[handle].destructor_called) {
EG(objects_store).object_buckets[handle].destructor_called = 1;
if (obj->dtor) {
if (handlers && !obj->handlers) {
obj->handlers = handlers;
}
zend_try {
obj->dtor(obj->object, handle TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
}
/* re-read the object from the object store as the store might have been reallocated in the dtor */
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
if (obj->refcount == 1) {
GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
if (obj->free_storage) {
zend_try {
obj->free_storage(obj->object TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST();
}
}
}
obj->refcount--;
#if ZEND_DEBUG_OBJECTS
if (obj->refcount == 0) {
fprintf(stderr, "Deallocated object id #%d\n", handle);
} else {
fprintf(stderr, "Decreased refcount of object id #%d\n", handle);
}
#endif
if (failure) {
zend_bailout();
}
}
/* }}} */
ZEND_API zend_object_value zend_objects_store_clone_obj(zval *zobject TSRMLS_DC)
{
zend_object_value retval;
void *new_object;
struct _store_object *obj;
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
if (obj->clone == NULL) {
zend_error(E_CORE_ERROR, "Trying to clone uncloneable object of class %s", Z_OBJCE_P(zobject)->name);
}
obj->clone(obj->object, &new_object TSRMLS_CC);
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
retval.handle = zend_objects_store_put(new_object, obj->dtor, obj->free_storage, obj->clone TSRMLS_CC);
retval.handlers = Z_OBJ_HT_P(zobject);
EG(objects_store).object_buckets[handle].bucket.obj.handlers = retval.handlers;
return retval;
}
ZEND_API void *zend_object_store_get_object(const zval *zobject TSRMLS_DC)
{
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
return EG(objects_store).object_buckets[handle].bucket.obj.object;
}
/*
* Retrieve an entry from the objects store given the object handle.
*/
ZEND_API void *zend_object_store_get_object_by_handle(zend_object_handle handle TSRMLS_DC)
{
return EG(objects_store).object_buckets[handle].bucket.obj.object;
}
/* zend_object_store_set_object:
* It is ONLY valid to call this function from within the constructor of an
* overloaded object. Its purpose is to set the object pointer for the object
* when you can't possibly know its value until you have parsed the arguments
* from the constructor function. You MUST NOT use this function for any other
* weird games, or call it at any other time after the object is constructed.
* */
ZEND_API void zend_object_store_set_object(zval *zobject, void *object TSRMLS_DC)
{
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
EG(objects_store).object_buckets[handle].bucket.obj.object = object;
}
/* Called when the ctor was terminated by an exception */
ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC)
{
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
zend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle];
obj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject);
obj_bucket->destructor_called = 1;
}
/* Proxy objects workings */
typedef struct _zend_proxy_object {
zval *object;
zval *property;
} zend_proxy_object;
static zend_object_handlers zend_object_proxy_handlers;
ZEND_API void zend_objects_proxy_destroy(zend_object *object, zend_object_handle handle TSRMLS_DC)
{
}
ZEND_API void zend_objects_proxy_free_storage(zend_proxy_object *object TSRMLS_DC)
{
zval_ptr_dtor(&object->object);
zval_ptr_dtor(&object->property);
efree(object);
}
ZEND_API void zend_objects_proxy_clone(zend_proxy_object *object, zend_proxy_object **object_clone TSRMLS_DC)
{
*object_clone = emalloc(sizeof(zend_proxy_object));
(*object_clone)->object = object->object;
(*object_clone)->property = object->property;
zval_add_ref(&(*object_clone)->property);
zval_add_ref(&(*object_clone)->object);
}
ZEND_API zval *zend_object_create_proxy(zval *object, zval *member TSRMLS_DC)
{
zend_proxy_object *pobj = emalloc(sizeof(zend_proxy_object));
zval *retval;
pobj->object = object;
zval_add_ref(&pobj->object);
ALLOC_ZVAL(pobj->property);
INIT_PZVAL_COPY(pobj->property, member);
zval_copy_ctor(pobj->property);
MAKE_STD_ZVAL(retval);
Z_TYPE_P(retval) = IS_OBJECT;
Z_OBJ_HANDLE_P(retval) = zend_objects_store_put(pobj, (zend_objects_store_dtor_t)zend_objects_proxy_destroy, (zend_objects_free_object_storage_t) zend_objects_proxy_free_storage, (zend_objects_store_clone_t) zend_objects_proxy_clone TSRMLS_CC);
Z_OBJ_HT_P(retval) = &zend_object_proxy_handlers;
return retval;
}
ZEND_API void zend_object_proxy_set(zval **property, zval *value TSRMLS_DC)
{
zend_proxy_object *probj = zend_object_store_get_object(*property TSRMLS_CC);
if (Z_OBJ_HT_P(probj->object) && Z_OBJ_HT_P(probj->object)->write_property) {
Z_OBJ_HT_P(probj->object)->write_property(probj->object, probj->property, value, 0 TSRMLS_CC);
} else {
zend_error(E_WARNING, "Cannot write property of object - no write handler defined");
}
}
ZEND_API zval* zend_object_proxy_get(zval *property TSRMLS_DC)
{
zend_proxy_object *probj = zend_object_store_get_object(property TSRMLS_CC);
if (Z_OBJ_HT_P(probj->object) && Z_OBJ_HT_P(probj->object)->read_property) {
return Z_OBJ_HT_P(probj->object)->read_property(probj->object, probj->property, BP_VAR_R, 0 TSRMLS_CC);
} else {
zend_error(E_WARNING, "Cannot read property of object - no read handler defined");
}
return NULL;
}
ZEND_API zend_object_handlers *zend_get_std_object_handlers(void)
{
return &std_object_handlers;
}
static zend_object_handlers zend_object_proxy_handlers = {
ZEND_OBJECTS_STORE_HANDLERS,
NULL, /* read_property */
NULL, /* write_property */
NULL, /* read dimension */
NULL, /* write_dimension */
NULL, /* get_property_ptr_ptr */
zend_object_proxy_get, /* get */
zend_object_proxy_set, /* set */
NULL, /* has_property */
NULL, /* unset_property */
NULL, /* has_dimension */
NULL, /* unset_dimension */
NULL, /* get_properties */
NULL, /* get_method */
NULL, /* call_method */
NULL, /* get_constructor */
NULL, /* get_class_entry */
NULL, /* get_class_name */
NULL, /* compare_objects */
NULL, /* cast_object */
NULL, /* count_elements */
};
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* indent-tabs-mode: t
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5280_0 |
crossvul-cpp_data_bad_3476_0 | /*
* This is the new netlink-based wireless configuration interface.
*
* Copyright 2006-2010 Johannes Berg <johannes@sipsolutions.net>
*/
#include <linux/if.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/if_ether.h>
#include <linux/ieee80211.h>
#include <linux/nl80211.h>
#include <linux/rtnetlink.h>
#include <linux/netlink.h>
#include <linux/etherdevice.h>
#include <net/net_namespace.h>
#include <net/genetlink.h>
#include <net/cfg80211.h>
#include <net/sock.h>
#include "core.h"
#include "nl80211.h"
#include "reg.h"
static int nl80211_pre_doit(struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info);
static void nl80211_post_doit(struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info);
/* the netlink family */
static struct genl_family nl80211_fam = {
.id = GENL_ID_GENERATE, /* don't bother with a hardcoded ID */
.name = "nl80211", /* have users key off the name instead */
.hdrsize = 0, /* no private header */
.version = 1, /* no particular meaning now */
.maxattr = NL80211_ATTR_MAX,
.netnsok = true,
.pre_doit = nl80211_pre_doit,
.post_doit = nl80211_post_doit,
};
/* internal helper: get rdev and dev */
static int get_rdev_dev_by_info_ifindex(struct genl_info *info,
struct cfg80211_registered_device **rdev,
struct net_device **dev)
{
struct nlattr **attrs = info->attrs;
int ifindex;
if (!attrs[NL80211_ATTR_IFINDEX])
return -EINVAL;
ifindex = nla_get_u32(attrs[NL80211_ATTR_IFINDEX]);
*dev = dev_get_by_index(genl_info_net(info), ifindex);
if (!*dev)
return -ENODEV;
*rdev = cfg80211_get_dev_from_ifindex(genl_info_net(info), ifindex);
if (IS_ERR(*rdev)) {
dev_put(*dev);
return PTR_ERR(*rdev);
}
return 0;
}
/* policy for the attributes */
static const struct nla_policy nl80211_policy[NL80211_ATTR_MAX+1] = {
[NL80211_ATTR_WIPHY] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_NAME] = { .type = NLA_NUL_STRING,
.len = 20-1 },
[NL80211_ATTR_WIPHY_TXQ_PARAMS] = { .type = NLA_NESTED },
[NL80211_ATTR_WIPHY_FREQ] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_CHANNEL_TYPE] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_RETRY_SHORT] = { .type = NLA_U8 },
[NL80211_ATTR_WIPHY_RETRY_LONG] = { .type = NLA_U8 },
[NL80211_ATTR_WIPHY_FRAG_THRESHOLD] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_RTS_THRESHOLD] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_COVERAGE_CLASS] = { .type = NLA_U8 },
[NL80211_ATTR_IFTYPE] = { .type = NLA_U32 },
[NL80211_ATTR_IFINDEX] = { .type = NLA_U32 },
[NL80211_ATTR_IFNAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ-1 },
[NL80211_ATTR_MAC] = { .type = NLA_BINARY, .len = ETH_ALEN },
[NL80211_ATTR_PREV_BSSID] = { .type = NLA_BINARY, .len = ETH_ALEN },
[NL80211_ATTR_KEY] = { .type = NLA_NESTED, },
[NL80211_ATTR_KEY_DATA] = { .type = NLA_BINARY,
.len = WLAN_MAX_KEY_LEN },
[NL80211_ATTR_KEY_IDX] = { .type = NLA_U8 },
[NL80211_ATTR_KEY_CIPHER] = { .type = NLA_U32 },
[NL80211_ATTR_KEY_DEFAULT] = { .type = NLA_FLAG },
[NL80211_ATTR_KEY_SEQ] = { .type = NLA_BINARY, .len = 8 },
[NL80211_ATTR_KEY_TYPE] = { .type = NLA_U32 },
[NL80211_ATTR_BEACON_INTERVAL] = { .type = NLA_U32 },
[NL80211_ATTR_DTIM_PERIOD] = { .type = NLA_U32 },
[NL80211_ATTR_BEACON_HEAD] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_BEACON_TAIL] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_STA_AID] = { .type = NLA_U16 },
[NL80211_ATTR_STA_FLAGS] = { .type = NLA_NESTED },
[NL80211_ATTR_STA_LISTEN_INTERVAL] = { .type = NLA_U16 },
[NL80211_ATTR_STA_SUPPORTED_RATES] = { .type = NLA_BINARY,
.len = NL80211_MAX_SUPP_RATES },
[NL80211_ATTR_STA_PLINK_ACTION] = { .type = NLA_U8 },
[NL80211_ATTR_STA_VLAN] = { .type = NLA_U32 },
[NL80211_ATTR_MNTR_FLAGS] = { /* NLA_NESTED can't be empty */ },
[NL80211_ATTR_MESH_ID] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_MESH_ID_LEN },
[NL80211_ATTR_MPATH_NEXT_HOP] = { .type = NLA_U32 },
[NL80211_ATTR_REG_ALPHA2] = { .type = NLA_STRING, .len = 2 },
[NL80211_ATTR_REG_RULES] = { .type = NLA_NESTED },
[NL80211_ATTR_BSS_CTS_PROT] = { .type = NLA_U8 },
[NL80211_ATTR_BSS_SHORT_PREAMBLE] = { .type = NLA_U8 },
[NL80211_ATTR_BSS_SHORT_SLOT_TIME] = { .type = NLA_U8 },
[NL80211_ATTR_BSS_BASIC_RATES] = { .type = NLA_BINARY,
.len = NL80211_MAX_SUPP_RATES },
[NL80211_ATTR_BSS_HT_OPMODE] = { .type = NLA_U16 },
[NL80211_ATTR_MESH_CONFIG] = { .type = NLA_NESTED },
[NL80211_ATTR_SUPPORT_MESH_AUTH] = { .type = NLA_FLAG },
[NL80211_ATTR_HT_CAPABILITY] = { .type = NLA_BINARY,
.len = NL80211_HT_CAPABILITY_LEN },
[NL80211_ATTR_MGMT_SUBTYPE] = { .type = NLA_U8 },
[NL80211_ATTR_IE] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_SCAN_FREQUENCIES] = { .type = NLA_NESTED },
[NL80211_ATTR_SCAN_SSIDS] = { .type = NLA_NESTED },
[NL80211_ATTR_SSID] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_SSID_LEN },
[NL80211_ATTR_AUTH_TYPE] = { .type = NLA_U32 },
[NL80211_ATTR_REASON_CODE] = { .type = NLA_U16 },
[NL80211_ATTR_FREQ_FIXED] = { .type = NLA_FLAG },
[NL80211_ATTR_TIMED_OUT] = { .type = NLA_FLAG },
[NL80211_ATTR_USE_MFP] = { .type = NLA_U32 },
[NL80211_ATTR_STA_FLAGS2] = {
.len = sizeof(struct nl80211_sta_flag_update),
},
[NL80211_ATTR_CONTROL_PORT] = { .type = NLA_FLAG },
[NL80211_ATTR_CONTROL_PORT_ETHERTYPE] = { .type = NLA_U16 },
[NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT] = { .type = NLA_FLAG },
[NL80211_ATTR_PRIVACY] = { .type = NLA_FLAG },
[NL80211_ATTR_CIPHER_SUITE_GROUP] = { .type = NLA_U32 },
[NL80211_ATTR_WPA_VERSIONS] = { .type = NLA_U32 },
[NL80211_ATTR_PID] = { .type = NLA_U32 },
[NL80211_ATTR_4ADDR] = { .type = NLA_U8 },
[NL80211_ATTR_PMKID] = { .type = NLA_BINARY,
.len = WLAN_PMKID_LEN },
[NL80211_ATTR_DURATION] = { .type = NLA_U32 },
[NL80211_ATTR_COOKIE] = { .type = NLA_U64 },
[NL80211_ATTR_TX_RATES] = { .type = NLA_NESTED },
[NL80211_ATTR_FRAME] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_FRAME_MATCH] = { .type = NLA_BINARY, },
[NL80211_ATTR_PS_STATE] = { .type = NLA_U32 },
[NL80211_ATTR_CQM] = { .type = NLA_NESTED, },
[NL80211_ATTR_LOCAL_STATE_CHANGE] = { .type = NLA_FLAG },
[NL80211_ATTR_AP_ISOLATE] = { .type = NLA_U8 },
[NL80211_ATTR_WIPHY_TX_POWER_SETTING] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_TX_POWER_LEVEL] = { .type = NLA_U32 },
[NL80211_ATTR_FRAME_TYPE] = { .type = NLA_U16 },
[NL80211_ATTR_WIPHY_ANTENNA_TX] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_ANTENNA_RX] = { .type = NLA_U32 },
[NL80211_ATTR_MCAST_RATE] = { .type = NLA_U32 },
[NL80211_ATTR_OFFCHANNEL_TX_OK] = { .type = NLA_FLAG },
[NL80211_ATTR_KEY_DEFAULT_TYPES] = { .type = NLA_NESTED },
[NL80211_ATTR_WOWLAN_TRIGGERS] = { .type = NLA_NESTED },
[NL80211_ATTR_STA_PLINK_STATE] = { .type = NLA_U8 },
[NL80211_ATTR_SCHED_SCAN_INTERVAL] = { .type = NLA_U32 },
};
/* policy for the key attributes */
static const struct nla_policy nl80211_key_policy[NL80211_KEY_MAX + 1] = {
[NL80211_KEY_DATA] = { .type = NLA_BINARY, .len = WLAN_MAX_KEY_LEN },
[NL80211_KEY_IDX] = { .type = NLA_U8 },
[NL80211_KEY_CIPHER] = { .type = NLA_U32 },
[NL80211_KEY_SEQ] = { .type = NLA_BINARY, .len = 8 },
[NL80211_KEY_DEFAULT] = { .type = NLA_FLAG },
[NL80211_KEY_DEFAULT_MGMT] = { .type = NLA_FLAG },
[NL80211_KEY_TYPE] = { .type = NLA_U32 },
[NL80211_KEY_DEFAULT_TYPES] = { .type = NLA_NESTED },
};
/* policy for the key default flags */
static const struct nla_policy
nl80211_key_default_policy[NUM_NL80211_KEY_DEFAULT_TYPES] = {
[NL80211_KEY_DEFAULT_TYPE_UNICAST] = { .type = NLA_FLAG },
[NL80211_KEY_DEFAULT_TYPE_MULTICAST] = { .type = NLA_FLAG },
};
/* policy for WoWLAN attributes */
static const struct nla_policy
nl80211_wowlan_policy[NUM_NL80211_WOWLAN_TRIG] = {
[NL80211_WOWLAN_TRIG_ANY] = { .type = NLA_FLAG },
[NL80211_WOWLAN_TRIG_DISCONNECT] = { .type = NLA_FLAG },
[NL80211_WOWLAN_TRIG_MAGIC_PKT] = { .type = NLA_FLAG },
[NL80211_WOWLAN_TRIG_PKT_PATTERN] = { .type = NLA_NESTED },
};
/* ifidx get helper */
static int nl80211_get_ifidx(struct netlink_callback *cb)
{
int res;
res = nlmsg_parse(cb->nlh, GENL_HDRLEN + nl80211_fam.hdrsize,
nl80211_fam.attrbuf, nl80211_fam.maxattr,
nl80211_policy);
if (res)
return res;
if (!nl80211_fam.attrbuf[NL80211_ATTR_IFINDEX])
return -EINVAL;
res = nla_get_u32(nl80211_fam.attrbuf[NL80211_ATTR_IFINDEX]);
if (!res)
return -EINVAL;
return res;
}
static int nl80211_prepare_netdev_dump(struct sk_buff *skb,
struct netlink_callback *cb,
struct cfg80211_registered_device **rdev,
struct net_device **dev)
{
int ifidx = cb->args[0];
int err;
if (!ifidx)
ifidx = nl80211_get_ifidx(cb);
if (ifidx < 0)
return ifidx;
cb->args[0] = ifidx;
rtnl_lock();
*dev = __dev_get_by_index(sock_net(skb->sk), ifidx);
if (!*dev) {
err = -ENODEV;
goto out_rtnl;
}
*rdev = cfg80211_get_dev_from_ifindex(sock_net(skb->sk), ifidx);
if (IS_ERR(*rdev)) {
err = PTR_ERR(*rdev);
goto out_rtnl;
}
return 0;
out_rtnl:
rtnl_unlock();
return err;
}
static void nl80211_finish_netdev_dump(struct cfg80211_registered_device *rdev)
{
cfg80211_unlock_rdev(rdev);
rtnl_unlock();
}
/* IE validation */
static bool is_valid_ie_attr(const struct nlattr *attr)
{
const u8 *pos;
int len;
if (!attr)
return true;
pos = nla_data(attr);
len = nla_len(attr);
while (len) {
u8 elemlen;
if (len < 2)
return false;
len -= 2;
elemlen = pos[1];
if (elemlen > len)
return false;
len -= elemlen;
pos += 2 + elemlen;
}
return true;
}
/* message building helper */
static inline void *nl80211hdr_put(struct sk_buff *skb, u32 pid, u32 seq,
int flags, u8 cmd)
{
/* since there is no private header just add the generic one */
return genlmsg_put(skb, pid, seq, &nl80211_fam, flags, cmd);
}
static int nl80211_msg_put_channel(struct sk_buff *msg,
struct ieee80211_channel *chan)
{
NLA_PUT_U32(msg, NL80211_FREQUENCY_ATTR_FREQ,
chan->center_freq);
if (chan->flags & IEEE80211_CHAN_DISABLED)
NLA_PUT_FLAG(msg, NL80211_FREQUENCY_ATTR_DISABLED);
if (chan->flags & IEEE80211_CHAN_PASSIVE_SCAN)
NLA_PUT_FLAG(msg, NL80211_FREQUENCY_ATTR_PASSIVE_SCAN);
if (chan->flags & IEEE80211_CHAN_NO_IBSS)
NLA_PUT_FLAG(msg, NL80211_FREQUENCY_ATTR_NO_IBSS);
if (chan->flags & IEEE80211_CHAN_RADAR)
NLA_PUT_FLAG(msg, NL80211_FREQUENCY_ATTR_RADAR);
NLA_PUT_U32(msg, NL80211_FREQUENCY_ATTR_MAX_TX_POWER,
DBM_TO_MBM(chan->max_power));
return 0;
nla_put_failure:
return -ENOBUFS;
}
/* netlink command implementations */
struct key_parse {
struct key_params p;
int idx;
int type;
bool def, defmgmt;
bool def_uni, def_multi;
};
static int nl80211_parse_key_new(struct nlattr *key, struct key_parse *k)
{
struct nlattr *tb[NL80211_KEY_MAX + 1];
int err = nla_parse_nested(tb, NL80211_KEY_MAX, key,
nl80211_key_policy);
if (err)
return err;
k->def = !!tb[NL80211_KEY_DEFAULT];
k->defmgmt = !!tb[NL80211_KEY_DEFAULT_MGMT];
if (k->def) {
k->def_uni = true;
k->def_multi = true;
}
if (k->defmgmt)
k->def_multi = true;
if (tb[NL80211_KEY_IDX])
k->idx = nla_get_u8(tb[NL80211_KEY_IDX]);
if (tb[NL80211_KEY_DATA]) {
k->p.key = nla_data(tb[NL80211_KEY_DATA]);
k->p.key_len = nla_len(tb[NL80211_KEY_DATA]);
}
if (tb[NL80211_KEY_SEQ]) {
k->p.seq = nla_data(tb[NL80211_KEY_SEQ]);
k->p.seq_len = nla_len(tb[NL80211_KEY_SEQ]);
}
if (tb[NL80211_KEY_CIPHER])
k->p.cipher = nla_get_u32(tb[NL80211_KEY_CIPHER]);
if (tb[NL80211_KEY_TYPE]) {
k->type = nla_get_u32(tb[NL80211_KEY_TYPE]);
if (k->type < 0 || k->type >= NUM_NL80211_KEYTYPES)
return -EINVAL;
}
if (tb[NL80211_KEY_DEFAULT_TYPES]) {
struct nlattr *kdt[NUM_NL80211_KEY_DEFAULT_TYPES];
int err = nla_parse_nested(kdt,
NUM_NL80211_KEY_DEFAULT_TYPES - 1,
tb[NL80211_KEY_DEFAULT_TYPES],
nl80211_key_default_policy);
if (err)
return err;
k->def_uni = kdt[NL80211_KEY_DEFAULT_TYPE_UNICAST];
k->def_multi = kdt[NL80211_KEY_DEFAULT_TYPE_MULTICAST];
}
return 0;
}
static int nl80211_parse_key_old(struct genl_info *info, struct key_parse *k)
{
if (info->attrs[NL80211_ATTR_KEY_DATA]) {
k->p.key = nla_data(info->attrs[NL80211_ATTR_KEY_DATA]);
k->p.key_len = nla_len(info->attrs[NL80211_ATTR_KEY_DATA]);
}
if (info->attrs[NL80211_ATTR_KEY_SEQ]) {
k->p.seq = nla_data(info->attrs[NL80211_ATTR_KEY_SEQ]);
k->p.seq_len = nla_len(info->attrs[NL80211_ATTR_KEY_SEQ]);
}
if (info->attrs[NL80211_ATTR_KEY_IDX])
k->idx = nla_get_u8(info->attrs[NL80211_ATTR_KEY_IDX]);
if (info->attrs[NL80211_ATTR_KEY_CIPHER])
k->p.cipher = nla_get_u32(info->attrs[NL80211_ATTR_KEY_CIPHER]);
k->def = !!info->attrs[NL80211_ATTR_KEY_DEFAULT];
k->defmgmt = !!info->attrs[NL80211_ATTR_KEY_DEFAULT_MGMT];
if (k->def) {
k->def_uni = true;
k->def_multi = true;
}
if (k->defmgmt)
k->def_multi = true;
if (info->attrs[NL80211_ATTR_KEY_TYPE]) {
k->type = nla_get_u32(info->attrs[NL80211_ATTR_KEY_TYPE]);
if (k->type < 0 || k->type >= NUM_NL80211_KEYTYPES)
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_KEY_DEFAULT_TYPES]) {
struct nlattr *kdt[NUM_NL80211_KEY_DEFAULT_TYPES];
int err = nla_parse_nested(
kdt, NUM_NL80211_KEY_DEFAULT_TYPES - 1,
info->attrs[NL80211_ATTR_KEY_DEFAULT_TYPES],
nl80211_key_default_policy);
if (err)
return err;
k->def_uni = kdt[NL80211_KEY_DEFAULT_TYPE_UNICAST];
k->def_multi = kdt[NL80211_KEY_DEFAULT_TYPE_MULTICAST];
}
return 0;
}
static int nl80211_parse_key(struct genl_info *info, struct key_parse *k)
{
int err;
memset(k, 0, sizeof(*k));
k->idx = -1;
k->type = -1;
if (info->attrs[NL80211_ATTR_KEY])
err = nl80211_parse_key_new(info->attrs[NL80211_ATTR_KEY], k);
else
err = nl80211_parse_key_old(info, k);
if (err)
return err;
if (k->def && k->defmgmt)
return -EINVAL;
if (k->defmgmt) {
if (k->def_uni || !k->def_multi)
return -EINVAL;
}
if (k->idx != -1) {
if (k->defmgmt) {
if (k->idx < 4 || k->idx > 5)
return -EINVAL;
} else if (k->def) {
if (k->idx < 0 || k->idx > 3)
return -EINVAL;
} else {
if (k->idx < 0 || k->idx > 5)
return -EINVAL;
}
}
return 0;
}
static struct cfg80211_cached_keys *
nl80211_parse_connkeys(struct cfg80211_registered_device *rdev,
struct nlattr *keys)
{
struct key_parse parse;
struct nlattr *key;
struct cfg80211_cached_keys *result;
int rem, err, def = 0;
result = kzalloc(sizeof(*result), GFP_KERNEL);
if (!result)
return ERR_PTR(-ENOMEM);
result->def = -1;
result->defmgmt = -1;
nla_for_each_nested(key, keys, rem) {
memset(&parse, 0, sizeof(parse));
parse.idx = -1;
err = nl80211_parse_key_new(key, &parse);
if (err)
goto error;
err = -EINVAL;
if (!parse.p.key)
goto error;
if (parse.idx < 0 || parse.idx > 4)
goto error;
if (parse.def) {
if (def)
goto error;
def = 1;
result->def = parse.idx;
if (!parse.def_uni || !parse.def_multi)
goto error;
} else if (parse.defmgmt)
goto error;
err = cfg80211_validate_key_settings(rdev, &parse.p,
parse.idx, false, NULL);
if (err)
goto error;
result->params[parse.idx].cipher = parse.p.cipher;
result->params[parse.idx].key_len = parse.p.key_len;
result->params[parse.idx].key = result->data[parse.idx];
memcpy(result->data[parse.idx], parse.p.key, parse.p.key_len);
}
return result;
error:
kfree(result);
return ERR_PTR(err);
}
static int nl80211_key_allowed(struct wireless_dev *wdev)
{
ASSERT_WDEV_LOCK(wdev);
switch (wdev->iftype) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_MESH_POINT:
break;
case NL80211_IFTYPE_ADHOC:
if (!wdev->current_bss)
return -ENOLINK;
break;
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_P2P_CLIENT:
if (wdev->sme_state != CFG80211_SME_CONNECTED)
return -ENOLINK;
break;
default:
return -EINVAL;
}
return 0;
}
static int nl80211_put_iftypes(struct sk_buff *msg, u32 attr, u16 ifmodes)
{
struct nlattr *nl_modes = nla_nest_start(msg, attr);
int i;
if (!nl_modes)
goto nla_put_failure;
i = 0;
while (ifmodes) {
if (ifmodes & 1)
NLA_PUT_FLAG(msg, i);
ifmodes >>= 1;
i++;
}
nla_nest_end(msg, nl_modes);
return 0;
nla_put_failure:
return -ENOBUFS;
}
static int nl80211_put_iface_combinations(struct wiphy *wiphy,
struct sk_buff *msg)
{
struct nlattr *nl_combis;
int i, j;
nl_combis = nla_nest_start(msg,
NL80211_ATTR_INTERFACE_COMBINATIONS);
if (!nl_combis)
goto nla_put_failure;
for (i = 0; i < wiphy->n_iface_combinations; i++) {
const struct ieee80211_iface_combination *c;
struct nlattr *nl_combi, *nl_limits;
c = &wiphy->iface_combinations[i];
nl_combi = nla_nest_start(msg, i + 1);
if (!nl_combi)
goto nla_put_failure;
nl_limits = nla_nest_start(msg, NL80211_IFACE_COMB_LIMITS);
if (!nl_limits)
goto nla_put_failure;
for (j = 0; j < c->n_limits; j++) {
struct nlattr *nl_limit;
nl_limit = nla_nest_start(msg, j + 1);
if (!nl_limit)
goto nla_put_failure;
NLA_PUT_U32(msg, NL80211_IFACE_LIMIT_MAX,
c->limits[j].max);
if (nl80211_put_iftypes(msg, NL80211_IFACE_LIMIT_TYPES,
c->limits[j].types))
goto nla_put_failure;
nla_nest_end(msg, nl_limit);
}
nla_nest_end(msg, nl_limits);
if (c->beacon_int_infra_match)
NLA_PUT_FLAG(msg,
NL80211_IFACE_COMB_STA_AP_BI_MATCH);
NLA_PUT_U32(msg, NL80211_IFACE_COMB_NUM_CHANNELS,
c->num_different_channels);
NLA_PUT_U32(msg, NL80211_IFACE_COMB_MAXNUM,
c->max_interfaces);
nla_nest_end(msg, nl_combi);
}
nla_nest_end(msg, nl_combis);
return 0;
nla_put_failure:
return -ENOBUFS;
}
static int nl80211_send_wiphy(struct sk_buff *msg, u32 pid, u32 seq, int flags,
struct cfg80211_registered_device *dev)
{
void *hdr;
struct nlattr *nl_bands, *nl_band;
struct nlattr *nl_freqs, *nl_freq;
struct nlattr *nl_rates, *nl_rate;
struct nlattr *nl_cmds;
enum ieee80211_band band;
struct ieee80211_channel *chan;
struct ieee80211_rate *rate;
int i;
const struct ieee80211_txrx_stypes *mgmt_stypes =
dev->wiphy.mgmt_stypes;
hdr = nl80211hdr_put(msg, pid, seq, flags, NL80211_CMD_NEW_WIPHY);
if (!hdr)
return -1;
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, dev->wiphy_idx);
NLA_PUT_STRING(msg, NL80211_ATTR_WIPHY_NAME, wiphy_name(&dev->wiphy));
NLA_PUT_U32(msg, NL80211_ATTR_GENERATION,
cfg80211_rdev_list_generation);
NLA_PUT_U8(msg, NL80211_ATTR_WIPHY_RETRY_SHORT,
dev->wiphy.retry_short);
NLA_PUT_U8(msg, NL80211_ATTR_WIPHY_RETRY_LONG,
dev->wiphy.retry_long);
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD,
dev->wiphy.frag_threshold);
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD,
dev->wiphy.rts_threshold);
NLA_PUT_U8(msg, NL80211_ATTR_WIPHY_COVERAGE_CLASS,
dev->wiphy.coverage_class);
NLA_PUT_U8(msg, NL80211_ATTR_MAX_NUM_SCAN_SSIDS,
dev->wiphy.max_scan_ssids);
NLA_PUT_U16(msg, NL80211_ATTR_MAX_SCAN_IE_LEN,
dev->wiphy.max_scan_ie_len);
if (dev->wiphy.flags & WIPHY_FLAG_IBSS_RSN)
NLA_PUT_FLAG(msg, NL80211_ATTR_SUPPORT_IBSS_RSN);
if (dev->wiphy.flags & WIPHY_FLAG_MESH_AUTH)
NLA_PUT_FLAG(msg, NL80211_ATTR_SUPPORT_MESH_AUTH);
NLA_PUT(msg, NL80211_ATTR_CIPHER_SUITES,
sizeof(u32) * dev->wiphy.n_cipher_suites,
dev->wiphy.cipher_suites);
NLA_PUT_U8(msg, NL80211_ATTR_MAX_NUM_PMKIDS,
dev->wiphy.max_num_pmkids);
if (dev->wiphy.flags & WIPHY_FLAG_CONTROL_PORT_PROTOCOL)
NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT_ETHERTYPE);
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_ANTENNA_AVAIL_TX,
dev->wiphy.available_antennas_tx);
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_ANTENNA_AVAIL_RX,
dev->wiphy.available_antennas_rx);
if ((dev->wiphy.available_antennas_tx ||
dev->wiphy.available_antennas_rx) && dev->ops->get_antenna) {
u32 tx_ant = 0, rx_ant = 0;
int res;
res = dev->ops->get_antenna(&dev->wiphy, &tx_ant, &rx_ant);
if (!res) {
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_ANTENNA_TX, tx_ant);
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_ANTENNA_RX, rx_ant);
}
}
if (nl80211_put_iftypes(msg, NL80211_ATTR_SUPPORTED_IFTYPES,
dev->wiphy.interface_modes))
goto nla_put_failure;
nl_bands = nla_nest_start(msg, NL80211_ATTR_WIPHY_BANDS);
if (!nl_bands)
goto nla_put_failure;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
if (!dev->wiphy.bands[band])
continue;
nl_band = nla_nest_start(msg, band);
if (!nl_band)
goto nla_put_failure;
/* add HT info */
if (dev->wiphy.bands[band]->ht_cap.ht_supported) {
NLA_PUT(msg, NL80211_BAND_ATTR_HT_MCS_SET,
sizeof(dev->wiphy.bands[band]->ht_cap.mcs),
&dev->wiphy.bands[band]->ht_cap.mcs);
NLA_PUT_U16(msg, NL80211_BAND_ATTR_HT_CAPA,
dev->wiphy.bands[band]->ht_cap.cap);
NLA_PUT_U8(msg, NL80211_BAND_ATTR_HT_AMPDU_FACTOR,
dev->wiphy.bands[band]->ht_cap.ampdu_factor);
NLA_PUT_U8(msg, NL80211_BAND_ATTR_HT_AMPDU_DENSITY,
dev->wiphy.bands[band]->ht_cap.ampdu_density);
}
/* add frequencies */
nl_freqs = nla_nest_start(msg, NL80211_BAND_ATTR_FREQS);
if (!nl_freqs)
goto nla_put_failure;
for (i = 0; i < dev->wiphy.bands[band]->n_channels; i++) {
nl_freq = nla_nest_start(msg, i);
if (!nl_freq)
goto nla_put_failure;
chan = &dev->wiphy.bands[band]->channels[i];
if (nl80211_msg_put_channel(msg, chan))
goto nla_put_failure;
nla_nest_end(msg, nl_freq);
}
nla_nest_end(msg, nl_freqs);
/* add bitrates */
nl_rates = nla_nest_start(msg, NL80211_BAND_ATTR_RATES);
if (!nl_rates)
goto nla_put_failure;
for (i = 0; i < dev->wiphy.bands[band]->n_bitrates; i++) {
nl_rate = nla_nest_start(msg, i);
if (!nl_rate)
goto nla_put_failure;
rate = &dev->wiphy.bands[band]->bitrates[i];
NLA_PUT_U32(msg, NL80211_BITRATE_ATTR_RATE,
rate->bitrate);
if (rate->flags & IEEE80211_RATE_SHORT_PREAMBLE)
NLA_PUT_FLAG(msg,
NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE);
nla_nest_end(msg, nl_rate);
}
nla_nest_end(msg, nl_rates);
nla_nest_end(msg, nl_band);
}
nla_nest_end(msg, nl_bands);
nl_cmds = nla_nest_start(msg, NL80211_ATTR_SUPPORTED_COMMANDS);
if (!nl_cmds)
goto nla_put_failure;
i = 0;
#define CMD(op, n) \
do { \
if (dev->ops->op) { \
i++; \
NLA_PUT_U32(msg, i, NL80211_CMD_ ## n); \
} \
} while (0)
CMD(add_virtual_intf, NEW_INTERFACE);
CMD(change_virtual_intf, SET_INTERFACE);
CMD(add_key, NEW_KEY);
CMD(add_beacon, NEW_BEACON);
CMD(add_station, NEW_STATION);
CMD(add_mpath, NEW_MPATH);
CMD(update_mesh_config, SET_MESH_CONFIG);
CMD(change_bss, SET_BSS);
CMD(auth, AUTHENTICATE);
CMD(assoc, ASSOCIATE);
CMD(deauth, DEAUTHENTICATE);
CMD(disassoc, DISASSOCIATE);
CMD(join_ibss, JOIN_IBSS);
CMD(join_mesh, JOIN_MESH);
CMD(set_pmksa, SET_PMKSA);
CMD(del_pmksa, DEL_PMKSA);
CMD(flush_pmksa, FLUSH_PMKSA);
CMD(remain_on_channel, REMAIN_ON_CHANNEL);
CMD(set_bitrate_mask, SET_TX_BITRATE_MASK);
CMD(mgmt_tx, FRAME);
CMD(mgmt_tx_cancel_wait, FRAME_WAIT_CANCEL);
if (dev->wiphy.flags & WIPHY_FLAG_NETNS_OK) {
i++;
NLA_PUT_U32(msg, i, NL80211_CMD_SET_WIPHY_NETNS);
}
CMD(set_channel, SET_CHANNEL);
CMD(set_wds_peer, SET_WDS_PEER);
if (dev->wiphy.flags & WIPHY_FLAG_SUPPORTS_SCHED_SCAN)
CMD(sched_scan_start, START_SCHED_SCAN);
#undef CMD
if (dev->ops->connect || dev->ops->auth) {
i++;
NLA_PUT_U32(msg, i, NL80211_CMD_CONNECT);
}
if (dev->ops->disconnect || dev->ops->deauth) {
i++;
NLA_PUT_U32(msg, i, NL80211_CMD_DISCONNECT);
}
nla_nest_end(msg, nl_cmds);
if (dev->ops->remain_on_channel)
NLA_PUT_U32(msg, NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION,
dev->wiphy.max_remain_on_channel_duration);
/* for now at least assume all drivers have it */
if (dev->ops->mgmt_tx)
NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
if (mgmt_stypes) {
u16 stypes;
struct nlattr *nl_ftypes, *nl_ifs;
enum nl80211_iftype ift;
nl_ifs = nla_nest_start(msg, NL80211_ATTR_TX_FRAME_TYPES);
if (!nl_ifs)
goto nla_put_failure;
for (ift = 0; ift < NUM_NL80211_IFTYPES; ift++) {
nl_ftypes = nla_nest_start(msg, ift);
if (!nl_ftypes)
goto nla_put_failure;
i = 0;
stypes = mgmt_stypes[ift].tx;
while (stypes) {
if (stypes & 1)
NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE,
(i << 4) | IEEE80211_FTYPE_MGMT);
stypes >>= 1;
i++;
}
nla_nest_end(msg, nl_ftypes);
}
nla_nest_end(msg, nl_ifs);
nl_ifs = nla_nest_start(msg, NL80211_ATTR_RX_FRAME_TYPES);
if (!nl_ifs)
goto nla_put_failure;
for (ift = 0; ift < NUM_NL80211_IFTYPES; ift++) {
nl_ftypes = nla_nest_start(msg, ift);
if (!nl_ftypes)
goto nla_put_failure;
i = 0;
stypes = mgmt_stypes[ift].rx;
while (stypes) {
if (stypes & 1)
NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE,
(i << 4) | IEEE80211_FTYPE_MGMT);
stypes >>= 1;
i++;
}
nla_nest_end(msg, nl_ftypes);
}
nla_nest_end(msg, nl_ifs);
}
if (dev->wiphy.wowlan.flags || dev->wiphy.wowlan.n_patterns) {
struct nlattr *nl_wowlan;
nl_wowlan = nla_nest_start(msg,
NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED);
if (!nl_wowlan)
goto nla_put_failure;
if (dev->wiphy.wowlan.flags & WIPHY_WOWLAN_ANY)
NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_ANY);
if (dev->wiphy.wowlan.flags & WIPHY_WOWLAN_DISCONNECT)
NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_DISCONNECT);
if (dev->wiphy.wowlan.flags & WIPHY_WOWLAN_MAGIC_PKT)
NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_MAGIC_PKT);
if (dev->wiphy.wowlan.n_patterns) {
struct nl80211_wowlan_pattern_support pat = {
.max_patterns = dev->wiphy.wowlan.n_patterns,
.min_pattern_len =
dev->wiphy.wowlan.pattern_min_len,
.max_pattern_len =
dev->wiphy.wowlan.pattern_max_len,
};
NLA_PUT(msg, NL80211_WOWLAN_TRIG_PKT_PATTERN,
sizeof(pat), &pat);
}
nla_nest_end(msg, nl_wowlan);
}
if (nl80211_put_iftypes(msg, NL80211_ATTR_SOFTWARE_IFTYPES,
dev->wiphy.software_iftypes))
goto nla_put_failure;
if (nl80211_put_iface_combinations(&dev->wiphy, msg))
goto nla_put_failure;
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_wiphy(struct sk_buff *skb, struct netlink_callback *cb)
{
int idx = 0;
int start = cb->args[0];
struct cfg80211_registered_device *dev;
mutex_lock(&cfg80211_mutex);
list_for_each_entry(dev, &cfg80211_rdev_list, list) {
if (!net_eq(wiphy_net(&dev->wiphy), sock_net(skb->sk)))
continue;
if (++idx <= start)
continue;
if (nl80211_send_wiphy(skb, NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
dev) < 0) {
idx--;
break;
}
}
mutex_unlock(&cfg80211_mutex);
cb->args[0] = idx;
return skb->len;
}
static int nl80211_get_wiphy(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
struct cfg80211_registered_device *dev = info->user_ptr[0];
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (nl80211_send_wiphy(msg, info->snd_pid, info->snd_seq, 0, dev) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
static const struct nla_policy txq_params_policy[NL80211_TXQ_ATTR_MAX + 1] = {
[NL80211_TXQ_ATTR_QUEUE] = { .type = NLA_U8 },
[NL80211_TXQ_ATTR_TXOP] = { .type = NLA_U16 },
[NL80211_TXQ_ATTR_CWMIN] = { .type = NLA_U16 },
[NL80211_TXQ_ATTR_CWMAX] = { .type = NLA_U16 },
[NL80211_TXQ_ATTR_AIFS] = { .type = NLA_U8 },
};
static int parse_txq_params(struct nlattr *tb[],
struct ieee80211_txq_params *txq_params)
{
if (!tb[NL80211_TXQ_ATTR_QUEUE] || !tb[NL80211_TXQ_ATTR_TXOP] ||
!tb[NL80211_TXQ_ATTR_CWMIN] || !tb[NL80211_TXQ_ATTR_CWMAX] ||
!tb[NL80211_TXQ_ATTR_AIFS])
return -EINVAL;
txq_params->queue = nla_get_u8(tb[NL80211_TXQ_ATTR_QUEUE]);
txq_params->txop = nla_get_u16(tb[NL80211_TXQ_ATTR_TXOP]);
txq_params->cwmin = nla_get_u16(tb[NL80211_TXQ_ATTR_CWMIN]);
txq_params->cwmax = nla_get_u16(tb[NL80211_TXQ_ATTR_CWMAX]);
txq_params->aifs = nla_get_u8(tb[NL80211_TXQ_ATTR_AIFS]);
return 0;
}
static bool nl80211_can_set_dev_channel(struct wireless_dev *wdev)
{
/*
* You can only set the channel explicitly for AP, mesh
* and WDS type interfaces; all others have their channel
* managed via their respective "establish a connection"
* command (connect, join, ...)
*
* Monitors are special as they are normally slaved to
* whatever else is going on, so they behave as though
* you tried setting the wiphy channel itself.
*/
return !wdev ||
wdev->iftype == NL80211_IFTYPE_AP ||
wdev->iftype == NL80211_IFTYPE_WDS ||
wdev->iftype == NL80211_IFTYPE_MESH_POINT ||
wdev->iftype == NL80211_IFTYPE_MONITOR ||
wdev->iftype == NL80211_IFTYPE_P2P_GO;
}
static int __nl80211_set_channel(struct cfg80211_registered_device *rdev,
struct wireless_dev *wdev,
struct genl_info *info)
{
enum nl80211_channel_type channel_type = NL80211_CHAN_NO_HT;
u32 freq;
int result;
if (!info->attrs[NL80211_ATTR_WIPHY_FREQ])
return -EINVAL;
if (!nl80211_can_set_dev_channel(wdev))
return -EOPNOTSUPP;
if (info->attrs[NL80211_ATTR_WIPHY_CHANNEL_TYPE]) {
channel_type = nla_get_u32(info->attrs[
NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
if (channel_type != NL80211_CHAN_NO_HT &&
channel_type != NL80211_CHAN_HT20 &&
channel_type != NL80211_CHAN_HT40PLUS &&
channel_type != NL80211_CHAN_HT40MINUS)
return -EINVAL;
}
freq = nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_FREQ]);
mutex_lock(&rdev->devlist_mtx);
if (wdev) {
wdev_lock(wdev);
result = cfg80211_set_freq(rdev, wdev, freq, channel_type);
wdev_unlock(wdev);
} else {
result = cfg80211_set_freq(rdev, NULL, freq, channel_type);
}
mutex_unlock(&rdev->devlist_mtx);
return result;
}
static int nl80211_set_channel(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *netdev = info->user_ptr[1];
return __nl80211_set_channel(rdev, netdev->ieee80211_ptr, info);
}
static int nl80211_set_wds_peer(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
const u8 *bssid;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (netif_running(dev))
return -EBUSY;
if (!rdev->ops->set_wds_peer)
return -EOPNOTSUPP;
if (wdev->iftype != NL80211_IFTYPE_WDS)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
return rdev->ops->set_wds_peer(wdev->wiphy, dev, bssid);
}
static int nl80211_set_wiphy(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev;
struct net_device *netdev = NULL;
struct wireless_dev *wdev;
int result = 0, rem_txq_params = 0;
struct nlattr *nl_txq_params;
u32 changed;
u8 retry_short = 0, retry_long = 0;
u32 frag_threshold = 0, rts_threshold = 0;
u8 coverage_class = 0;
/*
* Try to find the wiphy and netdev. Normally this
* function shouldn't need the netdev, but this is
* done for backward compatibility -- previously
* setting the channel was done per wiphy, but now
* it is per netdev. Previous userland like hostapd
* also passed a netdev to set_wiphy, so that it is
* possible to let that go to the right netdev!
*/
mutex_lock(&cfg80211_mutex);
if (info->attrs[NL80211_ATTR_IFINDEX]) {
int ifindex = nla_get_u32(info->attrs[NL80211_ATTR_IFINDEX]);
netdev = dev_get_by_index(genl_info_net(info), ifindex);
if (netdev && netdev->ieee80211_ptr) {
rdev = wiphy_to_dev(netdev->ieee80211_ptr->wiphy);
mutex_lock(&rdev->mtx);
} else
netdev = NULL;
}
if (!netdev) {
rdev = __cfg80211_rdev_from_info(info);
if (IS_ERR(rdev)) {
mutex_unlock(&cfg80211_mutex);
return PTR_ERR(rdev);
}
wdev = NULL;
netdev = NULL;
result = 0;
mutex_lock(&rdev->mtx);
} else if (netif_running(netdev) &&
nl80211_can_set_dev_channel(netdev->ieee80211_ptr))
wdev = netdev->ieee80211_ptr;
else
wdev = NULL;
/*
* end workaround code, by now the rdev is available
* and locked, and wdev may or may not be NULL.
*/
if (info->attrs[NL80211_ATTR_WIPHY_NAME])
result = cfg80211_dev_rename(
rdev, nla_data(info->attrs[NL80211_ATTR_WIPHY_NAME]));
mutex_unlock(&cfg80211_mutex);
if (result)
goto bad_res;
if (info->attrs[NL80211_ATTR_WIPHY_TXQ_PARAMS]) {
struct ieee80211_txq_params txq_params;
struct nlattr *tb[NL80211_TXQ_ATTR_MAX + 1];
if (!rdev->ops->set_txq_params) {
result = -EOPNOTSUPP;
goto bad_res;
}
nla_for_each_nested(nl_txq_params,
info->attrs[NL80211_ATTR_WIPHY_TXQ_PARAMS],
rem_txq_params) {
nla_parse(tb, NL80211_TXQ_ATTR_MAX,
nla_data(nl_txq_params),
nla_len(nl_txq_params),
txq_params_policy);
result = parse_txq_params(tb, &txq_params);
if (result)
goto bad_res;
result = rdev->ops->set_txq_params(&rdev->wiphy,
&txq_params);
if (result)
goto bad_res;
}
}
if (info->attrs[NL80211_ATTR_WIPHY_FREQ]) {
result = __nl80211_set_channel(rdev, wdev, info);
if (result)
goto bad_res;
}
if (info->attrs[NL80211_ATTR_WIPHY_TX_POWER_SETTING]) {
enum nl80211_tx_power_setting type;
int idx, mbm = 0;
if (!rdev->ops->set_tx_power) {
result = -EOPNOTSUPP;
goto bad_res;
}
idx = NL80211_ATTR_WIPHY_TX_POWER_SETTING;
type = nla_get_u32(info->attrs[idx]);
if (!info->attrs[NL80211_ATTR_WIPHY_TX_POWER_LEVEL] &&
(type != NL80211_TX_POWER_AUTOMATIC)) {
result = -EINVAL;
goto bad_res;
}
if (type != NL80211_TX_POWER_AUTOMATIC) {
idx = NL80211_ATTR_WIPHY_TX_POWER_LEVEL;
mbm = nla_get_u32(info->attrs[idx]);
}
result = rdev->ops->set_tx_power(&rdev->wiphy, type, mbm);
if (result)
goto bad_res;
}
if (info->attrs[NL80211_ATTR_WIPHY_ANTENNA_TX] &&
info->attrs[NL80211_ATTR_WIPHY_ANTENNA_RX]) {
u32 tx_ant, rx_ant;
if ((!rdev->wiphy.available_antennas_tx &&
!rdev->wiphy.available_antennas_rx) ||
!rdev->ops->set_antenna) {
result = -EOPNOTSUPP;
goto bad_res;
}
tx_ant = nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_ANTENNA_TX]);
rx_ant = nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_ANTENNA_RX]);
/* reject antenna configurations which don't match the
* available antenna masks, except for the "all" mask */
if ((~tx_ant && (tx_ant & ~rdev->wiphy.available_antennas_tx)) ||
(~rx_ant && (rx_ant & ~rdev->wiphy.available_antennas_rx))) {
result = -EINVAL;
goto bad_res;
}
tx_ant = tx_ant & rdev->wiphy.available_antennas_tx;
rx_ant = rx_ant & rdev->wiphy.available_antennas_rx;
result = rdev->ops->set_antenna(&rdev->wiphy, tx_ant, rx_ant);
if (result)
goto bad_res;
}
changed = 0;
if (info->attrs[NL80211_ATTR_WIPHY_RETRY_SHORT]) {
retry_short = nla_get_u8(
info->attrs[NL80211_ATTR_WIPHY_RETRY_SHORT]);
if (retry_short == 0) {
result = -EINVAL;
goto bad_res;
}
changed |= WIPHY_PARAM_RETRY_SHORT;
}
if (info->attrs[NL80211_ATTR_WIPHY_RETRY_LONG]) {
retry_long = nla_get_u8(
info->attrs[NL80211_ATTR_WIPHY_RETRY_LONG]);
if (retry_long == 0) {
result = -EINVAL;
goto bad_res;
}
changed |= WIPHY_PARAM_RETRY_LONG;
}
if (info->attrs[NL80211_ATTR_WIPHY_FRAG_THRESHOLD]) {
frag_threshold = nla_get_u32(
info->attrs[NL80211_ATTR_WIPHY_FRAG_THRESHOLD]);
if (frag_threshold < 256) {
result = -EINVAL;
goto bad_res;
}
if (frag_threshold != (u32) -1) {
/*
* Fragments (apart from the last one) are required to
* have even length. Make the fragmentation code
* simpler by stripping LSB should someone try to use
* odd threshold value.
*/
frag_threshold &= ~0x1;
}
changed |= WIPHY_PARAM_FRAG_THRESHOLD;
}
if (info->attrs[NL80211_ATTR_WIPHY_RTS_THRESHOLD]) {
rts_threshold = nla_get_u32(
info->attrs[NL80211_ATTR_WIPHY_RTS_THRESHOLD]);
changed |= WIPHY_PARAM_RTS_THRESHOLD;
}
if (info->attrs[NL80211_ATTR_WIPHY_COVERAGE_CLASS]) {
coverage_class = nla_get_u8(
info->attrs[NL80211_ATTR_WIPHY_COVERAGE_CLASS]);
changed |= WIPHY_PARAM_COVERAGE_CLASS;
}
if (changed) {
u8 old_retry_short, old_retry_long;
u32 old_frag_threshold, old_rts_threshold;
u8 old_coverage_class;
if (!rdev->ops->set_wiphy_params) {
result = -EOPNOTSUPP;
goto bad_res;
}
old_retry_short = rdev->wiphy.retry_short;
old_retry_long = rdev->wiphy.retry_long;
old_frag_threshold = rdev->wiphy.frag_threshold;
old_rts_threshold = rdev->wiphy.rts_threshold;
old_coverage_class = rdev->wiphy.coverage_class;
if (changed & WIPHY_PARAM_RETRY_SHORT)
rdev->wiphy.retry_short = retry_short;
if (changed & WIPHY_PARAM_RETRY_LONG)
rdev->wiphy.retry_long = retry_long;
if (changed & WIPHY_PARAM_FRAG_THRESHOLD)
rdev->wiphy.frag_threshold = frag_threshold;
if (changed & WIPHY_PARAM_RTS_THRESHOLD)
rdev->wiphy.rts_threshold = rts_threshold;
if (changed & WIPHY_PARAM_COVERAGE_CLASS)
rdev->wiphy.coverage_class = coverage_class;
result = rdev->ops->set_wiphy_params(&rdev->wiphy, changed);
if (result) {
rdev->wiphy.retry_short = old_retry_short;
rdev->wiphy.retry_long = old_retry_long;
rdev->wiphy.frag_threshold = old_frag_threshold;
rdev->wiphy.rts_threshold = old_rts_threshold;
rdev->wiphy.coverage_class = old_coverage_class;
}
}
bad_res:
mutex_unlock(&rdev->mtx);
if (netdev)
dev_put(netdev);
return result;
}
static int nl80211_send_iface(struct sk_buff *msg, u32 pid, u32 seq, int flags,
struct cfg80211_registered_device *rdev,
struct net_device *dev)
{
void *hdr;
hdr = nl80211hdr_put(msg, pid, seq, flags, NL80211_CMD_NEW_INTERFACE);
if (!hdr)
return -1;
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, dev->ifindex);
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, dev->name);
NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, dev->ieee80211_ptr->iftype);
NLA_PUT_U32(msg, NL80211_ATTR_GENERATION,
rdev->devlist_generation ^
(cfg80211_rdev_list_generation << 2));
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_interface(struct sk_buff *skb, struct netlink_callback *cb)
{
int wp_idx = 0;
int if_idx = 0;
int wp_start = cb->args[0];
int if_start = cb->args[1];
struct cfg80211_registered_device *rdev;
struct wireless_dev *wdev;
mutex_lock(&cfg80211_mutex);
list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
if (!net_eq(wiphy_net(&rdev->wiphy), sock_net(skb->sk)))
continue;
if (wp_idx < wp_start) {
wp_idx++;
continue;
}
if_idx = 0;
mutex_lock(&rdev->devlist_mtx);
list_for_each_entry(wdev, &rdev->netdev_list, list) {
if (if_idx < if_start) {
if_idx++;
continue;
}
if (nl80211_send_iface(skb, NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
rdev, wdev->netdev) < 0) {
mutex_unlock(&rdev->devlist_mtx);
goto out;
}
if_idx++;
}
mutex_unlock(&rdev->devlist_mtx);
wp_idx++;
}
out:
mutex_unlock(&cfg80211_mutex);
cb->args[0] = wp_idx;
cb->args[1] = if_idx;
return skb->len;
}
static int nl80211_get_interface(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
struct cfg80211_registered_device *dev = info->user_ptr[0];
struct net_device *netdev = info->user_ptr[1];
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (nl80211_send_iface(msg, info->snd_pid, info->snd_seq, 0,
dev, netdev) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
static const struct nla_policy mntr_flags_policy[NL80211_MNTR_FLAG_MAX + 1] = {
[NL80211_MNTR_FLAG_FCSFAIL] = { .type = NLA_FLAG },
[NL80211_MNTR_FLAG_PLCPFAIL] = { .type = NLA_FLAG },
[NL80211_MNTR_FLAG_CONTROL] = { .type = NLA_FLAG },
[NL80211_MNTR_FLAG_OTHER_BSS] = { .type = NLA_FLAG },
[NL80211_MNTR_FLAG_COOK_FRAMES] = { .type = NLA_FLAG },
};
static int parse_monitor_flags(struct nlattr *nla, u32 *mntrflags)
{
struct nlattr *flags[NL80211_MNTR_FLAG_MAX + 1];
int flag;
*mntrflags = 0;
if (!nla)
return -EINVAL;
if (nla_parse_nested(flags, NL80211_MNTR_FLAG_MAX,
nla, mntr_flags_policy))
return -EINVAL;
for (flag = 1; flag <= NL80211_MNTR_FLAG_MAX; flag++)
if (flags[flag])
*mntrflags |= (1<<flag);
return 0;
}
static int nl80211_valid_4addr(struct cfg80211_registered_device *rdev,
struct net_device *netdev, u8 use_4addr,
enum nl80211_iftype iftype)
{
if (!use_4addr) {
if (netdev && (netdev->priv_flags & IFF_BRIDGE_PORT))
return -EBUSY;
return 0;
}
switch (iftype) {
case NL80211_IFTYPE_AP_VLAN:
if (rdev->wiphy.flags & WIPHY_FLAG_4ADDR_AP)
return 0;
break;
case NL80211_IFTYPE_STATION:
if (rdev->wiphy.flags & WIPHY_FLAG_4ADDR_STATION)
return 0;
break;
default:
break;
}
return -EOPNOTSUPP;
}
static int nl80211_set_interface(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct vif_params params;
int err;
enum nl80211_iftype otype, ntype;
struct net_device *dev = info->user_ptr[1];
u32 _flags, *flags = NULL;
bool change = false;
memset(¶ms, 0, sizeof(params));
otype = ntype = dev->ieee80211_ptr->iftype;
if (info->attrs[NL80211_ATTR_IFTYPE]) {
ntype = nla_get_u32(info->attrs[NL80211_ATTR_IFTYPE]);
if (otype != ntype)
change = true;
if (ntype > NL80211_IFTYPE_MAX)
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_MESH_ID]) {
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (ntype != NL80211_IFTYPE_MESH_POINT)
return -EINVAL;
if (netif_running(dev))
return -EBUSY;
wdev_lock(wdev);
BUILD_BUG_ON(IEEE80211_MAX_SSID_LEN !=
IEEE80211_MAX_MESH_ID_LEN);
wdev->mesh_id_up_len =
nla_len(info->attrs[NL80211_ATTR_MESH_ID]);
memcpy(wdev->ssid, nla_data(info->attrs[NL80211_ATTR_MESH_ID]),
wdev->mesh_id_up_len);
wdev_unlock(wdev);
}
if (info->attrs[NL80211_ATTR_4ADDR]) {
params.use_4addr = !!nla_get_u8(info->attrs[NL80211_ATTR_4ADDR]);
change = true;
err = nl80211_valid_4addr(rdev, dev, params.use_4addr, ntype);
if (err)
return err;
} else {
params.use_4addr = -1;
}
if (info->attrs[NL80211_ATTR_MNTR_FLAGS]) {
if (ntype != NL80211_IFTYPE_MONITOR)
return -EINVAL;
err = parse_monitor_flags(info->attrs[NL80211_ATTR_MNTR_FLAGS],
&_flags);
if (err)
return err;
flags = &_flags;
change = true;
}
if (change)
err = cfg80211_change_iface(rdev, dev, ntype, flags, ¶ms);
else
err = 0;
if (!err && params.use_4addr != -1)
dev->ieee80211_ptr->use_4addr = params.use_4addr;
return err;
}
static int nl80211_new_interface(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct vif_params params;
struct net_device *dev;
int err;
enum nl80211_iftype type = NL80211_IFTYPE_UNSPECIFIED;
u32 flags;
memset(¶ms, 0, sizeof(params));
if (!info->attrs[NL80211_ATTR_IFNAME])
return -EINVAL;
if (info->attrs[NL80211_ATTR_IFTYPE]) {
type = nla_get_u32(info->attrs[NL80211_ATTR_IFTYPE]);
if (type > NL80211_IFTYPE_MAX)
return -EINVAL;
}
if (!rdev->ops->add_virtual_intf ||
!(rdev->wiphy.interface_modes & (1 << type)))
return -EOPNOTSUPP;
if (info->attrs[NL80211_ATTR_4ADDR]) {
params.use_4addr = !!nla_get_u8(info->attrs[NL80211_ATTR_4ADDR]);
err = nl80211_valid_4addr(rdev, NULL, params.use_4addr, type);
if (err)
return err;
}
err = parse_monitor_flags(type == NL80211_IFTYPE_MONITOR ?
info->attrs[NL80211_ATTR_MNTR_FLAGS] : NULL,
&flags);
dev = rdev->ops->add_virtual_intf(&rdev->wiphy,
nla_data(info->attrs[NL80211_ATTR_IFNAME]),
type, err ? NULL : &flags, ¶ms);
if (IS_ERR(dev))
return PTR_ERR(dev);
if (type == NL80211_IFTYPE_MESH_POINT &&
info->attrs[NL80211_ATTR_MESH_ID]) {
struct wireless_dev *wdev = dev->ieee80211_ptr;
wdev_lock(wdev);
BUILD_BUG_ON(IEEE80211_MAX_SSID_LEN !=
IEEE80211_MAX_MESH_ID_LEN);
wdev->mesh_id_up_len =
nla_len(info->attrs[NL80211_ATTR_MESH_ID]);
memcpy(wdev->ssid, nla_data(info->attrs[NL80211_ATTR_MESH_ID]),
wdev->mesh_id_up_len);
wdev_unlock(wdev);
}
return 0;
}
static int nl80211_del_interface(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
if (!rdev->ops->del_virtual_intf)
return -EOPNOTSUPP;
return rdev->ops->del_virtual_intf(&rdev->wiphy, dev);
}
struct get_key_cookie {
struct sk_buff *msg;
int error;
int idx;
};
static void get_key_callback(void *c, struct key_params *params)
{
struct nlattr *key;
struct get_key_cookie *cookie = c;
if (params->key)
NLA_PUT(cookie->msg, NL80211_ATTR_KEY_DATA,
params->key_len, params->key);
if (params->seq)
NLA_PUT(cookie->msg, NL80211_ATTR_KEY_SEQ,
params->seq_len, params->seq);
if (params->cipher)
NLA_PUT_U32(cookie->msg, NL80211_ATTR_KEY_CIPHER,
params->cipher);
key = nla_nest_start(cookie->msg, NL80211_ATTR_KEY);
if (!key)
goto nla_put_failure;
if (params->key)
NLA_PUT(cookie->msg, NL80211_KEY_DATA,
params->key_len, params->key);
if (params->seq)
NLA_PUT(cookie->msg, NL80211_KEY_SEQ,
params->seq_len, params->seq);
if (params->cipher)
NLA_PUT_U32(cookie->msg, NL80211_KEY_CIPHER,
params->cipher);
NLA_PUT_U8(cookie->msg, NL80211_ATTR_KEY_IDX, cookie->idx);
nla_nest_end(cookie->msg, key);
return;
nla_put_failure:
cookie->error = 1;
}
static int nl80211_get_key(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
u8 key_idx = 0;
const u8 *mac_addr = NULL;
bool pairwise;
struct get_key_cookie cookie = {
.error = 0,
};
void *hdr;
struct sk_buff *msg;
if (info->attrs[NL80211_ATTR_KEY_IDX])
key_idx = nla_get_u8(info->attrs[NL80211_ATTR_KEY_IDX]);
if (key_idx > 5)
return -EINVAL;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
pairwise = !!mac_addr;
if (info->attrs[NL80211_ATTR_KEY_TYPE]) {
u32 kt = nla_get_u32(info->attrs[NL80211_ATTR_KEY_TYPE]);
if (kt >= NUM_NL80211_KEYTYPES)
return -EINVAL;
if (kt != NL80211_KEYTYPE_GROUP &&
kt != NL80211_KEYTYPE_PAIRWISE)
return -EINVAL;
pairwise = kt == NL80211_KEYTYPE_PAIRWISE;
}
if (!rdev->ops->get_key)
return -EOPNOTSUPP;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
NL80211_CMD_NEW_KEY);
if (IS_ERR(hdr))
return PTR_ERR(hdr);
cookie.msg = msg;
cookie.idx = key_idx;
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, dev->ifindex);
NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
if (mac_addr)
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, mac_addr);
if (pairwise && mac_addr &&
!(rdev->wiphy.flags & WIPHY_FLAG_IBSS_RSN))
return -ENOENT;
err = rdev->ops->get_key(&rdev->wiphy, dev, key_idx, pairwise,
mac_addr, &cookie, get_key_callback);
if (err)
goto free_msg;
if (cookie.error)
goto nla_put_failure;
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static int nl80211_set_key(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct key_parse key;
int err;
struct net_device *dev = info->user_ptr[1];
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (key.idx < 0)
return -EINVAL;
/* only support setting default key */
if (!key.def && !key.defmgmt)
return -EINVAL;
wdev_lock(dev->ieee80211_ptr);
if (key.def) {
if (!rdev->ops->set_default_key) {
err = -EOPNOTSUPP;
goto out;
}
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (err)
goto out;
err = rdev->ops->set_default_key(&rdev->wiphy, dev, key.idx,
key.def_uni, key.def_multi);
if (err)
goto out;
#ifdef CONFIG_CFG80211_WEXT
dev->ieee80211_ptr->wext.default_key = key.idx;
#endif
} else {
if (key.def_uni || !key.def_multi) {
err = -EINVAL;
goto out;
}
if (!rdev->ops->set_default_mgmt_key) {
err = -EOPNOTSUPP;
goto out;
}
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (err)
goto out;
err = rdev->ops->set_default_mgmt_key(&rdev->wiphy,
dev, key.idx);
if (err)
goto out;
#ifdef CONFIG_CFG80211_WEXT
dev->ieee80211_ptr->wext.default_mgmt_key = key.idx;
#endif
}
out:
wdev_unlock(dev->ieee80211_ptr);
return err;
}
static int nl80211_new_key(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
struct key_parse key;
const u8 *mac_addr = NULL;
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (!key.p.key)
return -EINVAL;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (key.type == -1) {
if (mac_addr)
key.type = NL80211_KEYTYPE_PAIRWISE;
else
key.type = NL80211_KEYTYPE_GROUP;
}
/* for now */
if (key.type != NL80211_KEYTYPE_PAIRWISE &&
key.type != NL80211_KEYTYPE_GROUP)
return -EINVAL;
if (!rdev->ops->add_key)
return -EOPNOTSUPP;
if (cfg80211_validate_key_settings(rdev, &key.p, key.idx,
key.type == NL80211_KEYTYPE_PAIRWISE,
mac_addr))
return -EINVAL;
wdev_lock(dev->ieee80211_ptr);
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (!err)
err = rdev->ops->add_key(&rdev->wiphy, dev, key.idx,
key.type == NL80211_KEYTYPE_PAIRWISE,
mac_addr, &key.p);
wdev_unlock(dev->ieee80211_ptr);
return err;
}
static int nl80211_del_key(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
u8 *mac_addr = NULL;
struct key_parse key;
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (key.type == -1) {
if (mac_addr)
key.type = NL80211_KEYTYPE_PAIRWISE;
else
key.type = NL80211_KEYTYPE_GROUP;
}
/* for now */
if (key.type != NL80211_KEYTYPE_PAIRWISE &&
key.type != NL80211_KEYTYPE_GROUP)
return -EINVAL;
if (!rdev->ops->del_key)
return -EOPNOTSUPP;
wdev_lock(dev->ieee80211_ptr);
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (key.type == NL80211_KEYTYPE_PAIRWISE && mac_addr &&
!(rdev->wiphy.flags & WIPHY_FLAG_IBSS_RSN))
err = -ENOENT;
if (!err)
err = rdev->ops->del_key(&rdev->wiphy, dev, key.idx,
key.type == NL80211_KEYTYPE_PAIRWISE,
mac_addr);
#ifdef CONFIG_CFG80211_WEXT
if (!err) {
if (key.idx == dev->ieee80211_ptr->wext.default_key)
dev->ieee80211_ptr->wext.default_key = -1;
else if (key.idx == dev->ieee80211_ptr->wext.default_mgmt_key)
dev->ieee80211_ptr->wext.default_mgmt_key = -1;
}
#endif
wdev_unlock(dev->ieee80211_ptr);
return err;
}
static int nl80211_addset_beacon(struct sk_buff *skb, struct genl_info *info)
{
int (*call)(struct wiphy *wiphy, struct net_device *dev,
struct beacon_parameters *info);
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct beacon_parameters params;
int haveinfo = 0, err;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_BEACON_TAIL]))
return -EINVAL;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EOPNOTSUPP;
memset(¶ms, 0, sizeof(params));
switch (info->genlhdr->cmd) {
case NL80211_CMD_NEW_BEACON:
/* these are required for NEW_BEACON */
if (!info->attrs[NL80211_ATTR_BEACON_INTERVAL] ||
!info->attrs[NL80211_ATTR_DTIM_PERIOD] ||
!info->attrs[NL80211_ATTR_BEACON_HEAD])
return -EINVAL;
params.interval =
nla_get_u32(info->attrs[NL80211_ATTR_BEACON_INTERVAL]);
params.dtim_period =
nla_get_u32(info->attrs[NL80211_ATTR_DTIM_PERIOD]);
err = cfg80211_validate_beacon_int(rdev, params.interval);
if (err)
return err;
call = rdev->ops->add_beacon;
break;
case NL80211_CMD_SET_BEACON:
call = rdev->ops->set_beacon;
break;
default:
WARN_ON(1);
return -EOPNOTSUPP;
}
if (!call)
return -EOPNOTSUPP;
if (info->attrs[NL80211_ATTR_BEACON_HEAD]) {
params.head = nla_data(info->attrs[NL80211_ATTR_BEACON_HEAD]);
params.head_len =
nla_len(info->attrs[NL80211_ATTR_BEACON_HEAD]);
haveinfo = 1;
}
if (info->attrs[NL80211_ATTR_BEACON_TAIL]) {
params.tail = nla_data(info->attrs[NL80211_ATTR_BEACON_TAIL]);
params.tail_len =
nla_len(info->attrs[NL80211_ATTR_BEACON_TAIL]);
haveinfo = 1;
}
if (!haveinfo)
return -EINVAL;
err = call(&rdev->wiphy, dev, ¶ms);
if (!err && params.interval)
wdev->beacon_interval = params.interval;
return err;
}
static int nl80211_del_beacon(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
int err;
if (!rdev->ops->del_beacon)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EOPNOTSUPP;
err = rdev->ops->del_beacon(&rdev->wiphy, dev);
if (!err)
wdev->beacon_interval = 0;
return err;
}
static const struct nla_policy sta_flags_policy[NL80211_STA_FLAG_MAX + 1] = {
[NL80211_STA_FLAG_AUTHORIZED] = { .type = NLA_FLAG },
[NL80211_STA_FLAG_SHORT_PREAMBLE] = { .type = NLA_FLAG },
[NL80211_STA_FLAG_WME] = { .type = NLA_FLAG },
[NL80211_STA_FLAG_MFP] = { .type = NLA_FLAG },
[NL80211_STA_FLAG_AUTHENTICATED] = { .type = NLA_FLAG },
};
static int parse_station_flags(struct genl_info *info,
struct station_parameters *params)
{
struct nlattr *flags[NL80211_STA_FLAG_MAX + 1];
struct nlattr *nla;
int flag;
/*
* Try parsing the new attribute first so userspace
* can specify both for older kernels.
*/
nla = info->attrs[NL80211_ATTR_STA_FLAGS2];
if (nla) {
struct nl80211_sta_flag_update *sta_flags;
sta_flags = nla_data(nla);
params->sta_flags_mask = sta_flags->mask;
params->sta_flags_set = sta_flags->set;
if ((params->sta_flags_mask |
params->sta_flags_set) & BIT(__NL80211_STA_FLAG_INVALID))
return -EINVAL;
return 0;
}
/* if present, parse the old attribute */
nla = info->attrs[NL80211_ATTR_STA_FLAGS];
if (!nla)
return 0;
if (nla_parse_nested(flags, NL80211_STA_FLAG_MAX,
nla, sta_flags_policy))
return -EINVAL;
params->sta_flags_mask = (1 << __NL80211_STA_FLAG_AFTER_LAST) - 1;
params->sta_flags_mask &= ~1;
for (flag = 1; flag <= NL80211_STA_FLAG_MAX; flag++)
if (flags[flag])
params->sta_flags_set |= (1<<flag);
return 0;
}
static bool nl80211_put_sta_rate(struct sk_buff *msg, struct rate_info *info,
int attr)
{
struct nlattr *rate;
u16 bitrate;
rate = nla_nest_start(msg, attr);
if (!rate)
goto nla_put_failure;
/* cfg80211_calculate_bitrate will return 0 for mcs >= 32 */
bitrate = cfg80211_calculate_bitrate(info);
if (bitrate > 0)
NLA_PUT_U16(msg, NL80211_RATE_INFO_BITRATE, bitrate);
if (info->flags & RATE_INFO_FLAGS_MCS)
NLA_PUT_U8(msg, NL80211_RATE_INFO_MCS, info->mcs);
if (info->flags & RATE_INFO_FLAGS_40_MHZ_WIDTH)
NLA_PUT_FLAG(msg, NL80211_RATE_INFO_40_MHZ_WIDTH);
if (info->flags & RATE_INFO_FLAGS_SHORT_GI)
NLA_PUT_FLAG(msg, NL80211_RATE_INFO_SHORT_GI);
nla_nest_end(msg, rate);
return true;
nla_put_failure:
return false;
}
static int nl80211_send_station(struct sk_buff *msg, u32 pid, u32 seq,
int flags, struct net_device *dev,
const u8 *mac_addr, struct station_info *sinfo)
{
void *hdr;
struct nlattr *sinfoattr, *bss_param;
hdr = nl80211hdr_put(msg, pid, seq, flags, NL80211_CMD_NEW_STATION);
if (!hdr)
return -1;
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, dev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, mac_addr);
NLA_PUT_U32(msg, NL80211_ATTR_GENERATION, sinfo->generation);
sinfoattr = nla_nest_start(msg, NL80211_ATTR_STA_INFO);
if (!sinfoattr)
goto nla_put_failure;
if (sinfo->filled & STATION_INFO_CONNECTED_TIME)
NLA_PUT_U32(msg, NL80211_STA_INFO_CONNECTED_TIME,
sinfo->connected_time);
if (sinfo->filled & STATION_INFO_INACTIVE_TIME)
NLA_PUT_U32(msg, NL80211_STA_INFO_INACTIVE_TIME,
sinfo->inactive_time);
if (sinfo->filled & STATION_INFO_RX_BYTES)
NLA_PUT_U32(msg, NL80211_STA_INFO_RX_BYTES,
sinfo->rx_bytes);
if (sinfo->filled & STATION_INFO_TX_BYTES)
NLA_PUT_U32(msg, NL80211_STA_INFO_TX_BYTES,
sinfo->tx_bytes);
if (sinfo->filled & STATION_INFO_LLID)
NLA_PUT_U16(msg, NL80211_STA_INFO_LLID,
sinfo->llid);
if (sinfo->filled & STATION_INFO_PLID)
NLA_PUT_U16(msg, NL80211_STA_INFO_PLID,
sinfo->plid);
if (sinfo->filled & STATION_INFO_PLINK_STATE)
NLA_PUT_U8(msg, NL80211_STA_INFO_PLINK_STATE,
sinfo->plink_state);
if (sinfo->filled & STATION_INFO_SIGNAL)
NLA_PUT_U8(msg, NL80211_STA_INFO_SIGNAL,
sinfo->signal);
if (sinfo->filled & STATION_INFO_SIGNAL_AVG)
NLA_PUT_U8(msg, NL80211_STA_INFO_SIGNAL_AVG,
sinfo->signal_avg);
if (sinfo->filled & STATION_INFO_TX_BITRATE) {
if (!nl80211_put_sta_rate(msg, &sinfo->txrate,
NL80211_STA_INFO_TX_BITRATE))
goto nla_put_failure;
}
if (sinfo->filled & STATION_INFO_RX_BITRATE) {
if (!nl80211_put_sta_rate(msg, &sinfo->rxrate,
NL80211_STA_INFO_RX_BITRATE))
goto nla_put_failure;
}
if (sinfo->filled & STATION_INFO_RX_PACKETS)
NLA_PUT_U32(msg, NL80211_STA_INFO_RX_PACKETS,
sinfo->rx_packets);
if (sinfo->filled & STATION_INFO_TX_PACKETS)
NLA_PUT_U32(msg, NL80211_STA_INFO_TX_PACKETS,
sinfo->tx_packets);
if (sinfo->filled & STATION_INFO_TX_RETRIES)
NLA_PUT_U32(msg, NL80211_STA_INFO_TX_RETRIES,
sinfo->tx_retries);
if (sinfo->filled & STATION_INFO_TX_FAILED)
NLA_PUT_U32(msg, NL80211_STA_INFO_TX_FAILED,
sinfo->tx_failed);
if (sinfo->filled & STATION_INFO_BSS_PARAM) {
bss_param = nla_nest_start(msg, NL80211_STA_INFO_BSS_PARAM);
if (!bss_param)
goto nla_put_failure;
if (sinfo->bss_param.flags & BSS_PARAM_FLAGS_CTS_PROT)
NLA_PUT_FLAG(msg, NL80211_STA_BSS_PARAM_CTS_PROT);
if (sinfo->bss_param.flags & BSS_PARAM_FLAGS_SHORT_PREAMBLE)
NLA_PUT_FLAG(msg, NL80211_STA_BSS_PARAM_SHORT_PREAMBLE);
if (sinfo->bss_param.flags & BSS_PARAM_FLAGS_SHORT_SLOT_TIME)
NLA_PUT_FLAG(msg,
NL80211_STA_BSS_PARAM_SHORT_SLOT_TIME);
NLA_PUT_U8(msg, NL80211_STA_BSS_PARAM_DTIM_PERIOD,
sinfo->bss_param.dtim_period);
NLA_PUT_U16(msg, NL80211_STA_BSS_PARAM_BEACON_INTERVAL,
sinfo->bss_param.beacon_interval);
nla_nest_end(msg, bss_param);
}
nla_nest_end(msg, sinfoattr);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_station(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct station_info sinfo;
struct cfg80211_registered_device *dev;
struct net_device *netdev;
u8 mac_addr[ETH_ALEN];
int sta_idx = cb->args[1];
int err;
err = nl80211_prepare_netdev_dump(skb, cb, &dev, &netdev);
if (err)
return err;
if (!dev->ops->dump_station) {
err = -EOPNOTSUPP;
goto out_err;
}
while (1) {
err = dev->ops->dump_station(&dev->wiphy, netdev, sta_idx,
mac_addr, &sinfo);
if (err == -ENOENT)
break;
if (err)
goto out_err;
if (nl80211_send_station(skb,
NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
netdev, mac_addr,
&sinfo) < 0)
goto out;
sta_idx++;
}
out:
cb->args[1] = sta_idx;
err = skb->len;
out_err:
nl80211_finish_netdev_dump(dev);
return err;
}
static int nl80211_get_station(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct station_info sinfo;
struct sk_buff *msg;
u8 *mac_addr = NULL;
int err;
memset(&sinfo, 0, sizeof(sinfo));
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (!rdev->ops->get_station)
return -EOPNOTSUPP;
err = rdev->ops->get_station(&rdev->wiphy, dev, mac_addr, &sinfo);
if (err)
return err;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (nl80211_send_station(msg, info->snd_pid, info->snd_seq, 0,
dev, mac_addr, &sinfo) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
/*
* Get vlan interface making sure it is running and on the right wiphy.
*/
static int get_vlan(struct genl_info *info,
struct cfg80211_registered_device *rdev,
struct net_device **vlan)
{
struct nlattr *vlanattr = info->attrs[NL80211_ATTR_STA_VLAN];
*vlan = NULL;
if (vlanattr) {
*vlan = dev_get_by_index(genl_info_net(info),
nla_get_u32(vlanattr));
if (!*vlan)
return -ENODEV;
if (!(*vlan)->ieee80211_ptr)
return -EINVAL;
if ((*vlan)->ieee80211_ptr->wiphy != &rdev->wiphy)
return -EINVAL;
if (!netif_running(*vlan))
return -ENETDOWN;
}
return 0;
}
static int nl80211_set_station(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
struct station_parameters params;
u8 *mac_addr = NULL;
memset(¶ms, 0, sizeof(params));
params.listen_interval = -1;
params.plink_state = -1;
if (info->attrs[NL80211_ATTR_STA_AID])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES]) {
params.supported_rates =
nla_data(info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES]);
params.supported_rates_len =
nla_len(info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES]);
}
if (info->attrs[NL80211_ATTR_STA_LISTEN_INTERVAL])
params.listen_interval =
nla_get_u16(info->attrs[NL80211_ATTR_STA_LISTEN_INTERVAL]);
if (info->attrs[NL80211_ATTR_HT_CAPABILITY])
params.ht_capa =
nla_data(info->attrs[NL80211_ATTR_HT_CAPABILITY]);
if (parse_station_flags(info, ¶ms))
return -EINVAL;
if (info->attrs[NL80211_ATTR_STA_PLINK_ACTION])
params.plink_action =
nla_get_u8(info->attrs[NL80211_ATTR_STA_PLINK_ACTION]);
if (info->attrs[NL80211_ATTR_STA_PLINK_STATE])
params.plink_state =
nla_get_u8(info->attrs[NL80211_ATTR_STA_PLINK_STATE]);
err = get_vlan(info, rdev, ¶ms.vlan);
if (err)
goto out;
/* validate settings */
err = 0;
switch (dev->ieee80211_ptr->iftype) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_P2P_GO:
/* disallow mesh-specific things */
if (params.plink_action)
err = -EINVAL;
break;
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_STATION:
/* disallow everything but AUTHORIZED flag */
if (params.plink_action)
err = -EINVAL;
if (params.vlan)
err = -EINVAL;
if (params.supported_rates)
err = -EINVAL;
if (params.ht_capa)
err = -EINVAL;
if (params.listen_interval >= 0)
err = -EINVAL;
if (params.sta_flags_mask & ~BIT(NL80211_STA_FLAG_AUTHORIZED))
err = -EINVAL;
break;
case NL80211_IFTYPE_MESH_POINT:
/* disallow things mesh doesn't support */
if (params.vlan)
err = -EINVAL;
if (params.ht_capa)
err = -EINVAL;
if (params.listen_interval >= 0)
err = -EINVAL;
if (params.sta_flags_mask &
~(BIT(NL80211_STA_FLAG_AUTHENTICATED) |
BIT(NL80211_STA_FLAG_MFP) |
BIT(NL80211_STA_FLAG_AUTHORIZED)))
err = -EINVAL;
break;
default:
err = -EINVAL;
}
if (err)
goto out;
if (!rdev->ops->change_station) {
err = -EOPNOTSUPP;
goto out;
}
err = rdev->ops->change_station(&rdev->wiphy, dev, mac_addr, ¶ms);
out:
if (params.vlan)
dev_put(params.vlan);
return err;
}
static int nl80211_new_station(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
struct station_parameters params;
u8 *mac_addr = NULL;
memset(¶ms, 0, sizeof(params));
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_STA_LISTEN_INTERVAL])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_STA_AID])
return -EINVAL;
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
params.supported_rates =
nla_data(info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES]);
params.supported_rates_len =
nla_len(info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES]);
params.listen_interval =
nla_get_u16(info->attrs[NL80211_ATTR_STA_LISTEN_INTERVAL]);
params.aid = nla_get_u16(info->attrs[NL80211_ATTR_STA_AID]);
if (!params.aid || params.aid > IEEE80211_MAX_AID)
return -EINVAL;
if (info->attrs[NL80211_ATTR_HT_CAPABILITY])
params.ht_capa =
nla_data(info->attrs[NL80211_ATTR_HT_CAPABILITY]);
if (info->attrs[NL80211_ATTR_STA_PLINK_ACTION])
params.plink_action =
nla_get_u8(info->attrs[NL80211_ATTR_STA_PLINK_ACTION]);
if (parse_station_flags(info, ¶ms))
return -EINVAL;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP_VLAN &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EINVAL;
err = get_vlan(info, rdev, ¶ms.vlan);
if (err)
goto out;
/* validate settings */
err = 0;
if (!rdev->ops->add_station) {
err = -EOPNOTSUPP;
goto out;
}
err = rdev->ops->add_station(&rdev->wiphy, dev, mac_addr, ¶ms);
out:
if (params.vlan)
dev_put(params.vlan);
return err;
}
static int nl80211_del_station(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *mac_addr = NULL;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP_VLAN &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EINVAL;
if (!rdev->ops->del_station)
return -EOPNOTSUPP;
return rdev->ops->del_station(&rdev->wiphy, dev, mac_addr);
}
static int nl80211_send_mpath(struct sk_buff *msg, u32 pid, u32 seq,
int flags, struct net_device *dev,
u8 *dst, u8 *next_hop,
struct mpath_info *pinfo)
{
void *hdr;
struct nlattr *pinfoattr;
hdr = nl80211hdr_put(msg, pid, seq, flags, NL80211_CMD_NEW_STATION);
if (!hdr)
return -1;
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, dev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, dst);
NLA_PUT(msg, NL80211_ATTR_MPATH_NEXT_HOP, ETH_ALEN, next_hop);
NLA_PUT_U32(msg, NL80211_ATTR_GENERATION, pinfo->generation);
pinfoattr = nla_nest_start(msg, NL80211_ATTR_MPATH_INFO);
if (!pinfoattr)
goto nla_put_failure;
if (pinfo->filled & MPATH_INFO_FRAME_QLEN)
NLA_PUT_U32(msg, NL80211_MPATH_INFO_FRAME_QLEN,
pinfo->frame_qlen);
if (pinfo->filled & MPATH_INFO_SN)
NLA_PUT_U32(msg, NL80211_MPATH_INFO_SN,
pinfo->sn);
if (pinfo->filled & MPATH_INFO_METRIC)
NLA_PUT_U32(msg, NL80211_MPATH_INFO_METRIC,
pinfo->metric);
if (pinfo->filled & MPATH_INFO_EXPTIME)
NLA_PUT_U32(msg, NL80211_MPATH_INFO_EXPTIME,
pinfo->exptime);
if (pinfo->filled & MPATH_INFO_FLAGS)
NLA_PUT_U8(msg, NL80211_MPATH_INFO_FLAGS,
pinfo->flags);
if (pinfo->filled & MPATH_INFO_DISCOVERY_TIMEOUT)
NLA_PUT_U32(msg, NL80211_MPATH_INFO_DISCOVERY_TIMEOUT,
pinfo->discovery_timeout);
if (pinfo->filled & MPATH_INFO_DISCOVERY_RETRIES)
NLA_PUT_U8(msg, NL80211_MPATH_INFO_DISCOVERY_RETRIES,
pinfo->discovery_retries);
nla_nest_end(msg, pinfoattr);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_mpath(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct mpath_info pinfo;
struct cfg80211_registered_device *dev;
struct net_device *netdev;
u8 dst[ETH_ALEN];
u8 next_hop[ETH_ALEN];
int path_idx = cb->args[1];
int err;
err = nl80211_prepare_netdev_dump(skb, cb, &dev, &netdev);
if (err)
return err;
if (!dev->ops->dump_mpath) {
err = -EOPNOTSUPP;
goto out_err;
}
if (netdev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT) {
err = -EOPNOTSUPP;
goto out_err;
}
while (1) {
err = dev->ops->dump_mpath(&dev->wiphy, netdev, path_idx,
dst, next_hop, &pinfo);
if (err == -ENOENT)
break;
if (err)
goto out_err;
if (nl80211_send_mpath(skb, NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
netdev, dst, next_hop,
&pinfo) < 0)
goto out;
path_idx++;
}
out:
cb->args[1] = path_idx;
err = skb->len;
out_err:
nl80211_finish_netdev_dump(dev);
return err;
}
static int nl80211_get_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
struct mpath_info pinfo;
struct sk_buff *msg;
u8 *dst = NULL;
u8 next_hop[ETH_ALEN];
memset(&pinfo, 0, sizeof(pinfo));
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (!rdev->ops->get_mpath)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
err = rdev->ops->get_mpath(&rdev->wiphy, dev, dst, next_hop, &pinfo);
if (err)
return err;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (nl80211_send_mpath(msg, info->snd_pid, info->snd_seq, 0,
dev, dst, next_hop, &pinfo) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
static int nl80211_set_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *dst = NULL;
u8 *next_hop = NULL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MPATH_NEXT_HOP])
return -EINVAL;
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
next_hop = nla_data(info->attrs[NL80211_ATTR_MPATH_NEXT_HOP]);
if (!rdev->ops->change_mpath)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
return rdev->ops->change_mpath(&rdev->wiphy, dev, dst, next_hop);
}
static int nl80211_new_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *dst = NULL;
u8 *next_hop = NULL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MPATH_NEXT_HOP])
return -EINVAL;
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
next_hop = nla_data(info->attrs[NL80211_ATTR_MPATH_NEXT_HOP]);
if (!rdev->ops->add_mpath)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
return rdev->ops->add_mpath(&rdev->wiphy, dev, dst, next_hop);
}
static int nl80211_del_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *dst = NULL;
if (info->attrs[NL80211_ATTR_MAC])
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (!rdev->ops->del_mpath)
return -EOPNOTSUPP;
return rdev->ops->del_mpath(&rdev->wiphy, dev, dst);
}
static int nl80211_set_bss(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct bss_parameters params;
memset(¶ms, 0, sizeof(params));
/* default to not changing parameters */
params.use_cts_prot = -1;
params.use_short_preamble = -1;
params.use_short_slot_time = -1;
params.ap_isolate = -1;
params.ht_opmode = -1;
if (info->attrs[NL80211_ATTR_BSS_CTS_PROT])
params.use_cts_prot =
nla_get_u8(info->attrs[NL80211_ATTR_BSS_CTS_PROT]);
if (info->attrs[NL80211_ATTR_BSS_SHORT_PREAMBLE])
params.use_short_preamble =
nla_get_u8(info->attrs[NL80211_ATTR_BSS_SHORT_PREAMBLE]);
if (info->attrs[NL80211_ATTR_BSS_SHORT_SLOT_TIME])
params.use_short_slot_time =
nla_get_u8(info->attrs[NL80211_ATTR_BSS_SHORT_SLOT_TIME]);
if (info->attrs[NL80211_ATTR_BSS_BASIC_RATES]) {
params.basic_rates =
nla_data(info->attrs[NL80211_ATTR_BSS_BASIC_RATES]);
params.basic_rates_len =
nla_len(info->attrs[NL80211_ATTR_BSS_BASIC_RATES]);
}
if (info->attrs[NL80211_ATTR_AP_ISOLATE])
params.ap_isolate = !!nla_get_u8(info->attrs[NL80211_ATTR_AP_ISOLATE]);
if (info->attrs[NL80211_ATTR_BSS_HT_OPMODE])
params.ht_opmode =
nla_get_u16(info->attrs[NL80211_ATTR_BSS_HT_OPMODE]);
if (!rdev->ops->change_bss)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EOPNOTSUPP;
return rdev->ops->change_bss(&rdev->wiphy, dev, ¶ms);
}
static const struct nla_policy reg_rule_policy[NL80211_REG_RULE_ATTR_MAX + 1] = {
[NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
[NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
[NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
[NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
[NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
[NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
};
static int parse_reg_rule(struct nlattr *tb[],
struct ieee80211_reg_rule *reg_rule)
{
struct ieee80211_freq_range *freq_range = ®_rule->freq_range;
struct ieee80211_power_rule *power_rule = ®_rule->power_rule;
if (!tb[NL80211_ATTR_REG_RULE_FLAGS])
return -EINVAL;
if (!tb[NL80211_ATTR_FREQ_RANGE_START])
return -EINVAL;
if (!tb[NL80211_ATTR_FREQ_RANGE_END])
return -EINVAL;
if (!tb[NL80211_ATTR_FREQ_RANGE_MAX_BW])
return -EINVAL;
if (!tb[NL80211_ATTR_POWER_RULE_MAX_EIRP])
return -EINVAL;
reg_rule->flags = nla_get_u32(tb[NL80211_ATTR_REG_RULE_FLAGS]);
freq_range->start_freq_khz =
nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]);
freq_range->end_freq_khz =
nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]);
freq_range->max_bandwidth_khz =
nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]);
power_rule->max_eirp =
nla_get_u32(tb[NL80211_ATTR_POWER_RULE_MAX_EIRP]);
if (tb[NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN])
power_rule->max_antenna_gain =
nla_get_u32(tb[NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN]);
return 0;
}
static int nl80211_req_set_reg(struct sk_buff *skb, struct genl_info *info)
{
int r;
char *data = NULL;
/*
* You should only get this when cfg80211 hasn't yet initialized
* completely when built-in to the kernel right between the time
* window between nl80211_init() and regulatory_init(), if that is
* even possible.
*/
mutex_lock(&cfg80211_mutex);
if (unlikely(!cfg80211_regdomain)) {
mutex_unlock(&cfg80211_mutex);
return -EINPROGRESS;
}
mutex_unlock(&cfg80211_mutex);
if (!info->attrs[NL80211_ATTR_REG_ALPHA2])
return -EINVAL;
data = nla_data(info->attrs[NL80211_ATTR_REG_ALPHA2]);
r = regulatory_hint_user(data);
return r;
}
static int nl80211_get_mesh_config(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct mesh_config cur_params;
int err = 0;
void *hdr;
struct nlattr *pinfoattr;
struct sk_buff *msg;
if (wdev->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
if (!rdev->ops->get_mesh_config)
return -EOPNOTSUPP;
wdev_lock(wdev);
/* If not connected, get default parameters */
if (!wdev->mesh_id_len)
memcpy(&cur_params, &default_mesh_config, sizeof(cur_params));
else
err = rdev->ops->get_mesh_config(&rdev->wiphy, dev,
&cur_params);
wdev_unlock(wdev);
if (err)
return err;
/* Draw up a netlink message to send back */
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
NL80211_CMD_GET_MESH_CONFIG);
if (!hdr)
goto out;
pinfoattr = nla_nest_start(msg, NL80211_ATTR_MESH_CONFIG);
if (!pinfoattr)
goto nla_put_failure;
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, dev->ifindex);
NLA_PUT_U16(msg, NL80211_MESHCONF_RETRY_TIMEOUT,
cur_params.dot11MeshRetryTimeout);
NLA_PUT_U16(msg, NL80211_MESHCONF_CONFIRM_TIMEOUT,
cur_params.dot11MeshConfirmTimeout);
NLA_PUT_U16(msg, NL80211_MESHCONF_HOLDING_TIMEOUT,
cur_params.dot11MeshHoldingTimeout);
NLA_PUT_U16(msg, NL80211_MESHCONF_MAX_PEER_LINKS,
cur_params.dot11MeshMaxPeerLinks);
NLA_PUT_U8(msg, NL80211_MESHCONF_MAX_RETRIES,
cur_params.dot11MeshMaxRetries);
NLA_PUT_U8(msg, NL80211_MESHCONF_TTL,
cur_params.dot11MeshTTL);
NLA_PUT_U8(msg, NL80211_MESHCONF_ELEMENT_TTL,
cur_params.element_ttl);
NLA_PUT_U8(msg, NL80211_MESHCONF_AUTO_OPEN_PLINKS,
cur_params.auto_open_plinks);
NLA_PUT_U8(msg, NL80211_MESHCONF_HWMP_MAX_PREQ_RETRIES,
cur_params.dot11MeshHWMPmaxPREQretries);
NLA_PUT_U32(msg, NL80211_MESHCONF_PATH_REFRESH_TIME,
cur_params.path_refresh_time);
NLA_PUT_U16(msg, NL80211_MESHCONF_MIN_DISCOVERY_TIMEOUT,
cur_params.min_discovery_timeout);
NLA_PUT_U32(msg, NL80211_MESHCONF_HWMP_ACTIVE_PATH_TIMEOUT,
cur_params.dot11MeshHWMPactivePathTimeout);
NLA_PUT_U16(msg, NL80211_MESHCONF_HWMP_PREQ_MIN_INTERVAL,
cur_params.dot11MeshHWMPpreqMinInterval);
NLA_PUT_U16(msg, NL80211_MESHCONF_HWMP_NET_DIAM_TRVS_TIME,
cur_params.dot11MeshHWMPnetDiameterTraversalTime);
NLA_PUT_U8(msg, NL80211_MESHCONF_HWMP_ROOTMODE,
cur_params.dot11MeshHWMPRootMode);
nla_nest_end(msg, pinfoattr);
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
genlmsg_cancel(msg, hdr);
out:
nlmsg_free(msg);
return -ENOBUFS;
}
static const struct nla_policy nl80211_meshconf_params_policy[NL80211_MESHCONF_ATTR_MAX+1] = {
[NL80211_MESHCONF_RETRY_TIMEOUT] = { .type = NLA_U16 },
[NL80211_MESHCONF_CONFIRM_TIMEOUT] = { .type = NLA_U16 },
[NL80211_MESHCONF_HOLDING_TIMEOUT] = { .type = NLA_U16 },
[NL80211_MESHCONF_MAX_PEER_LINKS] = { .type = NLA_U16 },
[NL80211_MESHCONF_MAX_RETRIES] = { .type = NLA_U8 },
[NL80211_MESHCONF_TTL] = { .type = NLA_U8 },
[NL80211_MESHCONF_ELEMENT_TTL] = { .type = NLA_U8 },
[NL80211_MESHCONF_AUTO_OPEN_PLINKS] = { .type = NLA_U8 },
[NL80211_MESHCONF_HWMP_MAX_PREQ_RETRIES] = { .type = NLA_U8 },
[NL80211_MESHCONF_PATH_REFRESH_TIME] = { .type = NLA_U32 },
[NL80211_MESHCONF_MIN_DISCOVERY_TIMEOUT] = { .type = NLA_U16 },
[NL80211_MESHCONF_HWMP_ACTIVE_PATH_TIMEOUT] = { .type = NLA_U32 },
[NL80211_MESHCONF_HWMP_PREQ_MIN_INTERVAL] = { .type = NLA_U16 },
[NL80211_MESHCONF_HWMP_NET_DIAM_TRVS_TIME] = { .type = NLA_U16 },
};
static const struct nla_policy
nl80211_mesh_setup_params_policy[NL80211_MESH_SETUP_ATTR_MAX+1] = {
[NL80211_MESH_SETUP_ENABLE_VENDOR_PATH_SEL] = { .type = NLA_U8 },
[NL80211_MESH_SETUP_ENABLE_VENDOR_METRIC] = { .type = NLA_U8 },
[NL80211_MESH_SETUP_USERSPACE_AUTH] = { .type = NLA_FLAG },
[NL80211_MESH_SETUP_IE] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_MESH_SETUP_USERSPACE_AMPE] = { .type = NLA_FLAG },
};
static int nl80211_parse_mesh_config(struct genl_info *info,
struct mesh_config *cfg,
u32 *mask_out)
{
struct nlattr *tb[NL80211_MESHCONF_ATTR_MAX + 1];
u32 mask = 0;
#define FILL_IN_MESH_PARAM_IF_SET(table, cfg, param, mask, attr_num, nla_fn) \
do {\
if (table[attr_num]) {\
cfg->param = nla_fn(table[attr_num]); \
mask |= (1 << (attr_num - 1)); \
} \
} while (0);\
if (!info->attrs[NL80211_ATTR_MESH_CONFIG])
return -EINVAL;
if (nla_parse_nested(tb, NL80211_MESHCONF_ATTR_MAX,
info->attrs[NL80211_ATTR_MESH_CONFIG],
nl80211_meshconf_params_policy))
return -EINVAL;
/* This makes sure that there aren't more than 32 mesh config
* parameters (otherwise our bitfield scheme would not work.) */
BUILD_BUG_ON(NL80211_MESHCONF_ATTR_MAX > 32);
/* Fill in the params struct */
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshRetryTimeout,
mask, NL80211_MESHCONF_RETRY_TIMEOUT, nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshConfirmTimeout,
mask, NL80211_MESHCONF_CONFIRM_TIMEOUT, nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHoldingTimeout,
mask, NL80211_MESHCONF_HOLDING_TIMEOUT, nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshMaxPeerLinks,
mask, NL80211_MESHCONF_MAX_PEER_LINKS, nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshMaxRetries,
mask, NL80211_MESHCONF_MAX_RETRIES, nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshTTL,
mask, NL80211_MESHCONF_TTL, nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, element_ttl,
mask, NL80211_MESHCONF_ELEMENT_TTL, nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, auto_open_plinks,
mask, NL80211_MESHCONF_AUTO_OPEN_PLINKS, nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHWMPmaxPREQretries,
mask, NL80211_MESHCONF_HWMP_MAX_PREQ_RETRIES,
nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, path_refresh_time,
mask, NL80211_MESHCONF_PATH_REFRESH_TIME, nla_get_u32);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, min_discovery_timeout,
mask, NL80211_MESHCONF_MIN_DISCOVERY_TIMEOUT,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHWMPactivePathTimeout,
mask, NL80211_MESHCONF_HWMP_ACTIVE_PATH_TIMEOUT,
nla_get_u32);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHWMPpreqMinInterval,
mask, NL80211_MESHCONF_HWMP_PREQ_MIN_INTERVAL,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg,
dot11MeshHWMPnetDiameterTraversalTime,
mask, NL80211_MESHCONF_HWMP_NET_DIAM_TRVS_TIME,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg,
dot11MeshHWMPRootMode, mask,
NL80211_MESHCONF_HWMP_ROOTMODE,
nla_get_u8);
if (mask_out)
*mask_out = mask;
return 0;
#undef FILL_IN_MESH_PARAM_IF_SET
}
static int nl80211_parse_mesh_setup(struct genl_info *info,
struct mesh_setup *setup)
{
struct nlattr *tb[NL80211_MESH_SETUP_ATTR_MAX + 1];
if (!info->attrs[NL80211_ATTR_MESH_SETUP])
return -EINVAL;
if (nla_parse_nested(tb, NL80211_MESH_SETUP_ATTR_MAX,
info->attrs[NL80211_ATTR_MESH_SETUP],
nl80211_mesh_setup_params_policy))
return -EINVAL;
if (tb[NL80211_MESH_SETUP_ENABLE_VENDOR_PATH_SEL])
setup->path_sel_proto =
(nla_get_u8(tb[NL80211_MESH_SETUP_ENABLE_VENDOR_PATH_SEL])) ?
IEEE80211_PATH_PROTOCOL_VENDOR :
IEEE80211_PATH_PROTOCOL_HWMP;
if (tb[NL80211_MESH_SETUP_ENABLE_VENDOR_METRIC])
setup->path_metric =
(nla_get_u8(tb[NL80211_MESH_SETUP_ENABLE_VENDOR_METRIC])) ?
IEEE80211_PATH_METRIC_VENDOR :
IEEE80211_PATH_METRIC_AIRTIME;
if (tb[NL80211_MESH_SETUP_IE]) {
struct nlattr *ieattr =
tb[NL80211_MESH_SETUP_IE];
if (!is_valid_ie_attr(ieattr))
return -EINVAL;
setup->ie = nla_data(ieattr);
setup->ie_len = nla_len(ieattr);
}
setup->is_authenticated = nla_get_flag(tb[NL80211_MESH_SETUP_USERSPACE_AUTH]);
setup->is_secure = nla_get_flag(tb[NL80211_MESH_SETUP_USERSPACE_AMPE]);
return 0;
}
static int nl80211_update_mesh_config(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct mesh_config cfg;
u32 mask;
int err;
if (wdev->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
if (!rdev->ops->update_mesh_config)
return -EOPNOTSUPP;
err = nl80211_parse_mesh_config(info, &cfg, &mask);
if (err)
return err;
wdev_lock(wdev);
if (!wdev->mesh_id_len)
err = -ENOLINK;
if (!err)
err = rdev->ops->update_mesh_config(&rdev->wiphy, dev,
mask, &cfg);
wdev_unlock(wdev);
return err;
}
static int nl80211_get_reg(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
void *hdr = NULL;
struct nlattr *nl_reg_rules;
unsigned int i;
int err = -EINVAL;
mutex_lock(&cfg80211_mutex);
if (!cfg80211_regdomain)
goto out;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg) {
err = -ENOBUFS;
goto out;
}
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
NL80211_CMD_GET_REG);
if (!hdr)
goto put_failure;
NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2,
cfg80211_regdomain->alpha2);
nl_reg_rules = nla_nest_start(msg, NL80211_ATTR_REG_RULES);
if (!nl_reg_rules)
goto nla_put_failure;
for (i = 0; i < cfg80211_regdomain->n_reg_rules; i++) {
struct nlattr *nl_reg_rule;
const struct ieee80211_reg_rule *reg_rule;
const struct ieee80211_freq_range *freq_range;
const struct ieee80211_power_rule *power_rule;
reg_rule = &cfg80211_regdomain->reg_rules[i];
freq_range = ®_rule->freq_range;
power_rule = ®_rule->power_rule;
nl_reg_rule = nla_nest_start(msg, i);
if (!nl_reg_rule)
goto nla_put_failure;
NLA_PUT_U32(msg, NL80211_ATTR_REG_RULE_FLAGS,
reg_rule->flags);
NLA_PUT_U32(msg, NL80211_ATTR_FREQ_RANGE_START,
freq_range->start_freq_khz);
NLA_PUT_U32(msg, NL80211_ATTR_FREQ_RANGE_END,
freq_range->end_freq_khz);
NLA_PUT_U32(msg, NL80211_ATTR_FREQ_RANGE_MAX_BW,
freq_range->max_bandwidth_khz);
NLA_PUT_U32(msg, NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN,
power_rule->max_antenna_gain);
NLA_PUT_U32(msg, NL80211_ATTR_POWER_RULE_MAX_EIRP,
power_rule->max_eirp);
nla_nest_end(msg, nl_reg_rule);
}
nla_nest_end(msg, nl_reg_rules);
genlmsg_end(msg, hdr);
err = genlmsg_reply(msg, info);
goto out;
nla_put_failure:
genlmsg_cancel(msg, hdr);
put_failure:
nlmsg_free(msg);
err = -EMSGSIZE;
out:
mutex_unlock(&cfg80211_mutex);
return err;
}
static int nl80211_set_reg(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr *tb[NL80211_REG_RULE_ATTR_MAX + 1];
struct nlattr *nl_reg_rule;
char *alpha2 = NULL;
int rem_reg_rules = 0, r = 0;
u32 num_rules = 0, rule_idx = 0, size_of_regd;
struct ieee80211_regdomain *rd = NULL;
if (!info->attrs[NL80211_ATTR_REG_ALPHA2])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_REG_RULES])
return -EINVAL;
alpha2 = nla_data(info->attrs[NL80211_ATTR_REG_ALPHA2]);
nla_for_each_nested(nl_reg_rule, info->attrs[NL80211_ATTR_REG_RULES],
rem_reg_rules) {
num_rules++;
if (num_rules > NL80211_MAX_SUPP_REG_RULES)
return -EINVAL;
}
mutex_lock(&cfg80211_mutex);
if (!reg_is_valid_request(alpha2)) {
r = -EINVAL;
goto bad_reg;
}
size_of_regd = sizeof(struct ieee80211_regdomain) +
(num_rules * sizeof(struct ieee80211_reg_rule));
rd = kzalloc(size_of_regd, GFP_KERNEL);
if (!rd) {
r = -ENOMEM;
goto bad_reg;
}
rd->n_reg_rules = num_rules;
rd->alpha2[0] = alpha2[0];
rd->alpha2[1] = alpha2[1];
nla_for_each_nested(nl_reg_rule, info->attrs[NL80211_ATTR_REG_RULES],
rem_reg_rules) {
nla_parse(tb, NL80211_REG_RULE_ATTR_MAX,
nla_data(nl_reg_rule), nla_len(nl_reg_rule),
reg_rule_policy);
r = parse_reg_rule(tb, &rd->reg_rules[rule_idx]);
if (r)
goto bad_reg;
rule_idx++;
if (rule_idx > NL80211_MAX_SUPP_REG_RULES) {
r = -EINVAL;
goto bad_reg;
}
}
BUG_ON(rule_idx != num_rules);
r = set_regdom(rd);
mutex_unlock(&cfg80211_mutex);
return r;
bad_reg:
mutex_unlock(&cfg80211_mutex);
kfree(rd);
return r;
}
static int validate_scan_freqs(struct nlattr *freqs)
{
struct nlattr *attr1, *attr2;
int n_channels = 0, tmp1, tmp2;
nla_for_each_nested(attr1, freqs, tmp1) {
n_channels++;
/*
* Some hardware has a limited channel list for
* scanning, and it is pretty much nonsensical
* to scan for a channel twice, so disallow that
* and don't require drivers to check that the
* channel list they get isn't longer than what
* they can scan, as long as they can scan all
* the channels they registered at once.
*/
nla_for_each_nested(attr2, freqs, tmp2)
if (attr1 != attr2 &&
nla_get_u32(attr1) == nla_get_u32(attr2))
return 0;
}
return n_channels;
}
static int nl80211_trigger_scan(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct cfg80211_scan_request *request;
struct nlattr *attr;
struct wiphy *wiphy;
int err, tmp, n_ssids = 0, n_channels, i;
enum ieee80211_band band;
size_t ie_len;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
wiphy = &rdev->wiphy;
if (!rdev->ops->scan)
return -EOPNOTSUPP;
if (rdev->scan_req)
return -EBUSY;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
n_channels = validate_scan_freqs(
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]);
if (!n_channels)
return -EINVAL;
} else {
n_channels = 0;
for (band = 0; band < IEEE80211_NUM_BANDS; band++)
if (wiphy->bands[band])
n_channels += wiphy->bands[band]->n_channels;
}
if (info->attrs[NL80211_ATTR_SCAN_SSIDS])
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp)
n_ssids++;
if (n_ssids > wiphy->max_scan_ssids)
return -EINVAL;
if (info->attrs[NL80211_ATTR_IE])
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
else
ie_len = 0;
if (ie_len > wiphy->max_scan_ie_len)
return -EINVAL;
request = kzalloc(sizeof(*request)
+ sizeof(*request->ssids) * n_ssids
+ sizeof(*request->channels) * n_channels
+ ie_len, GFP_KERNEL);
if (!request)
return -ENOMEM;
if (n_ssids)
request->ssids = (void *)&request->channels[n_channels];
request->n_ssids = n_ssids;
if (ie_len) {
if (request->ssids)
request->ie = (void *)(request->ssids + n_ssids);
else
request->ie = (void *)(request->channels + n_channels);
}
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
/* user specified, bail out if channel not found */
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_FREQUENCIES], tmp) {
struct ieee80211_channel *chan;
chan = ieee80211_get_channel(wiphy, nla_get_u32(attr));
if (!chan) {
err = -EINVAL;
goto out_free;
}
/* ignore disabled channels */
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
} else {
/* all channels */
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
struct ieee80211_channel *chan;
chan = &wiphy->bands[band]->channels[j];
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
}
}
if (!i) {
err = -EINVAL;
goto out_free;
}
request->n_channels = i;
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) {
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp) {
if (request->ssids[i].ssid_len > IEEE80211_MAX_SSID_LEN) {
err = -EINVAL;
goto out_free;
}
memcpy(request->ssids[i].ssid, nla_data(attr), nla_len(attr));
request->ssids[i].ssid_len = nla_len(attr);
i++;
}
}
if (info->attrs[NL80211_ATTR_IE]) {
request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
memcpy((void *)request->ie,
nla_data(info->attrs[NL80211_ATTR_IE]),
request->ie_len);
}
request->dev = dev;
request->wiphy = &rdev->wiphy;
rdev->scan_req = request;
err = rdev->ops->scan(&rdev->wiphy, dev, request);
if (!err) {
nl80211_send_scan_start(rdev, dev);
dev_hold(dev);
} else {
out_free:
rdev->scan_req = NULL;
kfree(request);
}
return err;
}
static int nl80211_start_sched_scan(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_sched_scan_request *request;
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct nlattr *attr;
struct wiphy *wiphy;
int err, tmp, n_ssids = 0, n_channels, i;
u32 interval;
enum ieee80211_band band;
size_t ie_len;
if (!(rdev->wiphy.flags & WIPHY_FLAG_SUPPORTS_SCHED_SCAN) ||
!rdev->ops->sched_scan_start)
return -EOPNOTSUPP;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (rdev->sched_scan_req)
return -EINPROGRESS;
if (!info->attrs[NL80211_ATTR_SCHED_SCAN_INTERVAL])
return -EINVAL;
interval = nla_get_u32(info->attrs[NL80211_ATTR_SCHED_SCAN_INTERVAL]);
if (interval == 0)
return -EINVAL;
wiphy = &rdev->wiphy;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
n_channels = validate_scan_freqs(
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]);
if (!n_channels)
return -EINVAL;
} else {
n_channels = 0;
for (band = 0; band < IEEE80211_NUM_BANDS; band++)
if (wiphy->bands[band])
n_channels += wiphy->bands[band]->n_channels;
}
if (info->attrs[NL80211_ATTR_SCAN_SSIDS])
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS],
tmp)
n_ssids++;
if (n_ssids > wiphy->max_scan_ssids)
return -EINVAL;
if (info->attrs[NL80211_ATTR_IE])
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
else
ie_len = 0;
if (ie_len > wiphy->max_scan_ie_len)
return -EINVAL;
request = kzalloc(sizeof(*request)
+ sizeof(*request->ssids) * n_ssids
+ sizeof(*request->channels) * n_channels
+ ie_len, GFP_KERNEL);
if (!request)
return -ENOMEM;
if (n_ssids)
request->ssids = (void *)&request->channels[n_channels];
request->n_ssids = n_ssids;
if (ie_len) {
if (request->ssids)
request->ie = (void *)(request->ssids + n_ssids);
else
request->ie = (void *)(request->channels + n_channels);
}
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
/* user specified, bail out if channel not found */
nla_for_each_nested(attr,
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES],
tmp) {
struct ieee80211_channel *chan;
chan = ieee80211_get_channel(wiphy, nla_get_u32(attr));
if (!chan) {
err = -EINVAL;
goto out_free;
}
/* ignore disabled channels */
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
} else {
/* all channels */
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
struct ieee80211_channel *chan;
chan = &wiphy->bands[band]->channels[j];
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
}
}
if (!i) {
err = -EINVAL;
goto out_free;
}
request->n_channels = i;
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) {
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS],
tmp) {
if (request->ssids[i].ssid_len >
IEEE80211_MAX_SSID_LEN) {
err = -EINVAL;
goto out_free;
}
memcpy(request->ssids[i].ssid, nla_data(attr),
nla_len(attr));
request->ssids[i].ssid_len = nla_len(attr);
i++;
}
}
if (info->attrs[NL80211_ATTR_IE]) {
request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
memcpy((void *)request->ie,
nla_data(info->attrs[NL80211_ATTR_IE]),
request->ie_len);
}
request->dev = dev;
request->wiphy = &rdev->wiphy;
request->interval = interval;
err = rdev->ops->sched_scan_start(&rdev->wiphy, dev, request);
if (!err) {
rdev->sched_scan_req = request;
nl80211_send_sched_scan(rdev, dev,
NL80211_CMD_START_SCHED_SCAN);
goto out;
}
out_free:
kfree(request);
out:
return err;
}
static int nl80211_stop_sched_scan(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
if (!(rdev->wiphy.flags & WIPHY_FLAG_SUPPORTS_SCHED_SCAN) ||
!rdev->ops->sched_scan_stop)
return -EOPNOTSUPP;
return __cfg80211_stop_sched_scan(rdev, false);
}
static int nl80211_send_bss(struct sk_buff *msg, u32 pid, u32 seq, int flags,
struct cfg80211_registered_device *rdev,
struct wireless_dev *wdev,
struct cfg80211_internal_bss *intbss)
{
struct cfg80211_bss *res = &intbss->pub;
void *hdr;
struct nlattr *bss;
int i;
ASSERT_WDEV_LOCK(wdev);
hdr = nl80211hdr_put(msg, pid, seq, flags,
NL80211_CMD_NEW_SCAN_RESULTS);
if (!hdr)
return -1;
NLA_PUT_U32(msg, NL80211_ATTR_GENERATION, rdev->bss_generation);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, wdev->netdev->ifindex);
bss = nla_nest_start(msg, NL80211_ATTR_BSS);
if (!bss)
goto nla_put_failure;
if (!is_zero_ether_addr(res->bssid))
NLA_PUT(msg, NL80211_BSS_BSSID, ETH_ALEN, res->bssid);
if (res->information_elements && res->len_information_elements)
NLA_PUT(msg, NL80211_BSS_INFORMATION_ELEMENTS,
res->len_information_elements,
res->information_elements);
if (res->beacon_ies && res->len_beacon_ies &&
res->beacon_ies != res->information_elements)
NLA_PUT(msg, NL80211_BSS_BEACON_IES,
res->len_beacon_ies, res->beacon_ies);
if (res->tsf)
NLA_PUT_U64(msg, NL80211_BSS_TSF, res->tsf);
if (res->beacon_interval)
NLA_PUT_U16(msg, NL80211_BSS_BEACON_INTERVAL, res->beacon_interval);
NLA_PUT_U16(msg, NL80211_BSS_CAPABILITY, res->capability);
NLA_PUT_U32(msg, NL80211_BSS_FREQUENCY, res->channel->center_freq);
NLA_PUT_U32(msg, NL80211_BSS_SEEN_MS_AGO,
jiffies_to_msecs(jiffies - intbss->ts));
switch (rdev->wiphy.signal_type) {
case CFG80211_SIGNAL_TYPE_MBM:
NLA_PUT_U32(msg, NL80211_BSS_SIGNAL_MBM, res->signal);
break;
case CFG80211_SIGNAL_TYPE_UNSPEC:
NLA_PUT_U8(msg, NL80211_BSS_SIGNAL_UNSPEC, res->signal);
break;
default:
break;
}
switch (wdev->iftype) {
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_STATION:
if (intbss == wdev->current_bss)
NLA_PUT_U32(msg, NL80211_BSS_STATUS,
NL80211_BSS_STATUS_ASSOCIATED);
else for (i = 0; i < MAX_AUTH_BSSES; i++) {
if (intbss != wdev->auth_bsses[i])
continue;
NLA_PUT_U32(msg, NL80211_BSS_STATUS,
NL80211_BSS_STATUS_AUTHENTICATED);
break;
}
break;
case NL80211_IFTYPE_ADHOC:
if (intbss == wdev->current_bss)
NLA_PUT_U32(msg, NL80211_BSS_STATUS,
NL80211_BSS_STATUS_IBSS_JOINED);
break;
default:
break;
}
nla_nest_end(msg, bss);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_scan(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct cfg80211_registered_device *rdev;
struct net_device *dev;
struct cfg80211_internal_bss *scan;
struct wireless_dev *wdev;
int start = cb->args[1], idx = 0;
int err;
err = nl80211_prepare_netdev_dump(skb, cb, &rdev, &dev);
if (err)
return err;
wdev = dev->ieee80211_ptr;
wdev_lock(wdev);
spin_lock_bh(&rdev->bss_lock);
cfg80211_bss_expire(rdev);
list_for_each_entry(scan, &rdev->bss_list, list) {
if (++idx <= start)
continue;
if (nl80211_send_bss(skb,
NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
rdev, wdev, scan) < 0) {
idx--;
break;
}
}
spin_unlock_bh(&rdev->bss_lock);
wdev_unlock(wdev);
cb->args[1] = idx;
nl80211_finish_netdev_dump(rdev);
return skb->len;
}
static int nl80211_send_survey(struct sk_buff *msg, u32 pid, u32 seq,
int flags, struct net_device *dev,
struct survey_info *survey)
{
void *hdr;
struct nlattr *infoattr;
/* Survey without a channel doesn't make sense */
if (!survey->channel)
return -EINVAL;
hdr = nl80211hdr_put(msg, pid, seq, flags,
NL80211_CMD_NEW_SURVEY_RESULTS);
if (!hdr)
return -ENOMEM;
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, dev->ifindex);
infoattr = nla_nest_start(msg, NL80211_ATTR_SURVEY_INFO);
if (!infoattr)
goto nla_put_failure;
NLA_PUT_U32(msg, NL80211_SURVEY_INFO_FREQUENCY,
survey->channel->center_freq);
if (survey->filled & SURVEY_INFO_NOISE_DBM)
NLA_PUT_U8(msg, NL80211_SURVEY_INFO_NOISE,
survey->noise);
if (survey->filled & SURVEY_INFO_IN_USE)
NLA_PUT_FLAG(msg, NL80211_SURVEY_INFO_IN_USE);
if (survey->filled & SURVEY_INFO_CHANNEL_TIME)
NLA_PUT_U64(msg, NL80211_SURVEY_INFO_CHANNEL_TIME,
survey->channel_time);
if (survey->filled & SURVEY_INFO_CHANNEL_TIME_BUSY)
NLA_PUT_U64(msg, NL80211_SURVEY_INFO_CHANNEL_TIME_BUSY,
survey->channel_time_busy);
if (survey->filled & SURVEY_INFO_CHANNEL_TIME_EXT_BUSY)
NLA_PUT_U64(msg, NL80211_SURVEY_INFO_CHANNEL_TIME_EXT_BUSY,
survey->channel_time_ext_busy);
if (survey->filled & SURVEY_INFO_CHANNEL_TIME_RX)
NLA_PUT_U64(msg, NL80211_SURVEY_INFO_CHANNEL_TIME_RX,
survey->channel_time_rx);
if (survey->filled & SURVEY_INFO_CHANNEL_TIME_TX)
NLA_PUT_U64(msg, NL80211_SURVEY_INFO_CHANNEL_TIME_TX,
survey->channel_time_tx);
nla_nest_end(msg, infoattr);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_survey(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct survey_info survey;
struct cfg80211_registered_device *dev;
struct net_device *netdev;
int survey_idx = cb->args[1];
int res;
res = nl80211_prepare_netdev_dump(skb, cb, &dev, &netdev);
if (res)
return res;
if (!dev->ops->dump_survey) {
res = -EOPNOTSUPP;
goto out_err;
}
while (1) {
res = dev->ops->dump_survey(&dev->wiphy, netdev, survey_idx,
&survey);
if (res == -ENOENT)
break;
if (res)
goto out_err;
if (nl80211_send_survey(skb,
NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
netdev,
&survey) < 0)
goto out;
survey_idx++;
}
out:
cb->args[1] = survey_idx;
res = skb->len;
out_err:
nl80211_finish_netdev_dump(dev);
return res;
}
static bool nl80211_valid_auth_type(enum nl80211_auth_type auth_type)
{
return auth_type <= NL80211_AUTHTYPE_MAX;
}
static bool nl80211_valid_wpa_versions(u32 wpa_versions)
{
return !(wpa_versions & ~(NL80211_WPA_VERSION_1 |
NL80211_WPA_VERSION_2));
}
static bool nl80211_valid_akm_suite(u32 akm)
{
return akm == WLAN_AKM_SUITE_8021X ||
akm == WLAN_AKM_SUITE_PSK;
}
static bool nl80211_valid_cipher_suite(u32 cipher)
{
return cipher == WLAN_CIPHER_SUITE_WEP40 ||
cipher == WLAN_CIPHER_SUITE_WEP104 ||
cipher == WLAN_CIPHER_SUITE_TKIP ||
cipher == WLAN_CIPHER_SUITE_CCMP ||
cipher == WLAN_CIPHER_SUITE_AES_CMAC;
}
static int nl80211_authenticate(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct ieee80211_channel *chan;
const u8 *bssid, *ssid, *ie = NULL;
int err, ssid_len, ie_len = 0;
enum nl80211_auth_type auth_type;
struct key_parse key;
bool local_state_change;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_AUTH_TYPE])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_SSID])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_WIPHY_FREQ])
return -EINVAL;
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (key.idx >= 0) {
if (key.type != -1 && key.type != NL80211_KEYTYPE_GROUP)
return -EINVAL;
if (!key.p.key || !key.p.key_len)
return -EINVAL;
if ((key.p.cipher != WLAN_CIPHER_SUITE_WEP40 ||
key.p.key_len != WLAN_KEY_LEN_WEP40) &&
(key.p.cipher != WLAN_CIPHER_SUITE_WEP104 ||
key.p.key_len != WLAN_KEY_LEN_WEP104))
return -EINVAL;
if (key.idx > 4)
return -EINVAL;
} else {
key.p.key_len = 0;
key.p.key = NULL;
}
if (key.idx >= 0) {
int i;
bool ok = false;
for (i = 0; i < rdev->wiphy.n_cipher_suites; i++) {
if (key.p.cipher == rdev->wiphy.cipher_suites[i]) {
ok = true;
break;
}
}
if (!ok)
return -EINVAL;
}
if (!rdev->ops->auth)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
chan = ieee80211_get_channel(&rdev->wiphy,
nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_FREQ]));
if (!chan || (chan->flags & IEEE80211_CHAN_DISABLED))
return -EINVAL;
ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
auth_type = nla_get_u32(info->attrs[NL80211_ATTR_AUTH_TYPE]);
if (!nl80211_valid_auth_type(auth_type))
return -EINVAL;
local_state_change = !!info->attrs[NL80211_ATTR_LOCAL_STATE_CHANGE];
return cfg80211_mlme_auth(rdev, dev, chan, auth_type, bssid,
ssid, ssid_len, ie, ie_len,
key.p.key, key.p.key_len, key.idx,
local_state_change);
}
static int nl80211_crypto_settings(struct cfg80211_registered_device *rdev,
struct genl_info *info,
struct cfg80211_crypto_settings *settings,
int cipher_limit)
{
memset(settings, 0, sizeof(*settings));
settings->control_port = info->attrs[NL80211_ATTR_CONTROL_PORT];
if (info->attrs[NL80211_ATTR_CONTROL_PORT_ETHERTYPE]) {
u16 proto;
proto = nla_get_u16(
info->attrs[NL80211_ATTR_CONTROL_PORT_ETHERTYPE]);
settings->control_port_ethertype = cpu_to_be16(proto);
if (!(rdev->wiphy.flags & WIPHY_FLAG_CONTROL_PORT_PROTOCOL) &&
proto != ETH_P_PAE)
return -EINVAL;
if (info->attrs[NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT])
settings->control_port_no_encrypt = true;
} else
settings->control_port_ethertype = cpu_to_be16(ETH_P_PAE);
if (info->attrs[NL80211_ATTR_CIPHER_SUITES_PAIRWISE]) {
void *data;
int len, i;
data = nla_data(info->attrs[NL80211_ATTR_CIPHER_SUITES_PAIRWISE]);
len = nla_len(info->attrs[NL80211_ATTR_CIPHER_SUITES_PAIRWISE]);
settings->n_ciphers_pairwise = len / sizeof(u32);
if (len % sizeof(u32))
return -EINVAL;
if (settings->n_ciphers_pairwise > cipher_limit)
return -EINVAL;
memcpy(settings->ciphers_pairwise, data, len);
for (i = 0; i < settings->n_ciphers_pairwise; i++)
if (!nl80211_valid_cipher_suite(
settings->ciphers_pairwise[i]))
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_CIPHER_SUITE_GROUP]) {
settings->cipher_group =
nla_get_u32(info->attrs[NL80211_ATTR_CIPHER_SUITE_GROUP]);
if (!nl80211_valid_cipher_suite(settings->cipher_group))
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_WPA_VERSIONS]) {
settings->wpa_versions =
nla_get_u32(info->attrs[NL80211_ATTR_WPA_VERSIONS]);
if (!nl80211_valid_wpa_versions(settings->wpa_versions))
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_AKM_SUITES]) {
void *data;
int len, i;
data = nla_data(info->attrs[NL80211_ATTR_AKM_SUITES]);
len = nla_len(info->attrs[NL80211_ATTR_AKM_SUITES]);
settings->n_akm_suites = len / sizeof(u32);
if (len % sizeof(u32))
return -EINVAL;
memcpy(settings->akm_suites, data, len);
for (i = 0; i < settings->n_ciphers_pairwise; i++)
if (!nl80211_valid_akm_suite(settings->akm_suites[i]))
return -EINVAL;
}
return 0;
}
static int nl80211_associate(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct cfg80211_crypto_settings crypto;
struct ieee80211_channel *chan;
const u8 *bssid, *ssid, *ie = NULL, *prev_bssid = NULL;
int err, ssid_len, ie_len = 0;
bool use_mfp = false;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC] ||
!info->attrs[NL80211_ATTR_SSID] ||
!info->attrs[NL80211_ATTR_WIPHY_FREQ])
return -EINVAL;
if (!rdev->ops->assoc)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
chan = ieee80211_get_channel(&rdev->wiphy,
nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_FREQ]));
if (!chan || (chan->flags & IEEE80211_CHAN_DISABLED))
return -EINVAL;
ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
if (info->attrs[NL80211_ATTR_USE_MFP]) {
enum nl80211_mfp mfp =
nla_get_u32(info->attrs[NL80211_ATTR_USE_MFP]);
if (mfp == NL80211_MFP_REQUIRED)
use_mfp = true;
else if (mfp != NL80211_MFP_NO)
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_PREV_BSSID])
prev_bssid = nla_data(info->attrs[NL80211_ATTR_PREV_BSSID]);
err = nl80211_crypto_settings(rdev, info, &crypto, 1);
if (!err)
err = cfg80211_mlme_assoc(rdev, dev, chan, bssid, prev_bssid,
ssid, ssid_len, ie, ie_len, use_mfp,
&crypto);
return err;
}
static int nl80211_deauthenticate(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
const u8 *ie = NULL, *bssid;
int ie_len = 0;
u16 reason_code;
bool local_state_change;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_REASON_CODE])
return -EINVAL;
if (!rdev->ops->deauth)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
reason_code = nla_get_u16(info->attrs[NL80211_ATTR_REASON_CODE]);
if (reason_code == 0) {
/* Reason Code 0 is reserved */
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_IE]) {
ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
local_state_change = !!info->attrs[NL80211_ATTR_LOCAL_STATE_CHANGE];
return cfg80211_mlme_deauth(rdev, dev, bssid, ie, ie_len, reason_code,
local_state_change);
}
static int nl80211_disassociate(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
const u8 *ie = NULL, *bssid;
int ie_len = 0;
u16 reason_code;
bool local_state_change;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_REASON_CODE])
return -EINVAL;
if (!rdev->ops->disassoc)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
reason_code = nla_get_u16(info->attrs[NL80211_ATTR_REASON_CODE]);
if (reason_code == 0) {
/* Reason Code 0 is reserved */
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_IE]) {
ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
local_state_change = !!info->attrs[NL80211_ATTR_LOCAL_STATE_CHANGE];
return cfg80211_mlme_disassoc(rdev, dev, bssid, ie, ie_len, reason_code,
local_state_change);
}
static bool
nl80211_parse_mcast_rate(struct cfg80211_registered_device *rdev,
int mcast_rate[IEEE80211_NUM_BANDS],
int rateval)
{
struct wiphy *wiphy = &rdev->wiphy;
bool found = false;
int band, i;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
struct ieee80211_supported_band *sband;
sband = wiphy->bands[band];
if (!sband)
continue;
for (i = 0; i < sband->n_bitrates; i++) {
if (sband->bitrates[i].bitrate == rateval) {
mcast_rate[band] = i + 1;
found = true;
break;
}
}
}
return found;
}
static int nl80211_join_ibss(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct cfg80211_ibss_params ibss;
struct wiphy *wiphy;
struct cfg80211_cached_keys *connkeys = NULL;
int err;
memset(&ibss, 0, sizeof(ibss));
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_WIPHY_FREQ] ||
!info->attrs[NL80211_ATTR_SSID] ||
!nla_len(info->attrs[NL80211_ATTR_SSID]))
return -EINVAL;
ibss.beacon_interval = 100;
if (info->attrs[NL80211_ATTR_BEACON_INTERVAL]) {
ibss.beacon_interval =
nla_get_u32(info->attrs[NL80211_ATTR_BEACON_INTERVAL]);
if (ibss.beacon_interval < 1 || ibss.beacon_interval > 10000)
return -EINVAL;
}
if (!rdev->ops->join_ibss)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_ADHOC)
return -EOPNOTSUPP;
wiphy = &rdev->wiphy;
if (info->attrs[NL80211_ATTR_MAC])
ibss.bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
ibss.ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
ibss.ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
ibss.ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ibss.ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
ibss.channel = ieee80211_get_channel(wiphy,
nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_FREQ]));
if (!ibss.channel ||
ibss.channel->flags & IEEE80211_CHAN_NO_IBSS ||
ibss.channel->flags & IEEE80211_CHAN_DISABLED)
return -EINVAL;
ibss.channel_fixed = !!info->attrs[NL80211_ATTR_FREQ_FIXED];
ibss.privacy = !!info->attrs[NL80211_ATTR_PRIVACY];
if (info->attrs[NL80211_ATTR_BSS_BASIC_RATES]) {
u8 *rates =
nla_data(info->attrs[NL80211_ATTR_BSS_BASIC_RATES]);
int n_rates =
nla_len(info->attrs[NL80211_ATTR_BSS_BASIC_RATES]);
struct ieee80211_supported_band *sband =
wiphy->bands[ibss.channel->band];
int i, j;
if (n_rates == 0)
return -EINVAL;
for (i = 0; i < n_rates; i++) {
int rate = (rates[i] & 0x7f) * 5;
bool found = false;
for (j = 0; j < sband->n_bitrates; j++) {
if (sband->bitrates[j].bitrate == rate) {
found = true;
ibss.basic_rates |= BIT(j);
break;
}
}
if (!found)
return -EINVAL;
}
}
if (info->attrs[NL80211_ATTR_MCAST_RATE] &&
!nl80211_parse_mcast_rate(rdev, ibss.mcast_rate,
nla_get_u32(info->attrs[NL80211_ATTR_MCAST_RATE])))
return -EINVAL;
if (ibss.privacy && info->attrs[NL80211_ATTR_KEYS]) {
connkeys = nl80211_parse_connkeys(rdev,
info->attrs[NL80211_ATTR_KEYS]);
if (IS_ERR(connkeys))
return PTR_ERR(connkeys);
}
err = cfg80211_join_ibss(rdev, dev, &ibss, connkeys);
if (err)
kfree(connkeys);
return err;
}
static int nl80211_leave_ibss(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
if (!rdev->ops->leave_ibss)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_ADHOC)
return -EOPNOTSUPP;
return cfg80211_leave_ibss(rdev, dev, false);
}
#ifdef CONFIG_NL80211_TESTMODE
static struct genl_multicast_group nl80211_testmode_mcgrp = {
.name = "testmode",
};
static int nl80211_testmode_do(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
if (!info->attrs[NL80211_ATTR_TESTDATA])
return -EINVAL;
err = -EOPNOTSUPP;
if (rdev->ops->testmode_cmd) {
rdev->testmode_info = info;
err = rdev->ops->testmode_cmd(&rdev->wiphy,
nla_data(info->attrs[NL80211_ATTR_TESTDATA]),
nla_len(info->attrs[NL80211_ATTR_TESTDATA]));
rdev->testmode_info = NULL;
}
return err;
}
static struct sk_buff *
__cfg80211_testmode_alloc_skb(struct cfg80211_registered_device *rdev,
int approxlen, u32 pid, u32 seq, gfp_t gfp)
{
struct sk_buff *skb;
void *hdr;
struct nlattr *data;
skb = nlmsg_new(approxlen + 100, gfp);
if (!skb)
return NULL;
hdr = nl80211hdr_put(skb, pid, seq, 0, NL80211_CMD_TESTMODE);
if (!hdr) {
kfree_skb(skb);
return NULL;
}
NLA_PUT_U32(skb, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
data = nla_nest_start(skb, NL80211_ATTR_TESTDATA);
((void **)skb->cb)[0] = rdev;
((void **)skb->cb)[1] = hdr;
((void **)skb->cb)[2] = data;
return skb;
nla_put_failure:
kfree_skb(skb);
return NULL;
}
struct sk_buff *cfg80211_testmode_alloc_reply_skb(struct wiphy *wiphy,
int approxlen)
{
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
if (WARN_ON(!rdev->testmode_info))
return NULL;
return __cfg80211_testmode_alloc_skb(rdev, approxlen,
rdev->testmode_info->snd_pid,
rdev->testmode_info->snd_seq,
GFP_KERNEL);
}
EXPORT_SYMBOL(cfg80211_testmode_alloc_reply_skb);
int cfg80211_testmode_reply(struct sk_buff *skb)
{
struct cfg80211_registered_device *rdev = ((void **)skb->cb)[0];
void *hdr = ((void **)skb->cb)[1];
struct nlattr *data = ((void **)skb->cb)[2];
if (WARN_ON(!rdev->testmode_info)) {
kfree_skb(skb);
return -EINVAL;
}
nla_nest_end(skb, data);
genlmsg_end(skb, hdr);
return genlmsg_reply(skb, rdev->testmode_info);
}
EXPORT_SYMBOL(cfg80211_testmode_reply);
struct sk_buff *cfg80211_testmode_alloc_event_skb(struct wiphy *wiphy,
int approxlen, gfp_t gfp)
{
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
return __cfg80211_testmode_alloc_skb(rdev, approxlen, 0, 0, gfp);
}
EXPORT_SYMBOL(cfg80211_testmode_alloc_event_skb);
void cfg80211_testmode_event(struct sk_buff *skb, gfp_t gfp)
{
void *hdr = ((void **)skb->cb)[1];
struct nlattr *data = ((void **)skb->cb)[2];
nla_nest_end(skb, data);
genlmsg_end(skb, hdr);
genlmsg_multicast(skb, 0, nl80211_testmode_mcgrp.id, gfp);
}
EXPORT_SYMBOL(cfg80211_testmode_event);
#endif
static int nl80211_connect(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct cfg80211_connect_params connect;
struct wiphy *wiphy;
struct cfg80211_cached_keys *connkeys = NULL;
int err;
memset(&connect, 0, sizeof(connect));
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_SSID] ||
!nla_len(info->attrs[NL80211_ATTR_SSID]))
return -EINVAL;
if (info->attrs[NL80211_ATTR_AUTH_TYPE]) {
connect.auth_type =
nla_get_u32(info->attrs[NL80211_ATTR_AUTH_TYPE]);
if (!nl80211_valid_auth_type(connect.auth_type))
return -EINVAL;
} else
connect.auth_type = NL80211_AUTHTYPE_AUTOMATIC;
connect.privacy = info->attrs[NL80211_ATTR_PRIVACY];
err = nl80211_crypto_settings(rdev, info, &connect.crypto,
NL80211_MAX_NR_CIPHER_SUITES);
if (err)
return err;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
wiphy = &rdev->wiphy;
if (info->attrs[NL80211_ATTR_MAC])
connect.bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
connect.ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
connect.ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
connect.ie = nla_data(info->attrs[NL80211_ATTR_IE]);
connect.ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
if (info->attrs[NL80211_ATTR_WIPHY_FREQ]) {
connect.channel =
ieee80211_get_channel(wiphy,
nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_FREQ]));
if (!connect.channel ||
connect.channel->flags & IEEE80211_CHAN_DISABLED)
return -EINVAL;
}
if (connect.privacy && info->attrs[NL80211_ATTR_KEYS]) {
connkeys = nl80211_parse_connkeys(rdev,
info->attrs[NL80211_ATTR_KEYS]);
if (IS_ERR(connkeys))
return PTR_ERR(connkeys);
}
err = cfg80211_connect(rdev, dev, &connect, connkeys);
if (err)
kfree(connkeys);
return err;
}
static int nl80211_disconnect(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u16 reason;
if (!info->attrs[NL80211_ATTR_REASON_CODE])
reason = WLAN_REASON_DEAUTH_LEAVING;
else
reason = nla_get_u16(info->attrs[NL80211_ATTR_REASON_CODE]);
if (reason == 0)
return -EINVAL;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
return cfg80211_disconnect(rdev, dev, reason, true);
}
static int nl80211_wiphy_netns(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net *net;
int err;
u32 pid;
if (!info->attrs[NL80211_ATTR_PID])
return -EINVAL;
pid = nla_get_u32(info->attrs[NL80211_ATTR_PID]);
net = get_net_ns_by_pid(pid);
if (IS_ERR(net))
return PTR_ERR(net);
err = 0;
/* check if anything to do */
if (!net_eq(wiphy_net(&rdev->wiphy), net))
err = cfg80211_switch_netns(rdev, net);
put_net(net);
return err;
}
static int nl80211_setdel_pmksa(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int (*rdev_ops)(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_pmksa *pmksa) = NULL;
struct net_device *dev = info->user_ptr[1];
struct cfg80211_pmksa pmksa;
memset(&pmksa, 0, sizeof(struct cfg80211_pmksa));
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_PMKID])
return -EINVAL;
pmksa.pmkid = nla_data(info->attrs[NL80211_ATTR_PMKID]);
pmksa.bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
switch (info->genlhdr->cmd) {
case NL80211_CMD_SET_PMKSA:
rdev_ops = rdev->ops->set_pmksa;
break;
case NL80211_CMD_DEL_PMKSA:
rdev_ops = rdev->ops->del_pmksa;
break;
default:
WARN_ON(1);
break;
}
if (!rdev_ops)
return -EOPNOTSUPP;
return rdev_ops(&rdev->wiphy, dev, &pmksa);
}
static int nl80211_flush_pmksa(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
if (!rdev->ops->flush_pmksa)
return -EOPNOTSUPP;
return rdev->ops->flush_pmksa(&rdev->wiphy, dev);
}
static int nl80211_remain_on_channel(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct ieee80211_channel *chan;
struct sk_buff *msg;
void *hdr;
u64 cookie;
enum nl80211_channel_type channel_type = NL80211_CHAN_NO_HT;
u32 freq, duration;
int err;
if (!info->attrs[NL80211_ATTR_WIPHY_FREQ] ||
!info->attrs[NL80211_ATTR_DURATION])
return -EINVAL;
duration = nla_get_u32(info->attrs[NL80211_ATTR_DURATION]);
/*
* We should be on that channel for at least one jiffie,
* and more than 5 seconds seems excessive.
*/
if (!duration || !msecs_to_jiffies(duration) ||
duration > rdev->wiphy.max_remain_on_channel_duration)
return -EINVAL;
if (!rdev->ops->remain_on_channel)
return -EOPNOTSUPP;
if (info->attrs[NL80211_ATTR_WIPHY_CHANNEL_TYPE]) {
channel_type = nla_get_u32(
info->attrs[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
if (channel_type != NL80211_CHAN_NO_HT &&
channel_type != NL80211_CHAN_HT20 &&
channel_type != NL80211_CHAN_HT40PLUS &&
channel_type != NL80211_CHAN_HT40MINUS)
return -EINVAL;
}
freq = nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_FREQ]);
chan = rdev_freq_to_chan(rdev, freq, channel_type);
if (chan == NULL)
return -EINVAL;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
NL80211_CMD_REMAIN_ON_CHANNEL);
if (IS_ERR(hdr)) {
err = PTR_ERR(hdr);
goto free_msg;
}
err = rdev->ops->remain_on_channel(&rdev->wiphy, dev, chan,
channel_type, duration, &cookie);
if (err)
goto free_msg;
NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie);
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static int nl80211_cancel_remain_on_channel(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u64 cookie;
if (!info->attrs[NL80211_ATTR_COOKIE])
return -EINVAL;
if (!rdev->ops->cancel_remain_on_channel)
return -EOPNOTSUPP;
cookie = nla_get_u64(info->attrs[NL80211_ATTR_COOKIE]);
return rdev->ops->cancel_remain_on_channel(&rdev->wiphy, dev, cookie);
}
static u32 rateset_to_mask(struct ieee80211_supported_band *sband,
u8 *rates, u8 rates_len)
{
u8 i;
u32 mask = 0;
for (i = 0; i < rates_len; i++) {
int rate = (rates[i] & 0x7f) * 5;
int ridx;
for (ridx = 0; ridx < sband->n_bitrates; ridx++) {
struct ieee80211_rate *srate =
&sband->bitrates[ridx];
if (rate == srate->bitrate) {
mask |= 1 << ridx;
break;
}
}
if (ridx == sband->n_bitrates)
return 0; /* rate not found */
}
return mask;
}
static const struct nla_policy nl80211_txattr_policy[NL80211_TXRATE_MAX + 1] = {
[NL80211_TXRATE_LEGACY] = { .type = NLA_BINARY,
.len = NL80211_MAX_SUPP_RATES },
};
static int nl80211_set_tx_bitrate_mask(struct sk_buff *skb,
struct genl_info *info)
{
struct nlattr *tb[NL80211_TXRATE_MAX + 1];
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct cfg80211_bitrate_mask mask;
int rem, i;
struct net_device *dev = info->user_ptr[1];
struct nlattr *tx_rates;
struct ieee80211_supported_band *sband;
if (info->attrs[NL80211_ATTR_TX_RATES] == NULL)
return -EINVAL;
if (!rdev->ops->set_bitrate_mask)
return -EOPNOTSUPP;
memset(&mask, 0, sizeof(mask));
/* Default to all rates enabled */
for (i = 0; i < IEEE80211_NUM_BANDS; i++) {
sband = rdev->wiphy.bands[i];
mask.control[i].legacy =
sband ? (1 << sband->n_bitrates) - 1 : 0;
}
/*
* The nested attribute uses enum nl80211_band as the index. This maps
* directly to the enum ieee80211_band values used in cfg80211.
*/
nla_for_each_nested(tx_rates, info->attrs[NL80211_ATTR_TX_RATES], rem)
{
enum ieee80211_band band = nla_type(tx_rates);
if (band < 0 || band >= IEEE80211_NUM_BANDS)
return -EINVAL;
sband = rdev->wiphy.bands[band];
if (sband == NULL)
return -EINVAL;
nla_parse(tb, NL80211_TXRATE_MAX, nla_data(tx_rates),
nla_len(tx_rates), nl80211_txattr_policy);
if (tb[NL80211_TXRATE_LEGACY]) {
mask.control[band].legacy = rateset_to_mask(
sband,
nla_data(tb[NL80211_TXRATE_LEGACY]),
nla_len(tb[NL80211_TXRATE_LEGACY]));
if (mask.control[band].legacy == 0)
return -EINVAL;
}
}
return rdev->ops->set_bitrate_mask(&rdev->wiphy, dev, NULL, &mask);
}
static int nl80211_register_mgmt(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u16 frame_type = IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_ACTION;
if (!info->attrs[NL80211_ATTR_FRAME_MATCH])
return -EINVAL;
if (info->attrs[NL80211_ATTR_FRAME_TYPE])
frame_type = nla_get_u16(info->attrs[NL80211_ATTR_FRAME_TYPE]);
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_ADHOC &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP_VLAN &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EOPNOTSUPP;
/* not much point in registering if we can't reply */
if (!rdev->ops->mgmt_tx)
return -EOPNOTSUPP;
return cfg80211_mlme_register_mgmt(dev->ieee80211_ptr, info->snd_pid,
frame_type,
nla_data(info->attrs[NL80211_ATTR_FRAME_MATCH]),
nla_len(info->attrs[NL80211_ATTR_FRAME_MATCH]));
}
static int nl80211_tx_mgmt(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct ieee80211_channel *chan;
enum nl80211_channel_type channel_type = NL80211_CHAN_NO_HT;
bool channel_type_valid = false;
u32 freq;
int err;
void *hdr;
u64 cookie;
struct sk_buff *msg;
unsigned int wait = 0;
bool offchan;
if (!info->attrs[NL80211_ATTR_FRAME] ||
!info->attrs[NL80211_ATTR_WIPHY_FREQ])
return -EINVAL;
if (!rdev->ops->mgmt_tx)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_ADHOC &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP_VLAN &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EOPNOTSUPP;
if (info->attrs[NL80211_ATTR_DURATION]) {
if (!rdev->ops->mgmt_tx_cancel_wait)
return -EINVAL;
wait = nla_get_u32(info->attrs[NL80211_ATTR_DURATION]);
}
if (info->attrs[NL80211_ATTR_WIPHY_CHANNEL_TYPE]) {
channel_type = nla_get_u32(
info->attrs[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
if (channel_type != NL80211_CHAN_NO_HT &&
channel_type != NL80211_CHAN_HT20 &&
channel_type != NL80211_CHAN_HT40PLUS &&
channel_type != NL80211_CHAN_HT40MINUS)
return -EINVAL;
channel_type_valid = true;
}
offchan = info->attrs[NL80211_ATTR_OFFCHANNEL_TX_OK];
freq = nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_FREQ]);
chan = rdev_freq_to_chan(rdev, freq, channel_type);
if (chan == NULL)
return -EINVAL;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
NL80211_CMD_FRAME);
if (IS_ERR(hdr)) {
err = PTR_ERR(hdr);
goto free_msg;
}
err = cfg80211_mlme_mgmt_tx(rdev, dev, chan, offchan, channel_type,
channel_type_valid, wait,
nla_data(info->attrs[NL80211_ATTR_FRAME]),
nla_len(info->attrs[NL80211_ATTR_FRAME]),
&cookie);
if (err)
goto free_msg;
NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie);
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static int nl80211_tx_mgmt_cancel_wait(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u64 cookie;
if (!info->attrs[NL80211_ATTR_COOKIE])
return -EINVAL;
if (!rdev->ops->mgmt_tx_cancel_wait)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_ADHOC &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP_VLAN &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EOPNOTSUPP;
cookie = nla_get_u64(info->attrs[NL80211_ATTR_COOKIE]);
return rdev->ops->mgmt_tx_cancel_wait(&rdev->wiphy, dev, cookie);
}
static int nl80211_set_power_save(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev;
struct net_device *dev = info->user_ptr[1];
u8 ps_state;
bool state;
int err;
if (!info->attrs[NL80211_ATTR_PS_STATE])
return -EINVAL;
ps_state = nla_get_u32(info->attrs[NL80211_ATTR_PS_STATE]);
if (ps_state != NL80211_PS_DISABLED && ps_state != NL80211_PS_ENABLED)
return -EINVAL;
wdev = dev->ieee80211_ptr;
if (!rdev->ops->set_power_mgmt)
return -EOPNOTSUPP;
state = (ps_state == NL80211_PS_ENABLED) ? true : false;
if (state == wdev->ps)
return 0;
err = rdev->ops->set_power_mgmt(wdev->wiphy, dev, state,
wdev->ps_timeout);
if (!err)
wdev->ps = state;
return err;
}
static int nl80211_get_power_save(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
enum nl80211_ps_state ps_state;
struct wireless_dev *wdev;
struct net_device *dev = info->user_ptr[1];
struct sk_buff *msg;
void *hdr;
int err;
wdev = dev->ieee80211_ptr;
if (!rdev->ops->set_power_mgmt)
return -EOPNOTSUPP;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
NL80211_CMD_GET_POWER_SAVE);
if (!hdr) {
err = -ENOBUFS;
goto free_msg;
}
if (wdev->ps)
ps_state = NL80211_PS_ENABLED;
else
ps_state = NL80211_PS_DISABLED;
NLA_PUT_U32(msg, NL80211_ATTR_PS_STATE, ps_state);
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static struct nla_policy
nl80211_attr_cqm_policy[NL80211_ATTR_CQM_MAX + 1] __read_mostly = {
[NL80211_ATTR_CQM_RSSI_THOLD] = { .type = NLA_U32 },
[NL80211_ATTR_CQM_RSSI_HYST] = { .type = NLA_U32 },
[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] = { .type = NLA_U32 },
};
static int nl80211_set_cqm_rssi(struct genl_info *info,
s32 threshold, u32 hysteresis)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev;
struct net_device *dev = info->user_ptr[1];
if (threshold > 0)
return -EINVAL;
wdev = dev->ieee80211_ptr;
if (!rdev->ops->set_cqm_rssi_config)
return -EOPNOTSUPP;
if (wdev->iftype != NL80211_IFTYPE_STATION &&
wdev->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
return rdev->ops->set_cqm_rssi_config(wdev->wiphy, dev,
threshold, hysteresis);
}
static int nl80211_set_cqm(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr *attrs[NL80211_ATTR_CQM_MAX + 1];
struct nlattr *cqm;
int err;
cqm = info->attrs[NL80211_ATTR_CQM];
if (!cqm) {
err = -EINVAL;
goto out;
}
err = nla_parse_nested(attrs, NL80211_ATTR_CQM_MAX, cqm,
nl80211_attr_cqm_policy);
if (err)
goto out;
if (attrs[NL80211_ATTR_CQM_RSSI_THOLD] &&
attrs[NL80211_ATTR_CQM_RSSI_HYST]) {
s32 threshold;
u32 hysteresis;
threshold = nla_get_u32(attrs[NL80211_ATTR_CQM_RSSI_THOLD]);
hysteresis = nla_get_u32(attrs[NL80211_ATTR_CQM_RSSI_HYST]);
err = nl80211_set_cqm_rssi(info, threshold, hysteresis);
} else
err = -EINVAL;
out:
return err;
}
static int nl80211_join_mesh(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct mesh_config cfg;
struct mesh_setup setup;
int err;
/* start with default */
memcpy(&cfg, &default_mesh_config, sizeof(cfg));
memcpy(&setup, &default_mesh_setup, sizeof(setup));
if (info->attrs[NL80211_ATTR_MESH_CONFIG]) {
/* and parse parameters if given */
err = nl80211_parse_mesh_config(info, &cfg, NULL);
if (err)
return err;
}
if (!info->attrs[NL80211_ATTR_MESH_ID] ||
!nla_len(info->attrs[NL80211_ATTR_MESH_ID]))
return -EINVAL;
setup.mesh_id = nla_data(info->attrs[NL80211_ATTR_MESH_ID]);
setup.mesh_id_len = nla_len(info->attrs[NL80211_ATTR_MESH_ID]);
if (info->attrs[NL80211_ATTR_MESH_SETUP]) {
/* parse additional setup parameters if given */
err = nl80211_parse_mesh_setup(info, &setup);
if (err)
return err;
}
return cfg80211_join_mesh(rdev, dev, &setup, &cfg);
}
static int nl80211_leave_mesh(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
return cfg80211_leave_mesh(rdev, dev);
}
static int nl80211_get_wowlan(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct sk_buff *msg;
void *hdr;
if (!rdev->wiphy.wowlan.flags && !rdev->wiphy.wowlan.n_patterns)
return -EOPNOTSUPP;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
NL80211_CMD_GET_WOWLAN);
if (!hdr)
goto nla_put_failure;
if (rdev->wowlan) {
struct nlattr *nl_wowlan;
nl_wowlan = nla_nest_start(msg, NL80211_ATTR_WOWLAN_TRIGGERS);
if (!nl_wowlan)
goto nla_put_failure;
if (rdev->wowlan->any)
NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_ANY);
if (rdev->wowlan->disconnect)
NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_DISCONNECT);
if (rdev->wowlan->magic_pkt)
NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_MAGIC_PKT);
if (rdev->wowlan->n_patterns) {
struct nlattr *nl_pats, *nl_pat;
int i, pat_len;
nl_pats = nla_nest_start(msg,
NL80211_WOWLAN_TRIG_PKT_PATTERN);
if (!nl_pats)
goto nla_put_failure;
for (i = 0; i < rdev->wowlan->n_patterns; i++) {
nl_pat = nla_nest_start(msg, i + 1);
if (!nl_pat)
goto nla_put_failure;
pat_len = rdev->wowlan->patterns[i].pattern_len;
NLA_PUT(msg, NL80211_WOWLAN_PKTPAT_MASK,
DIV_ROUND_UP(pat_len, 8),
rdev->wowlan->patterns[i].mask);
NLA_PUT(msg, NL80211_WOWLAN_PKTPAT_PATTERN,
pat_len,
rdev->wowlan->patterns[i].pattern);
nla_nest_end(msg, nl_pat);
}
nla_nest_end(msg, nl_pats);
}
nla_nest_end(msg, nl_wowlan);
}
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
nlmsg_free(msg);
return -ENOBUFS;
}
static int nl80211_set_wowlan(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct nlattr *tb[NUM_NL80211_WOWLAN_TRIG];
struct cfg80211_wowlan no_triggers = {};
struct cfg80211_wowlan new_triggers = {};
struct wiphy_wowlan_support *wowlan = &rdev->wiphy.wowlan;
int err, i;
if (!rdev->wiphy.wowlan.flags && !rdev->wiphy.wowlan.n_patterns)
return -EOPNOTSUPP;
if (!info->attrs[NL80211_ATTR_WOWLAN_TRIGGERS])
goto no_triggers;
err = nla_parse(tb, MAX_NL80211_WOWLAN_TRIG,
nla_data(info->attrs[NL80211_ATTR_WOWLAN_TRIGGERS]),
nla_len(info->attrs[NL80211_ATTR_WOWLAN_TRIGGERS]),
nl80211_wowlan_policy);
if (err)
return err;
if (tb[NL80211_WOWLAN_TRIG_ANY]) {
if (!(wowlan->flags & WIPHY_WOWLAN_ANY))
return -EINVAL;
new_triggers.any = true;
}
if (tb[NL80211_WOWLAN_TRIG_DISCONNECT]) {
if (!(wowlan->flags & WIPHY_WOWLAN_DISCONNECT))
return -EINVAL;
new_triggers.disconnect = true;
}
if (tb[NL80211_WOWLAN_TRIG_MAGIC_PKT]) {
if (!(wowlan->flags & WIPHY_WOWLAN_MAGIC_PKT))
return -EINVAL;
new_triggers.magic_pkt = true;
}
if (tb[NL80211_WOWLAN_TRIG_PKT_PATTERN]) {
struct nlattr *pat;
int n_patterns = 0;
int rem, pat_len, mask_len;
struct nlattr *pat_tb[NUM_NL80211_WOWLAN_PKTPAT];
nla_for_each_nested(pat, tb[NL80211_WOWLAN_TRIG_PKT_PATTERN],
rem)
n_patterns++;
if (n_patterns > wowlan->n_patterns)
return -EINVAL;
new_triggers.patterns = kcalloc(n_patterns,
sizeof(new_triggers.patterns[0]),
GFP_KERNEL);
if (!new_triggers.patterns)
return -ENOMEM;
new_triggers.n_patterns = n_patterns;
i = 0;
nla_for_each_nested(pat, tb[NL80211_WOWLAN_TRIG_PKT_PATTERN],
rem) {
nla_parse(pat_tb, MAX_NL80211_WOWLAN_PKTPAT,
nla_data(pat), nla_len(pat), NULL);
err = -EINVAL;
if (!pat_tb[NL80211_WOWLAN_PKTPAT_MASK] ||
!pat_tb[NL80211_WOWLAN_PKTPAT_PATTERN])
goto error;
pat_len = nla_len(pat_tb[NL80211_WOWLAN_PKTPAT_PATTERN]);
mask_len = DIV_ROUND_UP(pat_len, 8);
if (nla_len(pat_tb[NL80211_WOWLAN_PKTPAT_MASK]) !=
mask_len)
goto error;
if (pat_len > wowlan->pattern_max_len ||
pat_len < wowlan->pattern_min_len)
goto error;
new_triggers.patterns[i].mask =
kmalloc(mask_len + pat_len, GFP_KERNEL);
if (!new_triggers.patterns[i].mask) {
err = -ENOMEM;
goto error;
}
new_triggers.patterns[i].pattern =
new_triggers.patterns[i].mask + mask_len;
memcpy(new_triggers.patterns[i].mask,
nla_data(pat_tb[NL80211_WOWLAN_PKTPAT_MASK]),
mask_len);
new_triggers.patterns[i].pattern_len = pat_len;
memcpy(new_triggers.patterns[i].pattern,
nla_data(pat_tb[NL80211_WOWLAN_PKTPAT_PATTERN]),
pat_len);
i++;
}
}
if (memcmp(&new_triggers, &no_triggers, sizeof(new_triggers))) {
struct cfg80211_wowlan *ntrig;
ntrig = kmemdup(&new_triggers, sizeof(new_triggers),
GFP_KERNEL);
if (!ntrig) {
err = -ENOMEM;
goto error;
}
cfg80211_rdev_free_wowlan(rdev);
rdev->wowlan = ntrig;
} else {
no_triggers:
cfg80211_rdev_free_wowlan(rdev);
rdev->wowlan = NULL;
}
return 0;
error:
for (i = 0; i < new_triggers.n_patterns; i++)
kfree(new_triggers.patterns[i].mask);
kfree(new_triggers.patterns);
return err;
}
#define NL80211_FLAG_NEED_WIPHY 0x01
#define NL80211_FLAG_NEED_NETDEV 0x02
#define NL80211_FLAG_NEED_RTNL 0x04
#define NL80211_FLAG_CHECK_NETDEV_UP 0x08
#define NL80211_FLAG_NEED_NETDEV_UP (NL80211_FLAG_NEED_NETDEV |\
NL80211_FLAG_CHECK_NETDEV_UP)
static int nl80211_pre_doit(struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev;
struct net_device *dev;
int err;
bool rtnl = ops->internal_flags & NL80211_FLAG_NEED_RTNL;
if (rtnl)
rtnl_lock();
if (ops->internal_flags & NL80211_FLAG_NEED_WIPHY) {
rdev = cfg80211_get_dev_from_info(info);
if (IS_ERR(rdev)) {
if (rtnl)
rtnl_unlock();
return PTR_ERR(rdev);
}
info->user_ptr[0] = rdev;
} else if (ops->internal_flags & NL80211_FLAG_NEED_NETDEV) {
err = get_rdev_dev_by_info_ifindex(info, &rdev, &dev);
if (err) {
if (rtnl)
rtnl_unlock();
return err;
}
if (ops->internal_flags & NL80211_FLAG_CHECK_NETDEV_UP &&
!netif_running(dev)) {
cfg80211_unlock_rdev(rdev);
dev_put(dev);
if (rtnl)
rtnl_unlock();
return -ENETDOWN;
}
info->user_ptr[0] = rdev;
info->user_ptr[1] = dev;
}
return 0;
}
static void nl80211_post_doit(struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info)
{
if (info->user_ptr[0])
cfg80211_unlock_rdev(info->user_ptr[0]);
if (info->user_ptr[1])
dev_put(info->user_ptr[1]);
if (ops->internal_flags & NL80211_FLAG_NEED_RTNL)
rtnl_unlock();
}
static struct genl_ops nl80211_ops[] = {
{
.cmd = NL80211_CMD_GET_WIPHY,
.doit = nl80211_get_wiphy,
.dumpit = nl80211_dump_wiphy,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = NL80211_FLAG_NEED_WIPHY,
},
{
.cmd = NL80211_CMD_SET_WIPHY,
.doit = nl80211_set_wiphy,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_INTERFACE,
.doit = nl80211_get_interface,
.dumpit = nl80211_dump_interface,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = NL80211_FLAG_NEED_NETDEV,
},
{
.cmd = NL80211_CMD_SET_INTERFACE,
.doit = nl80211_set_interface,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_NEW_INTERFACE,
.doit = nl80211_new_interface,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEL_INTERFACE,
.doit = nl80211_del_interface,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_KEY,
.doit = nl80211_get_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_KEY,
.doit = nl80211_set_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_NEW_KEY,
.doit = nl80211_new_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEL_KEY,
.doit = nl80211_del_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_BEACON,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.doit = nl80211_addset_beacon,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_NEW_BEACON,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.doit = nl80211_addset_beacon,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEL_BEACON,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.doit = nl80211_del_beacon,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_STATION,
.doit = nl80211_get_station,
.dumpit = nl80211_dump_station,
.policy = nl80211_policy,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_STATION,
.doit = nl80211_set_station,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_NEW_STATION,
.doit = nl80211_new_station,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEL_STATION,
.doit = nl80211_del_station,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_MPATH,
.doit = nl80211_get_mpath,
.dumpit = nl80211_dump_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_MPATH,
.doit = nl80211_set_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_NEW_MPATH,
.doit = nl80211_new_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEL_MPATH,
.doit = nl80211_del_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_BSS,
.doit = nl80211_set_bss,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_REG,
.doit = nl80211_get_reg,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
},
{
.cmd = NL80211_CMD_SET_REG,
.doit = nl80211_set_reg,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
},
{
.cmd = NL80211_CMD_REQ_SET_REG,
.doit = nl80211_req_set_reg,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
},
{
.cmd = NL80211_CMD_GET_MESH_CONFIG,
.doit = nl80211_get_mesh_config,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_MESH_CONFIG,
.doit = nl80211_update_mesh_config,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_TRIGGER_SCAN,
.doit = nl80211_trigger_scan,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_SCAN,
.policy = nl80211_policy,
.dumpit = nl80211_dump_scan,
},
{
.cmd = NL80211_CMD_START_SCHED_SCAN,
.doit = nl80211_start_sched_scan,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_STOP_SCHED_SCAN,
.doit = nl80211_stop_sched_scan,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_AUTHENTICATE,
.doit = nl80211_authenticate,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_ASSOCIATE,
.doit = nl80211_associate,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEAUTHENTICATE,
.doit = nl80211_deauthenticate,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DISASSOCIATE,
.doit = nl80211_disassociate,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_JOIN_IBSS,
.doit = nl80211_join_ibss,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_LEAVE_IBSS,
.doit = nl80211_leave_ibss,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
#ifdef CONFIG_NL80211_TESTMODE
{
.cmd = NL80211_CMD_TESTMODE,
.doit = nl80211_testmode_do,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
#endif
{
.cmd = NL80211_CMD_CONNECT,
.doit = nl80211_connect,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DISCONNECT,
.doit = nl80211_disconnect,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_WIPHY_NETNS,
.doit = nl80211_wiphy_netns,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_SURVEY,
.policy = nl80211_policy,
.dumpit = nl80211_dump_survey,
},
{
.cmd = NL80211_CMD_SET_PMKSA,
.doit = nl80211_setdel_pmksa,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEL_PMKSA,
.doit = nl80211_setdel_pmksa,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_FLUSH_PMKSA,
.doit = nl80211_flush_pmksa,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_REMAIN_ON_CHANNEL,
.doit = nl80211_remain_on_channel,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL,
.doit = nl80211_cancel_remain_on_channel,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_TX_BITRATE_MASK,
.doit = nl80211_set_tx_bitrate_mask,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_REGISTER_FRAME,
.doit = nl80211_register_mgmt,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_FRAME,
.doit = nl80211_tx_mgmt,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_FRAME_WAIT_CANCEL,
.doit = nl80211_tx_mgmt_cancel_wait,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_POWER_SAVE,
.doit = nl80211_set_power_save,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_POWER_SAVE,
.doit = nl80211_get_power_save,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_CQM,
.doit = nl80211_set_cqm,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_CHANNEL,
.doit = nl80211_set_channel,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_WDS_PEER,
.doit = nl80211_set_wds_peer,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_JOIN_MESH,
.doit = nl80211_join_mesh,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_LEAVE_MESH,
.doit = nl80211_leave_mesh,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_WOWLAN,
.doit = nl80211_get_wowlan,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_WOWLAN,
.doit = nl80211_set_wowlan,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
};
static struct genl_multicast_group nl80211_mlme_mcgrp = {
.name = "mlme",
};
/* multicast groups */
static struct genl_multicast_group nl80211_config_mcgrp = {
.name = "config",
};
static struct genl_multicast_group nl80211_scan_mcgrp = {
.name = "scan",
};
static struct genl_multicast_group nl80211_regulatory_mcgrp = {
.name = "regulatory",
};
/* notification functions */
void nl80211_notify_dev_rename(struct cfg80211_registered_device *rdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (nl80211_send_wiphy(msg, 0, 0, 0, rdev) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_config_mcgrp.id, GFP_KERNEL);
}
static int nl80211_add_scan_req(struct sk_buff *msg,
struct cfg80211_registered_device *rdev)
{
struct cfg80211_scan_request *req = rdev->scan_req;
struct nlattr *nest;
int i;
ASSERT_RDEV_LOCK(rdev);
if (WARN_ON(!req))
return 0;
nest = nla_nest_start(msg, NL80211_ATTR_SCAN_SSIDS);
if (!nest)
goto nla_put_failure;
for (i = 0; i < req->n_ssids; i++)
NLA_PUT(msg, i, req->ssids[i].ssid_len, req->ssids[i].ssid);
nla_nest_end(msg, nest);
nest = nla_nest_start(msg, NL80211_ATTR_SCAN_FREQUENCIES);
if (!nest)
goto nla_put_failure;
for (i = 0; i < req->n_channels; i++)
NLA_PUT_U32(msg, i, req->channels[i]->center_freq);
nla_nest_end(msg, nest);
if (req->ie)
NLA_PUT(msg, NL80211_ATTR_IE, req->ie_len, req->ie);
return 0;
nla_put_failure:
return -ENOBUFS;
}
static int nl80211_send_scan_msg(struct sk_buff *msg,
struct cfg80211_registered_device *rdev,
struct net_device *netdev,
u32 pid, u32 seq, int flags,
u32 cmd)
{
void *hdr;
hdr = nl80211hdr_put(msg, pid, seq, flags, cmd);
if (!hdr)
return -1;
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
/* ignore errors and send incomplete event anyway */
nl80211_add_scan_req(msg, rdev);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int
nl80211_send_sched_scan_msg(struct sk_buff *msg,
struct cfg80211_registered_device *rdev,
struct net_device *netdev,
u32 pid, u32 seq, int flags, u32 cmd)
{
void *hdr;
hdr = nl80211hdr_put(msg, pid, seq, flags, cmd);
if (!hdr)
return -1;
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
void nl80211_send_scan_start(struct cfg80211_registered_device *rdev,
struct net_device *netdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!msg)
return;
if (nl80211_send_scan_msg(msg, rdev, netdev, 0, 0, 0,
NL80211_CMD_TRIGGER_SCAN) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_scan_mcgrp.id, GFP_KERNEL);
}
void nl80211_send_scan_done(struct cfg80211_registered_device *rdev,
struct net_device *netdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (nl80211_send_scan_msg(msg, rdev, netdev, 0, 0, 0,
NL80211_CMD_NEW_SCAN_RESULTS) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_scan_mcgrp.id, GFP_KERNEL);
}
void nl80211_send_scan_aborted(struct cfg80211_registered_device *rdev,
struct net_device *netdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (nl80211_send_scan_msg(msg, rdev, netdev, 0, 0, 0,
NL80211_CMD_SCAN_ABORTED) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_scan_mcgrp.id, GFP_KERNEL);
}
void nl80211_send_sched_scan_results(struct cfg80211_registered_device *rdev,
struct net_device *netdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (nl80211_send_sched_scan_msg(msg, rdev, netdev, 0, 0, 0,
NL80211_CMD_SCHED_SCAN_RESULTS) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_scan_mcgrp.id, GFP_KERNEL);
}
void nl80211_send_sched_scan(struct cfg80211_registered_device *rdev,
struct net_device *netdev, u32 cmd)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!msg)
return;
if (nl80211_send_sched_scan_msg(msg, rdev, netdev, 0, 0, 0, cmd) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_scan_mcgrp.id, GFP_KERNEL);
}
/*
* This can happen on global regulatory changes or device specific settings
* based on custom world regulatory domains.
*/
void nl80211_send_reg_change_event(struct regulatory_request *request)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_REG_CHANGE);
if (!hdr) {
nlmsg_free(msg);
return;
}
/* Userspace can always count this one always being set */
NLA_PUT_U8(msg, NL80211_ATTR_REG_INITIATOR, request->initiator);
if (request->alpha2[0] == '0' && request->alpha2[1] == '0')
NLA_PUT_U8(msg, NL80211_ATTR_REG_TYPE,
NL80211_REGDOM_TYPE_WORLD);
else if (request->alpha2[0] == '9' && request->alpha2[1] == '9')
NLA_PUT_U8(msg, NL80211_ATTR_REG_TYPE,
NL80211_REGDOM_TYPE_CUSTOM_WORLD);
else if ((request->alpha2[0] == '9' && request->alpha2[1] == '8') ||
request->intersect)
NLA_PUT_U8(msg, NL80211_ATTR_REG_TYPE,
NL80211_REGDOM_TYPE_INTERSECTION);
else {
NLA_PUT_U8(msg, NL80211_ATTR_REG_TYPE,
NL80211_REGDOM_TYPE_COUNTRY);
NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, request->alpha2);
}
if (wiphy_idx_valid(request->wiphy_idx))
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, request->wiphy_idx);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
rcu_read_lock();
genlmsg_multicast_allns(msg, 0, nl80211_regulatory_mcgrp.id,
GFP_ATOMIC);
rcu_read_unlock();
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
static void nl80211_send_mlme_event(struct cfg80211_registered_device *rdev,
struct net_device *netdev,
const u8 *buf, size_t len,
enum nl80211_commands cmd, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, cmd);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_FRAME, len, buf);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_rx_auth(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
nl80211_send_mlme_event(rdev, netdev, buf, len,
NL80211_CMD_AUTHENTICATE, gfp);
}
void nl80211_send_rx_assoc(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
nl80211_send_mlme_event(rdev, netdev, buf, len,
NL80211_CMD_ASSOCIATE, gfp);
}
void nl80211_send_deauth(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
nl80211_send_mlme_event(rdev, netdev, buf, len,
NL80211_CMD_DEAUTHENTICATE, gfp);
}
void nl80211_send_disassoc(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
nl80211_send_mlme_event(rdev, netdev, buf, len,
NL80211_CMD_DISASSOCIATE, gfp);
}
void nl80211_send_unprot_deauth(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
nl80211_send_mlme_event(rdev, netdev, buf, len,
NL80211_CMD_UNPROT_DEAUTHENTICATE, gfp);
}
void nl80211_send_unprot_disassoc(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
nl80211_send_mlme_event(rdev, netdev, buf, len,
NL80211_CMD_UNPROT_DISASSOCIATE, gfp);
}
static void nl80211_send_mlme_timeout(struct cfg80211_registered_device *rdev,
struct net_device *netdev, int cmd,
const u8 *addr, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, cmd);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
NLA_PUT_FLAG(msg, NL80211_ATTR_TIMED_OUT);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_auth_timeout(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *addr,
gfp_t gfp)
{
nl80211_send_mlme_timeout(rdev, netdev, NL80211_CMD_AUTHENTICATE,
addr, gfp);
}
void nl80211_send_assoc_timeout(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *addr,
gfp_t gfp)
{
nl80211_send_mlme_timeout(rdev, netdev, NL80211_CMD_ASSOCIATE,
addr, gfp);
}
void nl80211_send_connect_result(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *bssid,
const u8 *req_ie, size_t req_ie_len,
const u8 *resp_ie, size_t resp_ie_len,
u16 status, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_CONNECT);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
if (bssid)
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
NLA_PUT_U16(msg, NL80211_ATTR_STATUS_CODE, status);
if (req_ie)
NLA_PUT(msg, NL80211_ATTR_REQ_IE, req_ie_len, req_ie);
if (resp_ie)
NLA_PUT(msg, NL80211_ATTR_RESP_IE, resp_ie_len, resp_ie);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_roamed(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *bssid,
const u8 *req_ie, size_t req_ie_len,
const u8 *resp_ie, size_t resp_ie_len, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_ROAM);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
if (req_ie)
NLA_PUT(msg, NL80211_ATTR_REQ_IE, req_ie_len, req_ie);
if (resp_ie)
NLA_PUT(msg, NL80211_ATTR_RESP_IE, resp_ie_len, resp_ie);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_disconnected(struct cfg80211_registered_device *rdev,
struct net_device *netdev, u16 reason,
const u8 *ie, size_t ie_len, bool from_ap)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_DISCONNECT);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
if (from_ap && reason)
NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason);
if (from_ap)
NLA_PUT_FLAG(msg, NL80211_ATTR_DISCONNECTED_BY_AP);
if (ie)
NLA_PUT(msg, NL80211_ATTR_IE, ie_len, ie);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, GFP_KERNEL);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_ibss_bssid(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *bssid,
gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_JOIN_IBSS);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_new_peer_candidate(struct cfg80211_registered_device *rdev,
struct net_device *netdev,
const u8 *macaddr, const u8* ie, u8 ie_len,
gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_NEW_PEER_CANDIDATE);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, macaddr);
if (ie_len && ie)
NLA_PUT(msg, NL80211_ATTR_IE, ie_len , ie);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_michael_mic_failure(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *addr,
enum nl80211_key_type key_type, int key_id,
const u8 *tsc, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_MICHAEL_MIC_FAILURE);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
if (addr)
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE, key_type);
NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_id);
if (tsc)
NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, 6, tsc);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_beacon_hint_event(struct wiphy *wiphy,
struct ieee80211_channel *channel_before,
struct ieee80211_channel *channel_after)
{
struct sk_buff *msg;
void *hdr;
struct nlattr *nl_freq;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_REG_BEACON_HINT);
if (!hdr) {
nlmsg_free(msg);
return;
}
/*
* Since we are applying the beacon hint to a wiphy we know its
* wiphy_idx is valid
*/
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, get_wiphy_idx(wiphy));
/* Before */
nl_freq = nla_nest_start(msg, NL80211_ATTR_FREQ_BEFORE);
if (!nl_freq)
goto nla_put_failure;
if (nl80211_msg_put_channel(msg, channel_before))
goto nla_put_failure;
nla_nest_end(msg, nl_freq);
/* After */
nl_freq = nla_nest_start(msg, NL80211_ATTR_FREQ_AFTER);
if (!nl_freq)
goto nla_put_failure;
if (nl80211_msg_put_channel(msg, channel_after))
goto nla_put_failure;
nla_nest_end(msg, nl_freq);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
rcu_read_lock();
genlmsg_multicast_allns(msg, 0, nl80211_regulatory_mcgrp.id,
GFP_ATOMIC);
rcu_read_unlock();
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
static void nl80211_send_remain_on_chan_event(
int cmd, struct cfg80211_registered_device *rdev,
struct net_device *netdev, u64 cookie,
struct ieee80211_channel *chan,
enum nl80211_channel_type channel_type,
unsigned int duration, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, cmd);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, chan->center_freq);
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE, channel_type);
NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie);
if (cmd == NL80211_CMD_REMAIN_ON_CHANNEL)
NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_remain_on_channel(struct cfg80211_registered_device *rdev,
struct net_device *netdev, u64 cookie,
struct ieee80211_channel *chan,
enum nl80211_channel_type channel_type,
unsigned int duration, gfp_t gfp)
{
nl80211_send_remain_on_chan_event(NL80211_CMD_REMAIN_ON_CHANNEL,
rdev, netdev, cookie, chan,
channel_type, duration, gfp);
}
void nl80211_send_remain_on_channel_cancel(
struct cfg80211_registered_device *rdev, struct net_device *netdev,
u64 cookie, struct ieee80211_channel *chan,
enum nl80211_channel_type channel_type, gfp_t gfp)
{
nl80211_send_remain_on_chan_event(NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL,
rdev, netdev, cookie, chan,
channel_type, 0, gfp);
}
void nl80211_send_sta_event(struct cfg80211_registered_device *rdev,
struct net_device *dev, const u8 *mac_addr,
struct station_info *sinfo, gfp_t gfp)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
if (nl80211_send_station(msg, 0, 0, 0, dev, mac_addr, sinfo) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
}
void nl80211_send_sta_del_event(struct cfg80211_registered_device *rdev,
struct net_device *dev, const u8 *mac_addr,
gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_DEL_STATION);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, dev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, mac_addr);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
int nl80211_send_mgmt(struct cfg80211_registered_device *rdev,
struct net_device *netdev, u32 nlpid,
int freq, const u8 *buf, size_t len, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
int err;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_FRAME);
if (!hdr) {
nlmsg_free(msg);
return -ENOMEM;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
NLA_PUT(msg, NL80211_ATTR_FRAME, len, buf);
err = genlmsg_end(msg, hdr);
if (err < 0) {
nlmsg_free(msg);
return err;
}
err = genlmsg_unicast(wiphy_net(&rdev->wiphy), msg, nlpid);
if (err < 0)
return err;
return 0;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
return -ENOBUFS;
}
void nl80211_send_mgmt_tx_status(struct cfg80211_registered_device *rdev,
struct net_device *netdev, u64 cookie,
const u8 *buf, size_t len, bool ack,
gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_FRAME_TX_STATUS);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_FRAME, len, buf);
NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie);
if (ack)
NLA_PUT_FLAG(msg, NL80211_ATTR_ACK);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast(msg, 0, nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void
nl80211_send_cqm_rssi_notify(struct cfg80211_registered_device *rdev,
struct net_device *netdev,
enum nl80211_cqm_rssi_threshold_event rssi_event,
gfp_t gfp)
{
struct sk_buff *msg;
struct nlattr *pinfoattr;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_NOTIFY_CQM);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
pinfoattr = nla_nest_start(msg, NL80211_ATTR_CQM);
if (!pinfoattr)
goto nla_put_failure;
NLA_PUT_U32(msg, NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT,
rssi_event);
nla_nest_end(msg, pinfoattr);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void
nl80211_send_cqm_pktloss_notify(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *peer,
u32 num_packets, gfp_t gfp)
{
struct sk_buff *msg;
struct nlattr *pinfoattr;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_NOTIFY_CQM);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, peer);
pinfoattr = nla_nest_start(msg, NL80211_ATTR_CQM);
if (!pinfoattr)
goto nla_put_failure;
NLA_PUT_U32(msg, NL80211_ATTR_CQM_PKT_LOSS_EVENT, num_packets);
nla_nest_end(msg, pinfoattr);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
static int nl80211_netlink_notify(struct notifier_block * nb,
unsigned long state,
void *_notify)
{
struct netlink_notify *notify = _notify;
struct cfg80211_registered_device *rdev;
struct wireless_dev *wdev;
if (state != NETLINK_URELEASE)
return NOTIFY_DONE;
rcu_read_lock();
list_for_each_entry_rcu(rdev, &cfg80211_rdev_list, list)
list_for_each_entry_rcu(wdev, &rdev->netdev_list, list)
cfg80211_mlme_unregister_socket(wdev, notify->pid);
rcu_read_unlock();
return NOTIFY_DONE;
}
static struct notifier_block nl80211_netlink_notifier = {
.notifier_call = nl80211_netlink_notify,
};
/* initialisation/exit functions */
int nl80211_init(void)
{
int err;
err = genl_register_family_with_ops(&nl80211_fam,
nl80211_ops, ARRAY_SIZE(nl80211_ops));
if (err)
return err;
err = genl_register_mc_group(&nl80211_fam, &nl80211_config_mcgrp);
if (err)
goto err_out;
err = genl_register_mc_group(&nl80211_fam, &nl80211_scan_mcgrp);
if (err)
goto err_out;
err = genl_register_mc_group(&nl80211_fam, &nl80211_regulatory_mcgrp);
if (err)
goto err_out;
err = genl_register_mc_group(&nl80211_fam, &nl80211_mlme_mcgrp);
if (err)
goto err_out;
#ifdef CONFIG_NL80211_TESTMODE
err = genl_register_mc_group(&nl80211_fam, &nl80211_testmode_mcgrp);
if (err)
goto err_out;
#endif
err = netlink_register_notifier(&nl80211_netlink_notifier);
if (err)
goto err_out;
return 0;
err_out:
genl_unregister_family(&nl80211_fam);
return err;
}
void nl80211_exit(void)
{
netlink_unregister_notifier(&nl80211_netlink_notifier);
genl_unregister_family(&nl80211_fam);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3476_0 |
crossvul-cpp_data_good_4787_24 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% H H DDDD RRRR %
% H H D D R R %
% HHHHH D D RRRR %
% H H D D R R %
% H H DDDD R R %
% %
% %
% Read/Write Radiance RGBE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteHDRImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s H D R %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsHDR() returns MagickTrue if the image format type, identified by the
% magick string, is Radiance RGBE image format.
%
% The format of the IsHDR method is:
%
% MagickBooleanType IsHDR(const unsigned char *magick,
% const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsHDR(const unsigned char *magick,
const size_t length)
{
if (length < 10)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"#?RADIANCE",10) == 0)
return(MagickTrue);
if (LocaleNCompare((const char *) magick,"#?RGBE",6) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadHDRImage() reads the Radiance RGBE image format and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadHDRImage method is:
%
% Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
format[MaxTextExtent],
keyword[MaxTextExtent],
tag[MaxTextExtent],
value[MaxTextExtent];
double
gamma;
Image
*image;
int
c;
MagickBooleanType
status,
value_expected;
register PixelPacket
*q;
register unsigned char
*p;
register ssize_t
i,
x;
ssize_t
count,
y;
unsigned char
*end,
pixel[4],
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Decode image header.
*/
image->columns=0;
image->rows=0;
*format='\0';
c=ReadBlobByte(image);
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
while (isgraph(c) && (image->columns == 0) && (image->rows == 0))
{
if (c == (int) '#')
{
char
*comment;
register char
*p;
size_t
length;
/*
Read comment-- any text between # and end-of-line.
*/
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; comment != (char *) NULL; p++)
{
c=ReadBlobByte(image);
if ((c == EOF) || (c == (int) '\n'))
break;
if ((size_t) (p-comment+1) >= length)
{
*p='\0';
length<<=1;
comment=(char *) ResizeQuantumMemory(comment,length+
MaxTextExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) == MagickFalse)
c=ReadBlobByte(image);
else
{
register char
*p;
/*
Determine a keyword and its value.
*/
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c) || (c == '_'));
*p='\0';
value_expected=MagickFalse;
while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))
{
if (c == '=')
value_expected=MagickTrue;
c=ReadBlobByte(image);
}
if (LocaleCompare(keyword,"Y") == 0)
value_expected=MagickTrue;
if (value_expected == MagickFalse)
continue;
p=value;
while ((c != '\n') && (c != '\0'))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"format") == 0)
{
(void) CopyMagickString(format,value,MaxTextExtent);
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(value,(char **) NULL);
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"primaries") == 0)
{
float
chromaticity[6],
white_point[2];
(void) sscanf(value,"%g %g %g %g %g %g %g %g",
&chromaticity[0],&chromaticity[1],&chromaticity[2],
&chromaticity[3],&chromaticity[4],&chromaticity[5],
&white_point[0],&white_point[1]);
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
image->chromaticity.white_point.x=white_point[0],
image->chromaticity.white_point.y=white_point[1];
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value);
break;
}
case 'Y':
case 'y':
{
if (strcmp(keyword,"Y") == 0)
{
int
height,
width;
(void) sscanf(value,"%d +X %d",&height,&width);
image->columns=(size_t) width;
image->rows=(size_t) height;
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value);
break;
}
default:
{
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value);
break;
}
}
}
if ((image->columns == 0) && (image->rows == 0))
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) &&
(LocaleCompare(format,"32-bit_rle_xyze") != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
(void) SetImageColorspace(image,RGBColorspace);
if (LocaleCompare(format,"32-bit_rle_xyze") == 0)
(void) SetImageColorspace(image,XYZColorspace);
image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ?
NoCompression : RLECompression;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Read RGBE (red+green+blue+exponent) pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
if (image->compression != RLECompression)
{
count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
else
{
count=ReadBlob(image,4*sizeof(*pixel),pixel);
if (count != 4)
break;
if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns)
{
(void) memcpy(pixels,pixel,4*sizeof(*pixel));
count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4);
image->compression=NoCompression;
}
else
{
p=pixels;
for (i=0; i < 4; i++)
{
end=&pixels[(i+1)*image->columns];
while (p < end)
{
count=ReadBlob(image,2*sizeof(*pixel),pixel);
if (count < 1)
break;
if (pixel[0] > 128)
{
count=(ssize_t) pixel[0]-128;
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
while (count-- > 0)
*p++=pixel[1];
}
else
{
count=(ssize_t) pixel[0];
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
*p++=pixel[1];
if (--count > 0)
{
count=ReadBlob(image,(size_t) count*sizeof(*p),p);
if (count < 1)
break;
p+=count;
}
}
}
}
}
}
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->compression == RLECompression)
{
pixel[0]=pixels[x];
pixel[1]=pixels[x+image->columns];
pixel[2]=pixels[x+2*image->columns];
pixel[3]=pixels[x+3*image->columns];
}
else
{
pixel[0]=pixels[i++];
pixel[1]=pixels[i++];
pixel[2]=pixels[i++];
pixel[3]=pixels[i++];
}
SetPixelRed(q,0);
SetPixelGreen(q,0);
SetPixelBlue(q,0);
if (pixel[3] != 0)
{
gamma=pow(2.0,pixel[3]-(128.0+8.0));
SetPixelRed(q,ClampToQuantum(QuantumRange*gamma*pixel[0]));
SetPixelGreen(q,ClampToQuantum(QuantumRange*gamma*pixel[1]));
SetPixelBlue(q,ClampToQuantum(QuantumRange*gamma*pixel[2]));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterHDRImage() adds attributes for the Radiance RGBE image format to the
% list of supported formats. The attributes include the image format tag, a
% method to read and/or write the format, whether the format supports the
% saving of more than one frame to the same file or blob, whether the format
% supports native in-memory I/O, and a brief description of the format.
%
% The format of the RegisterHDRImage method is:
%
% size_t RegisterHDRImage(void)
%
*/
ModuleExport size_t RegisterHDRImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("HDR");
entry->decoder=(DecodeImageHandler *) ReadHDRImage;
entry->encoder=(EncodeImageHandler *) WriteHDRImage;
entry->description=ConstantString("Radiance RGBE image format");
entry->module=ConstantString("HDR");
entry->magick=(IsImageFormatHandler *) IsHDR;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterHDRImage() removes format registrations made by the
% HDR module from the list of supported formats.
%
% The format of the UnregisterHDRImage method is:
%
% UnregisterHDRImage(void)
%
*/
ModuleExport void UnregisterHDRImage(void)
{
(void) UnregisterMagickInfo("HDR");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteHDRImage() writes an image in the Radience RGBE image format.
%
% The format of the WriteHDRImage method is:
%
% MagickBooleanType WriteHDRImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static size_t HDRWriteRunlengthPixels(Image *image,unsigned char *pixels)
{
#define MinimumRunlength 4
register size_t
p,
q;
size_t
runlength;
ssize_t
count,
previous_count;
unsigned char
pixel[2];
for (p=0; p < image->columns; )
{
q=p;
runlength=0;
previous_count=0;
while ((runlength < MinimumRunlength) && (q < image->columns))
{
q+=runlength;
previous_count=(ssize_t) runlength;
runlength=1;
while ((pixels[q] == pixels[q+runlength]) &&
((q+runlength) < image->columns) && (runlength < 127))
runlength++;
}
if ((previous_count > 1) && (previous_count == (ssize_t) (q-p)))
{
pixel[0]=(unsigned char) (128+previous_count);
pixel[1]=pixels[p];
if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
break;
p=q;
}
while (p < q)
{
count=(ssize_t) (q-p);
if (count > 128)
count=128;
pixel[0]=(unsigned char) count;
if (WriteBlob(image,sizeof(*pixel),pixel) < 1)
break;
if (WriteBlob(image,(size_t) count*sizeof(*pixel),&pixels[p]) < 1)
break;
p+=count;
}
if (runlength >= MinimumRunlength)
{
pixel[0]=(unsigned char) (128+runlength);
pixel[1]=pixels[q];
if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
break;
p+=runlength;
}
}
return(p);
}
static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image)
{
char
header[MaxTextExtent];
const char
*property;
MagickBooleanType
status;
register const PixelPacket
*p;
register ssize_t
i,
x;
size_t
length;
ssize_t
count,
y;
unsigned char
pixel[4],
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
if (IsRGBColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Write header.
*/
(void) ResetMagickMemory(header,' ',MaxTextExtent);
length=CopyMagickString(header,"#?RGBE\n",MaxTextExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
property=GetImageProperty(image,"comment");
if ((property != (const char *) NULL) &&
(strchr(property,'\n') == (char *) NULL))
{
count=FormatLocaleString(header,MaxTextExtent,"#%s\n",property);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
property=GetImageProperty(image,"hdr:exposure");
if (property != (const char *) NULL)
{
count=FormatLocaleString(header,MaxTextExtent,"EXPOSURE=%g\n",
atof(property));
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
if (image->gamma != 0.0)
{
count=FormatLocaleString(header,MaxTextExtent,"GAMMA=%g\n",image->gamma);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
count=FormatLocaleString(header,MaxTextExtent,
"PRIMARIES=%g %g %g %g %g %g %g %g\n",
image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,
image->chromaticity.green_primary.x,image->chromaticity.green_primary.y,
image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y,
image->chromaticity.white_point.x,image->chromaticity.white_point.y);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
length=CopyMagickString(header,"FORMAT=32-bit_rle_rgbe\n\n",MaxTextExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
count=FormatLocaleString(header,MaxTextExtent,"-Y %.20g +X %.20g\n",
(double) image->rows,(double) image->columns);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
/*
Write HDR pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixel[0]=2;
pixel[1]=2;
pixel[2]=(unsigned char) (image->columns >> 8);
pixel[3]=(unsigned char) (image->columns & 0xff);
count=WriteBlob(image,4*sizeof(*pixel),pixel);
if (count != (ssize_t) (4*sizeof(*pixel)))
break;
}
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
pixel[0]=0;
pixel[1]=0;
pixel[2]=0;
pixel[3]=0;
gamma=QuantumScale*GetPixelRed(p);
if ((QuantumScale*GetPixelGreen(p)) > gamma)
gamma=QuantumScale*GetPixelGreen(p);
if ((QuantumScale*GetPixelBlue(p)) > gamma)
gamma=QuantumScale*GetPixelBlue(p);
if (gamma > MagickEpsilon)
{
int
exponent;
gamma=frexp(gamma,&exponent)*256.0/gamma;
pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(p));
pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(p));
pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(p));
pixel[3]=(unsigned char) (exponent+128);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixels[x]=pixel[0];
pixels[x+image->columns]=pixel[1];
pixels[x+2*image->columns]=pixel[2];
pixels[x+3*image->columns]=pixel[3];
}
else
{
pixels[i++]=pixel[0];
pixels[i++]=pixel[1];
pixels[i++]=pixel[2];
pixels[i++]=pixel[3];
}
p++;
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
for (i=0; i < 4; i++)
length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]);
}
else
{
count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_24 |
crossvul-cpp_data_good_252_4 | /**
* @file
* RFC2047 MIME extensions encoding / decoding routines
*
* @authors
* Copyright (C) 1996-2000,2010 Michael R. Elkins <me@mutt.org>
* Copyright (C) 2000-2002 Edmund Grimley Evans <edmundo@rano.org>
* Copyright (C) 2018 Pietro Cerutti <gahr@gahr.ch>
*
* @copyright
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @page rfc2047 RFC2047 encoding / decoding functions
*
* RFC2047 MIME extensions encoding / decoding routines.
*/
#include "config.h"
#include <assert.h>
#include <errno.h>
#include <stdbool.h>
#include <string.h>
#include "rfc2047.h"
#include "base64.h"
#include "buffer.h"
#include "charset.h"
#include "mbyte.h"
#include "memory.h"
#include "mime.h"
#include "regex3.h"
#include "string2.h"
#define ENCWORD_LEN_MAX 75
#define ENCWORD_LEN_MIN 9 /* strlen ("=?.?.?.?=") */
#define HSPACE(x) (((x) == '\0') || ((x) == ' ') || ((x) == '\t'))
#define CONTINUATION_BYTE(c) (((c) &0xc0) == 0x80)
typedef size_t (*encoder_t)(char *str, const char *buf, size_t buflen, const char *tocode);
/**
* b_encoder - Base64 Encode a string
* @param str String to encode
* @param buf Buffer for result
* @param buflen Length of buffer
* @param tocode Character encoding
* @retval num Bytes written to buffer
*/
static size_t b_encoder(char *str, const char *buf, size_t buflen, const char *tocode)
{
char *s0 = str;
memcpy(str, "=?", 2);
str += 2;
memcpy(str, tocode, strlen(tocode));
str += strlen(tocode);
memcpy(str, "?B?", 3);
str += 3;
while (buflen)
{
char encoded[11];
size_t ret;
size_t in_len = MIN(3, buflen);
ret = mutt_b64_encode(encoded, buf, in_len, sizeof(encoded));
for (size_t i = 0; i < ret; i++)
*str++ = encoded[i];
buflen -= in_len;
buf += in_len;
}
memcpy(str, "?=", 2);
str += 2;
return (str - s0);
}
/**
* q_encoder - Quoted-printable Encode a string
* @param str String to encode
* @param buf Buffer for result
* @param buflen Length of buffer
* @param tocode Character encoding
* @retval num Bytes written to buffer
*/
static size_t q_encoder(char *str, const char *buf, size_t buflen, const char *tocode)
{
static const char hex[] = "0123456789ABCDEF";
char *s0 = str;
memcpy(str, "=?", 2);
str += 2;
memcpy(str, tocode, strlen(tocode));
str += strlen(tocode);
memcpy(str, "?Q?", 3);
str += 3;
while (buflen--)
{
unsigned char c = *buf++;
if (c == ' ')
*str++ = '_';
else if ((c >= 0x7f) || (c < 0x20) || (c == '_') || strchr(MimeSpecials, c))
{
*str++ = '=';
*str++ = hex[(c & 0xf0) >> 4];
*str++ = hex[c & 0x0f];
}
else
*str++ = c;
}
memcpy(str, "?=", 2);
str += 2;
return (str - s0);
}
/**
* parse_encoded_word - Parse a string and report RFC2047 elements
* @param[in] str String to parse
* @param[out] enc Content encoding found in the first RFC2047 word
* @param[out] charset Charset found in the first RFC2047 word
* @param[out] charsetlen Length of the charset string found
* @param[out] text Start of the first RFC2047 encoded text
* @param[out] textlen Length of the encoded text found
* @retval ptr Start of the RFC2047 encoded word
* @retval NULL None was found
*/
static char *parse_encoded_word(char *str, enum ContentEncoding *enc, char **charset,
size_t *charsetlen, char **text, size_t *textlen)
{
static struct Regex *re = NULL;
regmatch_t match[4];
size_t nmatch = 4;
if (re == NULL)
{
re = mutt_regex_compile("=\\?"
"([^][()<>@,;:\\\"/?. =]+)" /* charset */
"\\?"
"([qQbB])" /* encoding */
"\\?"
"([^?]+)" /* encoded text - we accept whitespace
as some mailers do that, see #1189. */
"\\?=",
REG_EXTENDED);
assert(re && "Something is wrong with your RE engine.");
}
int rc = regexec(re->regex, str, nmatch, match, 0);
if (rc != 0)
return NULL;
/* Charset */
*charset = str + match[1].rm_so;
*charsetlen = match[1].rm_eo - match[1].rm_so;
/* Encoding: either Q or B */
*enc = ((str[match[2].rm_so] == 'Q') || (str[match[2].rm_so] == 'q')) ?
ENCQUOTEDPRINTABLE :
ENCBASE64;
*text = str + match[3].rm_so;
*textlen = match[3].rm_eo - match[3].rm_so;
return (str + match[0].rm_so);
}
/**
* try_block - Attempt to convert a block of text
* @param d String to convert
* @param dlen Length of string
* @param fromcode Original encoding
* @param tocode New encoding
* @param encoder Encoding function
* @param wlen Number of characters converted
* @retval 0 Success, string converted
* @retval >0 Error, number of bytes that could be converted
*
* If the data could be conveted using encoder, then set *encoder and *wlen.
* Otherwise return an upper bound on the maximum length of the data which
* could be converted.
*
* The data is converted from fromcode (which must be stateless) to tocode,
* unless fromcode is NULL, in which case the data is assumed to be already in
* tocode, which should be 8-bit and stateless.
*/
static size_t try_block(const char *d, size_t dlen, const char *fromcode,
const char *tocode, encoder_t *encoder, size_t *wlen)
{
char buf[ENCWORD_LEN_MAX - ENCWORD_LEN_MIN + 1];
const char *ib = NULL;
char *ob = NULL;
size_t ibl, obl;
int count, len, len_b, len_q;
if (fromcode)
{
iconv_t cd = mutt_ch_iconv_open(tocode, fromcode, 0);
assert(cd != (iconv_t)(-1));
ib = d;
ibl = dlen;
ob = buf;
obl = sizeof(buf) - strlen(tocode);
if (iconv(cd, (ICONV_CONST char **) &ib, &ibl, &ob, &obl) == (size_t)(-1) ||
iconv(cd, NULL, NULL, &ob, &obl) == (size_t)(-1))
{
assert(errno == E2BIG);
iconv_close(cd);
assert(ib > d);
return (ib - d == dlen) ? dlen : ib - d + 1;
}
iconv_close(cd);
}
else
{
if (dlen > (sizeof(buf) - strlen(tocode)))
return (sizeof(buf) - strlen(tocode) + 1);
memcpy(buf, d, dlen);
ob = buf + dlen;
}
count = 0;
for (char *p = buf; p < ob; p++)
{
unsigned char c = *p;
assert(strchr(MimeSpecials, '?'));
if ((c >= 0x7f) || (c < 0x20) || (*p == '_') ||
((c != ' ') && strchr(MimeSpecials, *p)))
{
count++;
}
}
len = ENCWORD_LEN_MIN - 2 + strlen(tocode);
len_b = len + (((ob - buf) + 2) / 3) * 4;
len_q = len + (ob - buf) + 2 * count;
/* Apparently RFC1468 says to use B encoding for iso-2022-jp. */
if (mutt_str_strcasecmp(tocode, "ISO-2022-JP") == 0)
len_q = ENCWORD_LEN_MAX + 1;
if ((len_b < len_q) && (len_b <= ENCWORD_LEN_MAX))
{
*encoder = b_encoder;
*wlen = len_b;
return 0;
}
else if (len_q <= ENCWORD_LEN_MAX)
{
*encoder = q_encoder;
*wlen = len_q;
return 0;
}
else
return dlen;
}
/**
* encode_block - Encode a block of text using an encoder
* @param str String to convert
* @param buf Buffer for result
* @param buflen Buffer length
* @param fromcode Original encoding
* @param tocode New encoding
* @param encoder Encoding function
* @retval num Length of the encoded word
*
* Encode the data (buf, buflen) into str using the encoder.
*/
static size_t encode_block(char *str, char *buf, size_t buflen, const char *fromcode,
const char *tocode, encoder_t encoder)
{
if (!fromcode)
{
return (*encoder)(str, buf, buflen, tocode);
}
const iconv_t cd = mutt_ch_iconv_open(tocode, fromcode, 0);
assert(cd != (iconv_t)(-1));
const char *ib = buf;
size_t ibl = buflen;
char tmp[ENCWORD_LEN_MAX - ENCWORD_LEN_MIN + 1];
char *ob = tmp;
size_t obl = sizeof(tmp) - strlen(tocode);
const size_t n1 = iconv(cd, (ICONV_CONST char **) &ib, &ibl, &ob, &obl);
const size_t n2 = iconv(cd, NULL, NULL, &ob, &obl);
assert(n1 != (size_t)(-1) && n2 != (size_t)(-1));
iconv_close(cd);
return (*encoder)(str, tmp, ob - tmp, tocode);
}
/**
* choose_block - Calculate how much data can be converted
* @param d String to convert
* @param dlen Length of string
* @param col Starting column to convert
* @param fromcode Original encoding
* @param tocode New encoding
* @param encoder Encoding function
* @param wlen Number of characters converted
* @retval num Bytes that can be converted
*
* Discover how much of the data (d, dlen) can be converted into a single
* encoded word. Return how much data can be converted, and set the length
* *wlen of the encoded word and *encoder. We start in column col, which
* limits the length of the word.
*/
static size_t choose_block(char *d, size_t dlen, int col, const char *fromcode,
const char *tocode, encoder_t *encoder, size_t *wlen)
{
const int utf8 = fromcode && (mutt_str_strcasecmp(fromcode, "utf-8") == 0);
size_t n = dlen;
while (true)
{
assert(n > 0);
const size_t nn = try_block(d, n, fromcode, tocode, encoder, wlen);
if ((nn == 0) && ((col + *wlen) <= (ENCWORD_LEN_MAX + 1) || (n <= 1)))
break;
n = (nn ? nn : n) - 1;
assert(n > 0);
if (utf8)
while ((n > 1) && CONTINUATION_BYTE(d[n]))
n--;
}
return n;
}
/**
* finalize_chunk - Perform charset conversion and filtering
* @param[out] res Buffer where the resulting string is appended
* @param[in] buf Buffer with the input string
* @param[in] charset Charset to use for the conversion
* @param[in] charsetlen Length of the charset parameter
*
* The buffer buf is reinitialized at the end of this function.
*/
static void finalize_chunk(struct Buffer *res, struct Buffer *buf, char *charset, size_t charsetlen)
{
char end = charset[charsetlen];
charset[charsetlen] = '\0';
mutt_ch_convert_string(&buf->data, charset, Charset, MUTT_ICONV_HOOK_FROM);
charset[charsetlen] = end;
mutt_mb_filter_unprintable(&buf->data);
mutt_buffer_addstr(res, buf->data);
FREE(&buf->data);
mutt_buffer_init(buf);
}
/**
* rfc2047_decode_word - Decode an RFC2047-encoded string
* @param s String to decode
* @param len Length of the string
* @param enc Encoding type
* @retval ptr Decoded string
*
* @note The caller must free the returned string
*/
static char *rfc2047_decode_word(const char *s, size_t len, enum ContentEncoding enc)
{
const char *it = s;
const char *end = s + len;
if (enc == ENCQUOTEDPRINTABLE)
{
struct Buffer buf = { 0 };
for (; it < end; ++it)
{
if (*it == '_')
{
mutt_buffer_addch(&buf, ' ');
}
else if ((*it == '=') && (!(it[1] & ~127) && hexval(it[1]) != -1) &&
(!(it[2] & ~127) && hexval(it[2]) != -1))
{
mutt_buffer_addch(&buf, (hexval(it[1]) << 4) | hexval(it[2]));
it += 2;
}
else
{
mutt_buffer_addch(&buf, *it);
}
}
mutt_buffer_addch(&buf, '\0');
return buf.data;
}
else if (enc == ENCBASE64)
{
const int olen = 3 * len / 4 + 1;
char *out = mutt_mem_malloc(olen);
int dlen = mutt_b64_decode(out, it, olen);
if (dlen == -1)
{
FREE(&out);
return NULL;
}
out[dlen] = '\0';
return out;
}
assert(0); /* The enc parameter has an invalid value */
return NULL;
}
/**
* rfc2047_encode - RFC2047-encode a string
* @param d String to convert
* @param dlen Length of string
* @param col Starting column to convert
* @param fromcode Original encoding
* @param charsets List of allowable encodings (colon separated)
* @param e Encoded string
* @param elen Length of encoded string
* @param specials Special characters to be encoded
* @retval 0 Success
*/
static int rfc2047_encode(const char *d, size_t dlen, int col, const char *fromcode,
const char *charsets, char **e, size_t *elen, const char *specials)
{
int rc = 0;
char *buf = NULL;
size_t bufpos, buflen;
char *t0 = NULL, *t1 = NULL, *t = NULL;
char *s0 = NULL, *s1 = NULL;
size_t ulen, r, wlen = 0;
encoder_t encoder = NULL;
char *tocode1 = NULL;
const char *tocode = NULL;
char *icode = "utf-8";
/* Try to convert to UTF-8. */
char *u = mutt_str_substr_dup(d, d + dlen);
if (mutt_ch_convert_string(&u, fromcode, icode, 0) != 0)
{
rc = 1;
icode = 0;
}
ulen = mutt_str_strlen(u);
/* Find earliest and latest things we must encode. */
s0 = s1 = t0 = t1 = 0;
for (t = u; t < (u + ulen); t++)
{
if ((*t & 0x80) || ((*t == '=') && (t[1] == '?') && ((t == u) || HSPACE(*(t - 1)))))
{
if (!t0)
t0 = t;
t1 = t;
}
else if (specials && *t && strchr(specials, *t))
{
if (!s0)
s0 = t;
s1 = t;
}
}
/* If we have something to encode, include RFC822 specials */
if (t0 && s0 && (s0 < t0))
t0 = s0;
if (t1 && s1 && (s1 > t1))
t1 = s1;
if (!t0)
{
/* No encoding is required. */
*e = u;
*elen = ulen;
return rc;
}
/* Choose target charset. */
tocode = fromcode;
if (icode)
{
tocode1 = mutt_ch_choose(icode, charsets, u, ulen, 0, 0);
if (tocode1)
tocode = tocode1;
else
{
rc = 2;
icode = 0;
}
}
/* Hack to avoid labelling 8-bit data as us-ascii. */
if (!icode && mutt_ch_is_us_ascii(tocode))
tocode = "unknown-8bit";
/* Adjust t0 for maximum length of line. */
t = u + (ENCWORD_LEN_MAX + 1) - col - ENCWORD_LEN_MIN;
if (t < u)
t = u;
if (t < t0)
t0 = t;
/* Adjust t0 until we can encode a character after a space. */
for (; t0 > u; t0--)
{
if (!HSPACE(*(t0 - 1)))
continue;
t = t0 + 1;
if (icode)
while ((t < (u + ulen)) && CONTINUATION_BYTE(*t))
t++;
if ((try_block(t0, t - t0, icode, tocode, &encoder, &wlen) == 0) &&
((col + (t0 - u) + wlen) <= (ENCWORD_LEN_MAX + 1)))
{
break;
}
}
/* Adjust t1 until we can encode a character before a space. */
for (; t1 < (u + ulen); t1++)
{
if (!HSPACE(*t1))
continue;
t = t1 - 1;
if (icode)
while (CONTINUATION_BYTE(*t))
t--;
if ((try_block(t, t1 - t, icode, tocode, &encoder, &wlen) == 0) &&
((1 + wlen + (u + ulen - t1)) <= (ENCWORD_LEN_MAX + 1)))
{
break;
}
}
/* We shall encode the region [t0,t1). */
/* Initialise the output buffer with the us-ascii prefix. */
buflen = 2 * ulen;
buf = mutt_mem_malloc(buflen);
bufpos = t0 - u;
memcpy(buf, u, t0 - u);
col += t0 - u;
t = t0;
while (true)
{
/* Find how much we can encode. */
size_t n = choose_block(t, t1 - t, col, icode, tocode, &encoder, &wlen);
if (n == (t1 - t))
{
/* See if we can fit the us-ascii suffix, too. */
if ((col + wlen + (u + ulen - t1)) <= (ENCWORD_LEN_MAX + 1))
break;
n = t1 - t - 1;
if (icode)
while (CONTINUATION_BYTE(t[n]))
n--;
if (!n)
{
/* This should only happen in the really stupid case where the
only word that needs encoding is one character long, but
there is too much us-ascii stuff after it to use a single
encoded word. We add the next word to the encoded region
and try again. */
assert(t1 < (u + ulen));
for (t1++; (t1 < (u + ulen)) && !HSPACE(*t1); t1++)
;
continue;
}
n = choose_block(t, n, col, icode, tocode, &encoder, &wlen);
}
/* Add to output buffer. */
const char *line_break = "\n\t";
const int lb_len = 2; /* strlen(line_break) */
if ((bufpos + wlen + lb_len) > buflen)
{
buflen = bufpos + wlen + lb_len;
mutt_mem_realloc(&buf, buflen);
}
r = encode_block(buf + bufpos, t, n, icode, tocode, encoder);
assert(r == wlen);
bufpos += wlen;
memcpy(buf + bufpos, line_break, lb_len);
bufpos += lb_len;
col = 1;
t += n;
}
/* Add last encoded word and us-ascii suffix to buffer. */
buflen = bufpos + wlen + (u + ulen - t1);
mutt_mem_realloc(&buf, buflen + 1);
r = encode_block(buf + bufpos, t, t1 - t, icode, tocode, encoder);
assert(r == wlen);
bufpos += wlen;
memcpy(buf + bufpos, t1, u + ulen - t1);
FREE(&tocode1);
FREE(&u);
buf[buflen] = '\0';
*e = buf;
*elen = buflen + 1;
return rc;
}
/**
* mutt_rfc2047_encode - RFC-2047-encode a string
* @param[in,out] pd String to be encoded, and resulting encoded string
* @param[in] specials Special characters to be encoded
* @param[in] col Starting index in string
* @param[in] charsets List of charsets to choose from
*/
void mutt_rfc2047_encode(char **pd, const char *specials, int col, const char *charsets)
{
char *e = NULL;
size_t elen;
if (!Charset || !*pd)
return;
if (!charsets || !*charsets)
charsets = "utf-8";
rfc2047_encode(*pd, strlen(*pd), col, Charset, charsets, &e, &elen, specials);
FREE(pd);
*pd = e;
}
/**
* mutt_rfc2047_decode - Decode any RFC2047-encoded header fields
* @param[in,out] pd String to be decoded, and resulting decoded string
*
* Try to decode anything that looks like a valid RFC2047 encoded header field,
* ignoring RFC822 parsing rules. If decoding fails, for example due to an
* invalid base64 string, the original input is left untouched.
*/
void mutt_rfc2047_decode(char **pd)
{
if (!pd || !*pd)
return;
struct Buffer buf = { 0 }; /* Output buffer */
char *s = *pd; /* Read pointer */
char *beg; /* Begin of encoded word */
enum ContentEncoding enc; /* ENCBASE64 or ENCQUOTEDPRINTABLE */
char *charset; /* Which charset */
size_t charsetlen; /* Length of the charset */
char *text; /* Encoded text */
size_t textlen; /* Length of encoded text */
/* Keep some state in case the next decoded word is using the same charset
* and it happens to be split in the middle of a multibyte character.
* See https://github.com/neomutt/neomutt/issues/1015
*/
struct Buffer prev = { 0 }; /* Previously decoded word */
char *prev_charset = NULL; /* Previously used charset */
size_t prev_charsetlen = 0; /* Length of the previously used charset */
while (*s)
{
beg = parse_encoded_word(s, &enc, &charset, &charsetlen, &text, &textlen);
if (beg != s)
{
/* Some non-encoded text was found */
size_t holelen = beg ? beg - s : mutt_str_strlen(s);
/* Ignore whitespace between encoded words */
if (beg && mutt_str_lws_len(s, holelen) == holelen)
{
s = beg;
continue;
}
/* If we have some previously decoded text, add it now */
if (prev.data)
{
finalize_chunk(&buf, &prev, prev_charset, prev_charsetlen);
}
/* Add non-encoded part */
{
if (AssumedCharset && *AssumedCharset)
{
char *conv = mutt_str_substr_dup(s, s + holelen);
mutt_ch_convert_nonmime_string(&conv);
mutt_buffer_addstr(&buf, conv);
FREE(&conv);
}
else
{
mutt_buffer_add(&buf, s, holelen);
}
}
s += holelen;
}
if (beg)
{
/* Some encoded text was found */
text[textlen] = '\0';
char *decoded = rfc2047_decode_word(text, textlen, enc);
if (decoded == NULL)
{
return;
}
if (prev.data && ((prev_charsetlen != charsetlen) ||
(strncmp(prev_charset, charset, charsetlen) != 0)))
{
/* Different charset, convert the previous chunk and add it to the
* final result */
finalize_chunk(&buf, &prev, prev_charset, prev_charsetlen);
}
mutt_buffer_addstr(&prev, decoded);
FREE(&decoded);
prev_charset = charset;
prev_charsetlen = charsetlen;
s = text + textlen + 2; /* Skip final ?= */
}
}
/* Save the last chunk */
if (prev.data)
{
finalize_chunk(&buf, &prev, prev_charset, prev_charsetlen);
}
mutt_buffer_addch(&buf, '\0');
*pd = buf.data;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_252_4 |
crossvul-cpp_data_good_1469_0 | /* Keyring handling
*
* Copyright (C) 2004-2005, 2008, 2013 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/security.h>
#include <linux/seq_file.h>
#include <linux/err.h>
#include <keys/keyring-type.h>
#include <keys/user-type.h>
#include <linux/assoc_array_priv.h>
#include <linux/uaccess.h>
#include "internal.h"
/*
* When plumbing the depths of the key tree, this sets a hard limit
* set on how deep we're willing to go.
*/
#define KEYRING_SEARCH_MAX_DEPTH 6
/*
* We keep all named keyrings in a hash to speed looking them up.
*/
#define KEYRING_NAME_HASH_SIZE (1 << 5)
/*
* We mark pointers we pass to the associative array with bit 1 set if
* they're keyrings and clear otherwise.
*/
#define KEYRING_PTR_SUBTYPE 0x2UL
static inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)
{
return (unsigned long)x & KEYRING_PTR_SUBTYPE;
}
static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)
{
void *object = assoc_array_ptr_to_leaf(x);
return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE);
}
static inline void *keyring_key_to_ptr(struct key *key)
{
if (key->type == &key_type_keyring)
return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);
return key;
}
static struct list_head keyring_name_hash[KEYRING_NAME_HASH_SIZE];
static DEFINE_RWLOCK(keyring_name_lock);
static inline unsigned keyring_hash(const char *desc)
{
unsigned bucket = 0;
for (; *desc; desc++)
bucket += (unsigned char)*desc;
return bucket & (KEYRING_NAME_HASH_SIZE - 1);
}
/*
* The keyring key type definition. Keyrings are simply keys of this type and
* can be treated as ordinary keys in addition to having their own special
* operations.
*/
static int keyring_preparse(struct key_preparsed_payload *prep);
static void keyring_free_preparse(struct key_preparsed_payload *prep);
static int keyring_instantiate(struct key *keyring,
struct key_preparsed_payload *prep);
static void keyring_revoke(struct key *keyring);
static void keyring_destroy(struct key *keyring);
static void keyring_describe(const struct key *keyring, struct seq_file *m);
static long keyring_read(const struct key *keyring,
char __user *buffer, size_t buflen);
struct key_type key_type_keyring = {
.name = "keyring",
.def_datalen = 0,
.preparse = keyring_preparse,
.free_preparse = keyring_free_preparse,
.instantiate = keyring_instantiate,
.revoke = keyring_revoke,
.destroy = keyring_destroy,
.describe = keyring_describe,
.read = keyring_read,
};
EXPORT_SYMBOL(key_type_keyring);
/*
* Semaphore to serialise link/link calls to prevent two link calls in parallel
* introducing a cycle.
*/
static DECLARE_RWSEM(keyring_serialise_link_sem);
/*
* Publish the name of a keyring so that it can be found by name (if it has
* one).
*/
static void keyring_publish_name(struct key *keyring)
{
int bucket;
if (keyring->description) {
bucket = keyring_hash(keyring->description);
write_lock(&keyring_name_lock);
if (!keyring_name_hash[bucket].next)
INIT_LIST_HEAD(&keyring_name_hash[bucket]);
list_add_tail(&keyring->type_data.link,
&keyring_name_hash[bucket]);
write_unlock(&keyring_name_lock);
}
}
/*
* Preparse a keyring payload
*/
static int keyring_preparse(struct key_preparsed_payload *prep)
{
return prep->datalen != 0 ? -EINVAL : 0;
}
/*
* Free a preparse of a user defined key payload
*/
static void keyring_free_preparse(struct key_preparsed_payload *prep)
{
}
/*
* Initialise a keyring.
*
* Returns 0 on success, -EINVAL if given any data.
*/
static int keyring_instantiate(struct key *keyring,
struct key_preparsed_payload *prep)
{
assoc_array_init(&keyring->keys);
/* make the keyring available by name if it has one */
keyring_publish_name(keyring);
return 0;
}
/*
* Multiply 64-bits by 32-bits to 96-bits and fold back to 64-bit. Ideally we'd
* fold the carry back too, but that requires inline asm.
*/
static u64 mult_64x32_and_fold(u64 x, u32 y)
{
u64 hi = (u64)(u32)(x >> 32) * y;
u64 lo = (u64)(u32)(x) * y;
return lo + ((u64)(u32)hi << 32) + (u32)(hi >> 32);
}
/*
* Hash a key type and description.
*/
static unsigned long hash_key_type_and_desc(const struct keyring_index_key *index_key)
{
const unsigned level_shift = ASSOC_ARRAY_LEVEL_STEP;
const unsigned long fan_mask = ASSOC_ARRAY_FAN_MASK;
const char *description = index_key->description;
unsigned long hash, type;
u32 piece;
u64 acc;
int n, desc_len = index_key->desc_len;
type = (unsigned long)index_key->type;
acc = mult_64x32_and_fold(type, desc_len + 13);
acc = mult_64x32_and_fold(acc, 9207);
for (;;) {
n = desc_len;
if (n <= 0)
break;
if (n > 4)
n = 4;
piece = 0;
memcpy(&piece, description, n);
description += n;
desc_len -= n;
acc = mult_64x32_and_fold(acc, piece);
acc = mult_64x32_and_fold(acc, 9207);
}
/* Fold the hash down to 32 bits if need be. */
hash = acc;
if (ASSOC_ARRAY_KEY_CHUNK_SIZE == 32)
hash ^= acc >> 32;
/* Squidge all the keyrings into a separate part of the tree to
* ordinary keys by making sure the lowest level segment in the hash is
* zero for keyrings and non-zero otherwise.
*/
if (index_key->type != &key_type_keyring && (hash & fan_mask) == 0)
return hash | (hash >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - level_shift)) | 1;
if (index_key->type == &key_type_keyring && (hash & fan_mask) != 0)
return (hash + (hash << level_shift)) & ~fan_mask;
return hash;
}
/*
* Build the next index key chunk.
*
* On 32-bit systems the index key is laid out as:
*
* 0 4 5 9...
* hash desclen typeptr desc[]
*
* On 64-bit systems:
*
* 0 8 9 17...
* hash desclen typeptr desc[]
*
* We return it one word-sized chunk at a time.
*/
static unsigned long keyring_get_key_chunk(const void *data, int level)
{
const struct keyring_index_key *index_key = data;
unsigned long chunk = 0;
long offset = 0;
int desc_len = index_key->desc_len, n = sizeof(chunk);
level /= ASSOC_ARRAY_KEY_CHUNK_SIZE;
switch (level) {
case 0:
return hash_key_type_and_desc(index_key);
case 1:
return ((unsigned long)index_key->type << 8) | desc_len;
case 2:
if (desc_len == 0)
return (u8)((unsigned long)index_key->type >>
(ASSOC_ARRAY_KEY_CHUNK_SIZE - 8));
n--;
offset = 1;
default:
offset += sizeof(chunk) - 1;
offset += (level - 3) * sizeof(chunk);
if (offset >= desc_len)
return 0;
desc_len -= offset;
if (desc_len > n)
desc_len = n;
offset += desc_len;
do {
chunk <<= 8;
chunk |= ((u8*)index_key->description)[--offset];
} while (--desc_len > 0);
if (level == 2) {
chunk <<= 8;
chunk |= (u8)((unsigned long)index_key->type >>
(ASSOC_ARRAY_KEY_CHUNK_SIZE - 8));
}
return chunk;
}
}
static unsigned long keyring_get_object_key_chunk(const void *object, int level)
{
const struct key *key = keyring_ptr_to_key(object);
return keyring_get_key_chunk(&key->index_key, level);
}
static bool keyring_compare_object(const void *object, const void *data)
{
const struct keyring_index_key *index_key = data;
const struct key *key = keyring_ptr_to_key(object);
return key->index_key.type == index_key->type &&
key->index_key.desc_len == index_key->desc_len &&
memcmp(key->index_key.description, index_key->description,
index_key->desc_len) == 0;
}
/*
* Compare the index keys of a pair of objects and determine the bit position
* at which they differ - if they differ.
*/
static int keyring_diff_objects(const void *object, const void *data)
{
const struct key *key_a = keyring_ptr_to_key(object);
const struct keyring_index_key *a = &key_a->index_key;
const struct keyring_index_key *b = data;
unsigned long seg_a, seg_b;
int level, i;
level = 0;
seg_a = hash_key_type_and_desc(a);
seg_b = hash_key_type_and_desc(b);
if ((seg_a ^ seg_b) != 0)
goto differ;
/* The number of bits contributed by the hash is controlled by a
* constant in the assoc_array headers. Everything else thereafter we
* can deal with as being machine word-size dependent.
*/
level += ASSOC_ARRAY_KEY_CHUNK_SIZE / 8;
seg_a = a->desc_len;
seg_b = b->desc_len;
if ((seg_a ^ seg_b) != 0)
goto differ;
/* The next bit may not work on big endian */
level++;
seg_a = (unsigned long)a->type;
seg_b = (unsigned long)b->type;
if ((seg_a ^ seg_b) != 0)
goto differ;
level += sizeof(unsigned long);
if (a->desc_len == 0)
goto same;
i = 0;
if (((unsigned long)a->description | (unsigned long)b->description) &
(sizeof(unsigned long) - 1)) {
do {
seg_a = *(unsigned long *)(a->description + i);
seg_b = *(unsigned long *)(b->description + i);
if ((seg_a ^ seg_b) != 0)
goto differ_plus_i;
i += sizeof(unsigned long);
} while (i < (a->desc_len & (sizeof(unsigned long) - 1)));
}
for (; i < a->desc_len; i++) {
seg_a = *(unsigned char *)(a->description + i);
seg_b = *(unsigned char *)(b->description + i);
if ((seg_a ^ seg_b) != 0)
goto differ_plus_i;
}
same:
return -1;
differ_plus_i:
level += i;
differ:
i = level * 8 + __ffs(seg_a ^ seg_b);
return i;
}
/*
* Free an object after stripping the keyring flag off of the pointer.
*/
static void keyring_free_object(void *object)
{
key_put(keyring_ptr_to_key(object));
}
/*
* Operations for keyring management by the index-tree routines.
*/
static const struct assoc_array_ops keyring_assoc_array_ops = {
.get_key_chunk = keyring_get_key_chunk,
.get_object_key_chunk = keyring_get_object_key_chunk,
.compare_object = keyring_compare_object,
.diff_objects = keyring_diff_objects,
.free_object = keyring_free_object,
};
/*
* Clean up a keyring when it is destroyed. Unpublish its name if it had one
* and dispose of its data.
*
* The garbage collector detects the final key_put(), removes the keyring from
* the serial number tree and then does RCU synchronisation before coming here,
* so we shouldn't need to worry about code poking around here with the RCU
* readlock held by this time.
*/
static void keyring_destroy(struct key *keyring)
{
if (keyring->description) {
write_lock(&keyring_name_lock);
if (keyring->type_data.link.next != NULL &&
!list_empty(&keyring->type_data.link))
list_del(&keyring->type_data.link);
write_unlock(&keyring_name_lock);
}
assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops);
}
/*
* Describe a keyring for /proc.
*/
static void keyring_describe(const struct key *keyring, struct seq_file *m)
{
if (keyring->description)
seq_puts(m, keyring->description);
else
seq_puts(m, "[anon]");
if (key_is_instantiated(keyring)) {
if (keyring->keys.nr_leaves_on_tree != 0)
seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
else
seq_puts(m, ": empty");
}
}
struct keyring_read_iterator_context {
size_t qty;
size_t count;
key_serial_t __user *buffer;
};
static int keyring_read_iterator(const void *object, void *data)
{
struct keyring_read_iterator_context *ctx = data;
const struct key *key = keyring_ptr_to_key(object);
int ret;
kenter("{%s,%d},,{%zu/%zu}",
key->type->name, key->serial, ctx->count, ctx->qty);
if (ctx->count >= ctx->qty)
return 1;
ret = put_user(key->serial, ctx->buffer);
if (ret < 0)
return ret;
ctx->buffer++;
ctx->count += sizeof(key->serial);
return 0;
}
/*
* Read a list of key IDs from the keyring's contents in binary form
*
* The keyring's semaphore is read-locked by the caller. This prevents someone
* from modifying it under us - which could cause us to read key IDs multiple
* times.
*/
static long keyring_read(const struct key *keyring,
char __user *buffer, size_t buflen)
{
struct keyring_read_iterator_context ctx;
unsigned long nr_keys;
int ret;
kenter("{%d},,%zu", key_serial(keyring), buflen);
if (buflen & (sizeof(key_serial_t) - 1))
return -EINVAL;
nr_keys = keyring->keys.nr_leaves_on_tree;
if (nr_keys == 0)
return 0;
/* Calculate how much data we could return */
ctx.qty = nr_keys * sizeof(key_serial_t);
if (!buffer || !buflen)
return ctx.qty;
if (buflen > ctx.qty)
ctx.qty = buflen;
/* Copy the IDs of the subscribed keys into the buffer */
ctx.buffer = (key_serial_t __user *)buffer;
ctx.count = 0;
ret = assoc_array_iterate(&keyring->keys, keyring_read_iterator, &ctx);
if (ret < 0) {
kleave(" = %d [iterate]", ret);
return ret;
}
kleave(" = %zu [ok]", ctx.count);
return ctx.count;
}
/*
* Allocate a keyring and link into the destination keyring.
*/
struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,
const struct cred *cred, key_perm_t perm,
unsigned long flags, struct key *dest)
{
struct key *keyring;
int ret;
keyring = key_alloc(&key_type_keyring, description,
uid, gid, cred, perm, flags);
if (!IS_ERR(keyring)) {
ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
if (ret < 0) {
key_put(keyring);
keyring = ERR_PTR(ret);
}
}
return keyring;
}
EXPORT_SYMBOL(keyring_alloc);
/*
* By default, we keys found by getting an exact match on their descriptions.
*/
bool key_default_cmp(const struct key *key,
const struct key_match_data *match_data)
{
return strcmp(key->description, match_data->raw_data) == 0;
}
/*
* Iteration function to consider each key found.
*/
static int keyring_search_iterator(const void *object, void *iterator_data)
{
struct keyring_search_context *ctx = iterator_data;
const struct key *key = keyring_ptr_to_key(object);
unsigned long kflags = key->flags;
kenter("{%d}", key->serial);
/* ignore keys not of this type */
if (key->type != ctx->index_key.type) {
kleave(" = 0 [!type]");
return 0;
}
/* skip invalidated, revoked and expired keys */
if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED))) {
ctx->result = ERR_PTR(-EKEYREVOKED);
kleave(" = %d [invrev]", ctx->skipped_ret);
goto skipped;
}
if (key->expiry && ctx->now.tv_sec >= key->expiry) {
if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
ctx->result = ERR_PTR(-EKEYEXPIRED);
kleave(" = %d [expire]", ctx->skipped_ret);
goto skipped;
}
}
/* keys that don't match */
if (!ctx->match_data.cmp(key, &ctx->match_data)) {
kleave(" = 0 [!match]");
return 0;
}
/* key must have search permissions */
if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
key_task_permission(make_key_ref(key, ctx->possessed),
ctx->cred, KEY_NEED_SEARCH) < 0) {
ctx->result = ERR_PTR(-EACCES);
kleave(" = %d [!perm]", ctx->skipped_ret);
goto skipped;
}
if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
/* we set a different error code if we pass a negative key */
if (kflags & (1 << KEY_FLAG_NEGATIVE)) {
smp_rmb();
ctx->result = ERR_PTR(key->type_data.reject_error);
kleave(" = %d [neg]", ctx->skipped_ret);
goto skipped;
}
}
/* Found */
ctx->result = make_key_ref(key, ctx->possessed);
kleave(" = 1 [found]");
return 1;
skipped:
return ctx->skipped_ret;
}
/*
* Search inside a keyring for a key. We can search by walking to it
* directly based on its index-key or we can iterate over the entire
* tree looking for it, based on the match function.
*/
static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)
{
if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {
const void *object;
object = assoc_array_find(&keyring->keys,
&keyring_assoc_array_ops,
&ctx->index_key);
return object ? ctx->iterator(object, ctx) : 0;
}
return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx);
}
/*
* Search a tree of keyrings that point to other keyrings up to the maximum
* depth.
*/
static bool search_nested_keyrings(struct key *keyring,
struct keyring_search_context *ctx)
{
struct {
struct key *keyring;
struct assoc_array_node *node;
int slot;
} stack[KEYRING_SEARCH_MAX_DEPTH];
struct assoc_array_shortcut *shortcut;
struct assoc_array_node *node;
struct assoc_array_ptr *ptr;
struct key *key;
int sp = 0, slot;
kenter("{%d},{%s,%s}",
keyring->serial,
ctx->index_key.type->name,
ctx->index_key.description);
#define STATE_CHECKS (KEYRING_SEARCH_NO_STATE_CHECK | KEYRING_SEARCH_DO_STATE_CHECK)
BUG_ON((ctx->flags & STATE_CHECKS) == 0 ||
(ctx->flags & STATE_CHECKS) == STATE_CHECKS);
if (ctx->index_key.description)
ctx->index_key.desc_len = strlen(ctx->index_key.description);
/* Check to see if this top-level keyring is what we are looking for
* and whether it is valid or not.
*/
if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||
keyring_compare_object(keyring, &ctx->index_key)) {
ctx->skipped_ret = 2;
switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) {
case 1:
goto found;
case 2:
return false;
default:
break;
}
}
ctx->skipped_ret = 0;
/* Start processing a new keyring */
descend_to_keyring:
kdebug("descend to %d", keyring->serial);
if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED)))
goto not_this_keyring;
/* Search through the keys in this keyring before its searching its
* subtrees.
*/
if (search_keyring(keyring, ctx))
goto found;
/* Then manually iterate through the keyrings nested in this one.
*
* Start from the root node of the index tree. Because of the way the
* hash function has been set up, keyrings cluster on the leftmost
* branch of the root node (root slot 0) or in the root node itself.
* Non-keyrings avoid the leftmost branch of the root entirely (root
* slots 1-15).
*/
ptr = ACCESS_ONCE(keyring->keys.root);
if (!ptr)
goto not_this_keyring;
if (assoc_array_ptr_is_shortcut(ptr)) {
/* If the root is a shortcut, either the keyring only contains
* keyring pointers (everything clusters behind root slot 0) or
* doesn't contain any keyring pointers.
*/
shortcut = assoc_array_ptr_to_shortcut(ptr);
smp_read_barrier_depends();
if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0)
goto not_this_keyring;
ptr = ACCESS_ONCE(shortcut->next_node);
node = assoc_array_ptr_to_node(ptr);
goto begin_node;
}
node = assoc_array_ptr_to_node(ptr);
smp_read_barrier_depends();
ptr = node->slots[0];
if (!assoc_array_ptr_is_meta(ptr))
goto begin_node;
descend_to_node:
/* Descend to a more distal node in this keyring's content tree and go
* through that.
*/
kdebug("descend");
if (assoc_array_ptr_is_shortcut(ptr)) {
shortcut = assoc_array_ptr_to_shortcut(ptr);
smp_read_barrier_depends();
ptr = ACCESS_ONCE(shortcut->next_node);
BUG_ON(!assoc_array_ptr_is_node(ptr));
}
node = assoc_array_ptr_to_node(ptr);
begin_node:
kdebug("begin_node");
smp_read_barrier_depends();
slot = 0;
ascend_to_node:
/* Go through the slots in a node */
for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = ACCESS_ONCE(node->slots[slot]);
if (assoc_array_ptr_is_meta(ptr) && node->back_pointer)
goto descend_to_node;
if (!keyring_ptr_is_keyring(ptr))
continue;
key = keyring_ptr_to_key(ptr);
if (sp >= KEYRING_SEARCH_MAX_DEPTH) {
if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) {
ctx->result = ERR_PTR(-ELOOP);
return false;
}
goto not_this_keyring;
}
/* Search a nested keyring */
if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
key_task_permission(make_key_ref(key, ctx->possessed),
ctx->cred, KEY_NEED_SEARCH) < 0)
continue;
/* stack the current position */
stack[sp].keyring = keyring;
stack[sp].node = node;
stack[sp].slot = slot;
sp++;
/* begin again with the new keyring */
keyring = key;
goto descend_to_keyring;
}
/* We've dealt with all the slots in the current node, so now we need
* to ascend to the parent and continue processing there.
*/
ptr = ACCESS_ONCE(node->back_pointer);
slot = node->parent_slot;
if (ptr && assoc_array_ptr_is_shortcut(ptr)) {
shortcut = assoc_array_ptr_to_shortcut(ptr);
smp_read_barrier_depends();
ptr = ACCESS_ONCE(shortcut->back_pointer);
slot = shortcut->parent_slot;
}
if (!ptr)
goto not_this_keyring;
node = assoc_array_ptr_to_node(ptr);
smp_read_barrier_depends();
slot++;
/* If we've ascended to the root (zero backpointer), we must have just
* finished processing the leftmost branch rather than the root slots -
* so there can't be any more keyrings for us to find.
*/
if (node->back_pointer) {
kdebug("ascend %d", slot);
goto ascend_to_node;
}
/* The keyring we're looking at was disqualified or didn't contain a
* matching key.
*/
not_this_keyring:
kdebug("not_this_keyring %d", sp);
if (sp <= 0) {
kleave(" = false");
return false;
}
/* Resume the processing of a keyring higher up in the tree */
sp--;
keyring = stack[sp].keyring;
node = stack[sp].node;
slot = stack[sp].slot + 1;
kdebug("ascend to %d [%d]", keyring->serial, slot);
goto ascend_to_node;
/* We found a viable match */
found:
key = key_ref_to_ptr(ctx->result);
key_check(key);
if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
key->last_used_at = ctx->now.tv_sec;
keyring->last_used_at = ctx->now.tv_sec;
while (sp > 0)
stack[--sp].keyring->last_used_at = ctx->now.tv_sec;
}
kleave(" = true");
return true;
}
/**
* keyring_search_aux - Search a keyring tree for a key matching some criteria
* @keyring_ref: A pointer to the keyring with possession indicator.
* @ctx: The keyring search context.
*
* Search the supplied keyring tree for a key that matches the criteria given.
* The root keyring and any linked keyrings must grant Search permission to the
* caller to be searchable and keys can only be found if they too grant Search
* to the caller. The possession flag on the root keyring pointer controls use
* of the possessor bits in permissions checking of the entire tree. In
* addition, the LSM gets to forbid keyring searches and key matches.
*
* The search is performed as a breadth-then-depth search up to the prescribed
* limit (KEYRING_SEARCH_MAX_DEPTH).
*
* Keys are matched to the type provided and are then filtered by the match
* function, which is given the description to use in any way it sees fit. The
* match function may use any attributes of a key that it wishes to to
* determine the match. Normally the match function from the key type would be
* used.
*
* RCU can be used to prevent the keyring key lists from disappearing without
* the need to take lots of locks.
*
* Returns a pointer to the found key and increments the key usage count if
* successful; -EAGAIN if no matching keys were found, or if expired or revoked
* keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
* specified keyring wasn't a keyring.
*
* In the case of a successful return, the possession attribute from
* @keyring_ref is propagated to the returned key reference.
*/
key_ref_t keyring_search_aux(key_ref_t keyring_ref,
struct keyring_search_context *ctx)
{
struct key *keyring;
long err;
ctx->iterator = keyring_search_iterator;
ctx->possessed = is_key_possessed(keyring_ref);
ctx->result = ERR_PTR(-EAGAIN);
keyring = key_ref_to_ptr(keyring_ref);
key_check(keyring);
if (keyring->type != &key_type_keyring)
return ERR_PTR(-ENOTDIR);
if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM)) {
err = key_task_permission(keyring_ref, ctx->cred, KEY_NEED_SEARCH);
if (err < 0)
return ERR_PTR(err);
}
rcu_read_lock();
ctx->now = current_kernel_time();
if (search_nested_keyrings(keyring, ctx))
__key_get(key_ref_to_ptr(ctx->result));
rcu_read_unlock();
return ctx->result;
}
/**
* keyring_search - Search the supplied keyring tree for a matching key
* @keyring: The root of the keyring tree to be searched.
* @type: The type of keyring we want to find.
* @description: The name of the keyring we want to find.
*
* As keyring_search_aux() above, but using the current task's credentials and
* type's default matching function and preferred search method.
*/
key_ref_t keyring_search(key_ref_t keyring,
struct key_type *type,
const char *description)
{
struct keyring_search_context ctx = {
.index_key.type = type,
.index_key.description = description,
.cred = current_cred(),
.match_data.cmp = key_default_cmp,
.match_data.raw_data = description,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_DO_STATE_CHECK,
};
key_ref_t key;
int ret;
if (type->match_preparse) {
ret = type->match_preparse(&ctx.match_data);
if (ret < 0)
return ERR_PTR(ret);
}
key = keyring_search_aux(keyring, &ctx);
if (type->match_free)
type->match_free(&ctx.match_data);
return key;
}
EXPORT_SYMBOL(keyring_search);
/*
* Search the given keyring for a key that might be updated.
*
* The caller must guarantee that the keyring is a keyring and that the
* permission is granted to modify the keyring as no check is made here. The
* caller must also hold a lock on the keyring semaphore.
*
* Returns a pointer to the found key with usage count incremented if
* successful and returns NULL if not found. Revoked and invalidated keys are
* skipped over.
*
* If successful, the possession indicator is propagated from the keyring ref
* to the returned key reference.
*/
key_ref_t find_key_to_update(key_ref_t keyring_ref,
const struct keyring_index_key *index_key)
{
struct key *keyring, *key;
const void *object;
keyring = key_ref_to_ptr(keyring_ref);
kenter("{%d},{%s,%s}",
keyring->serial, index_key->type->name, index_key->description);
object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
index_key);
if (object)
goto found;
kleave(" = NULL");
return NULL;
found:
key = keyring_ptr_to_key(object);
if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED))) {
kleave(" = NULL [x]");
return NULL;
}
__key_get(key);
kleave(" = {%d}", key->serial);
return make_key_ref(key, is_key_possessed(keyring_ref));
}
/*
* Find a keyring with the specified name.
*
* All named keyrings in the current user namespace are searched, provided they
* grant Search permission directly to the caller (unless this check is
* skipped). Keyrings whose usage points have reached zero or who have been
* revoked are skipped.
*
* Returns a pointer to the keyring with the keyring's refcount having being
* incremented on success. -ENOKEY is returned if a key could not be found.
*/
struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
{
struct key *keyring;
int bucket;
if (!name)
return ERR_PTR(-EINVAL);
bucket = keyring_hash(name);
read_lock(&keyring_name_lock);
if (keyring_name_hash[bucket].next) {
/* search this hash bucket for a keyring with a matching name
* that's readable and that hasn't been revoked */
list_for_each_entry(keyring,
&keyring_name_hash[bucket],
type_data.link
) {
if (!kuid_has_mapping(current_user_ns(), keyring->user->uid))
continue;
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
continue;
if (strcmp(keyring->description, name) != 0)
continue;
if (!skip_perm_check &&
key_permission(make_key_ref(keyring, 0),
KEY_NEED_SEARCH) < 0)
continue;
/* we've got a match but we might end up racing with
* key_cleanup() if the keyring is currently 'dead'
* (ie. it has a zero usage count) */
if (!atomic_inc_not_zero(&keyring->usage))
continue;
keyring->last_used_at = current_kernel_time().tv_sec;
goto out;
}
}
keyring = ERR_PTR(-ENOKEY);
out:
read_unlock(&keyring_name_lock);
return keyring;
}
static int keyring_detect_cycle_iterator(const void *object,
void *iterator_data)
{
struct keyring_search_context *ctx = iterator_data;
const struct key *key = keyring_ptr_to_key(object);
kenter("{%d}", key->serial);
/* We might get a keyring with matching index-key that is nonetheless a
* different keyring. */
if (key != ctx->match_data.raw_data)
return 0;
ctx->result = ERR_PTR(-EDEADLK);
return 1;
}
/*
* See if a cycle will will be created by inserting acyclic tree B in acyclic
* tree A at the topmost level (ie: as a direct child of A).
*
* Since we are adding B to A at the top level, checking for cycles should just
* be a matter of seeing if node A is somewhere in tree B.
*/
static int keyring_detect_cycle(struct key *A, struct key *B)
{
struct keyring_search_context ctx = {
.index_key = A->index_key,
.match_data.raw_data = A,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.iterator = keyring_detect_cycle_iterator,
.flags = (KEYRING_SEARCH_NO_STATE_CHECK |
KEYRING_SEARCH_NO_UPDATE_TIME |
KEYRING_SEARCH_NO_CHECK_PERM |
KEYRING_SEARCH_DETECT_TOO_DEEP),
};
rcu_read_lock();
search_nested_keyrings(B, &ctx);
rcu_read_unlock();
return PTR_ERR(ctx.result) == -EAGAIN ? 0 : PTR_ERR(ctx.result);
}
/*
* Preallocate memory so that a key can be linked into to a keyring.
*/
int __key_link_begin(struct key *keyring,
const struct keyring_index_key *index_key,
struct assoc_array_edit **_edit)
__acquires(&keyring->sem)
__acquires(&keyring_serialise_link_sem)
{
struct assoc_array_edit *edit;
int ret;
kenter("%d,%s,%s,",
keyring->serial, index_key->type->name, index_key->description);
BUG_ON(index_key->desc_len == 0);
if (keyring->type != &key_type_keyring)
return -ENOTDIR;
down_write(&keyring->sem);
ret = -EKEYREVOKED;
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
goto error_krsem;
/* serialise link/link calls to prevent parallel calls causing a cycle
* when linking two keyring in opposite orders */
if (index_key->type == &key_type_keyring)
down_write(&keyring_serialise_link_sem);
/* Create an edit script that will insert/replace the key in the
* keyring tree.
*/
edit = assoc_array_insert(&keyring->keys,
&keyring_assoc_array_ops,
index_key,
NULL);
if (IS_ERR(edit)) {
ret = PTR_ERR(edit);
goto error_sem;
}
/* If we're not replacing a link in-place then we're going to need some
* extra quota.
*/
if (!edit->dead_leaf) {
ret = key_payload_reserve(keyring,
keyring->datalen + KEYQUOTA_LINK_BYTES);
if (ret < 0)
goto error_cancel;
}
*_edit = edit;
kleave(" = 0");
return 0;
error_cancel:
assoc_array_cancel_edit(edit);
error_sem:
if (index_key->type == &key_type_keyring)
up_write(&keyring_serialise_link_sem);
error_krsem:
up_write(&keyring->sem);
kleave(" = %d", ret);
return ret;
}
/*
* Check already instantiated keys aren't going to be a problem.
*
* The caller must have called __key_link_begin(). Don't need to call this for
* keys that were created since __key_link_begin() was called.
*/
int __key_link_check_live_key(struct key *keyring, struct key *key)
{
if (key->type == &key_type_keyring)
/* check that we aren't going to create a cycle by linking one
* keyring to another */
return keyring_detect_cycle(keyring, key);
return 0;
}
/*
* Link a key into to a keyring.
*
* Must be called with __key_link_begin() having being called. Discards any
* already extant link to matching key if there is one, so that each keyring
* holds at most one link to any given key of a particular type+description
* combination.
*/
void __key_link(struct key *key, struct assoc_array_edit **_edit)
{
__key_get(key);
assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key));
assoc_array_apply_edit(*_edit);
*_edit = NULL;
}
/*
* Finish linking a key into to a keyring.
*
* Must be called with __key_link_begin() having being called.
*/
void __key_link_end(struct key *keyring,
const struct keyring_index_key *index_key,
struct assoc_array_edit *edit)
__releases(&keyring->sem)
__releases(&keyring_serialise_link_sem)
{
BUG_ON(index_key->type == NULL);
kenter("%d,%s,", keyring->serial, index_key->type->name);
if (index_key->type == &key_type_keyring)
up_write(&keyring_serialise_link_sem);
if (edit) {
if (!edit->dead_leaf) {
key_payload_reserve(keyring,
keyring->datalen - KEYQUOTA_LINK_BYTES);
}
assoc_array_cancel_edit(edit);
}
up_write(&keyring->sem);
}
/**
* key_link - Link a key to a keyring
* @keyring: The keyring to make the link in.
* @key: The key to link to.
*
* Make a link in a keyring to a key, such that the keyring holds a reference
* on that key and the key can potentially be found by searching that keyring.
*
* This function will write-lock the keyring's semaphore and will consume some
* of the user's key data quota to hold the link.
*
* Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
* -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
* full, -EDQUOT if there is insufficient key data quota remaining to add
* another link or -ENOMEM if there's insufficient memory.
*
* It is assumed that the caller has checked that it is permitted for a link to
* be made (the keyring should have Write permission and the key Link
* permission).
*/
int key_link(struct key *keyring, struct key *key)
{
struct assoc_array_edit *edit;
int ret;
kenter("{%d,%d}", keyring->serial, atomic_read(&keyring->usage));
key_check(keyring);
key_check(key);
if (test_bit(KEY_FLAG_TRUSTED_ONLY, &keyring->flags) &&
!test_bit(KEY_FLAG_TRUSTED, &key->flags))
return -EPERM;
ret = __key_link_begin(keyring, &key->index_key, &edit);
if (ret == 0) {
kdebug("begun {%d,%d}", keyring->serial, atomic_read(&keyring->usage));
ret = __key_link_check_live_key(keyring, key);
if (ret == 0)
__key_link(key, &edit);
__key_link_end(keyring, &key->index_key, edit);
}
kleave(" = %d {%d,%d}", ret, keyring->serial, atomic_read(&keyring->usage));
return ret;
}
EXPORT_SYMBOL(key_link);
/**
* key_unlink - Unlink the first link to a key from a keyring.
* @keyring: The keyring to remove the link from.
* @key: The key the link is to.
*
* Remove a link from a keyring to a key.
*
* This function will write-lock the keyring's semaphore.
*
* Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
* the key isn't linked to by the keyring or -ENOMEM if there's insufficient
* memory.
*
* It is assumed that the caller has checked that it is permitted for a link to
* be removed (the keyring should have Write permission; no permissions are
* required on the key).
*/
int key_unlink(struct key *keyring, struct key *key)
{
struct assoc_array_edit *edit;
int ret;
key_check(keyring);
key_check(key);
if (keyring->type != &key_type_keyring)
return -ENOTDIR;
down_write(&keyring->sem);
edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
&key->index_key);
if (IS_ERR(edit)) {
ret = PTR_ERR(edit);
goto error;
}
ret = -ENOENT;
if (edit == NULL)
goto error;
assoc_array_apply_edit(edit);
key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES);
ret = 0;
error:
up_write(&keyring->sem);
return ret;
}
EXPORT_SYMBOL(key_unlink);
/**
* keyring_clear - Clear a keyring
* @keyring: The keyring to clear.
*
* Clear the contents of the specified keyring.
*
* Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
*/
int keyring_clear(struct key *keyring)
{
struct assoc_array_edit *edit;
int ret;
if (keyring->type != &key_type_keyring)
return -ENOTDIR;
down_write(&keyring->sem);
edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
if (IS_ERR(edit)) {
ret = PTR_ERR(edit);
} else {
if (edit)
assoc_array_apply_edit(edit);
key_payload_reserve(keyring, 0);
ret = 0;
}
up_write(&keyring->sem);
return ret;
}
EXPORT_SYMBOL(keyring_clear);
/*
* Dispose of the links from a revoked keyring.
*
* This is called with the key sem write-locked.
*/
static void keyring_revoke(struct key *keyring)
{
struct assoc_array_edit *edit;
edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
if (!IS_ERR(edit)) {
if (edit)
assoc_array_apply_edit(edit);
key_payload_reserve(keyring, 0);
}
}
static bool keyring_gc_select_iterator(void *object, void *iterator_data)
{
struct key *key = keyring_ptr_to_key(object);
time_t *limit = iterator_data;
if (key_is_dead(key, *limit))
return false;
key_get(key);
return true;
}
static int keyring_gc_check_iterator(const void *object, void *iterator_data)
{
const struct key *key = keyring_ptr_to_key(object);
time_t *limit = iterator_data;
key_check(key);
return key_is_dead(key, *limit);
}
/*
* Garbage collect pointers from a keyring.
*
* Not called with any locks held. The keyring's key struct will not be
* deallocated under us as only our caller may deallocate it.
*/
void keyring_gc(struct key *keyring, time_t limit)
{
int result;
kenter("%x{%s}", keyring->serial, keyring->description ?: "");
if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED)))
goto dont_gc;
/* scan the keyring looking for dead keys */
rcu_read_lock();
result = assoc_array_iterate(&keyring->keys,
keyring_gc_check_iterator, &limit);
rcu_read_unlock();
if (result == true)
goto do_gc;
dont_gc:
kleave(" [no gc]");
return;
do_gc:
down_write(&keyring->sem);
assoc_array_gc(&keyring->keys, &keyring_assoc_array_ops,
keyring_gc_select_iterator, &limit);
up_write(&keyring->sem);
kleave(" [gc]");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1469_0 |
crossvul-cpp_data_bad_3522_0 | /*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/gfs2_ondisk.h>
#include <linux/crc32.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "glock.h"
#include "inode.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "super.h"
#include "trans.h"
#include "dir.h"
#include "util.h"
#include "trace_gfs2.h"
/* This doesn't need to be that large as max 64 bit pointers in a 4k
* block is 512, so __u16 is fine for that. It saves stack space to
* keep it small.
*/
struct metapath {
struct buffer_head *mp_bh[GFS2_MAX_META_HEIGHT];
__u16 mp_list[GFS2_MAX_META_HEIGHT];
};
struct strip_mine {
int sm_first;
unsigned int sm_height;
};
/**
* gfs2_unstuffer_page - unstuff a stuffed inode into a block cached by a page
* @ip: the inode
* @dibh: the dinode buffer
* @block: the block number that was allocated
* @page: The (optional) page. This is looked up if @page is NULL
*
* Returns: errno
*/
static int gfs2_unstuffer_page(struct gfs2_inode *ip, struct buffer_head *dibh,
u64 block, struct page *page)
{
struct inode *inode = &ip->i_inode;
struct buffer_head *bh;
int release = 0;
if (!page || page->index) {
page = grab_cache_page(inode->i_mapping, 0);
if (!page)
return -ENOMEM;
release = 1;
}
if (!PageUptodate(page)) {
void *kaddr = kmap(page);
u64 dsize = i_size_read(inode);
if (dsize > (dibh->b_size - sizeof(struct gfs2_dinode)))
dsize = dibh->b_size - sizeof(struct gfs2_dinode);
memcpy(kaddr, dibh->b_data + sizeof(struct gfs2_dinode), dsize);
memset(kaddr + dsize, 0, PAGE_CACHE_SIZE - dsize);
kunmap(page);
SetPageUptodate(page);
}
if (!page_has_buffers(page))
create_empty_buffers(page, 1 << inode->i_blkbits,
(1 << BH_Uptodate));
bh = page_buffers(page);
if (!buffer_mapped(bh))
map_bh(bh, inode->i_sb, block);
set_buffer_uptodate(bh);
if (!gfs2_is_jdata(ip))
mark_buffer_dirty(bh);
if (!gfs2_is_writeback(ip))
gfs2_trans_add_bh(ip->i_gl, bh, 0);
if (release) {
unlock_page(page);
page_cache_release(page);
}
return 0;
}
/**
* gfs2_unstuff_dinode - Unstuff a dinode when the data has grown too big
* @ip: The GFS2 inode to unstuff
* @page: The (optional) page. This is looked up if the @page is NULL
*
* This routine unstuffs a dinode and returns it to a "normal" state such
* that the height can be grown in the traditional way.
*
* Returns: errno
*/
int gfs2_unstuff_dinode(struct gfs2_inode *ip, struct page *page)
{
struct buffer_head *bh, *dibh;
struct gfs2_dinode *di;
u64 block = 0;
int isdir = gfs2_is_dir(ip);
int error;
down_write(&ip->i_rw_mutex);
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
goto out;
if (i_size_read(&ip->i_inode)) {
/* Get a free block, fill it with the stuffed data,
and write it out to disk */
unsigned int n = 1;
error = gfs2_alloc_block(ip, &block, &n);
if (error)
goto out_brelse;
if (isdir) {
gfs2_trans_add_unrevoke(GFS2_SB(&ip->i_inode), block, 1);
error = gfs2_dir_get_new_buffer(ip, block, &bh);
if (error)
goto out_brelse;
gfs2_buffer_copy_tail(bh, sizeof(struct gfs2_meta_header),
dibh, sizeof(struct gfs2_dinode));
brelse(bh);
} else {
error = gfs2_unstuffer_page(ip, dibh, block, page);
if (error)
goto out_brelse;
}
}
/* Set up the pointer to the new block */
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
di = (struct gfs2_dinode *)dibh->b_data;
gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode));
if (i_size_read(&ip->i_inode)) {
*(__be64 *)(di + 1) = cpu_to_be64(block);
gfs2_add_inode_blocks(&ip->i_inode, 1);
di->di_blocks = cpu_to_be64(gfs2_get_inode_blocks(&ip->i_inode));
}
ip->i_height = 1;
di->di_height = cpu_to_be16(1);
out_brelse:
brelse(dibh);
out:
up_write(&ip->i_rw_mutex);
return error;
}
/**
* find_metapath - Find path through the metadata tree
* @sdp: The superblock
* @mp: The metapath to return the result in
* @block: The disk block to look up
* @height: The pre-calculated height of the metadata tree
*
* This routine returns a struct metapath structure that defines a path
* through the metadata of inode "ip" to get to block "block".
*
* Example:
* Given: "ip" is a height 3 file, "offset" is 101342453, and this is a
* filesystem with a blocksize of 4096.
*
* find_metapath() would return a struct metapath structure set to:
* mp_offset = 101342453, mp_height = 3, mp_list[0] = 0, mp_list[1] = 48,
* and mp_list[2] = 165.
*
* That means that in order to get to the block containing the byte at
* offset 101342453, we would load the indirect block pointed to by pointer
* 0 in the dinode. We would then load the indirect block pointed to by
* pointer 48 in that indirect block. We would then load the data block
* pointed to by pointer 165 in that indirect block.
*
* ----------------------------------------
* | Dinode | |
* | | 4|
* | |0 1 2 3 4 5 9|
* | | 6|
* ----------------------------------------
* |
* |
* V
* ----------------------------------------
* | Indirect Block |
* | 5|
* | 4 4 4 4 4 5 5 1|
* |0 5 6 7 8 9 0 1 2|
* ----------------------------------------
* |
* |
* V
* ----------------------------------------
* | Indirect Block |
* | 1 1 1 1 1 5|
* | 6 6 6 6 6 1|
* |0 3 4 5 6 7 2|
* ----------------------------------------
* |
* |
* V
* ----------------------------------------
* | Data block containing offset |
* | 101342453 |
* | |
* | |
* ----------------------------------------
*
*/
static void find_metapath(const struct gfs2_sbd *sdp, u64 block,
struct metapath *mp, unsigned int height)
{
unsigned int i;
for (i = height; i--;)
mp->mp_list[i] = do_div(block, sdp->sd_inptrs);
}
static inline unsigned int metapath_branch_start(const struct metapath *mp)
{
if (mp->mp_list[0] == 0)
return 2;
return 1;
}
/**
* metapointer - Return pointer to start of metadata in a buffer
* @height: The metadata height (0 = dinode)
* @mp: The metapath
*
* Return a pointer to the block number of the next height of the metadata
* tree given a buffer containing the pointer to the current height of the
* metadata tree.
*/
static inline __be64 *metapointer(unsigned int height, const struct metapath *mp)
{
struct buffer_head *bh = mp->mp_bh[height];
unsigned int head_size = (height > 0) ?
sizeof(struct gfs2_meta_header) : sizeof(struct gfs2_dinode);
return ((__be64 *)(bh->b_data + head_size)) + mp->mp_list[height];
}
/**
* lookup_metapath - Walk the metadata tree to a specific point
* @ip: The inode
* @mp: The metapath
*
* Assumes that the inode's buffer has already been looked up and
* hooked onto mp->mp_bh[0] and that the metapath has been initialised
* by find_metapath().
*
* If this function encounters part of the tree which has not been
* allocated, it returns the current height of the tree at the point
* at which it found the unallocated block. Blocks which are found are
* added to the mp->mp_bh[] list.
*
* Returns: error or height of metadata tree
*/
static int lookup_metapath(struct gfs2_inode *ip, struct metapath *mp)
{
unsigned int end_of_metadata = ip->i_height - 1;
unsigned int x;
__be64 *ptr;
u64 dblock;
int ret;
for (x = 0; x < end_of_metadata; x++) {
ptr = metapointer(x, mp);
dblock = be64_to_cpu(*ptr);
if (!dblock)
return x + 1;
ret = gfs2_meta_indirect_buffer(ip, x+1, dblock, 0, &mp->mp_bh[x+1]);
if (ret)
return ret;
}
return ip->i_height;
}
static inline void release_metapath(struct metapath *mp)
{
int i;
for (i = 0; i < GFS2_MAX_META_HEIGHT; i++) {
if (mp->mp_bh[i] == NULL)
break;
brelse(mp->mp_bh[i]);
}
}
/**
* gfs2_extent_length - Returns length of an extent of blocks
* @start: Start of the buffer
* @len: Length of the buffer in bytes
* @ptr: Current position in the buffer
* @limit: Max extent length to return (0 = unlimited)
* @eob: Set to 1 if we hit "end of block"
*
* If the first block is zero (unallocated) it will return the number of
* unallocated blocks in the extent, otherwise it will return the number
* of contiguous blocks in the extent.
*
* Returns: The length of the extent (minimum of one block)
*/
static inline unsigned int gfs2_extent_length(void *start, unsigned int len, __be64 *ptr, unsigned limit, int *eob)
{
const __be64 *end = (start + len);
const __be64 *first = ptr;
u64 d = be64_to_cpu(*ptr);
*eob = 0;
do {
ptr++;
if (ptr >= end)
break;
if (limit && --limit == 0)
break;
if (d)
d++;
} while(be64_to_cpu(*ptr) == d);
if (ptr >= end)
*eob = 1;
return (ptr - first);
}
static inline void bmap_lock(struct gfs2_inode *ip, int create)
{
if (create)
down_write(&ip->i_rw_mutex);
else
down_read(&ip->i_rw_mutex);
}
static inline void bmap_unlock(struct gfs2_inode *ip, int create)
{
if (create)
up_write(&ip->i_rw_mutex);
else
up_read(&ip->i_rw_mutex);
}
static inline __be64 *gfs2_indirect_init(struct metapath *mp,
struct gfs2_glock *gl, unsigned int i,
unsigned offset, u64 bn)
{
__be64 *ptr = (__be64 *)(mp->mp_bh[i - 1]->b_data +
((i > 1) ? sizeof(struct gfs2_meta_header) :
sizeof(struct gfs2_dinode)));
BUG_ON(i < 1);
BUG_ON(mp->mp_bh[i] != NULL);
mp->mp_bh[i] = gfs2_meta_new(gl, bn);
gfs2_trans_add_bh(gl, mp->mp_bh[i], 1);
gfs2_metatype_set(mp->mp_bh[i], GFS2_METATYPE_IN, GFS2_FORMAT_IN);
gfs2_buffer_clear_tail(mp->mp_bh[i], sizeof(struct gfs2_meta_header));
ptr += offset;
*ptr = cpu_to_be64(bn);
return ptr;
}
enum alloc_state {
ALLOC_DATA = 0,
ALLOC_GROW_DEPTH = 1,
ALLOC_GROW_HEIGHT = 2,
/* ALLOC_UNSTUFF = 3, TBD and rather complicated */
};
/**
* gfs2_bmap_alloc - Build a metadata tree of the requested height
* @inode: The GFS2 inode
* @lblock: The logical starting block of the extent
* @bh_map: This is used to return the mapping details
* @mp: The metapath
* @sheight: The starting height (i.e. whats already mapped)
* @height: The height to build to
* @maxlen: The max number of data blocks to alloc
*
* In this routine we may have to alloc:
* i) Indirect blocks to grow the metadata tree height
* ii) Indirect blocks to fill in lower part of the metadata tree
* iii) Data blocks
*
* The function is in two parts. The first part works out the total
* number of blocks which we need. The second part does the actual
* allocation asking for an extent at a time (if enough contiguous free
* blocks are available, there will only be one request per bmap call)
* and uses the state machine to initialise the blocks in order.
*
* Returns: errno on error
*/
static int gfs2_bmap_alloc(struct inode *inode, const sector_t lblock,
struct buffer_head *bh_map, struct metapath *mp,
const unsigned int sheight,
const unsigned int height,
const unsigned int maxlen)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *dibh = mp->mp_bh[0];
u64 bn, dblock = 0;
unsigned n, i, blks, alloced = 0, iblks = 0, branch_start = 0;
unsigned dblks = 0;
unsigned ptrs_per_blk;
const unsigned end_of_metadata = height - 1;
int eob = 0;
enum alloc_state state;
__be64 *ptr;
__be64 zero_bn = 0;
BUG_ON(sheight < 1);
BUG_ON(dibh == NULL);
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
if (height == sheight) {
struct buffer_head *bh;
/* Bottom indirect block exists, find unalloced extent size */
ptr = metapointer(end_of_metadata, mp);
bh = mp->mp_bh[end_of_metadata];
dblks = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen,
&eob);
BUG_ON(dblks < 1);
state = ALLOC_DATA;
} else {
/* Need to allocate indirect blocks */
ptrs_per_blk = height > 1 ? sdp->sd_inptrs : sdp->sd_diptrs;
dblks = min(maxlen, ptrs_per_blk - mp->mp_list[end_of_metadata]);
if (height == ip->i_height) {
/* Writing into existing tree, extend tree down */
iblks = height - sheight;
state = ALLOC_GROW_DEPTH;
} else {
/* Building up tree height */
state = ALLOC_GROW_HEIGHT;
iblks = height - ip->i_height;
branch_start = metapath_branch_start(mp);
iblks += (height - branch_start);
}
}
/* start of the second part of the function (state machine) */
blks = dblks + iblks;
i = sheight;
do {
int error;
n = blks - alloced;
error = gfs2_alloc_block(ip, &bn, &n);
if (error)
return error;
alloced += n;
if (state != ALLOC_DATA || gfs2_is_jdata(ip))
gfs2_trans_add_unrevoke(sdp, bn, n);
switch (state) {
/* Growing height of tree */
case ALLOC_GROW_HEIGHT:
if (i == 1) {
ptr = (__be64 *)(dibh->b_data +
sizeof(struct gfs2_dinode));
zero_bn = *ptr;
}
for (; i - 1 < height - ip->i_height && n > 0; i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i, 0, bn++);
if (i - 1 == height - ip->i_height) {
i--;
gfs2_buffer_copy_tail(mp->mp_bh[i],
sizeof(struct gfs2_meta_header),
dibh, sizeof(struct gfs2_dinode));
gfs2_buffer_clear_tail(dibh,
sizeof(struct gfs2_dinode) +
sizeof(__be64));
ptr = (__be64 *)(mp->mp_bh[i]->b_data +
sizeof(struct gfs2_meta_header));
*ptr = zero_bn;
state = ALLOC_GROW_DEPTH;
for(i = branch_start; i < height; i++) {
if (mp->mp_bh[i] == NULL)
break;
brelse(mp->mp_bh[i]);
mp->mp_bh[i] = NULL;
}
i = branch_start;
}
if (n == 0)
break;
/* Branching from existing tree */
case ALLOC_GROW_DEPTH:
if (i > 1 && i < height)
gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[i-1], 1);
for (; i < height && n > 0; i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i,
mp->mp_list[i-1], bn++);
if (i == height)
state = ALLOC_DATA;
if (n == 0)
break;
/* Tree complete, adding data blocks */
case ALLOC_DATA:
BUG_ON(n > dblks);
BUG_ON(mp->mp_bh[end_of_metadata] == NULL);
gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[end_of_metadata], 1);
dblks = n;
ptr = metapointer(end_of_metadata, mp);
dblock = bn;
while (n-- > 0)
*ptr++ = cpu_to_be64(bn++);
break;
}
} while ((state != ALLOC_DATA) || !dblock);
ip->i_height = height;
gfs2_add_inode_blocks(&ip->i_inode, alloced);
gfs2_dinode_out(ip, mp->mp_bh[0]->b_data);
map_bh(bh_map, inode->i_sb, dblock);
bh_map->b_size = dblks << inode->i_blkbits;
set_buffer_new(bh_map);
return 0;
}
/**
* gfs2_block_map - Map a block from an inode to a disk block
* @inode: The inode
* @lblock: The logical block number
* @bh_map: The bh to be mapped
* @create: True if its ok to alloc blocks to satify the request
*
* Sets buffer_mapped() if successful, sets buffer_boundary() if a
* read of metadata will be required before the next block can be
* mapped. Sets buffer_new() if new blocks were allocated.
*
* Returns: errno
*/
int gfs2_block_map(struct inode *inode, sector_t lblock,
struct buffer_head *bh_map, int create)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
unsigned int bsize = sdp->sd_sb.sb_bsize;
const unsigned int maxlen = bh_map->b_size >> inode->i_blkbits;
const u64 *arr = sdp->sd_heightsize;
__be64 *ptr;
u64 size;
struct metapath mp;
int ret;
int eob;
unsigned int len;
struct buffer_head *bh;
u8 height;
BUG_ON(maxlen == 0);
memset(mp.mp_bh, 0, sizeof(mp.mp_bh));
bmap_lock(ip, create);
clear_buffer_mapped(bh_map);
clear_buffer_new(bh_map);
clear_buffer_boundary(bh_map);
trace_gfs2_bmap(ip, bh_map, lblock, create, 1);
if (gfs2_is_dir(ip)) {
bsize = sdp->sd_jbsize;
arr = sdp->sd_jheightsize;
}
ret = gfs2_meta_inode_buffer(ip, &mp.mp_bh[0]);
if (ret)
goto out;
height = ip->i_height;
size = (lblock + 1) * bsize;
while (size > arr[height])
height++;
find_metapath(sdp, lblock, &mp, height);
ret = 1;
if (height > ip->i_height || gfs2_is_stuffed(ip))
goto do_alloc;
ret = lookup_metapath(ip, &mp);
if (ret < 0)
goto out;
if (ret != ip->i_height)
goto do_alloc;
ptr = metapointer(ip->i_height - 1, &mp);
if (*ptr == 0)
goto do_alloc;
map_bh(bh_map, inode->i_sb, be64_to_cpu(*ptr));
bh = mp.mp_bh[ip->i_height - 1];
len = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen, &eob);
bh_map->b_size = (len << inode->i_blkbits);
if (eob)
set_buffer_boundary(bh_map);
ret = 0;
out:
release_metapath(&mp);
trace_gfs2_bmap(ip, bh_map, lblock, create, ret);
bmap_unlock(ip, create);
return ret;
do_alloc:
/* All allocations are done here, firstly check create flag */
if (!create) {
BUG_ON(gfs2_is_stuffed(ip));
ret = 0;
goto out;
}
/* At this point ret is the tree depth of already allocated blocks */
ret = gfs2_bmap_alloc(inode, lblock, bh_map, &mp, ret, height, maxlen);
goto out;
}
/*
* Deprecated: do not use in new code
*/
int gfs2_extent_map(struct inode *inode, u64 lblock, int *new, u64 *dblock, unsigned *extlen)
{
struct buffer_head bh = { .b_state = 0, .b_blocknr = 0 };
int ret;
int create = *new;
BUG_ON(!extlen);
BUG_ON(!dblock);
BUG_ON(!new);
bh.b_size = 1 << (inode->i_blkbits + (create ? 0 : 5));
ret = gfs2_block_map(inode, lblock, &bh, create);
*extlen = bh.b_size >> inode->i_blkbits;
*dblock = bh.b_blocknr;
if (buffer_new(&bh))
*new = 1;
else
*new = 0;
return ret;
}
/**
* do_strip - Look for a layer a particular layer of the file and strip it off
* @ip: the inode
* @dibh: the dinode buffer
* @bh: A buffer of pointers
* @top: The first pointer in the buffer
* @bottom: One more than the last pointer
* @height: the height this buffer is at
* @data: a pointer to a struct strip_mine
*
* Returns: errno
*/
static int do_strip(struct gfs2_inode *ip, struct buffer_head *dibh,
struct buffer_head *bh, __be64 *top, __be64 *bottom,
unsigned int height, struct strip_mine *sm)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_rgrp_list rlist;
u64 bn, bstart;
u32 blen, btotal;
__be64 *p;
unsigned int rg_blocks = 0;
int metadata;
unsigned int revokes = 0;
int x;
int error = 0;
if (!*top)
sm->sm_first = 0;
if (height != sm->sm_height)
return 0;
if (sm->sm_first) {
top++;
sm->sm_first = 0;
}
metadata = (height != ip->i_height - 1);
if (metadata)
revokes = (height) ? sdp->sd_inptrs : sdp->sd_diptrs;
else if (ip->i_depth)
revokes = sdp->sd_inptrs;
if (error)
return error;
memset(&rlist, 0, sizeof(struct gfs2_rgrp_list));
bstart = 0;
blen = 0;
for (p = top; p < bottom; p++) {
if (!*p)
continue;
bn = be64_to_cpu(*p);
if (bstart + blen == bn)
blen++;
else {
if (bstart)
gfs2_rlist_add(ip, &rlist, bstart);
bstart = bn;
blen = 1;
}
}
if (bstart)
gfs2_rlist_add(ip, &rlist, bstart);
else
goto out; /* Nothing to do */
gfs2_rlist_alloc(&rlist, LM_ST_EXCLUSIVE);
for (x = 0; x < rlist.rl_rgrps; x++) {
struct gfs2_rgrpd *rgd;
rgd = rlist.rl_ghs[x].gh_gl->gl_object;
rg_blocks += rgd->rd_length;
}
error = gfs2_glock_nq_m(rlist.rl_rgrps, rlist.rl_ghs);
if (error)
goto out_rlist;
error = gfs2_trans_begin(sdp, rg_blocks + RES_DINODE +
RES_INDIRECT + RES_STATFS + RES_QUOTA,
revokes);
if (error)
goto out_rg_gunlock;
down_write(&ip->i_rw_mutex);
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
gfs2_trans_add_bh(ip->i_gl, bh, 1);
bstart = 0;
blen = 0;
btotal = 0;
for (p = top; p < bottom; p++) {
if (!*p)
continue;
bn = be64_to_cpu(*p);
if (bstart + blen == bn)
blen++;
else {
if (bstart) {
__gfs2_free_blocks(ip, bstart, blen, metadata);
btotal += blen;
}
bstart = bn;
blen = 1;
}
*p = 0;
gfs2_add_inode_blocks(&ip->i_inode, -1);
}
if (bstart) {
__gfs2_free_blocks(ip, bstart, blen, metadata);
btotal += blen;
}
gfs2_statfs_change(sdp, 0, +btotal, 0);
gfs2_quota_change(ip, -(s64)btotal, ip->i_inode.i_uid,
ip->i_inode.i_gid);
ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME;
gfs2_dinode_out(ip, dibh->b_data);
up_write(&ip->i_rw_mutex);
gfs2_trans_end(sdp);
out_rg_gunlock:
gfs2_glock_dq_m(rlist.rl_rgrps, rlist.rl_ghs);
out_rlist:
gfs2_rlist_free(&rlist);
out:
return error;
}
/**
* recursive_scan - recursively scan through the end of a file
* @ip: the inode
* @dibh: the dinode buffer
* @mp: the path through the metadata to the point to start
* @height: the height the recursion is at
* @block: the indirect block to look at
* @first: 1 if this is the first block
* @sm: data opaque to this function to pass to @bc
*
* When this is first called @height and @block should be zero and
* @first should be 1.
*
* Returns: errno
*/
static int recursive_scan(struct gfs2_inode *ip, struct buffer_head *dibh,
struct metapath *mp, unsigned int height,
u64 block, int first, struct strip_mine *sm)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct buffer_head *bh = NULL;
__be64 *top, *bottom, *t2;
u64 bn;
int error;
int mh_size = sizeof(struct gfs2_meta_header);
if (!height) {
error = gfs2_meta_inode_buffer(ip, &bh);
if (error)
return error;
dibh = bh;
top = (__be64 *)(bh->b_data + sizeof(struct gfs2_dinode)) + mp->mp_list[0];
bottom = (__be64 *)(bh->b_data + sizeof(struct gfs2_dinode)) + sdp->sd_diptrs;
} else {
error = gfs2_meta_indirect_buffer(ip, height, block, 0, &bh);
if (error)
return error;
top = (__be64 *)(bh->b_data + mh_size) +
(first ? mp->mp_list[height] : 0);
bottom = (__be64 *)(bh->b_data + mh_size) + sdp->sd_inptrs;
}
error = do_strip(ip, dibh, bh, top, bottom, height, sm);
if (error)
goto out;
if (height < ip->i_height - 1) {
struct buffer_head *rabh;
for (t2 = top; t2 < bottom; t2++, first = 0) {
if (!*t2)
continue;
bn = be64_to_cpu(*t2);
rabh = gfs2_getbuf(ip->i_gl, bn, CREATE);
if (trylock_buffer(rabh)) {
if (buffer_uptodate(rabh)) {
unlock_buffer(rabh);
brelse(rabh);
continue;
}
rabh->b_end_io = end_buffer_read_sync;
submit_bh(READA | REQ_META, rabh);
continue;
}
brelse(rabh);
}
for (; top < bottom; top++, first = 0) {
if (!*top)
continue;
bn = be64_to_cpu(*top);
error = recursive_scan(ip, dibh, mp, height + 1, bn,
first, sm);
if (error)
break;
}
}
out:
brelse(bh);
return error;
}
/**
* gfs2_block_truncate_page - Deal with zeroing out data for truncate
*
* This is partly borrowed from ext3.
*/
static int gfs2_block_truncate_page(struct address_space *mapping, loff_t from)
{
struct inode *inode = mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
unsigned long index = from >> PAGE_CACHE_SHIFT;
unsigned offset = from & (PAGE_CACHE_SIZE-1);
unsigned blocksize, iblock, length, pos;
struct buffer_head *bh;
struct page *page;
int err;
page = grab_cache_page(mapping, index);
if (!page)
return 0;
blocksize = inode->i_sb->s_blocksize;
length = blocksize - (offset & (blocksize - 1));
iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
if (!page_has_buffers(page))
create_empty_buffers(page, blocksize, 0);
/* Find the buffer that contains "offset" */
bh = page_buffers(page);
pos = blocksize;
while (offset >= pos) {
bh = bh->b_this_page;
iblock++;
pos += blocksize;
}
err = 0;
if (!buffer_mapped(bh)) {
gfs2_block_map(inode, iblock, bh, 0);
/* unmapped? It's a hole - nothing to do */
if (!buffer_mapped(bh))
goto unlock;
}
/* Ok, it's mapped. Make sure it's up-to-date */
if (PageUptodate(page))
set_buffer_uptodate(bh);
if (!buffer_uptodate(bh)) {
err = -EIO;
ll_rw_block(READ, 1, &bh);
wait_on_buffer(bh);
/* Uhhuh. Read error. Complain and punt. */
if (!buffer_uptodate(bh))
goto unlock;
err = 0;
}
if (!gfs2_is_writeback(ip))
gfs2_trans_add_bh(ip->i_gl, bh, 0);
zero_user(page, offset, length);
mark_buffer_dirty(bh);
unlock:
unlock_page(page);
page_cache_release(page);
return err;
}
static int trunc_start(struct inode *inode, u64 oldsize, u64 newsize)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct address_space *mapping = inode->i_mapping;
struct buffer_head *dibh;
int journaled = gfs2_is_jdata(ip);
int error;
error = gfs2_trans_begin(sdp,
RES_DINODE + (journaled ? RES_JDATA : 0), 0);
if (error)
return error;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
goto out;
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
if (gfs2_is_stuffed(ip)) {
gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode) + newsize);
} else {
if (newsize & (u64)(sdp->sd_sb.sb_bsize - 1)) {
error = gfs2_block_truncate_page(mapping, newsize);
if (error)
goto out_brelse;
}
ip->i_diskflags |= GFS2_DIF_TRUNC_IN_PROG;
}
i_size_write(inode, newsize);
ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME;
gfs2_dinode_out(ip, dibh->b_data);
truncate_pagecache(inode, oldsize, newsize);
out_brelse:
brelse(dibh);
out:
gfs2_trans_end(sdp);
return error;
}
static int trunc_dealloc(struct gfs2_inode *ip, u64 size)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
unsigned int height = ip->i_height;
u64 lblock;
struct metapath mp;
int error;
if (!size)
lblock = 0;
else
lblock = (size - 1) >> sdp->sd_sb.sb_bsize_shift;
find_metapath(sdp, lblock, &mp, ip->i_height);
if (!gfs2_alloc_get(ip))
return -ENOMEM;
error = gfs2_quota_hold(ip, NO_QUOTA_CHANGE, NO_QUOTA_CHANGE);
if (error)
goto out;
while (height--) {
struct strip_mine sm;
sm.sm_first = !!size;
sm.sm_height = height;
error = recursive_scan(ip, NULL, &mp, 0, 0, 1, &sm);
if (error)
break;
}
gfs2_quota_unhold(ip);
out:
gfs2_alloc_put(ip);
return error;
}
static int trunc_end(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct buffer_head *dibh;
int error;
error = gfs2_trans_begin(sdp, RES_DINODE, 0);
if (error)
return error;
down_write(&ip->i_rw_mutex);
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
goto out;
if (!i_size_read(&ip->i_inode)) {
ip->i_height = 0;
ip->i_goal = ip->i_no_addr;
gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode));
}
ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME;
ip->i_diskflags &= ~GFS2_DIF_TRUNC_IN_PROG;
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
gfs2_dinode_out(ip, dibh->b_data);
brelse(dibh);
out:
up_write(&ip->i_rw_mutex);
gfs2_trans_end(sdp);
return error;
}
/**
* do_shrink - make a file smaller
* @inode: the inode
* @oldsize: the current inode size
* @newsize: the size to make the file
*
* Called with an exclusive lock on @inode. The @size must
* be equal to or smaller than the current inode size.
*
* Returns: errno
*/
static int do_shrink(struct inode *inode, u64 oldsize, u64 newsize)
{
struct gfs2_inode *ip = GFS2_I(inode);
int error;
error = trunc_start(inode, oldsize, newsize);
if (error < 0)
return error;
if (gfs2_is_stuffed(ip))
return 0;
error = trunc_dealloc(ip, newsize);
if (error == 0)
error = trunc_end(ip);
return error;
}
void gfs2_trim_blocks(struct inode *inode)
{
u64 size = inode->i_size;
int ret;
ret = do_shrink(inode, size, size);
WARN_ON(ret != 0);
}
/**
* do_grow - Touch and update inode size
* @inode: The inode
* @size: The new size
*
* This function updates the timestamps on the inode and
* may also increase the size of the inode. This function
* must not be called with @size any smaller than the current
* inode size.
*
* Although it is not strictly required to unstuff files here,
* earlier versions of GFS2 have a bug in the stuffed file reading
* code which will result in a buffer overrun if the size is larger
* than the max stuffed file size. In order to prevent this from
* occurring, such files are unstuffed, but in other cases we can
* just update the inode size directly.
*
* Returns: 0 on success, or -ve on error
*/
static int do_grow(struct inode *inode, u64 size)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *dibh;
struct gfs2_alloc *al = NULL;
int error;
if (gfs2_is_stuffed(ip) &&
(size > (sdp->sd_sb.sb_bsize - sizeof(struct gfs2_dinode)))) {
al = gfs2_alloc_get(ip);
if (al == NULL)
return -ENOMEM;
error = gfs2_quota_lock_check(ip);
if (error)
goto do_grow_alloc_put;
al->al_requested = 1;
error = gfs2_inplace_reserve(ip);
if (error)
goto do_grow_qunlock;
}
error = gfs2_trans_begin(sdp, RES_DINODE + RES_STATFS + RES_RG_BIT, 0);
if (error)
goto do_grow_release;
if (al) {
error = gfs2_unstuff_dinode(ip, NULL);
if (error)
goto do_end_trans;
}
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
goto do_end_trans;
i_size_write(inode, size);
ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME;
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
gfs2_dinode_out(ip, dibh->b_data);
brelse(dibh);
do_end_trans:
gfs2_trans_end(sdp);
do_grow_release:
if (al) {
gfs2_inplace_release(ip);
do_grow_qunlock:
gfs2_quota_unlock(ip);
do_grow_alloc_put:
gfs2_alloc_put(ip);
}
return error;
}
/**
* gfs2_setattr_size - make a file a given size
* @inode: the inode
* @newsize: the size to make the file
*
* The file size can grow, shrink, or stay the same size. This
* is called holding i_mutex and an exclusive glock on the inode
* in question.
*
* Returns: errno
*/
int gfs2_setattr_size(struct inode *inode, u64 newsize)
{
int ret;
u64 oldsize;
BUG_ON(!S_ISREG(inode->i_mode));
ret = inode_newsize_ok(inode, newsize);
if (ret)
return ret;
inode_dio_wait(inode);
oldsize = inode->i_size;
if (newsize >= oldsize)
return do_grow(inode, newsize);
return do_shrink(inode, oldsize, newsize);
}
int gfs2_truncatei_resume(struct gfs2_inode *ip)
{
int error;
error = trunc_dealloc(ip, i_size_read(&ip->i_inode));
if (!error)
error = trunc_end(ip);
return error;
}
int gfs2_file_dealloc(struct gfs2_inode *ip)
{
return trunc_dealloc(ip, 0);
}
/**
* gfs2_write_alloc_required - figure out if a write will require an allocation
* @ip: the file being written to
* @offset: the offset to write to
* @len: the number of bytes being written
*
* Returns: 1 if an alloc is required, 0 otherwise
*/
int gfs2_write_alloc_required(struct gfs2_inode *ip, u64 offset,
unsigned int len)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct buffer_head bh;
unsigned int shift;
u64 lblock, lblock_stop, size;
u64 end_of_file;
if (!len)
return 0;
if (gfs2_is_stuffed(ip)) {
if (offset + len >
sdp->sd_sb.sb_bsize - sizeof(struct gfs2_dinode))
return 1;
return 0;
}
shift = sdp->sd_sb.sb_bsize_shift;
BUG_ON(gfs2_is_dir(ip));
end_of_file = (i_size_read(&ip->i_inode) + sdp->sd_sb.sb_bsize - 1) >> shift;
lblock = offset >> shift;
lblock_stop = (offset + len + sdp->sd_sb.sb_bsize - 1) >> shift;
if (lblock_stop > end_of_file)
return 1;
size = (lblock_stop - lblock) << shift;
do {
bh.b_state = 0;
bh.b_size = size;
gfs2_block_map(&ip->i_inode, lblock, &bh, 0);
if (!buffer_mapped(&bh))
return 1;
size -= bh.b_size;
lblock += (bh.b_size >> ip->i_inode.i_blkbits);
} while(size > 0);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3522_0 |
crossvul-cpp_data_bad_2131_0 | /*
* HID driver for some cherry "special" devices
*
* Copyright (c) 1999 Andreas Gal
* Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
* Copyright (c) 2006-2007 Jiri Kosina
* Copyright (c) 2008 Jiri Slaby
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <linux/device.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
/*
* Cherry Cymotion keyboard have an invalid HID report descriptor,
* that needs fixing before we can parse it.
*/
static __u8 *ch_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 17 && rdesc[11] == 0x3c && rdesc[12] == 0x02) {
hid_info(hdev, "fixing up Cherry Cymotion report descriptor\n");
rdesc[11] = rdesc[16] = 0xff;
rdesc[12] = rdesc[17] = 0x03;
}
return rdesc;
}
#define ch_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \
EV_KEY, (c))
static int ch_input_mapping(struct hid_device *hdev, struct hid_input *hi,
struct hid_field *field, struct hid_usage *usage,
unsigned long **bit, int *max)
{
if ((usage->hid & HID_USAGE_PAGE) != HID_UP_CONSUMER)
return 0;
switch (usage->hid & HID_USAGE) {
case 0x301: ch_map_key_clear(KEY_PROG1); break;
case 0x302: ch_map_key_clear(KEY_PROG2); break;
case 0x303: ch_map_key_clear(KEY_PROG3); break;
default:
return 0;
}
return 1;
}
static const struct hid_device_id ch_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_CHERRY, USB_DEVICE_ID_CHERRY_CYMOTION) },
{ HID_USB_DEVICE(USB_VENDOR_ID_CHERRY, USB_DEVICE_ID_CHERRY_CYMOTION_SOLAR) },
{ }
};
MODULE_DEVICE_TABLE(hid, ch_devices);
static struct hid_driver ch_driver = {
.name = "cherry",
.id_table = ch_devices,
.report_fixup = ch_report_fixup,
.input_mapping = ch_input_mapping,
};
module_hid_driver(ch_driver);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2131_0 |
crossvul-cpp_data_good_5743_0 | /*
* IPv6 output functions
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* Based on linux/net/ipv4/ip_output.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Changes:
* A.N.Kuznetsov : airthmetics in fragmentation.
* extension headers are implemented.
* route changes now work.
* ip6_forward does not confuse sniffers.
* etc.
*
* H. von Brand : Added missing #include <linux/string.h>
* Imran Patel : frag id should be in NBO
* Kazunori MIYAZAWA @USAGI
* : add ip6_append_data and related functions
* for datagram xmit
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/in6.h>
#include <linux/tcp.h>
#include <linux/route.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/protocol.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/rawv6.h>
#include <net/icmp.h>
#include <net/xfrm.h>
#include <net/checksum.h>
#include <linux/mroute6.h>
static int ip6_finish_output2(struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct net_device *dev = dst->dev;
struct neighbour *neigh;
struct in6_addr *nexthop;
int ret;
skb->protocol = htons(ETH_P_IPV6);
skb->dev = dev;
if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) {
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(skb->sk) &&
((mroute6_socket(dev_net(dev), skb) &&
!(IP6CB(skb)->flags & IP6SKB_FORWARDED)) ||
ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr,
&ipv6_hdr(skb)->saddr))) {
struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
/* Do not check for IFF_ALLMULTI; multicast routing
is not supported in any case.
*/
if (newskb)
NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING,
newskb, NULL, newskb->dev,
dev_loopback_xmit);
if (ipv6_hdr(skb)->hop_limit == 0) {
IP6_INC_STATS(dev_net(dev), idev,
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return 0;
}
}
IP6_UPD_PO_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTMCAST,
skb->len);
if (IPV6_ADDR_MC_SCOPE(&ipv6_hdr(skb)->daddr) <=
IPV6_ADDR_SCOPE_NODELOCAL &&
!(dev->flags & IFF_LOOPBACK)) {
kfree_skb(skb);
return 0;
}
}
rcu_read_lock_bh();
nexthop = rt6_nexthop((struct rt6_info *)dst, &ipv6_hdr(skb)->daddr);
neigh = __ipv6_neigh_lookup_noref(dst->dev, nexthop);
if (unlikely(!neigh))
neigh = __neigh_create(&nd_tbl, nexthop, dst->dev, false);
if (!IS_ERR(neigh)) {
ret = dst_neigh_output(dst, neigh, skb);
rcu_read_unlock_bh();
return ret;
}
rcu_read_unlock_bh();
IP6_INC_STATS_BH(dev_net(dst->dev),
ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(skb);
return -EINVAL;
}
static int ip6_finish_output(struct sk_buff *skb)
{
if ((skb->len > ip6_skb_dst_mtu(skb) && !skb_is_gso(skb)) ||
dst_allfrag(skb_dst(skb)))
return ip6_fragment(skb, ip6_finish_output2);
else
return ip6_finish_output2(skb);
}
int ip6_output(struct sk_buff *skb)
{
struct net_device *dev = skb_dst(skb)->dev;
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
if (unlikely(idev->cnf.disable_ipv6)) {
IP6_INC_STATS(dev_net(dev), idev,
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return 0;
}
return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING, skb, NULL, dev,
ip6_finish_output,
!(IP6CB(skb)->flags & IP6SKB_REROUTED));
}
/*
* xmit an sk_buff (used by TCP, SCTP and DCCP)
*/
int ip6_xmit(struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6,
struct ipv6_txoptions *opt, int tclass)
{
struct net *net = sock_net(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *first_hop = &fl6->daddr;
struct dst_entry *dst = skb_dst(skb);
struct ipv6hdr *hdr;
u8 proto = fl6->flowi6_proto;
int seg_len = skb->len;
int hlimit = -1;
u32 mtu;
if (opt) {
unsigned int head_room;
/* First: exthdrs may take lots of space (~8K for now)
MAX_HEADER is not enough.
*/
head_room = opt->opt_nflen + opt->opt_flen;
seg_len += head_room;
head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev);
if (skb_headroom(skb) < head_room) {
struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room);
if (skb2 == NULL) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return -ENOBUFS;
}
consume_skb(skb);
skb = skb2;
skb_set_owner_w(skb, sk);
}
if (opt->opt_flen)
ipv6_push_frag_opts(skb, opt, &proto);
if (opt->opt_nflen)
ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop);
}
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
hdr = ipv6_hdr(skb);
/*
* Fill in the IPv6 header
*/
if (np)
hlimit = np->hop_limit;
if (hlimit < 0)
hlimit = ip6_dst_hoplimit(dst);
ip6_flow_hdr(hdr, tclass, fl6->flowlabel);
hdr->payload_len = htons(seg_len);
hdr->nexthdr = proto;
hdr->hop_limit = hlimit;
hdr->saddr = fl6->saddr;
hdr->daddr = *first_hop;
skb->protocol = htons(ETH_P_IPV6);
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
mtu = dst_mtu(dst);
if ((skb->len <= mtu) || skb->local_df || skb_is_gso(skb)) {
IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUT, skb->len);
return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL,
dst->dev, dst_output);
}
skb->dev = dst->dev;
ipv6_local_error(sk, EMSGSIZE, fl6, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
EXPORT_SYMBOL(ip6_xmit);
static int ip6_call_ra_chain(struct sk_buff *skb, int sel)
{
struct ip6_ra_chain *ra;
struct sock *last = NULL;
read_lock(&ip6_ra_lock);
for (ra = ip6_ra_chain; ra; ra = ra->next) {
struct sock *sk = ra->sk;
if (sk && ra->sel == sel &&
(!sk->sk_bound_dev_if ||
sk->sk_bound_dev_if == skb->dev->ifindex)) {
if (last) {
struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2)
rawv6_rcv(last, skb2);
}
last = sk;
}
}
if (last) {
rawv6_rcv(last, skb);
read_unlock(&ip6_ra_lock);
return 1;
}
read_unlock(&ip6_ra_lock);
return 0;
}
static int ip6_forward_proxy_check(struct sk_buff *skb)
{
struct ipv6hdr *hdr = ipv6_hdr(skb);
u8 nexthdr = hdr->nexthdr;
__be16 frag_off;
int offset;
if (ipv6_ext_hdr(nexthdr)) {
offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off);
if (offset < 0)
return 0;
} else
offset = sizeof(struct ipv6hdr);
if (nexthdr == IPPROTO_ICMPV6) {
struct icmp6hdr *icmp6;
if (!pskb_may_pull(skb, (skb_network_header(skb) +
offset + 1 - skb->data)))
return 0;
icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset);
switch (icmp6->icmp6_type) {
case NDISC_ROUTER_SOLICITATION:
case NDISC_ROUTER_ADVERTISEMENT:
case NDISC_NEIGHBOUR_SOLICITATION:
case NDISC_NEIGHBOUR_ADVERTISEMENT:
case NDISC_REDIRECT:
/* For reaction involving unicast neighbor discovery
* message destined to the proxied address, pass it to
* input function.
*/
return 1;
default:
break;
}
}
/*
* The proxying router can't forward traffic sent to a link-local
* address, so signal the sender and discard the packet. This
* behavior is clarified by the MIPv6 specification.
*/
if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) {
dst_link_failure(skb);
return -1;
}
return 0;
}
static inline int ip6_forward_finish(struct sk_buff *skb)
{
return dst_output(skb);
}
int ip6_forward(struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct ipv6hdr *hdr = ipv6_hdr(skb);
struct inet6_skb_parm *opt = IP6CB(skb);
struct net *net = dev_net(dst->dev);
u32 mtu;
if (net->ipv6.devconf_all->forwarding == 0)
goto error;
if (skb_warn_if_lro(skb))
goto drop;
if (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) {
IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS);
goto drop;
}
if (skb->pkt_type != PACKET_HOST)
goto drop;
skb_forward_csum(skb);
/*
* We DO NOT make any processing on
* RA packets, pushing them to user level AS IS
* without ane WARRANTY that application will be able
* to interpret them. The reason is that we
* cannot make anything clever here.
*
* We are not end-node, so that if packet contains
* AH/ESP, we cannot make anything.
* Defragmentation also would be mistake, RA packets
* cannot be fragmented, because there is no warranty
* that different fragments will go along one path. --ANK
*/
if (unlikely(opt->flags & IP6SKB_ROUTERALERT)) {
if (ip6_call_ra_chain(skb, ntohs(opt->ra)))
return 0;
}
/*
* check and decrement ttl
*/
if (hdr->hop_limit <= 1) {
/* Force OUTPUT device used as source address */
skb->dev = dst->dev;
icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0);
IP6_INC_STATS_BH(net,
ip6_dst_idev(dst), IPSTATS_MIB_INHDRERRORS);
kfree_skb(skb);
return -ETIMEDOUT;
}
/* XXX: idev->cnf.proxy_ndp? */
if (net->ipv6.devconf_all->proxy_ndp &&
pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) {
int proxied = ip6_forward_proxy_check(skb);
if (proxied > 0)
return ip6_input(skb);
else if (proxied < 0) {
IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INDISCARDS);
goto drop;
}
}
if (!xfrm6_route_forward(skb)) {
IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS);
goto drop;
}
dst = skb_dst(skb);
/* IPv6 specs say nothing about it, but it is clear that we cannot
send redirects to source routed frames.
We don't send redirects to frames decapsulated from IPsec.
*/
if (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) {
struct in6_addr *target = NULL;
struct inet_peer *peer;
struct rt6_info *rt;
/*
* incoming and outgoing devices are the same
* send a redirect.
*/
rt = (struct rt6_info *) dst;
if (rt->rt6i_flags & RTF_GATEWAY)
target = &rt->rt6i_gateway;
else
target = &hdr->daddr;
peer = inet_getpeer_v6(net->ipv6.peers, &rt->rt6i_dst.addr, 1);
/* Limit redirects both by destination (here)
and by source (inside ndisc_send_redirect)
*/
if (inet_peer_xrlim_allow(peer, 1*HZ))
ndisc_send_redirect(skb, target);
if (peer)
inet_putpeer(peer);
} else {
int addrtype = ipv6_addr_type(&hdr->saddr);
/* This check is security critical. */
if (addrtype == IPV6_ADDR_ANY ||
addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK))
goto error;
if (addrtype & IPV6_ADDR_LINKLOCAL) {
icmpv6_send(skb, ICMPV6_DEST_UNREACH,
ICMPV6_NOT_NEIGHBOUR, 0);
goto error;
}
}
mtu = dst_mtu(dst);
if (mtu < IPV6_MIN_MTU)
mtu = IPV6_MIN_MTU;
if ((!skb->local_df && skb->len > mtu && !skb_is_gso(skb)) ||
(IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu)) {
/* Again, force OUTPUT device used as source address */
skb->dev = dst->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP6_INC_STATS_BH(net,
ip6_dst_idev(dst), IPSTATS_MIB_INTOOBIGERRORS);
IP6_INC_STATS_BH(net,
ip6_dst_idev(dst), IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
if (skb_cow(skb, dst->dev->hard_header_len)) {
IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTDISCARDS);
goto drop;
}
hdr = ipv6_hdr(skb);
/* Mangling hops number delayed to point after skb COW */
hdr->hop_limit--;
IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS);
IP6_ADD_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTOCTETS, skb->len);
return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, skb, skb->dev, dst->dev,
ip6_forward_finish);
error:
IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS);
drop:
kfree_skb(skb);
return -EINVAL;
}
static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from)
{
to->pkt_type = from->pkt_type;
to->priority = from->priority;
to->protocol = from->protocol;
skb_dst_drop(to);
skb_dst_set(to, dst_clone(skb_dst(from)));
to->dev = from->dev;
to->mark = from->mark;
#ifdef CONFIG_NET_SCHED
to->tc_index = from->tc_index;
#endif
nf_copy(to, from);
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
to->nf_trace = from->nf_trace;
#endif
skb_copy_secmark(to, from);
}
int ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *))
{
struct sk_buff *frag;
struct rt6_info *rt = (struct rt6_info*)skb_dst(skb);
struct ipv6_pinfo *np = skb->sk ? inet6_sk(skb->sk) : NULL;
struct ipv6hdr *tmp_hdr;
struct frag_hdr *fh;
unsigned int mtu, hlen, left, len;
int hroom, troom;
__be32 frag_id = 0;
int ptr, offset = 0, err=0;
u8 *prevhdr, nexthdr = 0;
struct net *net = dev_net(skb_dst(skb)->dev);
hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
mtu = ip6_skb_dst_mtu(skb);
/* We must not fragment if the socket is set to force MTU discovery
* or if the skb it not generated by a local socket.
*/
if (unlikely(!skb->local_df && skb->len > mtu) ||
(IP6CB(skb)->frag_max_size &&
IP6CB(skb)->frag_max_size > mtu)) {
if (skb->sk && dst_allfrag(skb_dst(skb)))
sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK);
skb->dev = skb_dst(skb)->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
if (np && np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
mtu -= hlen + sizeof(struct frag_hdr);
if (skb_has_frag_list(skb)) {
int first_len = skb_pagelen(skb);
struct sk_buff *frag2;
if (first_len - hlen > mtu ||
((first_len - hlen) & 7) ||
skb_cloned(skb))
goto slow_path;
skb_walk_frags(skb, frag) {
/* Correct geometry. */
if (frag->len > mtu ||
((frag->len & 7) && frag->next) ||
skb_headroom(frag) < hlen)
goto slow_path_clean;
/* Partially cloned skb? */
if (skb_shared(frag))
goto slow_path_clean;
BUG_ON(frag->sk);
if (skb->sk) {
frag->sk = skb->sk;
frag->destructor = sock_wfree;
}
skb->truesize -= frag->truesize;
}
err = 0;
offset = 0;
frag = skb_shinfo(skb)->frag_list;
skb_frag_list_init(skb);
/* BUILD HEADER */
*prevhdr = NEXTHDR_FRAGMENT;
tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
if (!tmp_hdr) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
return -ENOMEM;
}
__skb_pull(skb, hlen);
fh = (struct frag_hdr*)__skb_push(skb, sizeof(struct frag_hdr));
__skb_push(skb, hlen);
skb_reset_network_header(skb);
memcpy(skb_network_header(skb), tmp_hdr, hlen);
ipv6_select_ident(fh, rt);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(IP6_MF);
frag_id = fh->identification;
first_len = skb_pagelen(skb);
skb->data_len = first_len - skb_headlen(skb);
skb->len = first_len;
ipv6_hdr(skb)->payload_len = htons(first_len -
sizeof(struct ipv6hdr));
dst_hold(&rt->dst);
for (;;) {
/* Prepare header of the next frame,
* before previous one went down. */
if (frag) {
frag->ip_summed = CHECKSUM_NONE;
skb_reset_transport_header(frag);
fh = (struct frag_hdr*)__skb_push(frag, sizeof(struct frag_hdr));
__skb_push(frag, hlen);
skb_reset_network_header(frag);
memcpy(skb_network_header(frag), tmp_hdr,
hlen);
offset += skb->len - hlen - sizeof(struct frag_hdr);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(offset);
if (frag->next != NULL)
fh->frag_off |= htons(IP6_MF);
fh->identification = frag_id;
ipv6_hdr(frag)->payload_len =
htons(frag->len -
sizeof(struct ipv6hdr));
ip6_copy_metadata(frag, skb);
}
err = output(skb);
if(!err)
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGCREATES);
if (err || !frag)
break;
skb = frag;
frag = skb->next;
skb->next = NULL;
}
kfree(tmp_hdr);
if (err == 0) {
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGOKS);
ip6_rt_put(rt);
return 0;
}
while (frag) {
skb = frag->next;
kfree_skb(frag);
frag = skb;
}
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGFAILS);
ip6_rt_put(rt);
return err;
slow_path_clean:
skb_walk_frags(skb, frag2) {
if (frag2 == frag)
break;
frag2->sk = NULL;
frag2->destructor = NULL;
skb->truesize += frag2->truesize;
}
}
slow_path:
if ((skb->ip_summed == CHECKSUM_PARTIAL) &&
skb_checksum_help(skb))
goto fail;
left = skb->len - hlen; /* Space per frame */
ptr = hlen; /* Where to start from */
/*
* Fragment the datagram.
*/
*prevhdr = NEXTHDR_FRAGMENT;
hroom = LL_RESERVED_SPACE(rt->dst.dev);
troom = rt->dst.dev->needed_tailroom;
/*
* Keep copying data until we run out.
*/
while(left > 0) {
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending up to and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/*
* Allocate buffer.
*/
if ((frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) +
hroom + troom, GFP_ATOMIC)) == NULL) {
NETDEBUG(KERN_INFO "IPv6: frag: no memory for new fragment!\n");
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
/*
* Set up data on packet
*/
ip6_copy_metadata(frag, skb);
skb_reserve(frag, hroom);
skb_put(frag, len + hlen + sizeof(struct frag_hdr));
skb_reset_network_header(frag);
fh = (struct frag_hdr *)(skb_network_header(frag) + hlen);
frag->transport_header = (frag->network_header + hlen +
sizeof(struct frag_hdr));
/*
* Charge the memory for the fragment to any owner
* it might possess
*/
if (skb->sk)
skb_set_owner_w(frag, skb->sk);
/*
* Copy the packet header into the new buffer.
*/
skb_copy_from_linear_data(skb, skb_network_header(frag), hlen);
/*
* Build fragment header.
*/
fh->nexthdr = nexthdr;
fh->reserved = 0;
if (!frag_id) {
ipv6_select_ident(fh, rt);
frag_id = fh->identification;
} else
fh->identification = frag_id;
/*
* Copy a block of the IP datagram.
*/
if (skb_copy_bits(skb, ptr, skb_transport_header(frag), len))
BUG();
left -= len;
fh->frag_off = htons(offset);
if (left > 0)
fh->frag_off |= htons(IP6_MF);
ipv6_hdr(frag)->payload_len = htons(frag->len -
sizeof(struct ipv6hdr));
ptr += len;
offset += len;
/*
* Put this fragment into the sending queue.
*/
err = output(frag);
if (err)
goto fail;
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGCREATES);
}
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGOKS);
consume_skb(skb);
return err;
fail:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return err;
}
static inline int ip6_rt_check(const struct rt6key *rt_key,
const struct in6_addr *fl_addr,
const struct in6_addr *addr_cache)
{
return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) &&
(addr_cache == NULL || !ipv6_addr_equal(fl_addr, addr_cache));
}
static struct dst_entry *ip6_sk_dst_check(struct sock *sk,
struct dst_entry *dst,
const struct flowi6 *fl6)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct rt6_info *rt;
if (!dst)
goto out;
if (dst->ops->family != AF_INET6) {
dst_release(dst);
return NULL;
}
rt = (struct rt6_info *)dst;
/* Yes, checking route validity in not connected
* case is not very simple. Take into account,
* that we do not support routing by source, TOS,
* and MSG_DONTROUTE --ANK (980726)
*
* 1. ip6_rt_check(): If route was host route,
* check that cached destination is current.
* If it is network route, we still may
* check its validity using saved pointer
* to the last used address: daddr_cache.
* We do not want to save whole address now,
* (because main consumer of this service
* is tcp, which has not this problem),
* so that the last trick works only on connected
* sockets.
* 2. oif also should be the same.
*/
if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) ||
#ifdef CONFIG_IPV6_SUBTREES
ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) ||
#endif
(fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) {
dst_release(dst);
dst = NULL;
}
out:
return dst;
}
static int ip6_dst_lookup_tail(struct sock *sk,
struct dst_entry **dst, struct flowi6 *fl6)
{
struct net *net = sock_net(sk);
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
struct neighbour *n;
struct rt6_info *rt;
#endif
int err;
if (*dst == NULL)
*dst = ip6_route_output(net, sk, fl6);
if ((err = (*dst)->error))
goto out_err_release;
if (ipv6_addr_any(&fl6->saddr)) {
struct rt6_info *rt = (struct rt6_info *) *dst;
err = ip6_route_get_saddr(net, rt, &fl6->daddr,
sk ? inet6_sk(sk)->srcprefs : 0,
&fl6->saddr);
if (err)
goto out_err_release;
}
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
/*
* Here if the dst entry we've looked up
* has a neighbour entry that is in the INCOMPLETE
* state and the src address from the flow is
* marked as OPTIMISTIC, we release the found
* dst entry and replace it instead with the
* dst entry of the nexthop router
*/
rt = (struct rt6_info *) *dst;
rcu_read_lock_bh();
n = __ipv6_neigh_lookup_noref(rt->dst.dev, rt6_nexthop(rt, &fl6->daddr));
err = n && !(n->nud_state & NUD_VALID) ? -EINVAL : 0;
rcu_read_unlock_bh();
if (err) {
struct inet6_ifaddr *ifp;
struct flowi6 fl_gw6;
int redirect;
ifp = ipv6_get_ifaddr(net, &fl6->saddr,
(*dst)->dev, 1);
redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC);
if (ifp)
in6_ifa_put(ifp);
if (redirect) {
/*
* We need to get the dst entry for the
* default router instead
*/
dst_release(*dst);
memcpy(&fl_gw6, fl6, sizeof(struct flowi6));
memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr));
*dst = ip6_route_output(net, sk, &fl_gw6);
if ((err = (*dst)->error))
goto out_err_release;
}
}
#endif
return 0;
out_err_release:
if (err == -ENETUNREACH)
IP6_INC_STATS_BH(net, NULL, IPSTATS_MIB_OUTNOROUTES);
dst_release(*dst);
*dst = NULL;
return err;
}
/**
* ip6_dst_lookup - perform route lookup on flow
* @sk: socket which provides route info
* @dst: pointer to dst_entry * for result
* @fl6: flow to lookup
*
* This function performs a route lookup on the given flow.
*
* It returns zero on success, or a standard errno code on error.
*/
int ip6_dst_lookup(struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6)
{
*dst = NULL;
return ip6_dst_lookup_tail(sk, dst, fl6);
}
EXPORT_SYMBOL_GPL(ip6_dst_lookup);
/**
* ip6_dst_lookup_flow - perform route lookup on flow with ipsec
* @sk: socket which provides route info
* @fl6: flow to lookup
* @final_dst: final destination address for ipsec lookup
* @can_sleep: we are in a sleepable context
*
* This function performs a route lookup on the given flow.
*
* It returns a valid dst pointer on success, or a pointer encoded
* error code.
*/
struct dst_entry *ip6_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6,
const struct in6_addr *final_dst,
bool can_sleep)
{
struct dst_entry *dst = NULL;
int err;
err = ip6_dst_lookup_tail(sk, &dst, fl6);
if (err)
return ERR_PTR(err);
if (final_dst)
fl6->daddr = *final_dst;
if (can_sleep)
fl6->flowi6_flags |= FLOWI_FLAG_CAN_SLEEP;
return xfrm_lookup(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0);
}
EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow);
/**
* ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow
* @sk: socket which provides the dst cache and route info
* @fl6: flow to lookup
* @final_dst: final destination address for ipsec lookup
* @can_sleep: we are in a sleepable context
*
* This function performs a route lookup on the given flow with the
* possibility of using the cached route in the socket if it is valid.
* It will take the socket dst lock when operating on the dst cache.
* As a result, this function can only be used in process context.
*
* It returns a valid dst pointer on success, or a pointer encoded
* error code.
*/
struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6,
const struct in6_addr *final_dst,
bool can_sleep)
{
struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie);
int err;
dst = ip6_sk_dst_check(sk, dst, fl6);
err = ip6_dst_lookup_tail(sk, &dst, fl6);
if (err)
return ERR_PTR(err);
if (final_dst)
fl6->daddr = *final_dst;
if (can_sleep)
fl6->flowi6_flags |= FLOWI_FLAG_CAN_SLEEP;
return xfrm_lookup(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0);
}
EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow);
static inline int ip6_ufo_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int transhdrlen, int mtu,unsigned int flags,
struct rt6_info *rt)
{
struct sk_buff *skb;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {
struct frag_hdr fhdr;
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (skb == NULL)
return err;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb,fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_reset_network_header(skb);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum = 0;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
ipv6_select_ident(&fhdr, rt);
skb_shinfo(skb)->ip6_frag_id = fhdr.identification;
__skb_queue_tail(&sk->sk_write_queue, skb);
}
return skb_append_datato_frags(sk, skb, getfrag, from,
(length - transhdrlen));
}
static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src,
gfp_t gfp)
{
return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
}
static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src,
gfp_t gfp)
{
return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
}
static void ip6_append_data_mtu(unsigned int *mtu,
int *maxfraglen,
unsigned int fragheaderlen,
struct sk_buff *skb,
struct rt6_info *rt,
bool pmtuprobe)
{
if (!(rt->dst.flags & DST_XFRM_TUNNEL)) {
if (skb == NULL) {
/* first fragment, reserve header_len */
*mtu = *mtu - rt->dst.header_len;
} else {
/*
* this fragment is not first, the headers
* space is regarded as data space.
*/
*mtu = min(*mtu, pmtuprobe ?
rt->dst.dev->mtu :
dst_mtu(rt->dst.path));
}
*maxfraglen = ((*mtu - fragheaderlen) & ~7)
+ fragheaderlen - sizeof(struct frag_hdr);
}
}
int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to,
int offset, int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
int hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags, int dontfrag)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_cork *cork;
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen, mtu;
int exthdrlen;
int dst_exthdrlen;
int hh_len;
int copy;
int err;
int offset = 0;
__u8 tx_flags = 0;
if (flags&MSG_PROBE)
return 0;
cork = &inet->cork.base;
if (skb_queue_empty(&sk->sk_write_queue)) {
/*
* setup for corking
*/
if (opt) {
if (WARN_ON(np->cork.opt))
return -EINVAL;
np->cork.opt = kzalloc(opt->tot_len, sk->sk_allocation);
if (unlikely(np->cork.opt == NULL))
return -ENOBUFS;
np->cork.opt->tot_len = opt->tot_len;
np->cork.opt->opt_flen = opt->opt_flen;
np->cork.opt->opt_nflen = opt->opt_nflen;
np->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt,
sk->sk_allocation);
if (opt->dst0opt && !np->cork.opt->dst0opt)
return -ENOBUFS;
np->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt,
sk->sk_allocation);
if (opt->dst1opt && !np->cork.opt->dst1opt)
return -ENOBUFS;
np->cork.opt->hopopt = ip6_opt_dup(opt->hopopt,
sk->sk_allocation);
if (opt->hopopt && !np->cork.opt->hopopt)
return -ENOBUFS;
np->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt,
sk->sk_allocation);
if (opt->srcrt && !np->cork.opt->srcrt)
return -ENOBUFS;
/* need source address above miyazawa*/
}
dst_hold(&rt->dst);
cork->dst = &rt->dst;
inet->cork.fl.u.ip6 = *fl6;
np->cork.hop_limit = hlimit;
np->cork.tclass = tclass;
if (rt->dst.flags & DST_XFRM_TUNNEL)
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(&rt->dst);
else
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
if (np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
cork->fragsize = mtu;
if (dst_allfrag(rt->dst.path))
cork->flags |= IPCORK_ALLFRAG;
cork->length = 0;
exthdrlen = (opt ? opt->opt_flen : 0);
length += exthdrlen;
transhdrlen += exthdrlen;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
} else {
rt = (struct rt6_info *)cork->dst;
fl6 = &inet->cork.fl.u.ip6;
opt = np->cork.opt;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
mtu = cork->fragsize;
}
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr);
if (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) {
if (cork->length + length > sizeof(struct ipv6hdr) + IPV6_MAXPLEN - fragheaderlen) {
ipv6_local_error(sk, EMSGSIZE, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
}
/* For UDP, check if TX timestamp is enabled */
if (sk->sk_type == SOCK_DGRAM)
sock_tx_timestamp(sk, &tx_flags);
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
if ((length > mtu) && dontfrag && (sk->sk_protocol == IPPROTO_UDP ||
sk->sk_protocol == IPPROTO_RAW)) {
ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
skb = skb_peek_tail(&sk->sk_write_queue);
cork->length += length;
if (((length > mtu) ||
(skb && skb_is_gso(skb))) &&
(sk->sk_protocol == IPPROTO_UDP) &&
(rt->dst.dev->features & NETIF_F_UFO)) {
err = ip6_ufo_append_data(sk, getfrag, from, length,
hh_len, fragheaderlen,
transhdrlen, mtu, flags, rt);
if (err)
goto error;
return 0;
}
if (!skb)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (skb == NULL || skb_prev == NULL)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt,
np->pmtudisc ==
IPV6_PMTUDISC_PROBE);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(skb == NULL))
err = -ENOBUFS;
else {
/* Only the initial fragment
* is time stamped.
*/
tx_flags = 0;
}
}
if (skb == NULL)
goto error;
/*
* Fill in the control structures
*/
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = CHECKSUM_NONE;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
if (sk->sk_type == SOCK_DGRAM)
skb_shinfo(skb)->tx_flags = tx_flags;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(&sk->sk_write_queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
struct page_frag *pfrag = sk_page_frag(sk);
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
EXPORT_SYMBOL_GPL(ip6_append_data);
static void ip6_cork_release(struct inet_sock *inet, struct ipv6_pinfo *np)
{
if (np->cork.opt) {
kfree(np->cork.opt->dst0opt);
kfree(np->cork.opt->dst1opt);
kfree(np->cork.opt->hopopt);
kfree(np->cork.opt->srcrt);
kfree(np->cork.opt);
np->cork.opt = NULL;
}
if (inet->cork.base.dst) {
dst_release(inet->cork.base.dst);
inet->cork.base.dst = NULL;
inet->cork.base.flags &= ~IPCORK_ALLFRAG;
}
memset(&inet->cork.fl, 0, sizeof(inet->cork.fl));
}
int ip6_push_pending_frames(struct sock *sk)
{
struct sk_buff *skb, *tmp_skb;
struct sk_buff **tail_skb;
struct in6_addr final_dst_buf, *final_dst = &final_dst_buf;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct net *net = sock_net(sk);
struct ipv6hdr *hdr;
struct ipv6_txoptions *opt = np->cork.opt;
struct rt6_info *rt = (struct rt6_info *)inet->cork.base.dst;
struct flowi6 *fl6 = &inet->cork.fl.u.ip6;
unsigned char proto = fl6->flowi6_proto;
int err = 0;
if ((skb = __skb_dequeue(&sk->sk_write_queue)) == NULL)
goto out;
tail_skb = &(skb_shinfo(skb)->frag_list);
/* move skb->data to ip header from ext header */
if (skb->data < skb_network_header(skb))
__skb_pull(skb, skb_network_offset(skb));
while ((tmp_skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) {
__skb_pull(tmp_skb, skb_network_header_len(skb));
*tail_skb = tmp_skb;
tail_skb = &(tmp_skb->next);
skb->len += tmp_skb->len;
skb->data_len += tmp_skb->len;
skb->truesize += tmp_skb->truesize;
tmp_skb->destructor = NULL;
tmp_skb->sk = NULL;
}
/* Allow local fragmentation. */
if (np->pmtudisc < IPV6_PMTUDISC_DO)
skb->local_df = 1;
*final_dst = fl6->daddr;
__skb_pull(skb, skb_network_header_len(skb));
if (opt && opt->opt_flen)
ipv6_push_frag_opts(skb, opt, &proto);
if (opt && opt->opt_nflen)
ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst);
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
hdr = ipv6_hdr(skb);
ip6_flow_hdr(hdr, np->cork.tclass, fl6->flowlabel);
hdr->hop_limit = np->cork.hop_limit;
hdr->nexthdr = proto;
hdr->saddr = fl6->saddr;
hdr->daddr = *final_dst;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
skb_dst_set(skb, dst_clone(&rt->dst));
IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len);
if (proto == IPPROTO_ICMPV6) {
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
ICMP6MSGOUT_INC_STATS_BH(net, idev, icmp6_hdr(skb)->icmp6_type);
ICMP6_INC_STATS_BH(net, idev, ICMP6_MIB_OUTMSGS);
}
err = ip6_local_out(skb);
if (err) {
if (err > 0)
err = net_xmit_errno(err);
if (err)
goto error;
}
out:
ip6_cork_release(inet, np);
return err;
error:
IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
goto out;
}
EXPORT_SYMBOL_GPL(ip6_push_pending_frames);
void ip6_flush_pending_frames(struct sock *sk)
{
struct sk_buff *skb;
while ((skb = __skb_dequeue_tail(&sk->sk_write_queue)) != NULL) {
if (skb_dst(skb))
IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
}
ip6_cork_release(inet_sk(sk), inet6_sk(sk));
}
EXPORT_SYMBOL_GPL(ip6_flush_pending_frames);
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5743_0 |
crossvul-cpp_data_good_107_0 | #ifndef NGIFLIB_NO_FILE
#include <stdio.h>
#endif /* NGIFLIB_NO_FILE */
#include "ngiflib.h"
/* decodeur GIF en C portable (pas de pb big/little endian)
* Thomas BERNARD. janvier 2004.
* (c) 2004-2017 Thomas Bernard. All rights reserved
*/
/* Fonction de debug */
#ifdef DEBUG
void fprintf_ngiflib_img(FILE * f, struct ngiflib_img * i) {
fprintf(f, " * ngiflib_img @ %p\n", i);
fprintf(f, " next = %p\n", i->next);
fprintf(f, " parent = %p\n", i->parent);
fprintf(f, " palette = %p\n", i->palette);
fprintf(f, " %3d couleurs", i->ncolors);
if(i->interlaced) fprintf(f, " interlaced");
fprintf(f, "\n taille : %dx%d, pos (%d,%d)\n", i->width, i->height, i->posX, i->posY);
fprintf(f, " sort_flag=%x localpalbits=%d\n", i->sort_flag, i->localpalbits);
}
#endif /* DEBUG */
void GifImgDestroy(struct ngiflib_img * i) {
if(i==NULL) return;
if(i->next) GifImgDestroy(i->next);
if(i->palette && (i->palette != i->parent->palette))
ngiflib_free(i->palette);
ngiflib_free(i);
}
/* Fonction de debug */
#ifdef DEBUG
void fprintf_ngiflib_gif(FILE * f, struct ngiflib_gif * g) {
struct ngiflib_img * i;
fprintf(f, "* ngiflib_gif @ %p %s\n", g, g->signature);
fprintf(f, " %dx%d, %d bits, %d couleurs\n", g->width, g->height, g->imgbits, g->ncolors);
fprintf(f, " palette = %p, backgroundcolorindex %d\n", g->palette, g->backgroundindex);
fprintf(f, " pixelaspectratio = %d\n", g->pixaspectratio);
fprintf(f, " frbuff = %p\n", g->frbuff.p8);
fprintf(f, " cur_img = %p\n", g->cur_img);
fprintf(f, " %d images :\n", g->nimg);
i = g->first_img;
while(i) {
fprintf_ngiflib_img(f, i);
i = i->next;
}
}
#endif /* DEBUG */
void GifDestroy(struct ngiflib_gif * g) {
if(g==NULL) return;
if(g->palette) ngiflib_free(g->palette);
if(g->frbuff.p8) ngiflib_free(g->frbuff.p8);
GifImgDestroy(g->first_img);
ngiflib_free(g);
}
/* u8 GetByte(struct ngiflib_gif * g);
* fonction qui renvoie un octet du fichier .gif
* on pourait optimiser en faisant 2 fonctions.
*/
static u8 GetByte(struct ngiflib_gif * g) {
#ifndef NGIFLIB_NO_FILE
if(g->mode & NGIFLIB_MODE_FROM_MEM) {
#endif /* NGIFLIB_NO_FILE */
return *(g->input.bytes++);
#ifndef NGIFLIB_NO_FILE
} else {
return (u8)(getc(g->input.file));
}
#endif /* NGIFLIB_NO_FILE */
}
/* u16 GetWord()
* Renvoie un mot de 16bits
* N'est pas influencee par l'endianess du CPU !
*/
static u16 GetWord(struct ngiflib_gif * g) {
u16 r = (u16)GetByte(g);
r |= ((u16)GetByte(g) << 8);
return r;
}
/* int GetByteStr(struct ngiflib_gif * g, u8 * p, int n);
* prend en argument un pointeur sur la destination
* et le nombre d'octet a lire.
* Renvoie 0 si l'operation a reussi, -1 sinon.
*/
static int GetByteStr(struct ngiflib_gif * g, u8 * p, int n) {
if(!p) return -1;
#ifndef NGIFLIB_NO_FILE
if(g->mode & NGIFLIB_MODE_FROM_MEM) {
#endif /* NGIFLIB_NO_FILE */
ngiflib_memcpy(p, g->input.bytes, n);
g->input.bytes += n;
return 0;
#ifndef NGIFLIB_NO_FILE
} else {
size_t read;
read = fread(p, 1, n, g->input.file);
return ((int)read == n) ? 0 : -1;
}
#endif /* NGIFLIB_NO_FILE */
}
/* void WritePixel(struct ngiflib_img * i, u8 v);
* ecrit le pixel de valeur v dans le frame buffer
*/
static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) {
struct ngiflib_gif * p = i->parent;
if(v!=i->gce.transparent_color || !i->gce.transparent_flag) {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
*context->frbuff_p.p8 = v;
#ifndef NGIFLIB_INDEXED_ONLY
} else
*context->frbuff_p.p32 =
GifIndexToTrueColor(i->palette, v);
#endif /* NGIFLIB_INDEXED_ONLY */
}
if(--(context->Xtogo) <= 0) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(p->line_cb) p->line_cb(p, context->line_p, context->curY);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
context->Xtogo = i->width;
switch(context->pass) {
case 0:
context->curY++;
break;
case 1: /* 1st pass : every eighth row starting from 0 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 4;
}
break;
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 2;
}
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY += 4;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 1;
}
break;
case 4: /* 4th pass : every odd row */
context->curY += 2;
break;
}
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;
context->frbuff_p.p8 = context->line_p.p8 + i->posX;
#else
context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#ifndef NGIFLIB_INDEXED_ONLY
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;
context->frbuff_p.p32 = context->line_p.p32 + i->posX;
#else
context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
context->frbuff_p.p8++;
#ifndef NGIFLIB_INDEXED_ONLY
} else {
context->frbuff_p.p32++;
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
}
/* void WritePixels(struct ngiflib_img * i, const u8 * pixels, u16 n);
* ecrit les pixels dans le frame buffer
*/
static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) {
u16 tocopy;
struct ngiflib_gif * p = i->parent;
while(n > 0) {
tocopy = (context->Xtogo < n) ? context->Xtogo : n;
if(!i->gce.transparent_flag) {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy);
pixels += tocopy;
context->frbuff_p.p8 += tocopy;
#ifndef NGIFLIB_INDEXED_ONLY
} else {
int j;
for(j = (int)tocopy; j > 0; j--) {
*(context->frbuff_p.p32++) =
GifIndexToTrueColor(i->palette, *pixels++);
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
int j;
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels;
pixels++;
context->frbuff_p.p8++;
}
#ifndef NGIFLIB_INDEXED_ONLY
} else {
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) {
*context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels);
}
pixels++;
context->frbuff_p.p32++;
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
context->Xtogo -= tocopy;
if(context->Xtogo == 0) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(p->line_cb) p->line_cb(p, context->line_p, context->curY);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
context->Xtogo = i->width;
switch(context->pass) {
case 0:
context->curY++;
break;
case 1: /* 1st pass : every eighth row starting from 0 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 4;
}
break;
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 2;
}
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY += 4;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 1;
}
break;
case 4: /* 4th pass : every odd row */
context->curY += 2;
break;
}
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;
context->frbuff_p.p8 = context->line_p.p8 + i->posX;
#else
context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#ifndef NGIFLIB_INDEXED_ONLY
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;
context->frbuff_p.p32 = context->line_p.p32 + i->posX;
#else
context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
n -= tocopy;
}
}
/*
* u16 GetGifWord(struct ngiflib_img * i);
* Renvoie un code LZW (taille variable)
*/
static u16 GetGifWord(struct ngiflib_img * i, struct ngiflib_decode_context * context) {
u16 r;
int bits_todo;
u16 newbyte;
bits_todo = (int)context->nbbit - (int)context->restbits;
if( bits_todo <= 0) { /* nbbit <= restbits */
r = context->lbyte;
context->restbits -= context->nbbit;
context->lbyte >>= context->nbbit;
} else if( bits_todo > 8 ) { /* nbbit > restbits + 8 */
if(context->restbyte >= 2) {
context->restbyte -= 2;
r = *context->srcbyte++;
} else {
if(context->restbyte == 0) {
context->restbyte = GetByte(i->parent);
#if defined(DEBUG) && !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte);
#endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */
GetByteStr(i->parent, context->byte_buffer, context->restbyte);
context->srcbyte = context->byte_buffer;
}
r = *context->srcbyte++;
if(--context->restbyte == 0) {
context->restbyte = GetByte(i->parent);
#if defined(DEBUG) && !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte);
#endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */
GetByteStr(i->parent, context->byte_buffer, context->restbyte);
context->srcbyte = context->byte_buffer;
}
context->restbyte--;
}
newbyte = *context->srcbyte++;
r |= newbyte << 8;
r = (r << context->restbits) | context->lbyte;
context->restbits = 16 - bits_todo;
context->lbyte = newbyte >> (bits_todo - 8);
} else /*if( bits_todo > 0 )*/ { /* nbbit > restbits */
if(context->restbyte == 0) {
context->restbyte = GetByte(i->parent);
#if defined(DEBUG) && !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte);
#endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */
GetByteStr(i->parent, context->byte_buffer, context->restbyte);
context->srcbyte = context->byte_buffer;
}
newbyte = *context->srcbyte++;
context->restbyte--;
r = (newbyte << context->restbits) | context->lbyte;
context->restbits = 8 - bits_todo;
context->lbyte = newbyte >> bits_todo;
}
return (r & context->max); /* applique le bon masque pour eliminer les bits en trop */
}
/* ------------------------------------------------ */
static void FillGifBackGround(struct ngiflib_gif * g) {
long n = (long)g->width*g->height;
#ifndef NGIFLIB_INDEXED_ONLY
u32 bg_truecolor;
#endif /* NGIFLIB_INDEXED_ONLY */
if((g->frbuff.p8==NULL)||(g->palette==NULL)) return;
#ifndef NGIFLIB_INDEXED_ONLY
if(g->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
ngiflib_memset(g->frbuff.p8, g->backgroundindex, n);
#ifndef NGIFLIB_INDEXED_ONLY
} else {
u32 * p = g->frbuff.p32;
bg_truecolor = GifIndexToTrueColor(g->palette, g->backgroundindex);
while(n-->0) *p++ = bg_truecolor;
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
/* ------------------------------------------------ */
int CheckGif(u8 * b) {
return (b[0]=='G')&&(b[1]=='I')&&(b[2]=='F')&&(b[3]=='8');
}
/* ------------------------------------------------ */
static int DecodeGifImg(struct ngiflib_img * i) {
struct ngiflib_decode_context context;
long npix;
u8 * stackp;
u8 * stack_top;
u16 clr;
u16 eof;
u16 free;
u16 act_code = 0;
u16 old_code = 0;
u16 read_byt;
u16 ab_prfx[4096];
u8 ab_suffx[4096];
u8 ab_stack[4096];
u8 flags;
u8 casspecial = 0;
if(!i) return -1;
i->posX = GetWord(i->parent); /* offsetX */
i->posY = GetWord(i->parent); /* offsetY */
i->width = GetWord(i->parent); /* SizeX */
i->height = GetWord(i->parent); /* SizeY */
if((i->width > i->parent->width) || (i->height > i->parent->height)) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n");
#endif
return -1;
}
if((i->posX + i->width) > i->parent->width) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n");
#endif
i->posX = i->parent->width - i->width;
}
if((i->posY + i->height) > i->parent->height) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n");
#endif
i->posY = i->parent->height - i->height;
}
context.Xtogo = i->width;
context.curY = i->posY;
#ifdef NGIFLIB_INDEXED_ONLY
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#else
if(i->parent->mode & NGIFLIB_MODE_INDEXED) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width;
context.frbuff_p.p32 = context.line_p.p32 + i->posX;
#else
context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
npix = (long)i->width * i->height;
flags = GetByte(i->parent);
i->interlaced = (flags & 64) >> 6;
context.pass = i->interlaced ? 1 : 0;
i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */
i->localpalbits = (flags & 7) + 1;
if(flags&128) { /* palette locale */
int k;
int localpalsize = 1 << i->localpalbits;
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize);
for(k=0; k<localpalsize; k++) {
i->palette[k].r = GetByte(i->parent);
i->palette[k].g = GetByte(i->parent);
i->palette[k].b = GetByte(i->parent);
}
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
i->palette = i->parent->palette;
i->localpalbits = i->parent->imgbits;
}
i->ncolors = 1 << i->localpalbits;
i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) {
if(i->interlaced) fprintf(i->parent->log, "interlaced ");
fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n",
i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors);
}
#endif /* !defined(NGIFLIB_NO_FILE) */
if(i->imgbits==1) { /* fix for 1bit images ? */
i->imgbits = 2;
}
clr = 1 << i->imgbits;
eof = clr + 1;
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
stackp = stack_top = ab_stack + 4096;
context.restbits = 0; /* initialise le "buffer" de lecture */
context.restbyte = 0; /* des codes LZW */
context.lbyte = 0;
for(;;) {
act_code = GetGifWord(i, &context);
if(act_code==eof) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 0;
}
if(npix==0) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 1;
}
if(act_code==clr) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix);
#endif /* !defined(NGIFLIB_NO_FILE) */
/* clear */
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
act_code = GetGifWord(i, &context);
casspecial = (u8)act_code;
old_code = act_code;
if(npix > 0) WritePixel(i, &context, casspecial);
npix--;
} else {
read_byt = act_code;
if(act_code >= free) { /* code pas encore dans alphabet */
/* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */
*(--stackp) = casspecial; /* dernier debut de chaine ! */
act_code = old_code;
}
/* printf("actcode=%d\n", act_code); */
while(act_code > clr) { /* code non concret */
/* fillstackloop empile les suffixes ! */
*(--stackp) = ab_suffx[act_code];
act_code = ab_prfx[act_code]; /* prefixe */
}
/* act_code est concret */
casspecial = (u8)act_code; /* dernier debut de chaine ! */
*(--stackp) = casspecial; /* push on stack */
if(npix >= (stack_top - stackp)) {
WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */
} else if(npix > 0) { /* "pixel overflow" */
WritePixels(i, &context, stackp, npix);
}
npix -= (stack_top - stackp);
stackp = stack_top;
/* putchar('\n'); */
if(free < 4096) { /* la taille du dico est 4096 max ! */
ab_prfx[free] = old_code;
ab_suffx[free] = (u8)act_code;
free++;
if((free > context.max) && (context.nbbit < 12)) {
context.nbbit++; /* 1 bit de plus pour les codes LZW */
context.max += context.max + 1;
}
}
old_code = read_byt;
}
}
return 0;
}
/* ------------------------------------------------
* int LoadGif(struct ngiflib_gif *);
* s'assurer que nimg=0 au depart !
* retourne :
* 0 si GIF termin�
* un nombre negatif si ERREUR
* 1 si image Decod�e
* rappeler pour decoder les images suivantes
* ------------------------------------------------ */
int LoadGif(struct ngiflib_gif * g) {
struct ngiflib_gce gce;
u8 sign;
u8 tmp;
int i;
if(!g) return -1;
gce.gce_present = 0;
if(g->nimg==0) {
GetByteStr(g, g->signature, 6);
g->signature[6] = '\0';
if( g->signature[0] != 'G'
|| g->signature[1] != 'I'
|| g->signature[2] != 'F'
|| g->signature[3] != '8') {
return -1;
}
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "%s\n", g->signature);
#endif /* !defined(NGIFLIB_NO_FILE) */
g->width = GetWord(g);
g->height = GetWord(g);
/* allocate frame buffer */
#ifndef NGIFLIB_INDEXED_ONLY
if((g->mode & NGIFLIB_MODE_INDEXED)==0)
g->frbuff.p32 = ngiflib_malloc(4*(long)g->height*(long)g->width);
else
#endif /* NGIFLIB_INDEXED_ONLY */
g->frbuff.p8 = ngiflib_malloc((long)g->height*(long)g->width);
tmp = GetByte(g);/* <Packed Fields> = Global Color Table Flag 1 Bit
Color Resolution 3 Bits
Sort Flag 1 Bit
Size of Global Color Table 3 Bits */
g->colorresolution = ((tmp & 0x70) >> 4) + 1;
g->sort_flag = (tmp & 8) >> 3;
g->imgbits = (tmp & 7) + 1; /* Global Palette color resolution */
g->ncolors = 1 << g->imgbits;
g->backgroundindex = GetByte(g);
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "%hux%hu %hhubits %hu couleurs bg=%hhu\n",
g->width, g->height, g->imgbits, g->ncolors, g->backgroundindex);
#endif /* NGIFLIB_INDEXED_ONLY */
g->pixaspectratio = GetByte(g); /* pixel aspect ratio (0 : unspecified) */
if(tmp&0x80) {
/* la palette globale suit. */
g->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*g->ncolors);
for(i=0; i<g->ncolors; i++) {
g->palette[i].r = GetByte(g);
g->palette[i].g = GetByte(g);
g->palette[i].b = GetByte(g);
#if defined(DEBUG) && !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "%3d %02X %02X %02X\n", i, g->palette[i].r,g->palette[i].g,g->palette[i].b);
#endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */
}
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(g->palette_cb) g->palette_cb(g, g->palette, g->ncolors);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
g->palette = NULL;
}
g->netscape_loop_count = -1;
}
for(;;) {
char appid_auth[11];
u8 id,size;
int blockindex;
sign = GetByte(g); /* signature du prochain bloc */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "BLOCK SIGNATURE 0x%02X '%c'\n", sign, (sign >= 32) ? sign : '.');
#endif /* NGIFLIB_INDEXED_ONLY */
switch(sign) {
case 0x3B: /* END OF GIF */
return 0;
case '!': /* Extension introducer 0x21 */
id = GetByte(g);
blockindex = 0;
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "extension (id=0x%02hhx)\n", id);
#endif /* NGIFLIB_NO_FILE */
while( (size = GetByte(g)) ) {
u8 ext[256];
GetByteStr(g, ext, size);
switch(id) {
case 0xF9: /* Graphic Control Extension */
/* The scope of this extension is the first graphic
* rendering block to follow. */
gce.gce_present = 1;
gce.disposal_method = (ext[0] >> 2) & 7;
gce.transparent_flag = ext[0] & 1;
gce.user_input_flag = (ext[0] >> 1) & 1;
gce.delay_time = ext[1] | (ext[2]<<8);
gce.transparent_color = ext[3];
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "disposal_method=%hhu delay_time=%hu (transp=%hhu)transparent_color=0x%02hhX\n",
gce.disposal_method, gce.delay_time, gce.transparent_flag, gce.transparent_color);
#endif /* NGIFLIB_INDEXED_ONLY */
/* this propably should be adjusted depending on the disposal_method
* of the _previous_ image. */
if(gce.transparent_flag && ((g->nimg == 0) || gce.disposal_method == 2)) {
FillGifBackGround(g);
}
break;
case 0xFE: /* Comment Extension. */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
if(blockindex==0) fprintf(g->log, "-------------------- Comment extension --------------------\n");
ext[size] = '\0';
fputs((char *)ext, g->log);
}
#endif /* NGIFLIB_NO_FILE */
break;
case 0xFF: /* application extension */
/* NETSCAPE2.0 extension :
* http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension */
if(blockindex==0) {
ngiflib_memcpy(appid_auth, ext, 11);
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
fprintf(g->log, "---------------- Application extension ---------------\n");
fprintf(g->log, "Application identifier : '%.8s', auth code : %02X %02X %02X (",
appid_auth, ext[8], ext[9], ext[10]);
fputc((ext[8]<32)?' ':ext[8], g->log);
fputc((ext[9]<32)?' ':ext[9], g->log);
fputc((ext[10]<32)?' ':ext[10], g->log);
fprintf(g->log, ")\n");
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
fprintf(g->log, "Datas (as hex) : ");
for(i=0; i<size; i++) {
fprintf(g->log, "%02x ", ext[i]);
}
fprintf(g->log, "\nDatas (as text) : '");
for(i=0; i<size; i++) {
putc((ext[i]<32)?' ':ext[i], g->log);
}
fprintf(g->log, "'\n");
}
#endif /* NGIFLIB_INDEXED_ONLY */
if(0 == ngiflib_memcmp(appid_auth, "NETSCAPE2.0", 11)) {
/* ext[0] : Sub-block ID */
if(ext[0] == 1) {
/* 1 : Netscape Looping Extension. */
g->netscape_loop_count = (int)ext[1] | ((int)ext[2] << 8);
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
fprintf(g->log, "NETSCAPE loop_count = %d\n", g->netscape_loop_count);
}
#endif /* NGIFLIB_NO_FILE */
}
}
}
break;
case 0x01: /* plain text extension */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
fprintf(g->log, "Plain text extension blockindex=%d\n", blockindex);
for(i=0; i<size; i++) {
putc((ext[i]<32)?' ':ext[i], g->log);
}
putc('\n', g->log);
}
#endif /* NGIFLIB_INDEXED_ONLY */
break;
}
blockindex++;
}
switch(id) {
case 0x01: /* plain text extension */
case 0xFE: /* Comment Extension. */
case 0xFF: /* application extension */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) {
fprintf(g->log, "-----------------------------------------------------------\n");
}
#endif /* NGIFLIB_NO_FILE */
break;
}
break;
case 0x2C: /* Image separator */
if(g->nimg==0) {
g->cur_img = ngiflib_malloc(sizeof(struct ngiflib_img));
g->first_img = g->cur_img;
} else {
g->cur_img->next = ngiflib_malloc(sizeof(struct ngiflib_img));
g->cur_img = g->cur_img->next;
}
g->cur_img->next = NULL;
g->cur_img->parent = g;
if(gce.gce_present) {
ngiflib_memcpy(&g->cur_img->gce, &gce, sizeof(struct ngiflib_gce));
} else {
ngiflib_memset(&g->cur_img->gce, 0, sizeof(struct ngiflib_gce));
}
DecodeGifImg(g->cur_img);
g->nimg++;
tmp = GetByte(g);/* 0 final */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "ZERO TERMINATOR 0x%02X\n", tmp);
#endif /* NGIFLIB_INDEXED_ONLY */
return 1; /* image decod�e */
default:
/* unexpected byte */
#if !defined(NGIFLIB_NO_FILE)
if(g->log) fprintf(g->log, "unexpected signature 0x%02X\n", sign);
#endif /* NGIFLIB_INDEXED_ONLY */
return -1;
}
}
}
u32 GifIndexToTrueColor(struct ngiflib_rgb * palette, u8 v) {
return palette[v].b | (palette[v].g << 8) | (palette[v].r << 16);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_107_0 |
crossvul-cpp_data_good_4787_4 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% BBBB GGGG RRRR %
% B B G R R %
% BBBB G GG RRRR %
% B B G G R R %
% BBBB GGG R R %
% %
% %
% Read/Write Raw BGR Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/channel.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/utility.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteBGRImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d B G R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadBGRImage() reads an image of raw BGR, or BGRA samples and returns
% it. It allocates the memory necessary for the new Image structure and
% returns a pointer to the new image.
%
% The format of the ReadBGRImage method is:
%
% Image *ReadBGRImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadBGRImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*canvas_image,
*image;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
if (image_info->interlace != PartitionInterlace)
{
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
/*
Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]).
*/
canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse,
exception);
(void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod);
quantum_info=AcquireQuantumInfo(image_info,canvas_image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
quantum_type=BGRQuantum;
if (LocaleCompare(image_info->magick,"BGRA") == 0)
{
quantum_type=BGRAQuantum;
image->matte=MagickTrue;
}
if (image_info->number_scenes != 0)
while (image->scene < image_info->scene)
{
/*
Skip to next image.
*/
image->scene++;
length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
}
count=0;
length=0;
scene=0;
do
{
/*
Read pixels to virtual canvas image then push to image.
*/
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
switch (image_info->interlace)
{
case NoInterlace:
default:
{
/*
No interlacing: BGRBGRBGRBGRBGRBGR...
*/
if (scene == 0)
{
length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);
count=ReadBlob(image,length,pixels);
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,quantum_type,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=QueueAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
SetPixelGreen(q,GetPixelGreen(p));
SetPixelBlue(q,GetPixelBlue(p));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelOpacity(q,GetPixelOpacity(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
break;
}
case LineInterlace:
{
static QuantumType
quantum_types[4] =
{
BlueQuantum,
GreenQuantum,
RedQuantum,
AlphaQuantum
};
/*
Line interlacing: BBB...GGG...RRR...RRR...GGG...BBB...
*/
if (scene == 0)
{
length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum);
count=ReadBlob(image,length,pixels);
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
for (i=0; i < (ssize_t) (image->matte != MagickFalse ? 4 : 3); i++)
{
quantum_type=quantum_types[i];
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,quantum_type,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch (quantum_type)
{
case RedQuantum:
{
SetPixelRed(q,GetPixelRed(p));
break;
}
case GreenQuantum:
{
SetPixelGreen(q,GetPixelGreen(p));
break;
}
case BlueQuantum:
{
SetPixelBlue(q,GetPixelBlue(p));
break;
}
case OpacityQuantum:
{
SetPixelOpacity(q,GetPixelOpacity(p));
break;
}
case AlphaQuantum:
{
SetPixelAlpha(q,GetPixelAlpha(p));
break;
}
default:
break;
}
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
if (scene == 0)
{
length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum);
count=ReadBlob(image,length,pixels);
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,RedQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,1,6);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,GreenQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGreen(q,GetPixelGreen(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,2,6);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,BlueQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(q,GetPixelBlue(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,3,6);
if (status == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,4,6);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
{
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,
canvas_image->extract_info.x,0,canvas_image->columns,1,
exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelOpacity(q,GetPixelOpacity(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,5,6);
if (status == MagickFalse)
break;
}
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,6,6);
if (status == MagickFalse)
break;
}
break;
}
case PartitionInterlace:
{
/*
Partition interlacing: BBBBBB..., GGGGGG..., RRRRRR...
*/
AppendImageFormat("B",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
canvas_image=DestroyImageList(canvas_image);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum);
for (i=0; i < (ssize_t) scene; i++)
for (y=0; y < (ssize_t) image->extract_info.height; y++)
if (ReadBlob(image,length,pixels) != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
count=ReadBlob(image,length,pixels);
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,BlueQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,1,5);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
AppendImageFormat("G",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
canvas_image=DestroyImageList(canvas_image);
image=DestroyImageList(image);
return((Image *) NULL);
}
length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum);
for (i=0; i < (ssize_t) scene; i++)
for (y=0; y < (ssize_t) image->extract_info.height; y++)
if (ReadBlob(image,length,pixels) != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
count=ReadBlob(image,length,pixels);
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,GreenQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGreen(q,GetPixelGreen(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,2,5);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
AppendImageFormat("R",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
canvas_image=DestroyImageList(canvas_image);
image=DestroyImageList(image);
return((Image *) NULL);
}
length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum);
for (i=0; i < (ssize_t) scene; i++)
for (y=0; y < (ssize_t) image->extract_info.height; y++)
if (ReadBlob(image,length,pixels) != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
count=ReadBlob(image,length,pixels);
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,RedQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(q,GetPixelBlue(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,3,5);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
{
(void) CloseBlob(image);
AppendImageFormat("A",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
canvas_image=DestroyImageList(canvas_image);
image=DestroyImageList(image);
return((Image *) NULL);
}
length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum);
for (i=0; i < (ssize_t) scene; i++)
for (y=0; y < (ssize_t) image->extract_info.height; y++)
if (ReadBlob(image,length,pixels) != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
count=ReadBlob(image,length,pixels);
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,
quantum_info,BlueQuantum,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,
0,canvas_image->columns,1,exception);
q=GetAuthenticPixels(image,0,y-image->extract_info.y,
image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) ||
(q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelOpacity(q,GetPixelOpacity(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,4,5);
if (status == MagickFalse)
break;
}
}
(void) CloseBlob(image);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,5,5);
if (status == MagickFalse)
break;
}
break;
}
}
SetQuantumImageType(image,quantum_type);
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (count == (ssize_t) length)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
scene++;
} while (count == (ssize_t) length);
quantum_info=DestroyQuantumInfo(quantum_info);
InheritException(&image->exception,&canvas_image->exception);
canvas_image=DestroyImage(canvas_image);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r B G R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterBGRImage() adds attributes for the BGR image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterBGRImage method is:
%
% size_t RegisterBGRImage(void)
%
*/
ModuleExport size_t RegisterBGRImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("BGR");
entry->decoder=(DecodeImageHandler *) ReadBGRImage;
entry->encoder=(EncodeImageHandler *) WriteBGRImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Raw blue, green, and red samples");
entry->module=ConstantString("BGR");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("BGRA");
entry->decoder=(DecodeImageHandler *) ReadBGRImage;
entry->encoder=(EncodeImageHandler *) WriteBGRImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Raw blue, green, red, and alpha samples");
entry->module=ConstantString("BGR");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r B G R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterBGRImage() removes format registrations made by the BGR module
% from the list of supported formats.
%
% The format of the UnregisterBGRImage method is:
%
% UnregisterBGRImage(void)
%
*/
ModuleExport void UnregisterBGRImage(void)
{
(void) UnregisterMagickInfo("BGRA");
(void) UnregisterMagickInfo("BGR");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e B G R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteBGRImage() writes an image to a file in the BGR or BGRA
% rasterfile format.
%
% The format of the WriteBGRImage method is:
%
% MagickBooleanType WriteBGRImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteBGRImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Allocate memory for pixels.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image_info->interlace != PartitionInterlace)
{
/*
Open output image file.
*/
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
}
quantum_type=BGRQuantum;
if (LocaleCompare(image_info->magick,"BGRA") == 0)
{
quantum_type=BGRAQuantum;
image->matte=MagickTrue;
}
scene=0;
do
{
/*
Convert MIFF to BGR raster pixels.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if ((LocaleCompare(image_info->magick,"BGRA") == 0) &&
(image->matte == MagickFalse))
(void) SetImageAlphaChannel(image,ResetAlphaChannel);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
switch (image_info->interlace)
{
case NoInterlace:
default:
{
/*
No interlacing: BGRBGRBGRBGRBGRBGR...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case LineInterlace:
{
/*
Line interlacing: BBB...GGG...RRR...RRR...GGG...BBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
if (quantum_type == BGRAQuantum)
{
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,1,6);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,2,6);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,3,6);
if (status == MagickFalse)
break;
}
if (quantum_type == BGRAQuantum)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,5,6);
if (status == MagickFalse)
break;
}
}
if (image_info->interlace == PartitionInterlace)
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,6,6);
if (status == MagickFalse)
break;
}
break;
}
case PartitionInterlace:
{
/*
Partition interlacing: BBBBBB..., GGGGGG..., RRRRRR...
*/
AppendImageFormat("B",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,1,6);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
AppendImageFormat("G",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,2,6);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
AppendImageFormat("R",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,3,6);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
if (quantum_type == BGRAQuantum)
{
(void) CloseBlob(image);
AppendImageFormat("A",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,5,6);
if (status == MagickFalse)
break;
}
}
(void) CloseBlob(image);
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,6,6);
if (status == MagickFalse)
break;
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_4 |
crossvul-cpp_data_bad_4865_0 | /*
* The copyright in this software is being made available under the 2-clauses
* BSD License, included below. This software may be subject to other third
* party and contributor rights, including patent rights, and no such rights
* are granted under this license.
*
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2014, Professor Benoit Macq
* Copyright (c) 2001-2003, David Janssens
* Copyright (c) 2002-2003, Yannick Verschueren
* Copyright (c) 2003-2007, Francois-Olivier Devaux
* Copyright (c) 2003-2014, Antonin Descampe
* Copyright (c) 2005, Herve Drolon, FreeImage Team
* Copyright (c) 2006-2007, Parvatha Elangovan
* Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR
* Copyright (c) 2012, CS Systemes d'Information, France
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "opj_includes.h"
#include "opj_common.h"
/* ----------------------------------------------------------------------- */
/* TODO MSD: */
#ifdef TODO_MSD
void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t * img)
{
int tileno, compno, resno, bandno, precno;/*, cblkno;*/
fprintf(fd, "image {\n");
fprintf(fd, " tw=%d, th=%d x0=%d x1=%d y0=%d y1=%d\n",
img->tw, img->th, tcd->image->x0, tcd->image->x1, tcd->image->y0,
tcd->image->y1);
for (tileno = 0; tileno < img->th * img->tw; tileno++) {
opj_tcd_tile_t *tile = &tcd->tcd_image->tiles[tileno];
fprintf(fd, " tile {\n");
fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numcomps=%d\n",
tile->x0, tile->y0, tile->x1, tile->y1, tile->numcomps);
for (compno = 0; compno < tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
fprintf(fd, " tilec {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, numresolutions=%d\n",
tilec->x0, tilec->y0, tilec->x1, tilec->y1, tilec->numresolutions);
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
fprintf(fd, "\n res {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, pw=%d, ph=%d, numbands=%d\n",
res->x0, res->y0, res->x1, res->y1, res->pw, res->ph, res->numbands);
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
fprintf(fd, " band {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, stepsize=%f, numbps=%d\n",
band->x0, band->y0, band->x1, band->y1, band->stepsize, band->numbps);
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prec = &band->precincts[precno];
fprintf(fd, " prec {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, cw=%d, ch=%d\n",
prec->x0, prec->y0, prec->x1, prec->y1, prec->cw, prec->ch);
/*
for (cblkno = 0; cblkno < prec->cw * prec->ch; cblkno++) {
opj_tcd_cblk_t *cblk = &prec->cblks[cblkno];
fprintf(fd, " cblk {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d\n",
cblk->x0, cblk->y0, cblk->x1, cblk->y1);
fprintf(fd, " }\n");
}
*/
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, "}\n");
}
#endif
/**
* Initializes tile coding/decoding
*/
static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block,
opj_event_mgr_t* manager);
/**
* Allocates memory for a decoding code block.
*/
static OPJ_BOOL opj_tcd_code_block_dec_allocate(opj_tcd_cblk_dec_t *
p_code_block);
/**
* Deallocates the decoding data of the given precinct.
*/
static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct);
/**
* Allocates memory for an encoding code block (but not data).
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate(opj_tcd_cblk_enc_t *
p_code_block);
/**
* Allocates data for an encoding code block
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
p_code_block);
/**
* Deallocates the encoding data of the given precinct.
*/
static void opj_tcd_code_block_enc_deallocate(opj_tcd_precinct_t * p_precinct);
/**
Free the memory allocated for encoding
@param tcd TCD handle
*/
static void opj_tcd_free_tile(opj_tcd_t *tcd);
static OPJ_BOOL opj_tcd_t2_decode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_src_size,
opj_codestream_index_t *p_cstr_index,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_tcd_t1_decode(opj_tcd_t *p_tcd,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_tcd_dwt_decode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_tcd_dc_level_shift_decode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_dc_level_shift_encode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_mct_encode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info);
static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info);
/* ----------------------------------------------------------------------- */
/**
Create a new TCD handle
*/
opj_tcd_t* opj_tcd_create(OPJ_BOOL p_is_decoder)
{
opj_tcd_t *l_tcd = 00;
/* create the tcd structure */
l_tcd = (opj_tcd_t*) opj_calloc(1, sizeof(opj_tcd_t));
if (!l_tcd) {
return 00;
}
l_tcd->m_is_decoder = p_is_decoder ? 1 : 0;
l_tcd->tcd_image = (opj_tcd_image_t*)opj_calloc(1, sizeof(opj_tcd_image_t));
if (!l_tcd->tcd_image) {
opj_free(l_tcd);
return 00;
}
return l_tcd;
}
/* ----------------------------------------------------------------------- */
void opj_tcd_rateallocate_fixed(opj_tcd_t *tcd)
{
OPJ_UINT32 layno;
for (layno = 0; layno < tcd->tcp->numlayers; layno++) {
opj_tcd_makelayer_fixed(tcd, layno, 1);
}
}
void opj_tcd_makelayer(opj_tcd_t *tcd,
OPJ_UINT32 layno,
OPJ_FLOAT64 thresh,
OPJ_UINT32 final)
{
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
OPJ_UINT32 passno;
opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
tcd_tile->distolayer[layno] = 0; /* fixed_quality */
for (compno = 0; compno < tcd_tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prc = &band->precincts[precno];
for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
opj_tcd_layer_t *layer = &cblk->layers[layno];
OPJ_UINT32 n;
if (layno == 0) {
cblk->numpassesinlayers = 0;
}
n = cblk->numpassesinlayers;
for (passno = cblk->numpassesinlayers; passno < cblk->totalpasses; passno++) {
OPJ_UINT32 dr;
OPJ_FLOAT64 dd;
opj_tcd_pass_t *pass = &cblk->passes[passno];
if (n == 0) {
dr = pass->rate;
dd = pass->distortiondec;
} else {
dr = pass->rate - cblk->passes[n - 1].rate;
dd = pass->distortiondec - cblk->passes[n - 1].distortiondec;
}
if (!dr) {
if (dd != 0) {
n = passno + 1;
}
continue;
}
if (thresh - (dd / dr) <
DBL_EPSILON) { /* do not rely on float equality, check with DBL_EPSILON margin */
n = passno + 1;
}
}
layer->numpasses = n - cblk->numpassesinlayers;
if (!layer->numpasses) {
layer->disto = 0;
continue;
}
if (cblk->numpassesinlayers == 0) {
layer->len = cblk->passes[n - 1].rate;
layer->data = cblk->data;
layer->disto = cblk->passes[n - 1].distortiondec;
} else {
layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers -
1].rate;
layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate;
layer->disto = cblk->passes[n - 1].distortiondec -
cblk->passes[cblk->numpassesinlayers - 1].distortiondec;
}
tcd_tile->distolayer[layno] += layer->disto; /* fixed_quality */
if (final) {
cblk->numpassesinlayers = n;
}
}
}
}
}
}
}
void opj_tcd_makelayer_fixed(opj_tcd_t *tcd, OPJ_UINT32 layno,
OPJ_UINT32 final)
{
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
OPJ_INT32 value; /*, matrice[tcd_tcp->numlayers][tcd_tile->comps[0].numresolutions][3]; */
OPJ_INT32 matrice[10][10][3];
OPJ_UINT32 i, j, k;
opj_cp_t *cp = tcd->cp;
opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
opj_tcp_t *tcd_tcp = tcd->tcp;
for (compno = 0; compno < tcd_tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
for (i = 0; i < tcd_tcp->numlayers; i++) {
for (j = 0; j < tilec->numresolutions; j++) {
for (k = 0; k < 3; k++) {
matrice[i][j][k] =
(OPJ_INT32)((OPJ_FLOAT32)cp->m_specific_param.m_enc.m_matrice[i *
tilec->numresolutions * 3 + j * 3 + k]
* (OPJ_FLOAT32)(tcd->image->comps[compno].prec / 16.0));
}
}
}
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prc = &band->precincts[precno];
for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
opj_tcd_layer_t *layer = &cblk->layers[layno];
OPJ_UINT32 n;
OPJ_INT32 imsb = (OPJ_INT32)(tcd->image->comps[compno].prec -
cblk->numbps); /* number of bit-plan equal to zero */
/* Correction of the matrix of coefficient to include the IMSB information */
if (layno == 0) {
value = matrice[layno][resno][bandno];
if (imsb >= value) {
value = 0;
} else {
value -= imsb;
}
} else {
value = matrice[layno][resno][bandno] - matrice[layno - 1][resno][bandno];
if (imsb >= matrice[layno - 1][resno][bandno]) {
value -= (imsb - matrice[layno - 1][resno][bandno]);
if (value < 0) {
value = 0;
}
}
}
if (layno == 0) {
cblk->numpassesinlayers = 0;
}
n = cblk->numpassesinlayers;
if (cblk->numpassesinlayers == 0) {
if (value != 0) {
n = 3 * (OPJ_UINT32)value - 2 + cblk->numpassesinlayers;
} else {
n = cblk->numpassesinlayers;
}
} else {
n = 3 * (OPJ_UINT32)value + cblk->numpassesinlayers;
}
layer->numpasses = n - cblk->numpassesinlayers;
if (!layer->numpasses) {
continue;
}
if (cblk->numpassesinlayers == 0) {
layer->len = cblk->passes[n - 1].rate;
layer->data = cblk->data;
} else {
layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers -
1].rate;
layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate;
}
if (final) {
cblk->numpassesinlayers = n;
}
}
}
}
}
}
}
OPJ_BOOL opj_tcd_rateallocate(opj_tcd_t *tcd,
OPJ_BYTE *dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 len,
opj_codestream_info_t *cstr_info)
{
OPJ_UINT32 compno, resno, bandno, precno, cblkno, layno;
OPJ_UINT32 passno;
OPJ_FLOAT64 min, max;
OPJ_FLOAT64 cumdisto[100]; /* fixed_quality */
const OPJ_FLOAT64 K = 1; /* 1.1; fixed_quality */
OPJ_FLOAT64 maxSE = 0;
opj_cp_t *cp = tcd->cp;
opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
opj_tcp_t *tcd_tcp = tcd->tcp;
min = DBL_MAX;
max = 0;
tcd_tile->numpix = 0; /* fixed_quality */
for (compno = 0; compno < tcd_tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
tilec->numpix = 0;
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prc = &band->precincts[precno];
for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
for (passno = 0; passno < cblk->totalpasses; passno++) {
opj_tcd_pass_t *pass = &cblk->passes[passno];
OPJ_INT32 dr;
OPJ_FLOAT64 dd, rdslope;
if (passno == 0) {
dr = (OPJ_INT32)pass->rate;
dd = pass->distortiondec;
} else {
dr = (OPJ_INT32)(pass->rate - cblk->passes[passno - 1].rate);
dd = pass->distortiondec - cblk->passes[passno - 1].distortiondec;
}
if (dr == 0) {
continue;
}
rdslope = dd / dr;
if (rdslope < min) {
min = rdslope;
}
if (rdslope > max) {
max = rdslope;
}
} /* passno */
/* fixed_quality */
tcd_tile->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0));
tilec->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0));
} /* cbklno */
} /* precno */
} /* bandno */
} /* resno */
maxSE += (((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0)
* ((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0))
* ((OPJ_FLOAT64)(tilec->numpix));
} /* compno */
/* index file */
if (cstr_info) {
opj_tile_info_t *tile_info = &cstr_info->tile[tcd->tcd_tileno];
tile_info->numpix = tcd_tile->numpix;
tile_info->distotile = tcd_tile->distotile;
tile_info->thresh = (OPJ_FLOAT64 *) opj_malloc(tcd_tcp->numlayers * sizeof(
OPJ_FLOAT64));
if (!tile_info->thresh) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
}
for (layno = 0; layno < tcd_tcp->numlayers; layno++) {
OPJ_FLOAT64 lo = min;
OPJ_FLOAT64 hi = max;
OPJ_UINT32 maxlen = tcd_tcp->rates[layno] > 0.0f ? opj_uint_min(((
OPJ_UINT32) ceil(tcd_tcp->rates[layno])), len) : len;
OPJ_FLOAT64 goodthresh = 0;
OPJ_FLOAT64 stable_thresh = 0;
OPJ_UINT32 i;
OPJ_FLOAT64 distotarget; /* fixed_quality */
/* fixed_quality */
distotarget = tcd_tile->distotile - ((K * maxSE) / pow((OPJ_FLOAT32)10,
tcd_tcp->distoratio[layno] / 10));
/* Don't try to find an optimal threshold but rather take everything not included yet, if
-r xx,yy,zz,0 (disto_alloc == 1 and rates == 0)
-q xx,yy,zz,0 (fixed_quality == 1 and distoratio == 0)
==> possible to have some lossy layers and the last layer for sure lossless */
if (((cp->m_specific_param.m_enc.m_disto_alloc == 1) &&
(tcd_tcp->rates[layno] > 0.0f)) ||
((cp->m_specific_param.m_enc.m_fixed_quality == 1) &&
(tcd_tcp->distoratio[layno] > 0.0))) {
opj_t2_t*t2 = opj_t2_create(tcd->image, cp);
OPJ_FLOAT64 thresh = 0;
if (t2 == 00) {
return OPJ_FALSE;
}
for (i = 0; i < 128; ++i) {
OPJ_FLOAT64 distoachieved = 0; /* fixed_quality */
thresh = (lo + hi) / 2;
opj_tcd_makelayer(tcd, layno, thresh, 0);
if (cp->m_specific_param.m_enc.m_fixed_quality) { /* fixed_quality */
if (OPJ_IS_CINEMA(cp->rsiz)) {
if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,
p_data_written, maxlen, cstr_info, tcd->cur_tp_num, tcd->tp_pos, tcd->cur_pino,
THRESH_CALC)) {
lo = thresh;
continue;
} else {
distoachieved = layno == 0 ?
tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno];
if (distoachieved < distotarget) {
hi = thresh;
stable_thresh = thresh;
continue;
} else {
lo = thresh;
}
}
} else {
distoachieved = (layno == 0) ?
tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]);
if (distoachieved < distotarget) {
hi = thresh;
stable_thresh = thresh;
continue;
}
lo = thresh;
}
} else {
if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,
p_data_written, maxlen, cstr_info, tcd->cur_tp_num, tcd->tp_pos, tcd->cur_pino,
THRESH_CALC)) {
/* TODO: what to do with l ??? seek / tell ??? */
/* opj_event_msg(tcd->cinfo, EVT_INFO, "rate alloc: len=%d, max=%d\n", l, maxlen); */
lo = thresh;
continue;
}
hi = thresh;
stable_thresh = thresh;
}
}
goodthresh = stable_thresh == 0 ? thresh : stable_thresh;
opj_t2_destroy(t2);
} else {
goodthresh = min;
}
if (cstr_info) { /* Threshold for Marcela Index */
cstr_info->tile[tcd->tcd_tileno].thresh[layno] = goodthresh;
}
opj_tcd_makelayer(tcd, layno, goodthresh, 1);
/* fixed_quality */
cumdisto[layno] = (layno == 0) ? tcd_tile->distolayer[0] :
(cumdisto[layno - 1] + tcd_tile->distolayer[layno]);
}
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_init(opj_tcd_t *p_tcd,
opj_image_t * p_image,
opj_cp_t * p_cp,
opj_thread_pool_t* p_tp)
{
p_tcd->image = p_image;
p_tcd->cp = p_cp;
p_tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(1,
sizeof(opj_tcd_tile_t));
if (! p_tcd->tcd_image->tiles) {
return OPJ_FALSE;
}
p_tcd->tcd_image->tiles->comps = (opj_tcd_tilecomp_t *) opj_calloc(
p_image->numcomps, sizeof(opj_tcd_tilecomp_t));
if (! p_tcd->tcd_image->tiles->comps) {
return OPJ_FALSE;
}
p_tcd->tcd_image->tiles->numcomps = p_image->numcomps;
p_tcd->tp_pos = p_cp->m_specific_param.m_enc.m_tp_pos;
p_tcd->thread_pool = p_tp;
return OPJ_TRUE;
}
/**
Destroy a previously created TCD handle
*/
void opj_tcd_destroy(opj_tcd_t *tcd)
{
if (tcd) {
opj_tcd_free_tile(tcd);
if (tcd->tcd_image) {
opj_free(tcd->tcd_image);
tcd->tcd_image = 00;
}
opj_free(tcd);
}
}
OPJ_BOOL opj_alloc_tile_component_data(opj_tcd_tilecomp_t *l_tilec)
{
if ((l_tilec->data == 00) ||
((l_tilec->data_size_needed > l_tilec->data_size) &&
(l_tilec->ownsData == OPJ_FALSE))) {
l_tilec->data = (OPJ_INT32 *) opj_aligned_malloc(l_tilec->data_size_needed);
if (! l_tilec->data) {
return OPJ_FALSE;
}
/*fprintf(stderr, "tAllocate data of tilec (int): %d x OPJ_UINT32n",l_data_size);*/
l_tilec->data_size = l_tilec->data_size_needed;
l_tilec->ownsData = OPJ_TRUE;
} else if (l_tilec->data_size_needed > l_tilec->data_size) {
/* We don't need to keep old data */
opj_aligned_free(l_tilec->data);
l_tilec->data = (OPJ_INT32 *) opj_aligned_malloc(l_tilec->data_size_needed);
if (! l_tilec->data) {
l_tilec->data_size = 0;
l_tilec->data_size_needed = 0;
l_tilec->ownsData = OPJ_FALSE;
return OPJ_FALSE;
}
/*fprintf(stderr, "tReallocate data of tilec (int): from %d to %d x OPJ_UINT32n", l_tilec->data_size, l_data_size);*/
l_tilec->data_size = l_tilec->data_size_needed;
l_tilec->ownsData = OPJ_TRUE;
}
return OPJ_TRUE;
}
/* ----------------------------------------------------------------------- */
static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block,
opj_event_mgr_t* manager)
{
OPJ_UINT32(*l_gain_ptr)(OPJ_UINT32) = 00;
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
opj_tcp_t * l_tcp = 00;
opj_cp_t * l_cp = 00;
opj_tcd_tile_t * l_tile = 00;
opj_tccp_t *l_tccp = 00;
opj_tcd_tilecomp_t *l_tilec = 00;
opj_image_comp_t * l_image_comp = 00;
opj_tcd_resolution_t *l_res = 00;
opj_tcd_band_t *l_band = 00;
opj_stepsize_t * l_step_size = 00;
opj_tcd_precinct_t *l_current_precinct = 00;
opj_image_t *l_image = 00;
OPJ_UINT32 p, q;
OPJ_UINT32 l_level_no;
OPJ_UINT32 l_pdx, l_pdy;
OPJ_UINT32 l_gain;
OPJ_INT32 l_x0b, l_y0b;
OPJ_UINT32 l_tx0, l_ty0;
/* extent of precincts , top left, bottom right**/
OPJ_INT32 l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end, l_br_prc_y_end;
/* number of precinct for a resolution */
OPJ_UINT32 l_nb_precincts;
/* room needed to store l_nb_precinct precinct for a resolution */
OPJ_UINT32 l_nb_precinct_size;
/* number of code blocks for a precinct*/
OPJ_UINT32 l_nb_code_blocks;
/* room needed to store l_nb_code_blocks code blocks for a precinct*/
OPJ_UINT32 l_nb_code_blocks_size;
/* size of data for a tile */
OPJ_UINT32 l_data_size;
l_cp = p_tcd->cp;
l_tcp = &(l_cp->tcps[p_tile_no]);
l_tile = p_tcd->tcd_image->tiles;
l_tccp = l_tcp->tccps;
l_tilec = l_tile->comps;
l_image = p_tcd->image;
l_image_comp = p_tcd->image->comps;
p = p_tile_no % l_cp->tw; /* tile coordinates */
q = p_tile_no / l_cp->tw;
/*fprintf(stderr, "Tile coordinate = %d,%d\n", p, q);*/
/* 4 borders of the tile rescale on the image if necessary */
l_tx0 = l_cp->tx0 + p *
l_cp->tdx; /* can't be greater than l_image->x1 so won't overflow */
l_tile->x0 = (OPJ_INT32)opj_uint_max(l_tx0, l_image->x0);
l_tile->x1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, l_cp->tdx),
l_image->x1);
/* all those OPJ_UINT32 are casted to OPJ_INT32, let's do some sanity check */
if ((l_tile->x0 < 0) || (l_tile->x1 <= l_tile->x0)) {
opj_event_msg(manager, EVT_ERROR, "Tile X coordinates are not supported\n");
return OPJ_FALSE;
}
l_ty0 = l_cp->ty0 + q *
l_cp->tdy; /* can't be greater than l_image->y1 so won't overflow */
l_tile->y0 = (OPJ_INT32)opj_uint_max(l_ty0, l_image->y0);
l_tile->y1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, l_cp->tdy),
l_image->y1);
/* all those OPJ_UINT32 are casted to OPJ_INT32, let's do some sanity check */
if ((l_tile->y0 < 0) || (l_tile->y1 <= l_tile->y0)) {
opj_event_msg(manager, EVT_ERROR, "Tile Y coordinates are not supported\n");
return OPJ_FALSE;
}
/* testcase 1888.pdf.asan.35.988 */
if (l_tccp->numresolutions == 0) {
opj_event_msg(manager, EVT_ERROR, "tiles require at least one resolution\n");
return OPJ_FALSE;
}
/*fprintf(stderr, "Tile border = %d,%d,%d,%d\n", l_tile->x0, l_tile->y0,l_tile->x1,l_tile->y1);*/
/*tile->numcomps = image->numcomps; */
for (compno = 0; compno < l_tile->numcomps; ++compno) {
/*fprintf(stderr, "compno = %d/%d\n", compno, l_tile->numcomps);*/
l_image_comp->resno_decoded = 0;
/* border of each l_tile component (global) */
l_tilec->x0 = opj_int_ceildiv(l_tile->x0, (OPJ_INT32)l_image_comp->dx);
l_tilec->y0 = opj_int_ceildiv(l_tile->y0, (OPJ_INT32)l_image_comp->dy);
l_tilec->x1 = opj_int_ceildiv(l_tile->x1, (OPJ_INT32)l_image_comp->dx);
l_tilec->y1 = opj_int_ceildiv(l_tile->y1, (OPJ_INT32)l_image_comp->dy);
/*fprintf(stderr, "\tTile compo border = %d,%d,%d,%d\n", l_tilec->x0, l_tilec->y0,l_tilec->x1,l_tilec->y1);*/
/* compute l_data_size with overflow check */
l_data_size = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0);
/* issue 733, l_data_size == 0U, probably something wrong should be checked before getting here */
if ((l_data_size > 0U) &&
((((OPJ_UINT32) - 1) / l_data_size) < (OPJ_UINT32)(l_tilec->y1 -
l_tilec->y0))) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_data_size * (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0);
if ((((OPJ_UINT32) - 1) / (OPJ_UINT32)sizeof(OPJ_UINT32)) < l_data_size) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_data_size * (OPJ_UINT32)sizeof(OPJ_UINT32);
l_tilec->numresolutions = l_tccp->numresolutions;
if (l_tccp->numresolutions < l_cp->m_specific_param.m_dec.m_reduce) {
l_tilec->minimum_num_resolutions = 1;
} else {
l_tilec->minimum_num_resolutions = l_tccp->numresolutions -
l_cp->m_specific_param.m_dec.m_reduce;
}
l_tilec->data_size_needed = l_data_size;
if (p_tcd->m_is_decoder && !opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_tilec->numresolutions * (OPJ_UINT32)sizeof(
opj_tcd_resolution_t);
if (l_tilec->resolutions == 00) {
l_tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(l_data_size);
if (! l_tilec->resolutions) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\tAllocate resolutions of tilec (opj_tcd_resolution_t): %d\n",l_data_size);*/
l_tilec->resolutions_size = l_data_size;
memset(l_tilec->resolutions, 0, l_data_size);
} else if (l_data_size > l_tilec->resolutions_size) {
opj_tcd_resolution_t* new_resolutions = (opj_tcd_resolution_t *) opj_realloc(
l_tilec->resolutions, l_data_size);
if (! new_resolutions) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile resolutions\n");
opj_free(l_tilec->resolutions);
l_tilec->resolutions = NULL;
l_tilec->resolutions_size = 0;
return OPJ_FALSE;
}
l_tilec->resolutions = new_resolutions;
/*fprintf(stderr, "\tReallocate data of tilec (int): from %d to %d x OPJ_UINT32\n", l_tilec->resolutions_size, l_data_size);*/
memset(((OPJ_BYTE*) l_tilec->resolutions) + l_tilec->resolutions_size, 0,
l_data_size - l_tilec->resolutions_size);
l_tilec->resolutions_size = l_data_size;
}
l_level_no = l_tilec->numresolutions;
l_res = l_tilec->resolutions;
l_step_size = l_tccp->stepsizes;
if (l_tccp->qmfbid == 0) {
l_gain_ptr = &opj_dwt_getgain_real;
} else {
l_gain_ptr = &opj_dwt_getgain;
}
/*fprintf(stderr, "\tlevel_no=%d\n",l_level_no);*/
for (resno = 0; resno < l_tilec->numresolutions; ++resno) {
/*fprintf(stderr, "\t\tresno = %d/%d\n", resno, l_tilec->numresolutions);*/
OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/;
OPJ_UINT32 cbgwidthexpn, cbgheightexpn;
OPJ_UINT32 cblkwidthexpn, cblkheightexpn;
--l_level_no;
/* border for each resolution level (global) */
l_res->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
l_res->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
l_res->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
l_res->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
/*fprintf(stderr, "\t\t\tres_x0= %d, res_y0 =%d, res_x1=%d, res_y1=%d\n", l_res->x0, l_res->y0, l_res->x1, l_res->y1);*/
/* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
/*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/
/* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */
l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx;
l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy;
l_br_prc_x_end = opj_int_ceildivpow2(l_res->x1, (OPJ_INT32)l_pdx) << l_pdx;
l_br_prc_y_end = opj_int_ceildivpow2(l_res->y1, (OPJ_INT32)l_pdy) << l_pdy;
/*fprintf(stderr, "\t\t\tprc_x_start=%d, prc_y_start=%d, br_prc_x_end=%d, br_prc_y_end=%d \n", l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end ,l_br_prc_y_end );*/
l_res->pw = (l_res->x0 == l_res->x1) ? 0U : (OPJ_UINT32)((
l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx);
l_res->ph = (l_res->y0 == l_res->y1) ? 0U : (OPJ_UINT32)((
l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy);
/*fprintf(stderr, "\t\t\tres_pw=%d, res_ph=%d\n", l_res->pw, l_res->ph );*/
if ((l_res->pw != 0U) && ((((OPJ_UINT32) - 1) / l_res->pw) < l_res->ph)) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_nb_precincts = l_res->pw * l_res->ph;
if ((((OPJ_UINT32) - 1) / (OPJ_UINT32)sizeof(opj_tcd_precinct_t)) <
l_nb_precincts) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_nb_precinct_size = l_nb_precincts * (OPJ_UINT32)sizeof(opj_tcd_precinct_t);
if (resno == 0) {
tlcbgxstart = l_tl_prc_x_start;
tlcbgystart = l_tl_prc_y_start;
/*brcbgxend = l_br_prc_x_end;*/
/* brcbgyend = l_br_prc_y_end;*/
cbgwidthexpn = l_pdx;
cbgheightexpn = l_pdy;
l_res->numbands = 1;
} else {
tlcbgxstart = opj_int_ceildivpow2(l_tl_prc_x_start, 1);
tlcbgystart = opj_int_ceildivpow2(l_tl_prc_y_start, 1);
/*brcbgxend = opj_int_ceildivpow2(l_br_prc_x_end, 1);*/
/*brcbgyend = opj_int_ceildivpow2(l_br_prc_y_end, 1);*/
cbgwidthexpn = l_pdx - 1;
cbgheightexpn = l_pdy - 1;
l_res->numbands = 3;
}
cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn);
cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn);
l_band = l_res->bands;
for (bandno = 0; bandno < l_res->numbands; ++bandno, ++l_band, ++l_step_size) {
OPJ_INT32 numbps;
/*fprintf(stderr, "\t\t\tband_no=%d/%d\n", bandno, l_res->numbands );*/
if (resno == 0) {
l_band->bandno = 0 ;
l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
l_band->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
} else {
l_band->bandno = bandno + 1;
/* x0b = 1 if bandno = 1 or 3 */
l_x0b = l_band->bandno & 1;
/* y0b = 1 if bandno = 2 or 3 */
l_y0b = (OPJ_INT32)((l_band->bandno) >> 1);
/* l_band border (global) */
l_band->x0 = opj_int64_ceildivpow2(l_tilec->x0 - ((OPJ_INT64)l_x0b <<
l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->y0 = opj_int64_ceildivpow2(l_tilec->y0 - ((OPJ_INT64)l_y0b <<
l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->x1 = opj_int64_ceildivpow2(l_tilec->x1 - ((OPJ_INT64)l_x0b <<
l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->y1 = opj_int64_ceildivpow2(l_tilec->y1 - ((OPJ_INT64)l_y0b <<
l_level_no), (OPJ_INT32)(l_level_no + 1));
}
if (isEncoder) {
/* Skip empty bands */
if (opj_tcd_is_band_empty(l_band)) {
/* Do not zero l_band->precints to avoid leaks */
/* but make sure we don't use it later, since */
/* it will point to precincts of previous bands... */
continue;
}
}
/** avoid an if with storing function pointer */
l_gain = (*l_gain_ptr)(l_band->bandno);
numbps = (OPJ_INT32)(l_image_comp->prec + l_gain);
l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0,
(OPJ_INT32)(numbps - l_step_size->expn)))) * fraction;
l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits -
1; /* WHY -1 ? */
if (!l_band->precincts && (l_nb_precincts > 0U)) {
l_band->precincts = (opj_tcd_precinct_t *) opj_malloc(/*3 * */
l_nb_precinct_size);
if (! l_band->precincts) {
opj_event_msg(manager, EVT_ERROR,
"Not enough memory to handle band precints\n");
return OPJ_FALSE;
}
/*fprintf(stderr, "\t\t\t\tAllocate precincts of a band (opj_tcd_precinct_t): %d\n",l_nb_precinct_size); */
memset(l_band->precincts, 0, l_nb_precinct_size);
l_band->precincts_data_size = l_nb_precinct_size;
} else if (l_band->precincts_data_size < l_nb_precinct_size) {
opj_tcd_precinct_t * new_precincts = (opj_tcd_precinct_t *) opj_realloc(
l_band->precincts,/*3 * */ l_nb_precinct_size);
if (! new_precincts) {
opj_event_msg(manager, EVT_ERROR,
"Not enough memory to handle band precints\n");
opj_free(l_band->precincts);
l_band->precincts = NULL;
l_band->precincts_data_size = 0;
return OPJ_FALSE;
}
l_band->precincts = new_precincts;
/*fprintf(stderr, "\t\t\t\tReallocate precincts of a band (opj_tcd_precinct_t): from %d to %d\n",l_band->precincts_data_size, l_nb_precinct_size);*/
memset(((OPJ_BYTE *) l_band->precincts) + l_band->precincts_data_size, 0,
l_nb_precinct_size - l_band->precincts_data_size);
l_band->precincts_data_size = l_nb_precinct_size;
}
l_current_precinct = l_band->precincts;
for (precno = 0; precno < l_nb_precincts; ++precno) {
OPJ_INT32 tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend;
OPJ_INT32 cbgxstart = tlcbgxstart + (OPJ_INT32)(precno % l_res->pw) *
(1 << cbgwidthexpn);
OPJ_INT32 cbgystart = tlcbgystart + (OPJ_INT32)(precno / l_res->pw) *
(1 << cbgheightexpn);
OPJ_INT32 cbgxend = cbgxstart + (1 << cbgwidthexpn);
OPJ_INT32 cbgyend = cbgystart + (1 << cbgheightexpn);
/*fprintf(stderr, "\t precno=%d; bandno=%d, resno=%d; compno=%d\n", precno, bandno , resno, compno);*/
/*fprintf(stderr, "\t tlcbgxstart(=%d) + (precno(=%d) percent res->pw(=%d)) * (1 << cbgwidthexpn(=%d)) \n",tlcbgxstart,precno,l_res->pw,cbgwidthexpn);*/
/* precinct size (global) */
/*fprintf(stderr, "\t cbgxstart=%d, l_band->x0 = %d \n",cbgxstart, l_band->x0);*/
l_current_precinct->x0 = opj_int_max(cbgxstart, l_band->x0);
l_current_precinct->y0 = opj_int_max(cbgystart, l_band->y0);
l_current_precinct->x1 = opj_int_min(cbgxend, l_band->x1);
l_current_precinct->y1 = opj_int_min(cbgyend, l_band->y1);
/*fprintf(stderr, "\t prc_x0=%d; prc_y0=%d, prc_x1=%d; prc_y1=%d\n",l_current_precinct->x0, l_current_precinct->y0 ,l_current_precinct->x1, l_current_precinct->y1);*/
tlcblkxstart = opj_int_floordivpow2(l_current_precinct->x0,
(OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
/*fprintf(stderr, "\t tlcblkxstart =%d\n",tlcblkxstart );*/
tlcblkystart = opj_int_floordivpow2(l_current_precinct->y0,
(OPJ_INT32)cblkheightexpn) << cblkheightexpn;
/*fprintf(stderr, "\t tlcblkystart =%d\n",tlcblkystart );*/
brcblkxend = opj_int_ceildivpow2(l_current_precinct->x1,
(OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
/*fprintf(stderr, "\t brcblkxend =%d\n",brcblkxend );*/
brcblkyend = opj_int_ceildivpow2(l_current_precinct->y1,
(OPJ_INT32)cblkheightexpn) << cblkheightexpn;
/*fprintf(stderr, "\t brcblkyend =%d\n",brcblkyend );*/
l_current_precinct->cw = (OPJ_UINT32)((brcblkxend - tlcblkxstart) >>
cblkwidthexpn);
l_current_precinct->ch = (OPJ_UINT32)((brcblkyend - tlcblkystart) >>
cblkheightexpn);
l_nb_code_blocks = l_current_precinct->cw * l_current_precinct->ch;
/*fprintf(stderr, "\t\t\t\t precinct_cw = %d x recinct_ch = %d\n",l_current_precinct->cw, l_current_precinct->ch); */
l_nb_code_blocks_size = l_nb_code_blocks * (OPJ_UINT32)sizeof_block;
if (!l_current_precinct->cblks.blocks && (l_nb_code_blocks > 0U)) {
l_current_precinct->cblks.blocks = opj_malloc(l_nb_code_blocks_size);
if (! l_current_precinct->cblks.blocks) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\t\t\t\tAllocate cblks of a precinct (opj_tcd_cblk_dec_t): %d\n",l_nb_code_blocks_size);*/
memset(l_current_precinct->cblks.blocks, 0, l_nb_code_blocks_size);
l_current_precinct->block_size = l_nb_code_blocks_size;
} else if (l_nb_code_blocks_size > l_current_precinct->block_size) {
void *new_blocks = opj_realloc(l_current_precinct->cblks.blocks,
l_nb_code_blocks_size);
if (! new_blocks) {
opj_free(l_current_precinct->cblks.blocks);
l_current_precinct->cblks.blocks = NULL;
l_current_precinct->block_size = 0;
opj_event_msg(manager, EVT_ERROR,
"Not enough memory for current precinct codeblock element\n");
return OPJ_FALSE;
}
l_current_precinct->cblks.blocks = new_blocks;
/*fprintf(stderr, "\t\t\t\tReallocate cblks of a precinct (opj_tcd_cblk_dec_t): from %d to %d\n",l_current_precinct->block_size, l_nb_code_blocks_size); */
memset(((OPJ_BYTE *) l_current_precinct->cblks.blocks) +
l_current_precinct->block_size
, 0
, l_nb_code_blocks_size - l_current_precinct->block_size);
l_current_precinct->block_size = l_nb_code_blocks_size;
}
if (! l_current_precinct->incltree) {
l_current_precinct->incltree = opj_tgt_create(l_current_precinct->cw,
l_current_precinct->ch, manager);
} else {
l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree,
l_current_precinct->cw, l_current_precinct->ch, manager);
}
if (! l_current_precinct->imsbtree) {
l_current_precinct->imsbtree = opj_tgt_create(l_current_precinct->cw,
l_current_precinct->ch, manager);
} else {
l_current_precinct->imsbtree = opj_tgt_init(l_current_precinct->imsbtree,
l_current_precinct->cw, l_current_precinct->ch, manager);
}
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
OPJ_INT32 cblkxstart = tlcblkxstart + (OPJ_INT32)(cblkno %
l_current_precinct->cw) * (1 << cblkwidthexpn);
OPJ_INT32 cblkystart = tlcblkystart + (OPJ_INT32)(cblkno /
l_current_precinct->cw) * (1 << cblkheightexpn);
OPJ_INT32 cblkxend = cblkxstart + (1 << cblkwidthexpn);
OPJ_INT32 cblkyend = cblkystart + (1 << cblkheightexpn);
if (isEncoder) {
opj_tcd_cblk_enc_t* l_code_block = l_current_precinct->cblks.enc + cblkno;
if (! opj_tcd_code_block_enc_allocate(l_code_block)) {
return OPJ_FALSE;
}
/* code-block size (global) */
l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
if (! opj_tcd_code_block_enc_allocate_data(l_code_block)) {
return OPJ_FALSE;
}
} else {
opj_tcd_cblk_dec_t* l_code_block = l_current_precinct->cblks.dec + cblkno;
if (! opj_tcd_code_block_dec_allocate(l_code_block)) {
return OPJ_FALSE;
}
/* code-block size (global) */
l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
}
}
++l_current_precinct;
} /* precno */
} /* bandno */
++l_res;
} /* resno */
++l_tccp;
++l_tilec;
++l_image_comp;
} /* compno */
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_init_encode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
opj_event_mgr_t* p_manager)
{
return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_TRUE, 1.0F,
sizeof(opj_tcd_cblk_enc_t), p_manager);
}
OPJ_BOOL opj_tcd_init_decode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
opj_event_mgr_t* p_manager)
{
return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_FALSE, 0.5F,
sizeof(opj_tcd_cblk_dec_t), p_manager);
}
/**
* Allocates memory for an encoding code block (but not data memory).
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate(opj_tcd_cblk_enc_t *
p_code_block)
{
if (! p_code_block->layers) {
/* no memset since data */
p_code_block->layers = (opj_tcd_layer_t*) opj_calloc(100,
sizeof(opj_tcd_layer_t));
if (! p_code_block->layers) {
return OPJ_FALSE;
}
}
if (! p_code_block->passes) {
p_code_block->passes = (opj_tcd_pass_t*) opj_calloc(100,
sizeof(opj_tcd_pass_t));
if (! p_code_block->passes) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
/**
* Allocates data memory for an encoding code block.
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
p_code_block)
{
OPJ_UINT32 l_data_size;
l_data_size = (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *
(p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));
if (l_data_size > p_code_block->data_size) {
if (p_code_block->data) {
/* We refer to data - 1 since below we incremented it */
opj_free(p_code_block->data - 1);
}
p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);
if (! p_code_block->data) {
p_code_block->data_size = 0U;
return OPJ_FALSE;
}
p_code_block->data_size = l_data_size;
/* We reserve the initial byte as a fake byte to a non-FF value */
/* and increment the data pointer, so that opj_mqc_init_enc() */
/* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */
/* it. */
p_code_block->data[0] = 0;
p_code_block->data += 1; /*why +1 ?*/
}
return OPJ_TRUE;
}
/**
* Allocates memory for a decoding code block.
*/
static OPJ_BOOL opj_tcd_code_block_dec_allocate(opj_tcd_cblk_dec_t *
p_code_block)
{
if (! p_code_block->data) {
p_code_block->data = (OPJ_BYTE*) opj_malloc(OPJ_COMMON_DEFAULT_CBLK_DATA_SIZE);
if (! p_code_block->data) {
return OPJ_FALSE;
}
p_code_block->data_max_size = OPJ_COMMON_DEFAULT_CBLK_DATA_SIZE;
/*fprintf(stderr, "Allocate 8192 elements of code_block->data\n");*/
p_code_block->segs = (opj_tcd_seg_t *) opj_calloc(OPJ_J2K_DEFAULT_NB_SEGS,
sizeof(opj_tcd_seg_t));
if (! p_code_block->segs) {
return OPJ_FALSE;
}
/*fprintf(stderr, "Allocate %d elements of code_block->data\n", OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));*/
p_code_block->m_current_max_segs = OPJ_J2K_DEFAULT_NB_SEGS;
/*fprintf(stderr, "m_current_max_segs of code_block->data = %d\n", p_code_block->m_current_max_segs);*/
} else {
/* sanitize */
OPJ_BYTE* l_data = p_code_block->data;
OPJ_UINT32 l_data_max_size = p_code_block->data_max_size;
opj_tcd_seg_t * l_segs = p_code_block->segs;
OPJ_UINT32 l_current_max_segs = p_code_block->m_current_max_segs;
memset(p_code_block, 0, sizeof(opj_tcd_cblk_dec_t));
p_code_block->data = l_data;
p_code_block->data_max_size = l_data_max_size;
p_code_block->segs = l_segs;
p_code_block->m_current_max_segs = l_current_max_segs;
}
return OPJ_TRUE;
}
OPJ_UINT32 opj_tcd_get_decoded_tile_size(opj_tcd_t *p_tcd)
{
OPJ_UINT32 i;
OPJ_UINT32 l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tile_comp = 00;
opj_tcd_resolution_t * l_res = 00;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_UINT32 l_temp;
l_tile_comp = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
l_res = l_tile_comp->resolutions + l_tile_comp->minimum_num_resolutions - 1;
l_temp = (OPJ_UINT32)((l_res->x1 - l_res->x0) * (l_res->y1 -
l_res->y0)); /* x1*y1 can't overflow */
if (l_size_comp && UINT_MAX / l_size_comp < l_temp) {
return UINT_MAX;
}
l_temp *= l_size_comp;
if (l_temp > UINT_MAX - l_data_size) {
return UINT_MAX;
}
l_data_size += l_temp;
++l_img_comp;
++l_tile_comp;
}
return l_data_size;
}
OPJ_BOOL opj_tcd_encode_tile(opj_tcd_t *p_tcd,
OPJ_UINT32 p_tile_no,
OPJ_BYTE *p_dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_max_length,
opj_codestream_info_t *p_cstr_info)
{
if (p_tcd->cur_tp_num == 0) {
p_tcd->tcd_tileno = p_tile_no;
p_tcd->tcp = &p_tcd->cp->tcps[p_tile_no];
/* INDEX >> "Precinct_nb_X et Precinct_nb_Y" */
if (p_cstr_info) {
OPJ_UINT32 l_num_packs = 0;
OPJ_UINT32 i;
opj_tcd_tilecomp_t *l_tilec_idx =
&p_tcd->tcd_image->tiles->comps[0]; /* based on component 0 */
opj_tccp_t *l_tccp = p_tcd->tcp->tccps; /* based on component 0 */
for (i = 0; i < l_tilec_idx->numresolutions; i++) {
opj_tcd_resolution_t *l_res_idx = &l_tilec_idx->resolutions[i];
p_cstr_info->tile[p_tile_no].pw[i] = (int)l_res_idx->pw;
p_cstr_info->tile[p_tile_no].ph[i] = (int)l_res_idx->ph;
l_num_packs += l_res_idx->pw * l_res_idx->ph;
p_cstr_info->tile[p_tile_no].pdx[i] = (int)l_tccp->prcw[i];
p_cstr_info->tile[p_tile_no].pdy[i] = (int)l_tccp->prch[i];
}
p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t*) opj_calloc((
size_t)p_cstr_info->numcomps * (size_t)p_cstr_info->numlayers * l_num_packs,
sizeof(opj_packet_info_t));
if (!p_cstr_info->tile[p_tile_no].packet) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
}
/* << INDEX */
/* FIXME _ProfStart(PGROUP_DC_SHIFT); */
/*---------------TILE-------------------*/
if (! opj_tcd_dc_level_shift_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DC_SHIFT); */
/* FIXME _ProfStart(PGROUP_MCT); */
if (! opj_tcd_mct_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_MCT); */
/* FIXME _ProfStart(PGROUP_DWT); */
if (! opj_tcd_dwt_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DWT); */
/* FIXME _ProfStart(PGROUP_T1); */
if (! opj_tcd_t1_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T1); */
/* FIXME _ProfStart(PGROUP_RATE); */
if (! opj_tcd_rate_allocate_encode(p_tcd, p_dest, p_max_length, p_cstr_info)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_RATE); */
}
/*--------------TIER2------------------*/
/* INDEX */
if (p_cstr_info) {
p_cstr_info->index_write = 1;
}
/* FIXME _ProfStart(PGROUP_T2); */
if (! opj_tcd_t2_encode(p_tcd, p_dest, p_data_written, p_max_length,
p_cstr_info)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T2); */
/*---------------CLEAN-------------------*/
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_decode_tile(opj_tcd_t *p_tcd,
OPJ_BYTE *p_src,
OPJ_UINT32 p_max_length,
OPJ_UINT32 p_tile_no,
opj_codestream_index_t *p_cstr_index,
opj_event_mgr_t *p_manager
)
{
OPJ_UINT32 l_data_read;
p_tcd->tcd_tileno = p_tile_no;
p_tcd->tcp = &(p_tcd->cp->tcps[p_tile_no]);
#ifdef TODO_MSD /* FIXME */
/* INDEX >> */
if (p_cstr_info) {
OPJ_UINT32 resno, compno, numprec = 0;
for (compno = 0; compno < (OPJ_UINT32) p_cstr_info->numcomps; compno++) {
opj_tcp_t *tcp = &p_tcd->cp->tcps[0];
opj_tccp_t *tccp = &tcp->tccps[compno];
opj_tcd_tilecomp_t *tilec_idx = &p_tcd->tcd_image->tiles->comps[compno];
for (resno = 0; resno < tilec_idx->numresolutions; resno++) {
opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[resno];
p_cstr_info->tile[p_tile_no].pw[resno] = res_idx->pw;
p_cstr_info->tile[p_tile_no].ph[resno] = res_idx->ph;
numprec += res_idx->pw * res_idx->ph;
p_cstr_info->tile[p_tile_no].pdx[resno] = tccp->prcw[resno];
p_cstr_info->tile[p_tile_no].pdy[resno] = tccp->prch[resno];
}
}
p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t *) opj_malloc(
p_cstr_info->numlayers * numprec * sizeof(opj_packet_info_t));
p_cstr_info->packno = 0;
}
/* << INDEX */
#endif
/*--------------TIER2------------------*/
/* FIXME _ProfStart(PGROUP_T2); */
l_data_read = 0;
if (! opj_tcd_t2_decode(p_tcd, p_src, &l_data_read, p_max_length, p_cstr_index,
p_manager)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T2); */
/*------------------TIER1-----------------*/
/* FIXME _ProfStart(PGROUP_T1); */
if (! opj_tcd_t1_decode(p_tcd, p_manager)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T1); */
/*----------------DWT---------------------*/
/* FIXME _ProfStart(PGROUP_DWT); */
if
(! opj_tcd_dwt_decode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DWT); */
/*----------------MCT-------------------*/
/* FIXME _ProfStart(PGROUP_MCT); */
if
(! opj_tcd_mct_decode(p_tcd, p_manager)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_MCT); */
/* FIXME _ProfStart(PGROUP_DC_SHIFT); */
if
(! opj_tcd_dc_level_shift_decode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DC_SHIFT); */
/*---------------TILE-------------------*/
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_update_tile_data(opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest,
OPJ_UINT32 p_dest_length
)
{
OPJ_UINT32 i, j, k, l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
opj_tcd_resolution_t * l_res;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_UINT32 l_stride, l_width, l_height;
l_data_size = opj_tcd_get_decoded_tile_size(p_tcd);
if (l_data_size == UINT_MAX || l_data_size > p_dest_length) {
return OPJ_FALSE;
}
l_tilec = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
l_res = l_tilec->resolutions + l_img_comp->resno_decoded;
l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
l_stride = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0) - l_width;
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_dest_ptr = (OPJ_CHAR *) p_dest;
const OPJ_INT32 * l_src_ptr = l_tilec->data;
if (l_img_comp->sgnd) {
for (j = 0; j < l_height; ++j) {
for (k = 0; k < l_width; ++k) {
*(l_dest_ptr++) = (OPJ_CHAR)(*(l_src_ptr++));
}
l_src_ptr += l_stride;
}
} else {
for (j = 0; j < l_height; ++j) {
for (k = 0; k < l_width; ++k) {
*(l_dest_ptr++) = (OPJ_CHAR)((*(l_src_ptr++)) & 0xff);
}
l_src_ptr += l_stride;
}
}
p_dest = (OPJ_BYTE *)l_dest_ptr;
}
break;
case 2: {
const OPJ_INT32 * l_src_ptr = l_tilec->data;
OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_dest;
if (l_img_comp->sgnd) {
for (j = 0; j < l_height; ++j) {
for (k = 0; k < l_width; ++k) {
OPJ_INT16 val = (OPJ_INT16)(*(l_src_ptr++));
memcpy(l_dest_ptr, &val, sizeof(val));
l_dest_ptr ++;
}
l_src_ptr += l_stride;
}
} else {
for (j = 0; j < l_height; ++j) {
for (k = 0; k < l_width; ++k) {
OPJ_INT16 val = (OPJ_INT16)((*(l_src_ptr++)) & 0xffff);
memcpy(l_dest_ptr, &val, sizeof(val));
l_dest_ptr ++;
}
l_src_ptr += l_stride;
}
}
p_dest = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 4: {
OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_dest;
OPJ_INT32 * l_src_ptr = l_tilec->data;
for (j = 0; j < l_height; ++j) {
memcpy(l_dest_ptr, l_src_ptr, l_width * sizeof(OPJ_INT32));
l_dest_ptr += l_width;
l_src_ptr += l_width + l_stride;
}
p_dest = (OPJ_BYTE*) l_dest_ptr;
}
break;
}
++l_img_comp;
++l_tilec;
}
return OPJ_TRUE;
}
static void opj_tcd_free_tile(opj_tcd_t *p_tcd)
{
OPJ_UINT32 compno, resno, bandno, precno;
opj_tcd_tile_t *l_tile = 00;
opj_tcd_tilecomp_t *l_tile_comp = 00;
opj_tcd_resolution_t *l_res = 00;
opj_tcd_band_t *l_band = 00;
opj_tcd_precinct_t *l_precinct = 00;
OPJ_UINT32 l_nb_resolutions, l_nb_precincts;
void (* l_tcd_code_block_deallocate)(opj_tcd_precinct_t *) = 00;
if (! p_tcd) {
return;
}
if (! p_tcd->tcd_image) {
return;
}
if (p_tcd->m_is_decoder) {
l_tcd_code_block_deallocate = opj_tcd_code_block_dec_deallocate;
} else {
l_tcd_code_block_deallocate = opj_tcd_code_block_enc_deallocate;
}
l_tile = p_tcd->tcd_image->tiles;
if (! l_tile) {
return;
}
l_tile_comp = l_tile->comps;
for (compno = 0; compno < l_tile->numcomps; ++compno) {
l_res = l_tile_comp->resolutions;
if (l_res) {
l_nb_resolutions = l_tile_comp->resolutions_size / sizeof(opj_tcd_resolution_t);
for (resno = 0; resno < l_nb_resolutions; ++resno) {
l_band = l_res->bands;
for (bandno = 0; bandno < 3; ++bandno) {
l_precinct = l_band->precincts;
if (l_precinct) {
l_nb_precincts = l_band->precincts_data_size / sizeof(opj_tcd_precinct_t);
for (precno = 0; precno < l_nb_precincts; ++precno) {
opj_tgt_destroy(l_precinct->incltree);
l_precinct->incltree = 00;
opj_tgt_destroy(l_precinct->imsbtree);
l_precinct->imsbtree = 00;
(*l_tcd_code_block_deallocate)(l_precinct);
++l_precinct;
}
opj_free(l_band->precincts);
l_band->precincts = 00;
}
++l_band;
} /* for (resno */
++l_res;
}
opj_free(l_tile_comp->resolutions);
l_tile_comp->resolutions = 00;
}
if (l_tile_comp->ownsData && l_tile_comp->data) {
opj_aligned_free(l_tile_comp->data);
l_tile_comp->data = 00;
l_tile_comp->ownsData = 0;
l_tile_comp->data_size = 0;
l_tile_comp->data_size_needed = 0;
}
++l_tile_comp;
}
opj_free(l_tile->comps);
l_tile->comps = 00;
opj_free(p_tcd->tcd_image->tiles);
p_tcd->tcd_image->tiles = 00;
}
static OPJ_BOOL opj_tcd_t2_decode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_src_size,
opj_codestream_index_t *p_cstr_index,
opj_event_mgr_t *p_manager
)
{
opj_t2_t * l_t2;
l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
if (l_t2 == 00) {
return OPJ_FALSE;
}
if (! opj_t2_decode_packets(
l_t2,
p_tcd->tcd_tileno,
p_tcd->tcd_image->tiles,
p_src_data,
p_data_read,
p_max_src_size,
p_cstr_index,
p_manager)) {
opj_t2_destroy(l_t2);
return OPJ_FALSE;
}
opj_t2_destroy(l_t2);
/*---------------CLEAN-------------------*/
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_t1_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
{
OPJ_UINT32 compno;
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t* l_tile_comp = l_tile->comps;
opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
volatile OPJ_BOOL ret = OPJ_TRUE;
OPJ_BOOL check_pterm = OPJ_FALSE;
opj_mutex_t* p_manager_mutex = NULL;
p_manager_mutex = opj_mutex_create();
/* Only enable PTERM check if we decode all layers */
if (p_tcd->tcp->num_layers_to_decode == p_tcd->tcp->numlayers &&
(l_tccp->cblksty & J2K_CCP_CBLKSTY_PTERM) != 0) {
check_pterm = OPJ_TRUE;
}
for (compno = 0; compno < l_tile->numcomps; ++compno) {
opj_t1_decode_cblks(p_tcd->thread_pool, &ret, l_tile_comp, l_tccp,
p_manager, p_manager_mutex, check_pterm);
if (!ret) {
break;
}
++l_tile_comp;
++l_tccp;
}
opj_thread_pool_wait_completion(p_tcd->thread_pool, 0);
if (p_manager_mutex) {
opj_mutex_destroy(p_manager_mutex);
}
return ret;
}
static OPJ_BOOL opj_tcd_dwt_decode(opj_tcd_t *p_tcd)
{
OPJ_UINT32 compno;
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
opj_image_comp_t * l_img_comp = p_tcd->image->comps;
for (compno = 0; compno < l_tile->numcomps; compno++) {
/*
if (tcd->cp->reduce != 0) {
tcd->image->comps[compno].resno_decoded =
tile->comps[compno].numresolutions - tcd->cp->reduce - 1;
if (tcd->image->comps[compno].resno_decoded < 0)
{
return false;
}
}
numres2decode = tcd->image->comps[compno].resno_decoded + 1;
if(numres2decode > 0){
*/
if (l_tccp->qmfbid == 1) {
if (! opj_dwt_decode(p_tcd->thread_pool, l_tile_comp,
l_img_comp->resno_decoded + 1)) {
return OPJ_FALSE;
}
} else {
if (! opj_dwt_decode_real(l_tile_comp, l_img_comp->resno_decoded + 1)) {
return OPJ_FALSE;
}
}
++l_tile_comp;
++l_img_comp;
++l_tccp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
{
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcp_t * l_tcp = p_tcd->tcp;
opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
OPJ_UINT32 l_samples, i;
if (! l_tcp->mct) {
return OPJ_TRUE;
}
l_samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) *
(l_tile_comp->y1 - l_tile_comp->y0));
if (l_tile->numcomps >= 3) {
/* testcase 1336.pdf.asan.47.376 */
if ((l_tile->comps[0].x1 - l_tile->comps[0].x0) * (l_tile->comps[0].y1 -
l_tile->comps[0].y0) < (OPJ_INT32)l_samples ||
(l_tile->comps[1].x1 - l_tile->comps[1].x0) * (l_tile->comps[1].y1 -
l_tile->comps[1].y0) < (OPJ_INT32)l_samples ||
(l_tile->comps[2].x1 - l_tile->comps[2].x0) * (l_tile->comps[2].y1 -
l_tile->comps[2].y0) < (OPJ_INT32)l_samples) {
opj_event_msg(p_manager, EVT_ERROR,
"Tiles don't all have the same dimension. Skip the MCT step.\n");
return OPJ_FALSE;
} else if (l_tcp->mct == 2) {
OPJ_BYTE ** l_data;
if (! l_tcp->m_mct_decoding_matrix) {
return OPJ_TRUE;
}
l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*));
if (! l_data) {
return OPJ_FALSE;
}
for (i = 0; i < l_tile->numcomps; ++i) {
l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
++l_tile_comp;
}
if (! opj_mct_decode_custom(/* MCT data */
(OPJ_BYTE*) l_tcp->m_mct_decoding_matrix,
/* size of components */
l_samples,
/* components */
l_data,
/* nb of components (i.e. size of pData) */
l_tile->numcomps,
/* tells if the data is signed */
p_tcd->image->comps->sgnd)) {
opj_free(l_data);
return OPJ_FALSE;
}
opj_free(l_data);
} else {
if (l_tcp->tccps->qmfbid == 1) {
opj_mct_decode(l_tile->comps[0].data,
l_tile->comps[1].data,
l_tile->comps[2].data,
l_samples);
} else {
opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data,
(OPJ_FLOAT32*)l_tile->comps[1].data,
(OPJ_FLOAT32*)l_tile->comps[2].data,
l_samples);
}
}
} else {
opj_event_msg(p_manager, EVT_ERROR,
"Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",
l_tile->numcomps);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_dc_level_shift_decode(opj_tcd_t *p_tcd)
{
OPJ_UINT32 compno;
opj_tcd_tilecomp_t * l_tile_comp = 00;
opj_tccp_t * l_tccp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_resolution_t* l_res = 00;
opj_tcd_tile_t * l_tile;
OPJ_UINT32 l_width, l_height, i, j;
OPJ_INT32 * l_current_ptr;
OPJ_INT32 l_min, l_max;
OPJ_UINT32 l_stride;
l_tile = p_tcd->tcd_image->tiles;
l_tile_comp = l_tile->comps;
l_tccp = p_tcd->tcp->tccps;
l_img_comp = p_tcd->image->comps;
for (compno = 0; compno < l_tile->numcomps; compno++) {
l_res = l_tile_comp->resolutions + l_img_comp->resno_decoded;
l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
l_stride = (OPJ_UINT32)(l_tile_comp->x1 - l_tile_comp->x0) - l_width;
assert(l_height == 0 ||
l_width + l_stride <= l_tile_comp->data_size / l_height); /*MUPDF*/
if (l_img_comp->sgnd) {
l_min = -(1 << (l_img_comp->prec - 1));
l_max = (1 << (l_img_comp->prec - 1)) - 1;
} else {
l_min = 0;
l_max = (1 << l_img_comp->prec) - 1;
}
l_current_ptr = l_tile_comp->data;
if (l_tccp->qmfbid == 1) {
for (j = 0; j < l_height; ++j) {
for (i = 0; i < l_width; ++i) {
*l_current_ptr = opj_int_clamp(*l_current_ptr + l_tccp->m_dc_level_shift, l_min,
l_max);
++l_current_ptr;
}
l_current_ptr += l_stride;
}
} else {
for (j = 0; j < l_height; ++j) {
for (i = 0; i < l_width; ++i) {
OPJ_FLOAT32 l_value = *((OPJ_FLOAT32 *) l_current_ptr);
OPJ_INT32 l_value_int = (OPJ_INT32)opj_lrintf(l_value);
if (l_value > INT_MAX ||
(l_value_int > 0 && l_tccp->m_dc_level_shift > 0 &&
l_value_int > INT_MAX - l_tccp->m_dc_level_shift)) {
*l_current_ptr = l_max;
} else {
*l_current_ptr = opj_int_clamp(
l_value_int + l_tccp->m_dc_level_shift, l_min, l_max);
}
++l_current_ptr;
}
l_current_ptr += l_stride;
}
}
++l_img_comp;
++l_tccp;
++l_tile_comp;
}
return OPJ_TRUE;
}
/**
* Deallocates the encoding data of the given precinct.
*/
static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct)
{
OPJ_UINT32 cblkno, l_nb_code_blocks;
opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec;
if (l_code_block) {
/*fprintf(stderr,"deallocate codeblock:{\n");*/
/*fprintf(stderr,"\t x0=%d, y0=%d, x1=%d, y1=%d\n",l_code_block->x0, l_code_block->y0, l_code_block->x1, l_code_block->y1);*/
/*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ",
l_code_block->numbps, l_code_block->numlenbits, l_code_block->len, l_code_block->numnewpasses, l_code_block->real_num_segs, l_code_block->m_current_max_segs );*/
l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t);
/*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
if (l_code_block->data) {
opj_free(l_code_block->data);
l_code_block->data = 00;
}
if (l_code_block->segs) {
opj_free(l_code_block->segs);
l_code_block->segs = 00;
}
++l_code_block;
}
opj_free(p_precinct->cblks.dec);
p_precinct->cblks.dec = 00;
}
}
/**
* Deallocates the encoding data of the given precinct.
*/
static void opj_tcd_code_block_enc_deallocate(opj_tcd_precinct_t * p_precinct)
{
OPJ_UINT32 cblkno, l_nb_code_blocks;
opj_tcd_cblk_enc_t * l_code_block = p_precinct->cblks.enc;
if (l_code_block) {
l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_enc_t);
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
if (l_code_block->data) {
/* We refer to data - 1 since below we incremented it */
/* in opj_tcd_code_block_enc_allocate_data() */
opj_free(l_code_block->data - 1);
l_code_block->data = 00;
}
if (l_code_block->layers) {
opj_free(l_code_block->layers);
l_code_block->layers = 00;
}
if (l_code_block->passes) {
opj_free(l_code_block->passes);
l_code_block->passes = 00;
}
++l_code_block;
}
opj_free(p_precinct->cblks.enc);
p_precinct->cblks.enc = 00;
}
}
OPJ_UINT32 opj_tcd_get_encoded_tile_size(opj_tcd_t *p_tcd)
{
OPJ_UINT32 i, l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
OPJ_UINT32 l_size_comp, l_remaining;
l_tilec = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
l_data_size += l_size_comp * (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) *
(l_tilec->y1 - l_tilec->y0));
++l_img_comp;
++l_tilec;
}
return l_data_size;
}
static OPJ_BOOL opj_tcd_dc_level_shift_encode(opj_tcd_t *p_tcd)
{
OPJ_UINT32 compno;
opj_tcd_tilecomp_t * l_tile_comp = 00;
opj_tccp_t * l_tccp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tile_t * l_tile;
OPJ_UINT32 l_nb_elem, i;
OPJ_INT32 * l_current_ptr;
l_tile = p_tcd->tcd_image->tiles;
l_tile_comp = l_tile->comps;
l_tccp = p_tcd->tcp->tccps;
l_img_comp = p_tcd->image->comps;
for (compno = 0; compno < l_tile->numcomps; compno++) {
l_current_ptr = l_tile_comp->data;
l_nb_elem = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) *
(l_tile_comp->y1 - l_tile_comp->y0));
if (l_tccp->qmfbid == 1) {
for (i = 0; i < l_nb_elem; ++i) {
*l_current_ptr -= l_tccp->m_dc_level_shift ;
++l_current_ptr;
}
} else {
for (i = 0; i < l_nb_elem; ++i) {
*l_current_ptr = (*l_current_ptr - l_tccp->m_dc_level_shift) * (1 << 11);
++l_current_ptr;
}
}
++l_img_comp;
++l_tccp;
++l_tile_comp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_mct_encode(opj_tcd_t *p_tcd)
{
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
OPJ_UINT32 samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) *
(l_tile_comp->y1 - l_tile_comp->y0));
OPJ_UINT32 i;
OPJ_BYTE ** l_data = 00;
opj_tcp_t * l_tcp = p_tcd->tcp;
if (!p_tcd->tcp->mct) {
return OPJ_TRUE;
}
if (p_tcd->tcp->mct == 2) {
if (! p_tcd->tcp->m_mct_coding_matrix) {
return OPJ_TRUE;
}
l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*));
if (! l_data) {
return OPJ_FALSE;
}
for (i = 0; i < l_tile->numcomps; ++i) {
l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
++l_tile_comp;
}
if (! opj_mct_encode_custom(/* MCT data */
(OPJ_BYTE*) p_tcd->tcp->m_mct_coding_matrix,
/* size of components */
samples,
/* components */
l_data,
/* nb of components (i.e. size of pData) */
l_tile->numcomps,
/* tells if the data is signed */
p_tcd->image->comps->sgnd)) {
opj_free(l_data);
return OPJ_FALSE;
}
opj_free(l_data);
} else if (l_tcp->tccps->qmfbid == 0) {
opj_mct_encode_real(l_tile->comps[0].data, l_tile->comps[1].data,
l_tile->comps[2].data, samples);
} else {
opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data,
l_tile->comps[2].data, samples);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd)
{
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
OPJ_UINT32 compno;
for (compno = 0; compno < l_tile->numcomps; ++compno) {
if (l_tccp->qmfbid == 1) {
if (! opj_dwt_encode(l_tile_comp)) {
return OPJ_FALSE;
}
} else if (l_tccp->qmfbid == 0) {
if (! opj_dwt_encode_real(l_tile_comp)) {
return OPJ_FALSE;
}
}
++l_tile_comp;
++l_tccp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd)
{
opj_t1_t * l_t1;
const OPJ_FLOAT64 * l_mct_norms;
OPJ_UINT32 l_mct_numcomps = 0U;
opj_tcp_t * l_tcp = p_tcd->tcp;
l_t1 = opj_t1_create(OPJ_TRUE);
if (l_t1 == 00) {
return OPJ_FALSE;
}
if (l_tcp->mct == 1) {
l_mct_numcomps = 3U;
/* irreversible encoding */
if (l_tcp->tccps->qmfbid == 0) {
l_mct_norms = opj_mct_get_mct_norms_real();
} else {
l_mct_norms = opj_mct_get_mct_norms();
}
} else {
l_mct_numcomps = p_tcd->image->numcomps;
l_mct_norms = (const OPJ_FLOAT64 *)(l_tcp->mct_norms);
}
if (! opj_t1_encode_cblks(l_t1, p_tcd->tcd_image->tiles, l_tcp, l_mct_norms,
l_mct_numcomps)) {
opj_t1_destroy(l_t1);
return OPJ_FALSE;
}
opj_t1_destroy(l_t1);
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info)
{
opj_t2_t * l_t2;
l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
if (l_t2 == 00) {
return OPJ_FALSE;
}
if (! opj_t2_encode_packets(
l_t2,
p_tcd->tcd_tileno,
p_tcd->tcd_image->tiles,
p_tcd->tcp->numlayers,
p_dest_data,
p_data_written,
p_max_dest_size,
p_cstr_info,
p_tcd->tp_num,
p_tcd->tp_pos,
p_tcd->cur_pino,
FINAL_PASS)) {
opj_t2_destroy(l_t2);
return OPJ_FALSE;
}
opj_t2_destroy(l_t2);
/*---------------CLEAN-------------------*/
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info)
{
opj_cp_t * l_cp = p_tcd->cp;
OPJ_UINT32 l_nb_written = 0;
if (p_cstr_info) {
p_cstr_info->index_write = 0;
}
if (l_cp->m_specific_param.m_enc.m_disto_alloc ||
l_cp->m_specific_param.m_enc.m_fixed_quality) {
/* fixed_quality */
/* Normal Rate/distortion allocation */
if (! opj_tcd_rateallocate(p_tcd, p_dest_data, &l_nb_written, p_max_dest_size,
p_cstr_info)) {
return OPJ_FALSE;
}
} else {
/* Fixed layer allocation */
opj_tcd_rateallocate_fixed(p_tcd);
}
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_copy_tile_data(opj_tcd_t *p_tcd,
OPJ_BYTE * p_src,
OPJ_UINT32 p_src_length)
{
OPJ_UINT32 i, j, l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_UINT32 l_nb_elem;
l_data_size = opj_tcd_get_encoded_tile_size(p_tcd);
if (l_data_size != p_src_length) {
return OPJ_FALSE;
}
l_tilec = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
l_nb_elem = (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 -
l_tilec->y0));
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_src_ptr = (OPJ_CHAR *) p_src;
OPJ_INT32 * l_dest_ptr = l_tilec->data;
if (l_img_comp->sgnd) {
for (j = 0; j < l_nb_elem; ++j) {
*(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
}
} else {
for (j = 0; j < l_nb_elem; ++j) {
*(l_dest_ptr++) = (*(l_src_ptr++)) & 0xff;
}
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
case 2: {
OPJ_INT32 * l_dest_ptr = l_tilec->data;
OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_src;
if (l_img_comp->sgnd) {
for (j = 0; j < l_nb_elem; ++j) {
*(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
}
} else {
for (j = 0; j < l_nb_elem; ++j) {
*(l_dest_ptr++) = (*(l_src_ptr++)) & 0xffff;
}
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
case 4: {
OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_src;
OPJ_INT32 * l_dest_ptr = l_tilec->data;
for (j = 0; j < l_nb_elem; ++j) {
*(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
}
++l_img_comp;
++l_tilec;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_is_band_empty(opj_tcd_band_t* band)
{
return (band->x1 - band->x0 == 0) || (band->y1 - band->y0 == 0);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4865_0 |
crossvul-cpp_data_bad_5252_1 | /*
Mac-Telnet - Connect to RouterOS or mactelnetd devices via MAC address
Copyright (C) 2010, Håkon Nessjøen <haakon.nessjoen@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#define _POSIX_C_SOURCE 199309L
#define _XOPEN_SOURCE 600
#define _BSD_SOURCE
#define _DARWIN_C_SOURCE
#include <libintl.h>
#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#if defined(__APPLE__)
# include <sys/sysctl.h>
# include <libkern/OSByteOrder.h>
# define le16toh OSSwapLittleToHostInt16
# define htole32 OSSwapHostToLittleInt32
#elif defined(__FreeBSD__)
#include <sys/endian.h>
#else
#include <endian.h>
#endif
#if defined(__FreeBSD__) || defined(__APPLE__)
#include <paths.h>
#endif
#include <time.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <net/ethernet.h>
#include <netinet/in.h>
#if !defined(__FreeBSD__) && !defined(__APPLE__)
#include <netinet/ether.h>
#endif
#include <sys/time.h>
#include <time.h>
#include <sys/socket.h>
#include <string.h>
#ifdef __linux__
#include <linux/if_ether.h>
#include <sys/mman.h>
#else
#include <sys/time.h>
#endif
#include <sys/ioctl.h>
#include <sys/stat.h>
#if defined(__linux__)
#include <sys/sysinfo.h>
#endif
#include <pwd.h>
#if defined(__FreeBSD__) || defined(__APPLE__)
#include <sys/time.h>
/* This is the really Posix interface the Linux code should have used !!*/
#include <utmpx.h>
#else
#include <utmp.h>
#endif
#include <syslog.h>
#include <sys/utsname.h>
#include "md5.h"
#include "protocol.h"
#include "console.h"
#include "interfaces.h"
#include "users.h"
#include "config.h"
#include "utlist.h"
#define PROGRAM_NAME "MAC-Telnet Daemon"
#define MAX_INSOCKETS 100
#define MT_INTERFACE_LEN 128
/* Max ~5 pings per second */
#define MT_MAXPPS MT_MNDP_BROADCAST_INTERVAL * 5
#define _(String) gettext (String)
#define gettext_noop(String) String
static int sockfd;
static int insockfd;
static int mndpsockfd;
static int pings = 0;
struct net_interface *interfaces = NULL;
static int use_raw_socket = 0;
static struct in_addr sourceip;
static struct in_addr destip;
static int sourceport;
static time_t last_mndp_time = 0;
/* Protocol data direction */
unsigned char mt_direction_fromserver = 1;
/* Anti-timeout is every 10 seconds. Give up after 15. */
#define MT_CONNECTION_TIMEOUT 15
/* Connection states */
enum mt_connection_state {
STATE_AUTH,
STATE_CLOSED,
STATE_ACTIVE
};
/** Connection struct */
struct mt_connection {
struct net_interface *interface;
char interface_name[256];
unsigned short seskey;
unsigned int incounter;
unsigned int outcounter;
unsigned int lastack;
time_t lastdata;
int terminal_mode;
enum mt_connection_state state;
int ptsfd;
int slavefd;
int pid;
int wait_for_ack;
int have_pass_salt;
char username[MT_MNDP_MAX_STRING_SIZE];
unsigned char trypassword[17];
unsigned char srcip[IPV4_ALEN];
unsigned char srcmac[ETH_ALEN];
unsigned short srcport;
unsigned char dstmac[ETH_ALEN];
unsigned char pass_salt[16];
unsigned short terminal_width;
unsigned short terminal_height;
char terminal_type[30];
struct mt_connection *prev;
struct mt_connection *next;
};
static void uwtmp_login(struct mt_connection *);
static void uwtmp_logout(struct mt_connection *);
static struct mt_connection *connections_head = NULL;
static void list_add_connection(struct mt_connection *conn) {
DL_APPEND(connections_head, conn);
}
static void list_remove_connection(struct mt_connection *conn) {
if (connections_head == NULL) {
return;
}
if (conn->state == STATE_ACTIVE && conn->ptsfd > 0) {
close(conn->ptsfd);
}
if (conn->state == STATE_ACTIVE && conn->slavefd > 0) {
close(conn->slavefd);
}
uwtmp_logout(conn);
DL_DELETE(connections_head, conn);
free(conn);
}
static struct mt_connection *list_find_connection(unsigned short seskey, unsigned char *srcmac) {
struct mt_connection *p;
DL_FOREACH(connections_head, p) {
if (p->seskey == seskey && memcmp(srcmac, p->srcmac, ETH_ALEN) == 0) {
return p;
}
}
return NULL;
}
static struct net_interface *find_socket(unsigned char *mac) {
struct net_interface *interface;
DL_FOREACH(interfaces, interface) {
if (memcmp(mac, interface->mac_addr, ETH_ALEN) == 0) {
return interface;
}
}
return NULL;
}
static void setup_sockets() {
struct net_interface *interface;
DL_FOREACH(interfaces, interface) {
int optval = 1;
struct sockaddr_in si_me;
struct ether_addr *mac = (struct ether_addr *)&(interface->mac_addr);
if (!interface->has_mac) {
continue;
}
if (!use_raw_socket) {
interface->socketfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (interface->socketfd < 0) {
continue;
}
if (setsockopt(interface->socketfd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof (optval))==-1) {
perror("SO_BROADCAST");
continue;
}
setsockopt(interface->socketfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
/* Initialize receiving socket on the device chosen */
si_me.sin_family = AF_INET;
si_me.sin_port = htons(MT_MACTELNET_PORT);
memcpy(&(si_me.sin_addr.s_addr), interface->ipv4_addr, IPV4_ALEN);
if (bind(interface->socketfd, (struct sockaddr *)&si_me, sizeof(si_me))==-1) {
fprintf(stderr, _("Error binding to %s:%d, %s\n"), inet_ntoa(si_me.sin_addr), sourceport, strerror(errno));
continue;
}
}
syslog(LOG_NOTICE, _("Listening on %s for %s\n"), interface->name, ether_ntoa(mac));
}
}
static int send_udp(const struct mt_connection *conn, const struct mt_packet *packet) {
if (use_raw_socket) {
return net_send_udp(sockfd, conn->interface, conn->dstmac, conn->srcmac, &sourceip, sourceport, &destip, conn->srcport, packet->data, packet->size);
} else {
/* Init SendTo struct */
struct sockaddr_in socket_address;
socket_address.sin_family = AF_INET;
socket_address.sin_port = htons(conn->srcport);
socket_address.sin_addr.s_addr = htonl(INADDR_BROADCAST);
return sendto(conn->interface->socketfd, packet->data, packet->size, 0, (struct sockaddr*)&socket_address, sizeof(socket_address));
}
}
static int send_special_udp(struct net_interface *interface, unsigned short port, const struct mt_packet *packet) {
unsigned char dstmac[ETH_ALEN];
if (use_raw_socket) {
memset(dstmac, 0xff, ETH_ALEN);
return net_send_udp(sockfd, interface, interface->mac_addr, dstmac, (const struct in_addr *)&interface->ipv4_addr, port, &destip, port, packet->data, packet->size);
} else {
/* Init SendTo struct */
struct sockaddr_in socket_address;
socket_address.sin_family = AF_INET;
socket_address.sin_port = htons(port);
socket_address.sin_addr.s_addr = htonl(INADDR_BROADCAST);
return sendto(interface->socketfd, packet->data, packet->size, 0, (struct sockaddr*)&socket_address, sizeof(socket_address));
}
}
static void display_motd() {
FILE *fp;
int c;
if ((fp = fopen("/etc/motd", "r"))) {
while ((c = getc(fp)) != EOF) {
putchar(c);
}
fclose(fp);
}
}
static void display_nologin() {
FILE *fp;
int c;
if ((fp = fopen(_PATH_NOLOGIN, "r"))) {
while ((c = getc(fp)) != EOF) {
putchar(c);
}
fclose(fp);
}
}
static void uwtmp_login(struct mt_connection *conn) {
#if defined(__FreeBSD__) || defined(__APPLE__)
struct utmpx utent;
#else
struct utmp utent;
#endif
pid_t pid;
pid = getpid();
char *line = ttyname(conn->slavefd);
if (strncmp(line, "/dev/", 5) == 0) {
line += 5;
}
/* Setup utmp struct */
memset((void *) &utent, 0, sizeof(utent));
utent.ut_type = USER_PROCESS;
utent.ut_pid = pid;
strncpy(utent.ut_user, conn->username, sizeof(utent.ut_user));
strncpy(utent.ut_line, line, sizeof(utent.ut_line));
strncpy(utent.ut_id, utent.ut_line + 3, sizeof(utent.ut_id));
strncpy(utent.ut_host,
ether_ntoa((const struct ether_addr *)conn->srcmac),
sizeof(utent.ut_host));
#if defined(__FreeBSD__) || defined(__APPLE__)
gettimeofday(&utent.ut_tv, NULL);
#else
time((time_t *)&(utent.ut_time));
#endif
/* Update utmp and/or wtmp */
#if defined(__FreeBSD__) || defined(__APPLE__)
setutxent();
pututxline(&utent);
endutxent();
#else
setutent();
pututline(&utent);
endutent();
updwtmp(_PATH_WTMP, &utent);
#endif
}
static void uwtmp_logout(struct mt_connection *conn) {
if (conn->pid > 0) {
#if defined(__FreeBSD__) || defined(__APPLE__)
struct utmpx *utentp;
struct utmpx utent;
setutxent();
#else
struct utmp *utentp;
struct utmp utent;
setutent();
#endif
#if defined(__FreeBSD__) || defined(__APPLE__)
while ((utentp = getutxent()) != NULL) {
#else
while ((utentp = getutent()) != NULL) {
#endif
if (utentp->ut_pid == conn->pid && utentp->ut_id) {
break;
}
}
if (utentp) {
utent = *utentp;
utent.ut_type = DEAD_PROCESS;
utent.ut_tv.tv_sec = time(NULL);
#if defined(__FreeBSD__) || defined(__APPLE__)
pututxline(&utent);
endutxent();
#else
pututline(&utent);
endutent();
updwtmp(_PATH_WTMP, &utent);
#endif
}
}
}
static void abort_connection(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr, char *message) {
struct mt_packet pdata;
init_packet(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
add_control_packet(&pdata, MT_CPTYPE_PLAINDATA, message, strlen(message));
send_udp(curconn, &pdata);
/* Make connection time out; lets the previous message get acked before disconnecting */
curconn->state = STATE_CLOSED;
init_packet(&pdata, MT_PTYPE_END, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
send_udp(curconn, &pdata);
}
static void user_login(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr) {
struct mt_packet pdata;
unsigned char md5sum[17];
char md5data[100];
struct mt_credentials *user;
char *slavename;
/* Reparse user file before each login */
read_userfile();
if ((user = find_user(curconn->username)) != NULL) {
md5_state_t state;
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(md5data, sizeof(md5data));
mlock(md5sum, sizeof(md5sum));
if (user->password != NULL) {
mlock(user->password, strlen(user->password));
}
#endif
/* Concat string of 0 + password + pass_salt */
md5data[0] = 0;
strncpy(md5data + 1, user->password, 82);
memcpy(md5data + 1 + strlen(user->password), curconn->pass_salt, 16);
/* Generate md5 sum of md5data with a leading 0 */
md5_init(&state);
md5_append(&state, (const md5_byte_t *)md5data, strlen(user->password) + 17);
md5_finish(&state, (md5_byte_t *)md5sum + 1);
md5sum[0] = 0;
init_packet(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
curconn->outcounter += add_control_packet(&pdata, MT_CPTYPE_END_AUTH, NULL, 0);
send_udp(curconn, &pdata);
if (curconn->state == STATE_ACTIVE) {
return;
}
}
if (user == NULL || memcmp(md5sum, curconn->trypassword, 17) != 0) {
syslog(LOG_NOTICE, _("(%d) Invalid login by %s."), curconn->seskey, curconn->username);
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Login failed, incorrect username or password\r\n"));
/* TODO: should wait some time (not with sleep) before returning, to minimalize brute force attacks */
return;
}
/* User is logged in */
curconn->state = STATE_ACTIVE;
/* Enter terminal mode */
curconn->terminal_mode = 1;
/* Open pts handle */
curconn->ptsfd = posix_openpt(O_RDWR);
if (curconn->ptsfd == -1 || grantpt(curconn->ptsfd) == -1 || unlockpt(curconn->ptsfd) == -1) {
syslog(LOG_ERR, "posix_openpt: %s", strerror(errno));
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Terminal error\r\n"));
return;
}
/* Get file path for our pts */
slavename = ptsname(curconn->ptsfd);
if (slavename != NULL) {
pid_t pid;
struct stat sb;
struct passwd *user = (struct passwd *)malloc(sizeof(struct passwd));
struct passwd *tmpuser=user;
char *buffer = malloc(1024);
if (user == NULL || buffer == NULL) {
syslog(LOG_CRIT, _("(%d) Error allocating memory."), curconn->seskey);
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("System error, out of memory\r\n"));
return;
}
if (getpwnam_r(curconn->username, user, buffer, 1024, &tmpuser) != 0) {
syslog(LOG_WARNING, _("(%d) Login ok, but local user not accessible (%s)."), curconn->seskey, curconn->username);
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Local user not accessible\r\n"));
free(user);
free(buffer);
return;
}
/* Change the owner of the slave pts */
chown(slavename, user->pw_uid, user->pw_gid);
curconn->slavefd = open(slavename, O_RDWR);
if (curconn->slavefd == -1) {
syslog(LOG_ERR, _("Error opening %s: %s"), slavename, strerror(errno));
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Error opening terminal\r\n"));
list_remove_connection(curconn);
return;
}
if ((pid = fork()) == 0) {
struct net_interface *interface;
/* Add login information to utmp/wtmp */
uwtmp_login(curconn);
syslog(LOG_INFO, _("(%d) User %s logged in."), curconn->seskey, curconn->username);
/* Initialize terminal environment */
setenv("USER", user->pw_name, 1);
setenv("HOME", user->pw_dir, 1);
setenv("SHELL", user->pw_shell, 1);
setenv("TERM", curconn->terminal_type, 1);
close(sockfd);
close(insockfd);
DL_FOREACH(interfaces, interface) {
if (interface->socketfd > 0) {
close(interface->socketfd);
}
}
setsid();
/* Don't let shell process inherit slavefd */
fcntl (curconn->slavefd, F_SETFD, FD_CLOEXEC);
close(curconn->ptsfd);
/* Redirect STDIN/STDIO/STDERR */
close(0);
dup(curconn->slavefd);
close(1);
dup(curconn->slavefd);
close(2);
dup(curconn->slavefd);
/* Set controlling terminal */
ioctl(0, TIOCSCTTY, 1);
tcsetpgrp(0, getpid());
/* Set user id/group id */
if ((setgid(user->pw_gid) != 0) || (setuid(user->pw_uid) != 0)) {
syslog(LOG_ERR, _("(%d) Could not log in %s (%d:%d): setuid/setgid: %s"), curconn->seskey, curconn->username, user->pw_uid, user->pw_gid, strerror(errno));
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
abort_connection(curconn, pkthdr, _("Internal error\r\n"));
exit(0);
}
/* Abort login if /etc/nologin exists */
if (stat(_PATH_NOLOGIN, &sb) == 0 && getuid() != 0) {
syslog(LOG_NOTICE, _("(%d) User %s disconnected with " _PATH_NOLOGIN " message."), curconn->seskey, curconn->username);
display_nologin();
curconn->state = STATE_CLOSED;
init_packet(&pdata, MT_PTYPE_END, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
send_udp(curconn, &pdata);
exit(0);
}
/* Display MOTD */
display_motd();
chdir(user->pw_dir);
/* Spawn shell */
/* TODO: Maybe use "login -f USER" instead? renders motd and executes shell correctly for system */
execl(user->pw_shell, user->pw_shell, "-", (char *) 0);
exit(0); // just to be sure.
}
free(user);
free(buffer);
close(curconn->slavefd);
curconn->pid = pid;
set_terminal_size(curconn->ptsfd, curconn->terminal_width, curconn->terminal_height);
}
}
static void handle_data_packet(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr, int data_len) {
struct mt_mactelnet_control_hdr cpkt;
struct mt_packet pdata;
unsigned char *data = pkthdr->data;
unsigned int act_size = 0;
int got_user_packet = 0;
int got_pass_packet = 0;
int got_width_packet = 0;
int got_height_packet = 0;
int success;
/* Parse first control packet */
success = parse_control_packet(data, data_len - MT_HEADER_LEN, &cpkt);
while (success) {
if (cpkt.cptype == MT_CPTYPE_BEGINAUTH) {
int plen,i;
if (!curconn->have_pass_salt) {
for (i = 0; i < 16; ++i) {
curconn->pass_salt[i] = rand() % 256;
}
curconn->have_pass_salt = 1;
memset(curconn->trypassword, 0, sizeof(curconn->trypassword));
}
init_packet(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
plen = add_control_packet(&pdata, MT_CPTYPE_PASSSALT, (curconn->pass_salt), 16);
curconn->outcounter += plen;
send_udp(curconn, &pdata);
/* Don't change the username after the state is active */
} else if (cpkt.cptype == MT_CPTYPE_USERNAME && curconn->state != STATE_ACTIVE) {
memcpy(curconn->username, cpkt.data, act_size = (cpkt.length > MT_MNDP_MAX_STRING_SIZE - 1 ? MT_MNDP_MAX_STRING_SIZE - 1 : cpkt.length));
curconn->username[act_size] = 0;
got_user_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_WIDTH && cpkt.length >= 2) {
unsigned short width;
memcpy(&width, cpkt.data, 2);
curconn->terminal_width = le16toh(width);
got_width_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_HEIGHT && cpkt.length >= 2) {
unsigned short height;
memcpy(&height, cpkt.data, 2);
curconn->terminal_height = le16toh(height);
got_height_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_TYPE) {
memcpy(curconn->terminal_type, cpkt.data, act_size = (cpkt.length > 30 - 1 ? 30 - 1 : cpkt.length));
curconn->terminal_type[act_size] = 0;
} else if (cpkt.cptype == MT_CPTYPE_PASSWORD) {
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(curconn->trypassword, 17);
#endif
memcpy(curconn->trypassword, cpkt.data, 17);
got_pass_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) {
/* relay data from client to shell */
if (curconn->state == STATE_ACTIVE && curconn->ptsfd != -1) {
write(curconn->ptsfd, cpkt.data, cpkt.length);
}
} else {
syslog(LOG_WARNING, _("(%d) Unhandeled control packet type: %d"), curconn->seskey, cpkt.cptype);
}
/* Parse next control packet */
success = parse_control_packet(NULL, 0, &cpkt);
}
if (got_user_packet && got_pass_packet) {
user_login(curconn, pkthdr);
}
if (curconn->state == STATE_ACTIVE && (got_width_packet || got_height_packet)) {
set_terminal_size(curconn->ptsfd, curconn->terminal_width, curconn->terminal_height);
}
}
static void handle_packet(unsigned char *data, int data_len, const struct sockaddr_in *address) {
struct mt_mactelnet_hdr pkthdr;
struct mt_connection *curconn = NULL;
struct mt_packet pdata;
struct net_interface *interface;
/* Check for minimal size */
if (data_len < MT_HEADER_LEN - 4) {
return;
}
parse_packet(data, &pkthdr);
/* Drop packets not belonging to us */
if ((interface = find_socket(pkthdr.dstaddr)) < 0) {
return;
}
switch (pkthdr.ptype) {
case MT_PTYPE_PING:
if (pings++ > MT_MAXPPS) {
/* Don't want it to wrap around back to the valid range */
pings--;
break;
}
init_pongpacket(&pdata, (unsigned char *)&(pkthdr.dstaddr), (unsigned char *)&(pkthdr.srcaddr));
add_packetdata(&pdata, pkthdr.data - 4, data_len - (MT_HEADER_LEN - 4));
{
if (index >= 0) {
send_special_udp(interface, MT_MACTELNET_PORT, &pdata);
}
}
break;
case MT_PTYPE_SESSIONSTART:
curconn = list_find_connection(pkthdr.seskey, (unsigned char *)&(pkthdr.srcaddr));
if (curconn != NULL) {
/* Ignore multiple session starts from the same sender, this can be same mac but different interface */
break;
}
syslog(LOG_DEBUG, _("(%d) New connection from %s."), pkthdr.seskey, ether_ntoa((struct ether_addr*)&(pkthdr.srcaddr)));
curconn = calloc(1, sizeof(struct mt_connection));
curconn->seskey = pkthdr.seskey;
curconn->lastdata = time(NULL);
curconn->state = STATE_AUTH;
curconn->interface = interface;
strncpy(curconn->interface_name, interface->name, 254);
curconn->interface_name[255] = '\0';
memcpy(curconn->srcmac, pkthdr.srcaddr, ETH_ALEN);
memcpy(curconn->srcip, &(address->sin_addr), IPV4_ALEN);
curconn->srcport = htons(address->sin_port);
memcpy(curconn->dstmac, pkthdr.dstaddr, ETH_ALEN);
list_add_connection(curconn);
init_packet(&pdata, MT_PTYPE_ACK, pkthdr.dstaddr, pkthdr.srcaddr, pkthdr.seskey, pkthdr.counter);
send_udp(curconn, &pdata);
break;
case MT_PTYPE_END:
curconn = list_find_connection(pkthdr.seskey, (unsigned char *)&(pkthdr.srcaddr));
if (curconn == NULL) {
break;
}
if (curconn->state != STATE_CLOSED) {
init_packet(&pdata, MT_PTYPE_END, pkthdr.dstaddr, pkthdr.srcaddr, pkthdr.seskey, pkthdr.counter);
send_udp(curconn, &pdata);
}
syslog(LOG_DEBUG, _("(%d) Connection closed."), curconn->seskey);
list_remove_connection(curconn);
return;
case MT_PTYPE_ACK:
curconn = list_find_connection(pkthdr.seskey, (unsigned char *)&(pkthdr.srcaddr));
if (curconn == NULL) {
break;
}
if (pkthdr.counter <= curconn->outcounter) {
curconn->wait_for_ack = 0;
curconn->lastack = pkthdr.counter;
}
if (time(0) - curconn->lastdata > 9 || pkthdr.counter == curconn->lastack) {
// Answer to anti-timeout packet
init_packet(&pdata, MT_PTYPE_ACK, pkthdr.dstaddr, pkthdr.srcaddr, pkthdr.seskey, pkthdr.counter);
send_udp(curconn, &pdata);
}
curconn->lastdata = time(NULL);
return;
case MT_PTYPE_DATA:
curconn = list_find_connection(pkthdr.seskey, (unsigned char *)&(pkthdr.srcaddr));
if (curconn == NULL) {
break;
}
curconn->lastdata = time(NULL);
/* now check the right size */
if (data_len < MT_HEADER_LEN) {
/* Ignore illegal packet */
return;
}
/* ack the data packet */
init_packet(&pdata, MT_PTYPE_ACK, pkthdr.dstaddr, pkthdr.srcaddr, pkthdr.seskey, pkthdr.counter + (data_len - MT_HEADER_LEN));
send_udp(curconn, &pdata);
/* Accept first packet, and all packets greater than incounter, and if counter has
wrapped around. */
if (curconn->incounter == 0 || pkthdr.counter > curconn->incounter || (curconn->incounter - pkthdr.counter) > 16777216) {
curconn->incounter = pkthdr.counter;
} else {
/* Ignore double or old packets */
return;
}
handle_data_packet(curconn, &pkthdr, data_len);
break;
default:
if (curconn) {
syslog(LOG_WARNING, _("(%d) Unhandeled packet type: %d"), curconn->seskey, pkthdr.ptype);
init_packet(&pdata, MT_PTYPE_ACK, pkthdr.dstaddr, pkthdr.srcaddr, pkthdr.seskey, pkthdr.counter);
send_udp(curconn, &pdata);
}
}
if (0 && curconn != NULL) {
printf("Packet, incounter %d, outcounter %d\n", curconn->incounter, curconn->outcounter);
}
}
static void print_version() {
fprintf(stderr, PROGRAM_NAME " " PROGRAM_VERSION "\n");
}
void mndp_broadcast() {
struct mt_packet pdata;
struct utsname s_uname;
struct net_interface *interface;
unsigned int uptime;
#if defined(__APPLE__)
int mib[] = {CTL_KERN, KERN_BOOTTIME};
struct timeval boottime;
size_t tv_size = sizeof(boottime);
if (sysctl(mib, sizeof(mib)/sizeof(mib[0]), &boottime, &tv_size, NULL, 0) == -1) {
return;
}
uptime = htole32(boottime.tv_sec);
#elif defined(__linux__)
struct sysinfo s_sysinfo;
if (sysinfo(&s_sysinfo) != 0) {
return;
}
/* Seems like ping uptime is transmitted as little endian? */
uptime = htole32(s_sysinfo.uptime);
#else
struct timespec ts;
if (clock_gettime(CLOCK_UPTIME, &ts) != -1) {
uptime = htole32(((unsigned int)ts.tv_sec));
}
#endif
if (uname(&s_uname) != 0) {
return;
}
DL_FOREACH(interfaces, interface) {
struct mt_mndp_hdr *header = (struct mt_mndp_hdr *)&(pdata.data);
if (interface->has_mac == 0) {
continue;
}
mndp_init_packet(&pdata, 0, 1);
mndp_add_attribute(&pdata, MT_MNDPTYPE_ADDRESS, interface->mac_addr, ETH_ALEN);
mndp_add_attribute(&pdata, MT_MNDPTYPE_IDENTITY, s_uname.nodename, strlen(s_uname.nodename));
mndp_add_attribute(&pdata, MT_MNDPTYPE_VERSION, s_uname.release, strlen(s_uname.release));
mndp_add_attribute(&pdata, MT_MNDPTYPE_PLATFORM, PLATFORM_NAME, strlen(PLATFORM_NAME));
mndp_add_attribute(&pdata, MT_MNDPTYPE_HARDWARE, s_uname.machine, strlen(s_uname.machine));
mndp_add_attribute(&pdata, MT_MNDPTYPE_TIMESTAMP, &uptime, 4);
mndp_add_attribute(&pdata, MT_MNDPTYPE_SOFTID, MT_SOFTID_MACTELNET, strlen(MT_SOFTID_MACTELNET));
mndp_add_attribute(&pdata, MT_MNDPTYPE_IFNAME, interface->name, strlen(interface->name));
header->cksum = in_cksum((unsigned short *)&(pdata.data), pdata.size);
send_special_udp(interface, MT_MNDP_PORT, &pdata);
}
}
void sigterm_handler() {
struct mt_connection *p;
struct mt_packet pdata;
struct net_interface *interface, *tmp;
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
char message[] = gettext_noop("\r\n\r\nDaemon shutting down.\r\n");
syslog(LOG_NOTICE, _("Daemon shutting down"));
DL_FOREACH(connections_head, p) {
if (p->state == STATE_ACTIVE) {
init_packet(&pdata, MT_PTYPE_DATA, p->interface->mac_addr, p->srcmac, p->seskey, p->outcounter);
add_control_packet(&pdata, MT_CPTYPE_PLAINDATA, _(message), strlen(_(message)));
send_udp(p, &pdata);
init_packet(&pdata, MT_PTYPE_END, p->interface->mac_addr, p->srcmac, p->seskey, p->outcounter);
send_udp(p, &pdata);
}
}
/* Doesn't hurt to tidy up */
close(sockfd);
close(insockfd);
if (!use_raw_socket) {
DL_FOREACH(interfaces, interface) {
if (interface->socketfd > 0)
close(interface->socketfd);
}
}
DL_FOREACH_SAFE(interfaces, interface, tmp) {
DL_DELETE(interfaces, interface);
free(interface);
}
closelog();
exit(0);
}
void sighup_handler() {
struct mt_connection *p;
syslog(LOG_NOTICE, _("SIGHUP: Reloading interfaces"));
if (!use_raw_socket) {
struct net_interface *interface, *tmp;
DL_FOREACH_SAFE(interfaces, interface, tmp) {
close(interface->socketfd);
DL_DELETE(interfaces, interface);
free(interface);
}
interfaces = NULL;
}
if (net_get_interfaces(&interfaces) <= 0) {
syslog(LOG_ERR, _("No devices found! Exiting.\n"));
exit(1);
}
setup_sockets();
/* Reassign outgoing interfaces to connections again, since they may have changed */
DL_FOREACH(connections_head, p) {
if (p->interface_name != NULL) {
struct net_interface *interface = net_get_interface_ptr(&interfaces, p->interface_name, 0);
if (interface != NULL) {
p->interface = interface;
} else {
struct mt_connection tmp;
syslog(LOG_NOTICE, _("(%d) Connection closed because interface %s is gone."), p->seskey, p->interface_name);
tmp.next = p->next;
list_remove_connection(p);
p = &tmp;
}
}
}
}
/*
* TODO: Rewrite main() when all sub-functionality is tested
*/
int main (int argc, char **argv) {
int result;
struct sockaddr_in si_me;
struct sockaddr_in si_me_mndp;
struct timeval timeout;
struct mt_packet pdata;
struct net_interface *interface;
fd_set read_fds;
int c,optval = 1;
int print_help = 0;
int foreground = 0;
int interface_count = 0;
setlocale(LC_ALL, "");
bindtextdomain("mactelnet","/usr/share/locale");
textdomain("mactelnet");
while ((c = getopt(argc, argv, "fnvh?")) != -1) {
switch (c) {
case 'f':
foreground = 1;
break;
case 'n':
use_raw_socket = 1;
break;
case 'v':
print_version();
exit(0);
break;
case 'h':
case '?':
print_help = 1;
break;
}
}
if (print_help) {
print_version();
fprintf(stderr, _("Usage: %s [-f|-n|-h]\n"), argv[0]);
if (print_help) {
fprintf(stderr, _("\nParameters:\n"
" -f Run process in foreground.\n"
" -n Do not use broadcast packets. Just a tad less insecure.\n"
" -h This help.\n"
"\n"));
}
return 1;
}
if (geteuid() != 0) {
fprintf(stderr, _("You need to have root privileges to use %s.\n"), argv[0]);
return 1;
}
/* Try to read user file */
read_userfile();
/* Seed randomizer */
srand(time(NULL));
if (use_raw_socket) {
/* Transmit raw packets with this socket */
sockfd = net_init_raw_socket();
}
/* Receive regular udp packets with this socket */
insockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (insockfd < 0) {
perror("insockfd");
return 1;
}
/* Set source port */
sourceport = MT_MACTELNET_PORT;
/* Listen address*/
inet_pton(AF_INET, (char *)"0.0.0.0", &sourceip);
/* Set up global info about the connection */
inet_pton(AF_INET, (char *)"255.255.255.255", &destip);
/* Initialize receiving socket on the device chosen */
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(sourceport);
memcpy(&(si_me.sin_addr), &sourceip, IPV4_ALEN);
setsockopt(insockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (optval));
/* Bind to udp port */
if (bind(insockfd, (struct sockaddr *)&si_me, sizeof(si_me))==-1) {
fprintf(stderr, _("Error binding to %s:%d, %s\n"), inet_ntoa(si_me.sin_addr), sourceport, strerror(errno));
return 1;
}
/* TODO: Move socket initialization out of main() */
/* Receive mndp udp packets with this socket */
mndpsockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (mndpsockfd < 0) {
perror("mndpsockfd");
return 1;
}
memset((char *)&si_me_mndp, 0, sizeof(si_me_mndp));
si_me_mndp.sin_family = AF_INET;
si_me_mndp.sin_port = htons(MT_MNDP_PORT);
memcpy(&(si_me_mndp.sin_addr), &sourceip, IPV4_ALEN);
setsockopt(mndpsockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (optval));
/* Bind to udp port */
if (bind(mndpsockfd, (struct sockaddr *)&si_me_mndp, sizeof(si_me_mndp))==-1) {
fprintf(stderr, _("MNDP: Error binding to %s:%d, %s\n"), inet_ntoa(si_me_mndp.sin_addr), MT_MNDP_PORT, strerror(errno));
}
openlog("mactelnetd", LOG_PID, LOG_DAEMON);
syslog(LOG_NOTICE, _("Bound to %s:%d"), inet_ntoa(si_me.sin_addr), sourceport);
/* Enumerate available interfaces */
net_get_interfaces(&interfaces);
setup_sockets();
if (!foreground) {
daemon(0, 0);
}
/* Handle zombies etc */
signal(SIGCHLD,SIG_IGN);
signal(SIGTSTP,SIG_IGN);
signal(SIGTTOU,SIG_IGN);
signal(SIGTTIN,SIG_IGN);
signal(SIGHUP, sighup_handler);
signal(SIGTERM, sigterm_handler);
DL_FOREACH(interfaces, interface) {
if (interface->has_mac) {
interface_count++;
}
}
if (interface_count == 0) {
syslog(LOG_ERR, _("Unable to find any valid network interfaces\n"));
exit(1);
}
while (1) {
int reads;
struct mt_connection *p;
int maxfd=0;
time_t now;
/* Init select */
FD_ZERO(&read_fds);
FD_SET(insockfd, &read_fds);
FD_SET(mndpsockfd, &read_fds);
maxfd = insockfd > mndpsockfd ? insockfd : mndpsockfd;
/* Add active connections to select queue */
DL_FOREACH(connections_head, p) {
if (p->state == STATE_ACTIVE && p->wait_for_ack == 0 && p->ptsfd > 0) {
FD_SET(p->ptsfd, &read_fds);
if (p->ptsfd > maxfd) {
maxfd = p->ptsfd;
}
}
}
timeout.tv_sec = 1;
timeout.tv_usec = 0;
/* Wait for data or timeout */
reads = select(maxfd+1, &read_fds, NULL, NULL, &timeout);
if (reads > 0) {
/* Handle data from clients
TODO: Enable broadcast support (without raw sockets)
*/
if (FD_ISSET(insockfd, &read_fds)) {
unsigned char buff[MT_PACKET_LEN];
struct sockaddr_in saddress;
unsigned int slen = sizeof(saddress);
bzero(buff, MT_HEADER_LEN);
result = recvfrom(insockfd, buff, sizeof(buff), 0, (struct sockaddr *)&saddress, &slen);
handle_packet(buff, result, &saddress);
}
if (FD_ISSET(mndpsockfd, &read_fds)) {
unsigned char buff[MT_PACKET_LEN];
struct sockaddr_in saddress;
unsigned int slen = sizeof(saddress);
result = recvfrom(mndpsockfd, buff, sizeof(buff), 0, (struct sockaddr *)&saddress, &slen);
/* Handle MNDP broadcast request, max 1 rps */
if (result == 4 && time(NULL) - last_mndp_time > 0) {
mndp_broadcast();
time(&last_mndp_time);
}
}
/* Handle data from terminal sessions */
DL_FOREACH(connections_head, p) {
/* Check if we have data ready in the pty buffer for the active session */
if (p->state == STATE_ACTIVE && p->ptsfd > 0 && p->wait_for_ack == 0 && FD_ISSET(p->ptsfd, &read_fds)) {
unsigned char keydata[1024];
int datalen,plen;
/* Read it */
datalen = read(p->ptsfd, &keydata, sizeof(keydata));
if (datalen > 0) {
/* Send it */
init_packet(&pdata, MT_PTYPE_DATA, p->dstmac, p->srcmac, p->seskey, p->outcounter);
plen = add_control_packet(&pdata, MT_CPTYPE_PLAINDATA, &keydata, datalen);
p->outcounter += plen;
p->wait_for_ack = 1;
result = send_udp(p, &pdata);
} else {
/* Shell exited */
struct mt_connection tmp;
init_packet(&pdata, MT_PTYPE_END, p->dstmac, p->srcmac, p->seskey, p->outcounter);
send_udp(p, &pdata);
if (p->username != NULL) {
syslog(LOG_INFO, _("(%d) Connection to user %s closed."), p->seskey, p->username);
} else {
syslog(LOG_INFO, _("(%d) Connection closed."), p->seskey);
}
tmp.next = p->next;
list_remove_connection(p);
p = &tmp;
}
}
else if (p->state == STATE_ACTIVE && p->ptsfd > 0 && p->wait_for_ack == 1 && FD_ISSET(p->ptsfd, &read_fds)) {
printf(_("(%d) Waiting for ack\n"), p->seskey);
}
}
/* Handle select() timeout */
}
time(&now);
if (now - last_mndp_time > MT_MNDP_BROADCAST_INTERVAL) {
pings = 0;
mndp_broadcast();
last_mndp_time = now;
}
if (connections_head != NULL) {
struct mt_connection *p,tmp;
DL_FOREACH(connections_head, p) {
if (now - p->lastdata >= MT_CONNECTION_TIMEOUT) {
syslog(LOG_INFO, _("(%d) Session timed out"), p->seskey);
init_packet(&pdata, MT_PTYPE_DATA, p->dstmac, p->srcmac, p->seskey, p->outcounter);
/*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */
add_control_packet(&pdata, MT_CPTYPE_PLAINDATA, _("Timeout\r\n"), 9);
send_udp(p, &pdata);
init_packet(&pdata, MT_PTYPE_END, p->dstmac, p->srcmac, p->seskey, p->outcounter);
send_udp(p, &pdata);
tmp.next = p->next;
list_remove_connection(p);
p = &tmp;
}
}
}
}
/* Never reached */
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5252_1 |
crossvul-cpp_data_bad_1848_2 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD %
% T H H R R E SS H H O O L D D %
% T HHHHH RRRR EEE SSS HHHHH O O L D D %
% T H H R R E SS H H O O L D D %
% T H H R R EEEEE SSSSS H H OOO LLLLL DDDD %
% %
% %
% MagickCore Image Threshold Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/property.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/configure.h"
#include "MagickCore/constitute.h"
#include "MagickCore/decorate.h"
#include "MagickCore/draw.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/effect.h"
#include "MagickCore/fx.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/montage.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum.h"
#include "MagickCore/random_.h"
#include "MagickCore/random-private.h"
#include "MagickCore/resize.h"
#include "MagickCore/resource_.h"
#include "MagickCore/segment.h"
#include "MagickCore/shear.h"
#include "MagickCore/signature-private.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/token.h"
#include "MagickCore/transform.h"
#include "MagickCore/xml-tree.h"
#include "MagickCore/xml-tree-private.h"
/*
Define declarations.
*/
#define ThresholdsFilename "thresholds.xml"
/*
Typedef declarations.
*/
struct _ThresholdMap
{
char
*map_id,
*description;
size_t
width,
height;
ssize_t
divisor,
*levels;
};
/*
Static declarations.
*/
static const char
*MinimalThresholdMap =
"<?xml version=\"1.0\"?>"
"<thresholds>"
" <threshold map=\"threshold\" alias=\"1x1\">"
" <description>Threshold 1x1 (non-dither)</description>"
" <levels width=\"1\" height=\"1\" divisor=\"2\">"
" 1"
" </levels>"
" </threshold>"
" <threshold map=\"checks\" alias=\"2x1\">"
" <description>Checkerboard 2x1 (dither)</description>"
" <levels width=\"2\" height=\"2\" divisor=\"3\">"
" 1 2"
" 2 1"
" </levels>"
" </threshold>"
"</thresholds>";
/*
Forward declarations.
*/
static ThresholdMap
*GetThresholdMapFile(const char *,const char *,const char *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d a p t i v e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AdaptiveThresholdImage() selects an individual threshold for each pixel
% based on the range of intensity values in its local neighborhood. This
% allows for thresholding of an image whose global intensity histogram
% doesn't contain distinctive peaks.
%
% The format of the AdaptiveThresholdImage method is:
%
% Image *AdaptiveThresholdImage(const Image *image,const size_t width,
% const size_t height,const double bias,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the width of the local neighborhood.
%
% o height: the height of the local neighborhood.
%
% o bias: the mean bias.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const double bias,
ExceptionInfo *exception)
{
#define AdaptiveThresholdImageTag "AdaptiveThreshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickSizeType
number_pixels;
ssize_t
y;
/*
Initialize threshold image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
threshold_image=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
status=SetImageStorageClass(threshold_image,DirectClass,exception);
if (status == MagickFalse)
{
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Threshold image.
*/
status=MagickTrue;
progress=0;
number_pixels=(MagickSizeType) width*height;
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
channel_bias[MaxPixelChannels],
channel_sum[MaxPixelChannels];
register const Quantum
*restrict p,
*restrict pixels;
register Quantum
*restrict q;
register ssize_t
i,
x;
ssize_t
center,
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
(height/2L),image->columns+width,height,exception);
q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,
1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+
GetPixelChannels(image)*(width/2);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if (((threshold_traits & CopyPixelTrait) != 0) ||
(GetPixelReadMask(image,p) == 0))
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
pixels=p;
channel_bias[channel]=0.0;
channel_sum[channel]=0.0;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
channel_bias[channel]+=pixels[i];
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image);
}
pixels+=GetPixelChannels(image)*image->columns;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
mean;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if (((threshold_traits & CopyPixelTrait) != 0) ||
(GetPixelReadMask(image,p) == 0))
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
channel_sum[channel]-=channel_bias[channel];
channel_bias[channel]=0.0;
pixels=p;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias[channel]+=pixels[i];
pixels+=(width-1)*GetPixelChannels(image);
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image)*(image->columns+1);
}
mean=(double) (channel_sum[channel]/number_pixels+bias);
SetPixelChannel(threshold_image,channel,(Quantum) ((double)
p[center+i] <= mean ? 0 : QuantumRange),q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(threshold_image);
}
if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_AdaptiveThresholdImage)
#endif
proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_image->type=image->type;
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B i l e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BilevelImage() changes the value of individual pixels based on the
% intensity of each pixel channel. The result is a high-contrast image.
%
% More precisely each channel value of the image is 'thresholded' so that if
% it is equal to or less than the given value it is set to zero, while any
% value greater than that give is set to it maximum or QuantumRange.
%
% This function is what is used to implement the "-threshold" operator for
% the command line API.
%
% If the default channel setting is given the image is thresholded using just
% the gray 'intensity' of the image, rather than the individual channels.
%
% The format of the BilevelImage method is:
%
% MagickBooleanType BilevelImage(Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: define the threshold values.
%
% o exception: return any errors or warnings in this structure.
%
% Aside: You can get the same results as operator using LevelImages()
% with the 'threshold' value for both the black_point and the white_point.
%
*/
MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
/*
Bilevel threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
pixel=GetPixelIntensity(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (image->channel_mask != DefaultChannels)
pixel=(double) q[i];
q[i]=(Quantum) (pixel <= threshold ? 0 : QuantumRange);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_BilevelImage)
#endif
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l a c k T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlackThresholdImage() is like ThresholdImage() but forces all pixels below
% the threshold into black while leaving all pixels at or above the threshold
% unchanged.
%
% The format of the BlackThresholdImage method is:
%
% MagickBooleanType BlackThresholdImage(Image *image,
% const char *threshold,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType BlackThresholdImage(Image *image,
const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
GetPixelInfo(image,&threshold);
flags=ParseGeometry(thresholds,&geometry_info);
threshold.red=geometry_info.rho;
threshold.green=geometry_info.rho;
threshold.blue=geometry_info.rho;
threshold.black=geometry_info.rho;
threshold.alpha=100.0;
if ((flags & SigmaValue) != 0)
threshold.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
threshold.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
threshold.alpha=geometry_info.psi;
if (threshold.colorspace == CMYKColorspace)
{
if ((flags & PsiValue) != 0)
threshold.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
threshold.alpha=geometry_info.chi;
}
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.black*=(MagickRealType) (QuantumRange/100.0);
threshold.alpha*=(MagickRealType) (QuantumRange/100.0);
}
/*
White threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
pixel=GetPixelIntensity(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (image->channel_mask != DefaultChannels)
pixel=(double) q[i];
if (pixel <= GetPixelInfoChannel(&threshold,channel))
q[i]=(Quantum) 0;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_BlackThresholdImage)
#endif
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l a m p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClampImage() set each pixel whose value is below zero to zero and any the
% pixel whose value is above the quantum range to the quantum range (e.g.
% 65535) otherwise the pixel value remains unchanged.
%
% The format of the ClampImage method is:
%
% MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline Quantum ClampPixel(const MagickRealType value)
{
#if !defined(MAGICKCORE_HDRI_SUPPORT)
return((Quantum) value);
#else
if (value < 0.0f)
return(0.0);
if (value >= (MagickRealType) QuantumRange)
return((Quantum) QuantumRange);
return(value);
#endif
}
MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
{
#define ClampImageTag "Clamp/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelInfo
*restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
q->red=(double) ClampPixel(q->red);
q->green=(double) ClampPixel(q->green);
q->blue=(double) ClampPixel(q->blue);
q->alpha=(double) ClampPixel(q->alpha);
q++;
}
return(SyncImage(image,exception));
}
/*
Clamp image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampPixel(q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ClampImage)
#endif
proceed=SetImageProgress(image,ClampImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyThresholdMap() de-allocate the given ThresholdMap
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *DestroyThresholdMap(Threshold *map)
%
% A description of each parameter follows.
%
% o map: Pointer to the Threshold map to destroy
%
*/
MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map)
{
assert(map != (ThresholdMap *) NULL);
if (map->map_id != (char *) NULL)
map->map_id=DestroyString(map->map_id);
if (map->description != (char *) NULL)
map->description=DestroyString(map->description);
if (map->levels != (ssize_t *) NULL)
map->levels=(ssize_t *) RelinquishMagickMemory(map->levels);
map=(ThresholdMap *) RelinquishMagickMemory(map);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMap() loads and searches one or more threshold map files for the
% map matching the given name or alias.
%
% The format of the GetThresholdMap method is:
%
% ThresholdMap *GetThresholdMap(const char *map_id,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o map_id: ID of the map to look for.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ThresholdMap *GetThresholdMap(const char *map_id,
ExceptionInfo *exception)
{
const StringInfo
*option;
LinkedListInfo
*options;
ThresholdMap
*map;
map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception);
if (map != (ThresholdMap *) NULL)
return(map);
options=GetConfigureOptions(ThresholdsFilename,exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
map=GetThresholdMapFile((const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),map_id,exception);
if (map != (ThresholdMap *) NULL)
break;
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMapFile() look for a given threshold map name or alias in the
% given XML file data, and return the allocated the map when found.
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *GetThresholdMap(const char *xml,const char *filename,
% const char *map_id,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o map_id: ID of the map to look for in XML list.
%
% o exception: return any errors or warnings in this structure.
%
*/
static ThresholdMap *GetThresholdMapFile(const char *xml,const char *filename,
const char *map_id,ExceptionInfo *exception)
{
char
*p;
const char
*attribute,
*content;
double
value;
register ssize_t
i;
ThresholdMap
*map;
XMLTreeInfo
*description,
*levels,
*threshold,
*thresholds;
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
map=(ThresholdMap *) NULL;
thresholds=NewXMLTree(xml,exception);
if (thresholds == (XMLTreeInfo *) NULL)
return(map);
for (threshold=GetXMLTreeChild(thresholds,"threshold");
threshold != (XMLTreeInfo *) NULL;
threshold=GetNextXMLTreeTag(threshold))
{
attribute=GetXMLTreeAttribute(threshold,"map");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
attribute=GetXMLTreeAttribute(threshold,"alias");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
}
if (threshold == (XMLTreeInfo *) NULL)
{
thresholds=DestroyXMLTree(thresholds);
return(map);
}
description=GetXMLTreeChild(threshold,"description");
if (description == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
levels=GetXMLTreeChild(threshold,"levels");
if (levels == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<levels>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
map=(ThresholdMap *) AcquireMagickMemory(sizeof(ThresholdMap));
if (map == (ThresholdMap *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
map->map_id=(char *) NULL;
map->description=(char *) NULL;
map->levels=(ssize_t *) NULL;
attribute=GetXMLTreeAttribute(threshold,"map");
if (attribute != (char *) NULL)
map->map_id=ConstantString(attribute);
content=GetXMLTreeContent(description);
if (content != (char *) NULL)
map->description=ConstantString(content);
attribute=GetXMLTreeAttribute(levels,"width");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels width>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->width=StringToUnsignedLong(attribute);
if (map->width == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels width>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels,"height");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels height>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->height=StringToUnsignedLong(attribute);
if (map->height == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels height>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels,"divisor");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels divisor>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->divisor=(ssize_t) StringToLong(attribute);
if (map->divisor < 2)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels divisor>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
content=GetXMLTreeContent(levels);
if (content == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<levels>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height*
sizeof(*map->levels));
if (map->levels == (ssize_t *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
for (i=0; i < (ssize_t) (map->width*map->height); i++)
{
map->levels[i]=(ssize_t) strtol(content,&p,10);
if (p == content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too few values, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
if ((map->levels[i] < 0) || (map->levels[i] > map->divisor))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> %.20g out of range, map \"%s\"",
(double) map->levels[i],map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
content=p;
}
value=(double) strtol(content,&p,10);
(void) value;
if (p != content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too many values, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
thresholds=DestroyXMLTree(thresholds);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L i s t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMapFile() lists the threshold maps and their descriptions
% in the given XML file data.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,const char*xml,
% const char *filename,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml,
const char *filename,ExceptionInfo *exception)
{
const char
*alias,
*content,
*map;
XMLTreeInfo
*description,
*threshold,
*thresholds;
assert( xml != (char *) NULL );
assert( file != (FILE *) NULL );
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
thresholds=NewXMLTree(xml,exception);
if ( thresholds == (XMLTreeInfo *) NULL )
return(MagickFalse);
(void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description");
(void) FormatLocaleFile(file,
"----------------------------------------------------\n");
threshold=GetXMLTreeChild(thresholds,"threshold");
for ( ; threshold != (XMLTreeInfo *) NULL;
threshold=GetNextXMLTreeTag(threshold))
{
map=GetXMLTreeAttribute(threshold,"map");
if (map == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<map>");
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
alias=GetXMLTreeAttribute(threshold,"alias");
description=GetXMLTreeChild(threshold,"description");
if (description == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"",map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
content=GetXMLTreeContent(description);
if (content == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<description>, map \"%s\"", map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
(void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "",
content);
}
thresholds=DestroyXMLTree(thresholds);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i s t T h r e s h o l d M a p s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMaps() lists the threshold maps and their descriptions
% as defined by "threshold.xml" to a file.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ListThresholdMaps(FILE *file,
ExceptionInfo *exception)
{
const StringInfo
*option;
LinkedListInfo
*options;
MagickStatusType
status;
status=MagickTrue;
if (file == (FILE *) NULL)
file=stdout;
options=GetConfigureOptions(ThresholdsFilename,exception);
(void) FormatLocaleFile(file,
"\n Threshold Maps for Ordered Dither Operations\n");
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
(void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option));
status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O r d e r e d P o s t e r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OrderedPosterizeImage() will perform a ordered dither based on a number
% of pre-defined dithering threshold maps, but over multiple intensity
% levels, which can be different for different channels, according to the
% input argument.
%
% The format of the OrderedPosterizeImage method is:
%
% MagickBooleanType OrderedPosterizeImage(Image *image,
% const char *threshold_map,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold_map: A string containing the name of the threshold dither
% map to use, followed by zero or more numbers representing the number
% of color levels tho dither between.
%
% Any level number less than 2 will be equivalent to 2, and means only
% binary dithering will be applied to each color channel.
%
% No numbers also means a 2 level (bitmap) dither will be applied to all
% channels, while a single number is the number of levels applied to each
% channel in sequence. More numbers will be applied in turn to each of
% the color channels.
%
% For example: "o3x3,6" will generate a 6 level posterization of the
% image with a ordered 3x3 diffused pixel dither being applied between
% each level. While checker,8,8,4 will produce a 332 colormaped image
% with only a single checkerboard hash pattern (50% grey) between each
% color level, to basically double the number of color levels with
% a bare minimim of dithering.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
const char *threshold_map,ExceptionInfo *exception)
{
#define DitherImageTag "Dither/Image"
CacheView
*image_view;
char
token[MaxTextExtent];
const char
*p;
double
levels[CompositePixelChannel];
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
ThresholdMap
*map;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (threshold_map == (const char *) NULL)
return(MagickTrue);
p=(char *) threshold_map;
while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) &&
(*p != '\0'))
p++;
threshold_map=p;
while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) &&
(*p != '\0'))
{
if ((p-threshold_map) >= (MaxTextExtent-1))
break;
token[p-threshold_map]=(*p);
p++;
}
token[p-threshold_map]='\0';
map=GetThresholdMap(token,exception);
if (map == (ThresholdMap *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : '%s'","ordered-dither",threshold_map);
return(MagickFalse);
}
for (i=0; i < MaxPixelChannels; i++)
levels[i]=2.0;
p=strchr((char *) threshold_map,',');
if ((p != (char *) NULL) && (isdigit((int) ((unsigned char) *(++p))) != 0))
for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++)
{
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
levels[i]=StringToDouble(token,(char **) NULL);
}
for (i=0; i < MaxPixelChannels; i++)
if (fabs(levels[i]) >= 1)
levels[i]-=1.0;
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
ssize_t
n;
n=0;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
ssize_t
level,
threshold;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (fabs(levels[n++]) < MagickEpsilon)
continue;
threshold=(ssize_t) (QuantumScale*q[i]*(levels[n]*(map->divisor-1)+1));
level=threshold/(map->divisor-1);
threshold-=level*(map->divisor-1);
q[i]=ClampToQuantum((double) (level+(threshold >=
map->levels[(x % map->width)+map->width*(y % map->height)]))*
QuantumRange/levels[n]);
n++;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_OrderedPosterizeImage)
#endif
proceed=SetImageProgress(image,DitherImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
map=DestroyThresholdMap(map);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P e r c e p t i b l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PerceptibleImage() set each pixel whose value is less than |epsilon| to
% epsilon or -epsilon (whichever is closer) otherwise the pixel value remains
% unchanged.
%
% The format of the PerceptibleImage method is:
%
% MagickBooleanType PerceptibleImage(Image *image,const double epsilon,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o epsilon: the epsilon threshold (e.g. 1.0e-9).
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline Quantum PerceptibleThreshold(const Quantum quantum,
const double epsilon)
{
double
sign;
sign=(double) quantum < 0.0 ? -1.0 : 1.0;
if ((sign*quantum) >= epsilon)
return(quantum);
return((Quantum) (sign*epsilon));
}
MagickExport MagickBooleanType PerceptibleImage(Image *image,
const double epsilon,ExceptionInfo *exception)
{
#define PerceptibleImageTag "Perceptible/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelInfo
*restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
q->red=(double) PerceptibleThreshold(ClampToQuantum(q->red),
epsilon);
q->green=(double) PerceptibleThreshold(ClampToQuantum(q->green),
epsilon);
q->blue=(double) PerceptibleThreshold(ClampToQuantum(q->blue),
epsilon);
q->alpha=(double) PerceptibleThreshold(ClampToQuantum(q->alpha),
epsilon);
q++;
}
return(SyncImage(image,exception));
}
/*
Perceptible image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PerceptibleThreshold(q[i],epsilon);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_PerceptibleImage)
#endif
proceed=SetImageProgress(image,PerceptibleImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R a n d o m T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RandomThresholdImage() changes the value of individual pixels based on the
% intensity of each pixel compared to a random threshold. The result is a
% low-contrast, two color image.
%
% The format of the RandomThresholdImage method is:
%
% MagickBooleanType RandomThresholdImage(Image *image,
% const char *thresholds,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o thresholds: a geometry string containing low,high thresholds. If the
% string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4
% is performed instead.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RandomThresholdImage(Image *image,
const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
double
min_threshold,
max_threshold;
GeometryInfo
geometry_info;
MagickStatusType
flags;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
threshold;
RandomInfo
**restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
GetPixelInfo(image,&threshold);
min_threshold=0.0;
max_threshold=(double) QuantumRange;
flags=ParseGeometry(thresholds,&geometry_info);
min_threshold=geometry_info.rho;
max_threshold=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
max_threshold=min_threshold;
if (strchr(thresholds,'%') != (char *) NULL)
{
max_threshold*=(double) (0.01*QuantumRange);
min_threshold*=(double) (0.01*QuantumRange);
}
/*
Random threshold image.
*/
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#endif
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
threshold;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if ((double) q[i] < min_threshold)
threshold=min_threshold;
else
if ((double) q[i] > max_threshold)
threshold=max_threshold;
else
threshold=(double) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
q[i]=(double) q[i] <= threshold ? 0 : QuantumRange;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_RandomThresholdImage)
#endif
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W h i t e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WhiteThresholdImage() is like ThresholdImage() but forces all pixels above
% the threshold into white while leaving all pixels at or below the threshold
% unchanged.
%
% The format of the WhiteThresholdImage method is:
%
% MagickBooleanType WhiteThresholdImage(Image *image,
% const char *threshold,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: Define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
GetPixelInfo(image,&threshold);
flags=ParseGeometry(thresholds,&geometry_info);
threshold.red=geometry_info.rho;
threshold.green=geometry_info.rho;
threshold.blue=geometry_info.rho;
threshold.black=geometry_info.rho;
threshold.alpha=100.0;
if ((flags & SigmaValue) != 0)
threshold.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
threshold.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
threshold.alpha=geometry_info.psi;
if (threshold.colorspace == CMYKColorspace)
{
if ((flags & PsiValue) != 0)
threshold.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
threshold.alpha=geometry_info.chi;
}
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.black*=(MagickRealType) (QuantumRange/100.0);
threshold.alpha*=(MagickRealType) (QuantumRange/100.0);
}
/*
White threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
pixel=GetPixelIntensity(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (image->channel_mask != DefaultChannels)
pixel=(double) q[i];
if (pixel > GetPixelInfoChannel(&threshold,channel))
q[i]=QuantumRange;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_WhiteThresholdImage)
#endif
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1848_2 |
crossvul-cpp_data_good_3173_0 | /* radare - LGPL - Copyright 2011-2016 - pancake */
#include <r_cons.h>
#include <r_types.h>
#include <r_util.h>
#include <r_lib.h>
#include <r_bin.h>
#include "dex/dex.h"
#define r_hash_adler32 __adler32
#include "../../hash/adler32.c"
extern struct r_bin_dbginfo_t r_bin_dbginfo_dex;
#define DEBUG_PRINTF 0
#if DEBUG_PRINTF
#define dprintf eprintf
#else
#define dprintf if (0)eprintf
#endif
static bool dexdump = false;
static Sdb *mdb = NULL;
static Sdb *cdb = NULL; // TODO: remove if it is not used
static char *getstr(RBinDexObj *bin, int idx) {
ut8 buf[6];
ut64 len;
int uleblen;
if (!bin || idx < 0 || idx >= bin->header.strings_size ||
!bin->strings) {
return NULL;
}
if (bin->strings[idx] >= bin->size) {
return NULL;
}
if (r_buf_read_at (bin->b, bin->strings[idx], buf, sizeof (buf)) < 1) {
return NULL;
}
uleblen = r_uleb128 (buf, sizeof (buf), &len) - buf;
if (!uleblen || uleblen >= bin->size) {
return NULL;
}
if (!len || len >= bin->size) {
return NULL;
}
// TODO: improve this ugly fix
char c = 'a';
while (c) {
ut64 offset = bin->strings[idx] + uleblen + len;
if (offset >= bin->size || offset < len) {
return NULL;
}
r_buf_read_at (bin->b, offset, (ut8*)&c, 1);
len++;
}
if ((int)len > 0 && len < R_BIN_SIZEOF_STRINGS) {
char *str = calloc (1, len + 1);
if (str) {
r_buf_read_at (bin->b, (bin->strings[idx]) + uleblen,
(ut8 *)str, len);
str[len] = 0;
return str;
}
}
return NULL;
}
static int countOnes(ut32 val) {
int count = 0;
val = val - ((val >> 1) & 0x55555555);
val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
count = (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
return count;
}
typedef enum {
kAccessForClass = 0,
kAccessForMethod = 1,
kAccessForField = 2,
kAccessForMAX
} AccessFor;
static char *createAccessFlagStr(ut32 flags, AccessFor forWhat) {
#define NUM_FLAGS 18
static const char* kAccessStrings[kAccessForMAX][NUM_FLAGS] = {
{
/* class, inner class */
"PUBLIC", /* 0x0001 */
"PRIVATE", /* 0x0002 */
"PROTECTED", /* 0x0004 */
"STATIC", /* 0x0008 */
"FINAL", /* 0x0010 */
"?", /* 0x0020 */
"?", /* 0x0040 */
"?", /* 0x0080 */
"?", /* 0x0100 */
"INTERFACE", /* 0x0200 */
"ABSTRACT", /* 0x0400 */
"?", /* 0x0800 */
"SYNTHETIC", /* 0x1000 */
"ANNOTATION", /* 0x2000 */
"ENUM", /* 0x4000 */
"?", /* 0x8000 */
"VERIFIED", /* 0x10000 */
"OPTIMIZED", /* 0x20000 */
},
{
/* method */
"PUBLIC", /* 0x0001 */
"PRIVATE", /* 0x0002 */
"PROTECTED", /* 0x0004 */
"STATIC", /* 0x0008 */
"FINAL", /* 0x0010 */
"SYNCHRONIZED", /* 0x0020 */
"BRIDGE", /* 0x0040 */
"VARARGS", /* 0x0080 */
"NATIVE", /* 0x0100 */
"?", /* 0x0200 */
"ABSTRACT", /* 0x0400 */
"STRICT", /* 0x0800 */
"SYNTHETIC", /* 0x1000 */
"?", /* 0x2000 */
"?", /* 0x4000 */
"MIRANDA", /* 0x8000 */
"CONSTRUCTOR", /* 0x10000 */
"DECLARED_SYNCHRONIZED", /* 0x20000 */
},
{
/* field */
"PUBLIC", /* 0x0001 */
"PRIVATE", /* 0x0002 */
"PROTECTED", /* 0x0004 */
"STATIC", /* 0x0008 */
"FINAL", /* 0x0010 */
"?", /* 0x0020 */
"VOLATILE", /* 0x0040 */
"TRANSIENT", /* 0x0080 */
"?", /* 0x0100 */
"?", /* 0x0200 */
"?", /* 0x0400 */
"?", /* 0x0800 */
"SYNTHETIC", /* 0x1000 */
"?", /* 0x2000 */
"ENUM", /* 0x4000 */
"?", /* 0x8000 */
"?", /* 0x10000 */
"?", /* 0x20000 */
},
};
const int kLongest = 21;
int i, count;
char* str;
char* cp;
count = countOnes(flags);
// XXX check if this allocation is safe what if all the arithmetic
// produces a huge number????
cp = str = (char*) malloc (count * (kLongest + 1) + 1);
for (i = 0; i < NUM_FLAGS; i++) {
if (flags & 0x01) {
const char* accessStr = kAccessStrings[forWhat][i];
int len = strlen(accessStr);
if (cp != str) {
*cp++ = ' ';
}
memcpy(cp, accessStr, len);
cp += len;
}
flags >>= 1;
}
*cp = '\0';
return str;
}
static char *dex_type_descriptor(RBinDexObj *bin, int type_idx) {
if (type_idx < 0 || type_idx >= bin->header.types_size) {
return NULL;
}
return getstr (bin, bin->types[type_idx].descriptor_id);
}
static char *dex_method_signature(RBinDexObj *bin, int method_idx) {
ut32 proto_id, params_off, type_id, list_size;
char *r, *return_type = NULL, *signature = NULL, *buff = NULL;
ut8 *bufptr;
ut16 type_idx;
int pos = 0, i, size = 1;
if (method_idx < 0 || method_idx >= bin->header.method_size) {
return NULL;
}
proto_id = bin->methods[method_idx].proto_id;
if (proto_id >= bin->header.prototypes_size) {
return NULL;
}
params_off = bin->protos[proto_id].parameters_off;
if (params_off >= bin->size) {
return NULL;
}
type_id = bin->protos[proto_id].return_type_id;
if (type_id >= bin->header.types_size ) {
return NULL;
}
return_type = getstr (bin, bin->types[type_id].descriptor_id);
if (!return_type) {
return NULL;
}
if (!params_off) {
return r_str_newf ("()%s", return_type);;
}
bufptr = bin->b->buf;
// size of the list, in entries
list_size = r_read_le32 (bufptr + params_off);
//XXX again list_size is user controlled huge loop
for (i = 0; i < list_size; i++) {
int buff_len = 0;
if (params_off + 4 + (i * 2) >= bin->size) {
break;
}
type_idx = r_read_le16 (bufptr + params_off + 4 + (i * 2));
if (type_idx < 0 ||
type_idx >=
bin->header.types_size || type_idx >= bin->size) {
break;
}
buff = getstr (bin, bin->types[type_idx].descriptor_id);
if (!buff) {
break;
}
buff_len = strlen (buff);
size += buff_len + 1;
signature = realloc (signature, size);
strcpy (signature + pos, buff);
pos += buff_len;
signature[pos] = '\0';
}
r = r_str_newf ("(%s)%s", signature, return_type);
free (buff);
free (signature);
return r;
}
static RList *dex_method_signature2(RBinDexObj *bin, int method_idx) {
ut32 proto_id, params_off, list_size;
char *buff = NULL;
ut8 *bufptr;
ut16 type_idx;
int i;
RList *params = r_list_newf (free);
if (!params) {
return NULL;
}
if (method_idx < 0 || method_idx >= bin->header.method_size) {
goto out_error;
}
proto_id = bin->methods[method_idx].proto_id;
if (proto_id >= bin->header.prototypes_size) {
goto out_error;
}
params_off = bin->protos[proto_id].parameters_off;
if (params_off >= bin->size) {
goto out_error;
}
if (!params_off) {
return params;
}
bufptr = bin->b->buf;
// size of the list, in entries
list_size = r_read_le32 (bufptr + params_off);
//XXX list_size tainted it may produce huge loop
for (i = 0; i < list_size; i++) {
ut64 of = params_off + 4 + (i * 2);
if (of >= bin->size || of < params_off) {
break;
}
type_idx = r_read_le16 (bufptr + of);
if (type_idx >= bin->header.types_size ||
type_idx > bin->size) {
break;
}
buff = getstr (bin, bin->types[type_idx].descriptor_id);
if (!buff) {
break;
}
r_list_append (params, buff);
}
return params;
out_error:
r_list_free (params);
return NULL;
}
// TODO: fix this, now has more registers that it should
// https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L312
// https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L141
static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, int MI, int MA, int paddr, int ins_size,
int insns_size, char *class_name, int regsz,
int debug_info_off) {
struct r_bin_t *rbin = binfile->rbin;
const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL);
const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off;
ut64 line_start;
ut64 parameters_size;
ut64 param_type_idx;
ut16 argReg = regsz - ins_size;
ut64 source_file_idx = c->source_file;
RList *params, *debug_positions, *emitted_debug_locals = NULL;
bool keep = true;
if (argReg > regsz) {
return; // this return breaks tests
}
p4 = r_uleb128 (p4, p4_end - p4, &line_start);
p4 = r_uleb128 (p4, p4_end - p4, ¶meters_size);
// TODO: check when we should use source_file
// The state machine consists of five registers
ut32 address = 0;
ut32 line = line_start;
if (!(debug_positions = r_list_newf ((RListFree)free))) {
return;
}
if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) {
r_list_free (debug_positions);
return;
}
struct dex_debug_local_t debug_locals[regsz];
memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz);
if (!(MA & 0x0008)) {
debug_locals[argReg].name = "this";
debug_locals[argReg].descriptor = r_str_newf("%s;", class_name);
debug_locals[argReg].startAddress = 0;
debug_locals[argReg].signature = NULL;
debug_locals[argReg].live = true;
argReg++;
}
if (!(params = dex_method_signature2 (bin, MI))) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
return;
}
RListIter *iter = r_list_iterator (params);
char *name;
char *type;
int reg;
r_list_foreach (params, iter, type) {
if ((argReg >= regsz) || !type || parameters_size <= 0) {
r_list_free (debug_positions);
r_list_free (params);
r_list_free (emitted_debug_locals);
return;
}
p4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1
param_type_idx -= 1;
name = getstr (bin, param_type_idx);
reg = argReg;
switch (type[0]) {
case 'D':
case 'J':
argReg += 2;
break;
default:
argReg += 1;
break;
}
if (name) {
debug_locals[reg].name = name;
debug_locals[reg].descriptor = type;
debug_locals[reg].signature = NULL;
debug_locals[reg].startAddress = address;
debug_locals[reg].live = true;
}
--parameters_size;
}
ut8 opcode = *(p4++) & 0xff;
while (keep) {
switch (opcode) {
case 0x0: // DBG_END_SEQUENCE
keep = false;
break;
case 0x1: // DBG_ADVANCE_PC
{
ut64 addr_diff;
p4 = r_uleb128 (p4, p4_end - p4, &addr_diff);
address += addr_diff;
}
break;
case 0x2: // DBG_ADVANCE_LINE
{
st64 line_diff = r_sleb128 (&p4, p4_end);
line += line_diff;
}
break;
case 0x3: // DBG_START_LOCAL
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
// Emit what was previously there, if anything
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = NULL;
debug_locals[register_num].live = true;
//eprintf("DBG_START_LOCAL %x %x %x\n", register_num, name_idx, type_idx);
}
break;
case 0x4: //DBG_START_LOCAL_EXTENDED
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
ut64 sig_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &sig_idx);
sig_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
// Emit what was previously there, if anything
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = getstr (bin, sig_idx);
debug_locals[register_num].live = true;
}
break;
case 0x5: // DBG_END_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].live = false;
}
break;
case 0x6: // DBG_RESTART_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (!debug_locals[register_num].live) {
debug_locals[register_num].startAddress = address;
debug_locals[register_num].live = true;
}
}
break;
case 0x7: //DBG_SET_PROLOGUE_END
break;
case 0x8: //DBG_SET_PROLOGUE_BEGIN
break;
case 0x9:
{
p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx);
source_file_idx--;
}
break;
default:
{
int adjusted_opcode = opcode - 0x0a;
address += (adjusted_opcode / 15);
line += -4 + (adjusted_opcode % 15);
struct dex_debug_position_t *position =
malloc (sizeof (struct dex_debug_position_t));
if (!position) {
keep = false;
break;
}
position->source_file_idx = source_file_idx;
position->address = address;
position->line = line;
r_list_append (debug_positions, position);
}
break;
}
opcode = *(p4++) & 0xff;
}
if (!binfile->sdb_addrinfo) {
binfile->sdb_addrinfo = sdb_new0 ();
}
char *fileline;
char offset[64];
char *offset_ptr;
RListIter *iter1;
struct dex_debug_position_t *pos;
r_list_foreach (debug_positions, iter1, pos) {
fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line);
offset_ptr = sdb_itoa (pos->address + paddr, offset, 16);
sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0);
sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0);
}
if (!dexdump) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
return;
}
RListIter *iter2;
struct dex_debug_position_t *position;
rbin->cb_printf (" positions :\n");
r_list_foreach (debug_positions, iter2, position) {
rbin->cb_printf (" 0x%04llx line=%llu\n",
position->address, position->line);
}
rbin->cb_printf (" locals :\n");
RListIter *iter3;
struct dex_debug_local_t *local;
r_list_foreach (emitted_debug_locals, iter3, local) {
if (local->signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor,
local->signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor);
}
}
for (reg = 0; reg < regsz; reg++) {
if (debug_locals[reg].live) {
if (debug_locals[reg].signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s "
"%s\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor,
debug_locals[reg].signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s"
"\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor);
}
}
}
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
}
static int check (RBinFile *arch);
static int check_bytes (const ut8 *buf, ut64 length);
static Sdb *get_sdb (RBinObject *o) {
if (!o || !o->bin_obj) {
return NULL;
}
struct r_bin_dex_obj_t *bin = (struct r_bin_dex_obj_t *) o->bin_obj;
if (bin->kv) {
return bin->kv;
}
return NULL;
}
static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loadaddr, Sdb *sdb){
void *res = NULL;
RBuffer *tbuf = NULL;
if (!buf || !sz || sz == UT64_MAX) {
return NULL;
}
tbuf = r_buf_new ();
if (!tbuf) {
return NULL;
}
r_buf_set_bytes (tbuf, buf, sz);
res = r_bin_dex_new_buf (tbuf);
r_buf_free (tbuf);
return res;
}
static int load(RBinFile *arch) {
const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL;
ut64 sz = arch ? r_buf_size (arch->buf): 0;
if (!arch || !arch->o) {
return false;
}
arch->o->bin_obj = load_bytes (arch, bytes, sz, arch->o->loadaddr, arch->sdb);
return arch->o->bin_obj ? true: false;
}
static ut64 baddr(RBinFile *arch) {
return 0;
}
static int check(RBinFile *arch) {
const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL;
ut64 sz = arch ? r_buf_size (arch->buf): 0;
return check_bytes (bytes, sz);
}
static int check_bytes(const ut8 *buf, ut64 length) {
if (!buf || length < 8) {
return false;
}
// Non-extended opcode dex file
if (!memcmp (buf, "dex\n035\0", 8)) {
return true;
}
// Extended (jumnbo) opcode dex file, ICS+ only (sdk level 14+)
if (!memcmp (buf, "dex\n036\0", 8)) {
return true;
}
// M3 (Nov-Dec 07)
if (!memcmp (buf, "dex\n009\0", 8)) {
return true;
}
// M5 (Feb-Mar 08)
if (!memcmp (buf, "dex\n009\0", 8)) {
return true;
}
// Default fall through, should still be a dex file
if (!memcmp (buf, "dex\n", 4)) {
return true;
}
return false;
}
static RBinInfo *info(RBinFile *arch) {
RBinHash *h;
RBinInfo *ret = R_NEW0 (RBinInfo);
if (!ret) {
return NULL;
}
ret->file = arch->file? strdup (arch->file): NULL;
ret->type = strdup ("DEX CLASS");
ret->has_va = false;
ret->bclass = r_bin_dex_get_version (arch->o->bin_obj);
ret->rclass = strdup ("class");
ret->os = strdup ("linux");
ret->subsystem = strdup ("any");
ret->machine = strdup ("Dalvik VM");
h = &ret->sum[0];
h->type = "sha1";
h->len = 20;
h->addr = 12;
h->from = 12;
h->to = arch->buf->length-32;
memcpy (h->buf, arch->buf->buf+12, 20);
h = &ret->sum[1];
h->type = "adler32";
h->len = 4;
h->addr = 0x8;
h->from = 12;
h->to = arch->buf->length-h->from;
h = &ret->sum[2];
h->type = 0;
memcpy (h->buf, arch->buf->buf + 8, 4);
{
ut32 *fc = (ut32 *)(arch->buf->buf + 8);
ut32 cc = __adler32 (arch->buf->buf + 12, arch->buf->length - 12);
if (*fc != cc) {
eprintf ("# adler32 checksum doesn't match. Type this to fix it:\n");
eprintf ("wx `#sha1 $s-32 @32` @12 ; wx `#adler32 $s-12 @12` @8\n");
}
}
ret->arch = strdup ("dalvik");
ret->lang = "dalvik";
ret->bits = 32;
ret->big_endian = 0;
ret->dbg_info = 0; //1 | 4 | 8; /* Stripped | LineNums | Syms */
return ret;
}
static RList *strings(RBinFile *arch) {
struct r_bin_dex_obj_t *bin = NULL;
RBinString *ptr = NULL;
RList *ret = NULL;
int i, len;
ut8 buf[6];
ut64 off;
if (!arch || !arch->o) {
return NULL;
}
bin = (struct r_bin_dex_obj_t *) arch->o->bin_obj;
if (!bin || !bin->strings) {
return NULL;
}
if (bin->header.strings_size > bin->size) {
bin->strings = NULL;
return NULL;
}
if (!(ret = r_list_newf (free))) {
return NULL;
}
for (i = 0; i < bin->header.strings_size; i++) {
if (!(ptr = R_NEW0 (RBinString))) {
break;
}
if (bin->strings[i] > bin->size || bin->strings[i] + 6 > bin->size) {
goto out_error;
}
r_buf_read_at (bin->b, bin->strings[i], (ut8*)&buf, 6);
len = dex_read_uleb128 (buf);
if (len > 1 && len < R_BIN_SIZEOF_STRINGS) {
ptr->string = malloc (len + 1);
if (!ptr->string) {
goto out_error;
}
off = bin->strings[i] + dex_uleb128_len (buf);
if (off + len >= bin->size || off + len < len) {
free (ptr->string);
goto out_error;
}
r_buf_read_at (bin->b, off, (ut8*)ptr->string, len);
ptr->string[len] = 0;
ptr->vaddr = ptr->paddr = bin->strings[i];
ptr->size = len;
ptr->length = len;
ptr->ordinal = i+1;
r_list_append (ret, ptr);
} else {
free (ptr);
}
}
return ret;
out_error:
r_list_free (ret);
free (ptr);
return NULL;
}
static char *dex_method_name(RBinDexObj *bin, int idx) {
if (idx < 0 || idx >= bin->header.method_size) {
return NULL;
}
int cid = bin->methods[idx].class_id;
if (cid < 0 || cid >= bin->header.strings_size) {
return NULL;
}
int tid = bin->methods[idx].name_id;
if (tid < 0 || tid >= bin->header.strings_size) {
return NULL;
}
return getstr (bin, tid);
}
static char *dex_class_name_byid(RBinDexObj *bin, int cid) {
int tid;
if (!bin || !bin->types) {
return NULL;
}
if (cid < 0 || cid >= bin->header.types_size) {
return NULL;
}
tid = bin->types[cid].descriptor_id;
return getstr (bin, tid);
}
static char *dex_class_name(RBinDexObj *bin, RBinDexClass *c) {
return dex_class_name_byid (bin, c->class_id);
}
static char *dex_field_name(RBinDexObj *bin, int fid) {
int cid, tid, type_id;
if (!bin || !bin->fields) {
return NULL;
}
if (fid < 0 || fid >= bin->header.fields_size) {
return NULL;
}
cid = bin->fields[fid].class_id;
if (cid < 0 || cid >= bin->header.types_size) {
return NULL;
}
type_id = bin->fields[fid].type_id;
if (type_id < 0 || type_id >= bin->header.types_size) {
return NULL;
}
tid = bin->fields[fid].name_id;
return r_str_newf ("%s->%s %s", getstr (bin, bin->types[cid].descriptor_id),
getstr (bin, tid), getstr (bin, bin->types[type_id].descriptor_id));
}
static char *dex_method_fullname(RBinDexObj *bin, int method_idx) {
if (!bin || !bin->types) {
return NULL;
}
if (method_idx < 0 || method_idx >= bin->header.method_size) {
return NULL;
}
int cid = bin->methods[method_idx].class_id;
if (cid < 0 || cid >= bin->header.types_size) {
return NULL;
}
char *name = dex_method_name (bin, method_idx);
char *class_name = dex_class_name_byid (bin, cid);
class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func
char *signature = dex_method_signature (bin, method_idx);
char *flagname = r_str_newf ("%s.%s%s", class_name, name, signature);
free (name);
free (class_name);
free (signature);
return flagname;
}
static ut64 dex_get_type_offset(RBinFile *arch, int type_idx) {
RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj;
if (!bin || !bin->types) {
return 0;
}
if (type_idx < 0 || type_idx >= bin->header.types_size) {
return 0;
}
return bin->header.types_offset + type_idx * 0x04; //&bin->types[type_idx];
}
static void __r_bin_class_free(RBinClass *p) {
r_list_free (p->methods);
r_list_free (p->fields);
r_bin_class_free (p);
}
static char *dex_class_super_name(RBinDexObj *bin, RBinDexClass *c) {
int cid, tid;
if (!bin || !c || !bin->types) {
return NULL;
}
cid = c->super_class;
if (cid < 0 || cid >= bin->header.types_size) {
return NULL;
}
tid = bin->types[cid].descriptor_id;
return getstr (bin, tid);
}
static const ut8 *parse_dex_class_fields(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, RBinClass *cls,
const ut8 *p, const ut8 *p_end,
int *sym_count, ut64 fields_count,
bool is_sfield) {
struct r_bin_t *rbin = binfile->rbin;
ut64 lastIndex = 0;
ut8 ff[sizeof (DexField)] = {0};
int total, i, tid;
DexField field;
const char* type_str;
for (i = 0; i < fields_count; i++) {
ut64 fieldIndex, accessFlags;
p = r_uleb128 (p, p_end - p, &fieldIndex); // fieldIndex
p = r_uleb128 (p, p_end - p, &accessFlags); // accessFlags
fieldIndex += lastIndex;
total = bin->header.fields_offset + (sizeof (DexField) * fieldIndex);
if (total >= bin->size || total < bin->header.fields_offset) {
break;
}
if (r_buf_read_at (binfile->buf, total, ff,
sizeof (DexField)) != sizeof (DexField)) {
break;
}
field.class_id = r_read_le16 (ff);
field.type_id = r_read_le16 (ff + 2);
field.name_id = r_read_le32 (ff + 4);
char *fieldName = getstr (bin, field.name_id);
if (field.type_id >= bin->header.types_size) {
break;
}
tid = bin->types[field.type_id].descriptor_id;
type_str = getstr (bin, tid);
RBinSymbol *sym = R_NEW0 (RBinSymbol);
if (is_sfield) {
sym->name = r_str_newf ("%s.sfield_%s:%s", cls->name,
fieldName, type_str);
sym->type = r_str_const ("STATIC");
} else {
sym->name = r_str_newf ("%s.ifield_%s:%s", cls->name,
fieldName, type_str);
sym->type = r_str_const ("FIELD");
}
sym->name = r_str_replace (sym->name, "method.", "", 0);
//sym->name = r_str_replace (sym->name, ";", "", 0);
sym->paddr = sym->vaddr = total;
sym->ordinal = (*sym_count)++;
if (dexdump) {
const char *accessStr = createAccessFlagStr (
accessFlags, kAccessForField);
rbin->cb_printf (" #%d : (in %s;)\n", i,
cls->name);
rbin->cb_printf (" name : '%s'\n", fieldName);
rbin->cb_printf (" type : '%s'\n", type_str);
rbin->cb_printf (" access : 0x%04x (%s)\n",
(unsigned int)accessFlags, accessStr);
}
r_list_append (bin->methods_list, sym);
r_list_append (cls->fields, sym);
lastIndex = fieldIndex;
}
return p;
}
// TODO: refactor this method
// XXX it needs a lot of love!!!
static const ut8 *parse_dex_class_method(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, RBinClass *cls,
const ut8 *p, const ut8 *p_end,
int *sym_count, ut64 DM, int *methods,
bool is_direct) {
struct r_bin_t *rbin = binfile->rbin;
ut8 ff2[16] = {0};
ut8 ff3[8] = {0};
int i;
ut64 omi = 0;
bool catchAll;
ut16 regsz, ins_size, outs_size, tries_size;
ut16 handler_off, start_addr, insn_count;
ut32 debug_info_off, insns_size;
const ut8 *encoded_method_addr;
for (i = 0; i < DM; i++) {
encoded_method_addr = p;
char *method_name, *flag_name;
ut64 MI, MA, MC;
p = r_uleb128 (p, p_end - p, &MI);
MI += omi;
omi = MI;
p = r_uleb128 (p, p_end - p, &MA);
p = r_uleb128 (p, p_end - p, &MC);
// TODO: MOVE CHECKS OUTSIDE!
if (MI < bin->header.method_size) {
if (methods) {
methods[MI] = 1;
}
}
method_name = dex_method_name (bin, MI);
char *signature = dex_method_signature (bin, MI);
if (!method_name) {
method_name = strdup ("unknown");
}
flag_name = r_str_newf ("%s.method.%s%s", cls->name,
method_name, signature);
if (!flag_name) {
R_FREE (method_name);
R_FREE (signature);
continue;
}
// TODO: check size
// ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4;
ut64 v2, handler_type, handler_addr;
int t;
if (MC > 0) {
// TODO: parse debug info
// XXX why binfile->buf->base???
if (MC + 16 >= bin->size || MC + 16 < MC) {
R_FREE (method_name);
R_FREE (flag_name);
R_FREE (signature);
continue;
}
if (r_buf_read_at (binfile->buf,
binfile->buf->base + MC, ff2,
16) < 1) {
R_FREE (method_name);
R_FREE (flag_name);
R_FREE (signature);
continue;
}
regsz = r_read_le16 (ff2);
ins_size = r_read_le16 (ff2 + 2);
outs_size = r_read_le16 (ff2 + 4);
tries_size = r_read_le16 (ff2 + 6);
debug_info_off = r_read_le32 (ff2 + 8);
insns_size = r_read_le32 (ff2 + 12);
int padd = 0;
if (tries_size > 0 && insns_size % 2) {
padd = 2;
}
t = 16 + 2 * insns_size + padd;
}
if (dexdump) {
const char* accessStr = createAccessFlagStr (MA, kAccessForMethod);
rbin->cb_printf (" #%d : (in %s;)\n", i, cls->name);
rbin->cb_printf (" name : '%s'\n", method_name);
rbin->cb_printf (" type : '%s'\n", signature);
rbin->cb_printf (" access : 0x%04x (%s)\n",
(unsigned int)MA, accessStr);
}
if (MC > 0) {
if (dexdump) {
rbin->cb_printf (" code -\n");
rbin->cb_printf (" registers : %d\n", regsz);
rbin->cb_printf (" ins : %d\n", ins_size);
rbin->cb_printf (" outs : %d\n", outs_size);
rbin->cb_printf (
" insns size : %d 16-bit code "
"units\n",
insns_size);
}
if (tries_size > 0) {
if (dexdump) {
rbin->cb_printf (" catches : %d\n", tries_size);
}
int j, m = 0;
//XXX bucle controlled by tainted variable it could produces huge loop
for (j = 0; j < tries_size; ++j) {
ut64 offset = MC + t + j * 8;
if (offset >= bin->size || offset < MC) {
R_FREE (signature);
break;
}
if (r_buf_read_at (
binfile->buf,
binfile->buf->base + offset,
ff3, 8) < 1) {
// free (method_name);
R_FREE (signature);
break;
}
start_addr = r_read_le32 (ff3);
insn_count = r_read_le16 (ff3 + 4);
handler_off = r_read_le16 (ff3 + 6);
char* s = NULL;
if (dexdump) {
rbin->cb_printf (
" 0x%04x - "
"0x%04x\n",
start_addr,
(start_addr +
insn_count));
}
const ut8 *p3, *p3_end;
//XXX tries_size is tainted and oob here
int off = MC + t + tries_size * 8 + handler_off;
if (off >= bin->size || off < tries_size) {
R_FREE (signature);
break;
}
p3 = r_buf_get_at (binfile->buf, off, NULL);
p3_end = p3 + binfile->buf->length - off;
st64 size = r_sleb128 (&p3, p3_end);
if (size <= 0) {
catchAll = true;
size = -size;
} else {
catchAll = false;
}
for (m = 0; m < size; m++) {
p3 = r_uleb128 (p3, p3_end - p3, &handler_type);
p3 = r_uleb128 (p3, p3_end - p3, &handler_addr);
if (handler_type > 0 &&
handler_type <
bin->header.types_size) {
s = getstr (bin, bin->types[handler_type].descriptor_id);
if (dexdump) {
rbin->cb_printf (
" %s "
"-> 0x%04llx\n",
s,
handler_addr);
}
} else {
if (dexdump) {
rbin->cb_printf (
" "
"(error) -> "
"0x%04llx\n",
handler_addr);
}
}
}
if (catchAll) {
p3 = r_uleb128 (p3, p3_end - p3, &v2);
if (dexdump) {
rbin->cb_printf (
" "
"<any> -> "
"0x%04llx\n",
v2);
}
}
}
} else {
if (dexdump) {
rbin->cb_printf (
" catches : "
"(none)\n");
}
}
} else {
if (dexdump) {
rbin->cb_printf (
" code : (none)\n");
}
}
if (*flag_name) {
RBinSymbol *sym = R_NEW0 (RBinSymbol);
sym->name = flag_name;
// is_direct is no longer used
// if method has code *addr points to code
// otherwise it points to the encoded method
if (MC > 0) {
sym->type = r_str_const ("FUNC");
sym->paddr = MC;// + 0x10;
sym->vaddr = MC;// + 0x10;
} else {
sym->type = r_str_const ("METH");
sym->paddr = encoded_method_addr - binfile->buf->buf;
sym->vaddr = encoded_method_addr - binfile->buf->buf;
}
if ((MA & 0x1) == 0x1) {
sym->bind = r_str_const ("GLOBAL");
} else {
sym->bind = r_str_const ("LOCAL");
}
sym->ordinal = (*sym_count)++;
if (MC > 0) {
if (r_buf_read_at (binfile->buf, binfile->buf->base + MC, ff2, 16) < 1) {
R_FREE (sym);
R_FREE (signature);
continue;
}
//ut16 regsz = r_read_le16 (ff2);
//ut16 ins_size = r_read_le16 (ff2 + 2);
//ut16 outs_size = r_read_le16 (ff2 + 4);
ut16 tries_size = r_read_le16 (ff2 + 6);
//ut32 debug_info_off = r_read_le32 (ff2 + 8);
ut32 insns_size = r_read_le32 (ff2 + 12);
ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4;
if (tries_size > 0) {
//prolog_size += 2 + 8*tries_size; // we need to parse all so the catch info...
}
// TODO: prolog_size
sym->paddr = MC + prolog_size;// + 0x10;
sym->vaddr = MC + prolog_size;// + 0x10;
//if (is_direct) {
sym->size = insns_size * 2;
//}
//eprintf("%s (0x%x-0x%x) size=%d\nregsz=%d\ninsns_size=%d\nouts_size=%d\ntries_size=%d\ninsns_size=%d\n", flag_name, sym->vaddr, sym->vaddr+sym->size, prolog_size, regsz, ins_size, outs_size, tries_size, insns_size);
r_list_append (bin->methods_list, sym);
r_list_append (cls->methods, sym);
if (bin->code_from > sym->paddr) {
bin->code_from = sym->paddr;
}
if (bin->code_to < sym->paddr) {
bin->code_to = sym->paddr;
}
if (!mdb) {
mdb = sdb_new0 ();
}
sdb_num_set (mdb, sdb_fmt (0, "method.%d", MI), sym->paddr, 0);
// -----------------
// WORK IN PROGRESS
// -----------------
if (0) {
if (MA & 0x10000) { //ACC_CONSTRUCTOR
if (!cdb) {
cdb = sdb_new0 ();
}
sdb_num_set (cdb, sdb_fmt (0, "%d", c->class_id), sym->paddr, 0);
}
}
} else {
sym->size = 0;
r_list_append (bin->methods_list, sym);
r_list_append (cls->methods, sym);
}
if (MC > 0 && debug_info_off > 0 && bin->header.data_offset < debug_info_off &&
debug_info_off < bin->header.data_offset + bin->header.data_size) {
dex_parse_debug_item (binfile, bin, c, MI, MA, sym->paddr, ins_size,
insns_size, cls->name, regsz, debug_info_off);
} else if (MC > 0) {
if (dexdump) {
rbin->cb_printf (" positions :\n");
rbin->cb_printf (" locals :\n");
}
}
} else {
R_FREE (flag_name);
}
R_FREE (signature);
R_FREE (method_name);
}
return p;
}
static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c,
int class_index, int *methods, int *sym_count) {
struct r_bin_t *rbin = binfile->rbin;
char *class_name;
int z;
const ut8 *p, *p_end;
if (!c) {
return;
}
class_name = dex_class_name (bin, c);
class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func
if (!class_name || !*class_name) {
return;
}
RBinClass *cls = R_NEW0 (RBinClass);
if (!cls) {
return;
}
cls->name = class_name;
cls->index = class_index;
cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE;
cls->methods = r_list_new ();
if (!cls->methods) {
free (cls);
return;
}
cls->fields = r_list_new ();
if (!cls->fields) {
r_list_free (cls->methods);
free (cls);
return;
}
r_list_append (bin->classes_list, cls);
if (dexdump) {
rbin->cb_printf (" Class descriptor : '%s;'\n", class_name);
rbin->cb_printf (
" Access flags : 0x%04x (%s)\n", c->access_flags,
createAccessFlagStr (c->access_flags, kAccessForClass));
rbin->cb_printf (" Superclass : '%s'\n",
dex_class_super_name (bin, c));
rbin->cb_printf (" Interfaces -\n");
}
if (c->interfaces_offset > 0 &&
bin->header.data_offset < c->interfaces_offset &&
c->interfaces_offset <
bin->header.data_offset + bin->header.data_size) {
p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL);
int types_list_size = r_read_le32 (p);
if (types_list_size < 0 || types_list_size >= bin->header.types_size ) {
return;
}
for (z = 0; z < types_list_size; z++) {
int t = r_read_le16 (p + 4 + z * 2);
if (t > 0 && t < bin->header.types_size ) {
int tid = bin->types[t].descriptor_id;
if (dexdump) {
rbin->cb_printf (
" #%d : '%s'\n",
z, getstr (bin, tid));
}
}
}
}
// TODO: this is quite ugly
if (!c || !c->class_data_offset) {
if (dexdump) {
rbin->cb_printf (
" Static fields -\n Instance fields "
"-\n Direct methods -\n Virtual methods "
"-\n");
}
} else {
// TODO: move to func, def or inline
// class_data_offset => [class_offset, class_defs_off+class_defs_size*32]
if (bin->header.class_offset > c->class_data_offset ||
c->class_data_offset <
bin->header.class_offset +
bin->header.class_size * DEX_CLASS_SIZE) {
return;
}
p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL);
p_end = p + binfile->buf->length - c->class_data_offset;
//XXX check for NULL!!
c->class_data = (struct dex_class_data_item_t *)malloc (
sizeof (struct dex_class_data_item_t));
p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size);
p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size);
if (dexdump) {
rbin->cb_printf (" Static fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->static_fields_size, true);
if (dexdump) {
rbin->cb_printf (" Instance fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->instance_fields_size, false);
if (dexdump) {
rbin->cb_printf (" Direct methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->direct_methods_size, methods, true);
if (dexdump) {
rbin->cb_printf (" Virtual methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->virtual_methods_size, methods, false);
}
if (dexdump) {
char *source_file = getstr (bin, c->source_file);
if (!source_file) {
rbin->cb_printf (
" source_file_idx : %d (unknown)\n\n",
c->source_file);
} else {
rbin->cb_printf (" source_file_idx : %d (%s)\n\n",
c->source_file, source_file);
}
}
// TODO:!!!!
// FIX: FREE BEFORE ALLOCATE!!!
//free (class_name);
}
static bool is_class_idx_in_code_classes(RBinDexObj *bin, int class_idx) {
int i;
for (i = 0; i < bin->header.class_size; i++) {
if (class_idx == bin->classes[i].class_id) {
return true;
}
}
return false;
}
static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) {
struct r_bin_t *rbin = arch->rbin;
int i;
int *methods = NULL;
int sym_count = 0;
// doublecheck??
if (!bin || bin->methods_list) {
return false;
}
bin->code_from = UT64_MAX;
bin->code_to = 0;
bin->methods_list = r_list_newf ((RListFree)free);
if (!bin->methods_list) {
return false;
}
bin->imports_list = r_list_newf ((RListFree)free);
if (!bin->imports_list) {
r_list_free (bin->methods_list);
return false;
}
bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free);
if (!bin->classes_list) {
r_list_free (bin->methods_list);
r_list_free (bin->imports_list);
return false;
}
if (bin->header.method_size>bin->size) {
bin->header.method_size = 0;
return false;
}
/* WrapDown the header sizes to avoid huge allocations */
bin->header.method_size = R_MIN (bin->header.method_size, bin->size);
bin->header.class_size = R_MIN (bin->header.class_size, bin->size);
bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size);
// TODO: is this posible after R_MIN ??
if (bin->header.strings_size > bin->size) {
eprintf ("Invalid strings size\n");
return false;
}
if (bin->classes) {
ut64 amount = sizeof (int) * bin->header.method_size;
if (amount > UT32_MAX || amount < bin->header.method_size) {
return false;
}
methods = calloc (1, amount + 1);
for (i = 0; i < bin->header.class_size; i++) {
char *super_name, *class_name;
struct dex_class_t *c = &bin->classes[i];
class_name = dex_class_name (bin, c);
super_name = dex_class_super_name (bin, c);
if (dexdump) {
rbin->cb_printf ("Class #%d -\n", i);
}
parse_class (arch, bin, c, i, methods, &sym_count);
free (class_name);
free (super_name);
}
}
if (methods) {
int import_count = 0;
int sym_count = bin->methods_list->length;
for (i = 0; i < bin->header.method_size; i++) {
int len = 0;
if (methods[i]) {
continue;
}
if (bin->methods[i].class_id > bin->header.types_size - 1) {
continue;
}
if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) {
continue;
}
char *class_name = getstr (
bin, bin->types[bin->methods[i].class_id]
.descriptor_id);
if (!class_name) {
free (class_name);
continue;
}
len = strlen (class_name);
if (len < 1) {
continue;
}
class_name[len - 1] = 0; // remove last char ";"
char *method_name = dex_method_name (bin, i);
char *signature = dex_method_signature (bin, i);
if (method_name && *method_name) {
RBinImport *imp = R_NEW0 (RBinImport);
imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature);
imp->type = r_str_const ("FUNC");
imp->bind = r_str_const ("NONE");
imp->ordinal = import_count++;
r_list_append (bin->imports_list, imp);
RBinSymbol *sym = R_NEW0 (RBinSymbol);
sym->name = r_str_newf ("imp.%s", imp->name);
sym->type = r_str_const ("FUNC");
sym->bind = r_str_const ("NONE");
//XXX so damn unsafe check buffer boundaries!!!!
//XXX use r_buf API!!
sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ;
sym->ordinal = sym_count++;
r_list_append (bin->methods_list, sym);
sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0);
}
free (method_name);
free (signature);
free (class_name);
}
free (methods);
}
return true;
}
static RList* imports(RBinFile *arch) {
RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj;
if (!bin) {
return NULL;
}
if (bin && bin->imports_list) {
return bin->imports_list;
}
dex_loadcode (arch, bin);
return bin->imports_list;
}
static RList *methods(RBinFile *arch) {
RBinDexObj *bin;
if (!arch || !arch->o || !arch->o->bin_obj) {
return NULL;
}
bin = (RBinDexObj*) arch->o->bin_obj;
if (!bin->methods_list) {
dex_loadcode (arch, bin);
}
return bin->methods_list;
}
static RList *classes(RBinFile *arch) {
RBinDexObj *bin;
if (!arch || !arch->o || !arch->o->bin_obj) {
return NULL;
}
bin = (RBinDexObj*) arch->o->bin_obj;
if (!bin->classes_list) {
dex_loadcode (arch, bin);
}
return bin->classes_list;
}
static int already_entry(RList *entries, ut64 vaddr) {
RBinAddr *e;
RListIter *iter;
r_list_foreach (entries, iter, e) {
if (e->vaddr == vaddr) {
return 1;
}
}
return 0;
}
static RList *entries(RBinFile *arch) {
RListIter *iter;
RBinDexObj *bin;
RBinSymbol *m;
RBinAddr *ptr;
RList *ret;
if (!arch || !arch->o || !arch->o->bin_obj) {
return NULL;
}
bin = (RBinDexObj*) arch->o->bin_obj;
ret = r_list_newf ((RListFree)free);
if (!bin->methods_list) {
dex_loadcode (arch, bin);
}
// STEP 1. ".onCreate(Landroid/os/Bundle;)V"
r_list_foreach (bin->methods_list, iter, m) {
if (strlen (m->name) > 30 && m->bind &&
!strcmp(m->bind, "GLOBAL") &&
!strcmp (m->name + strlen (m->name) - 31,
".onCreate(Landroid/os/Bundle;)V")) {
if (!already_entry (ret, m->paddr)) {
if ((ptr = R_NEW0 (RBinAddr))) {
ptr->paddr = ptr->vaddr = m->paddr;
r_list_append (ret, ptr);
}
}
}
}
// STEP 2. ".main([Ljava/lang/String;)V"
if (r_list_empty (ret)) {
r_list_foreach (bin->methods_list, iter, m) {
if (strlen (m->name) > 26 &&
!strcmp (m->name + strlen (m->name) - 27,
".main([Ljava/lang/String;)V")) {
if (!already_entry (ret, m->paddr)) {
if ((ptr = R_NEW0 (RBinAddr))) {
ptr->paddr = ptr->vaddr = m->paddr;
r_list_append (ret, ptr);
}
}
}
}
}
// STEP 3. NOTHING FOUND POINT TO CODE_INIT
if (r_list_empty (ret)) {
if (!already_entry (ret, bin->code_from)) {
ptr = R_NEW0 (RBinAddr);
if (ptr) {
ptr->paddr = ptr->vaddr = bin->code_from;
r_list_append (ret, ptr);
}
}
}
return ret;
}
static ut64 offset_of_method_idx(RBinFile *arch, struct r_bin_dex_obj_t *dex, int idx) {
ut64 off = dex->header.method_offset + idx;
off = sdb_num_get (mdb, sdb_fmt (0, "method.%d", idx), 0);
return (ut64) off;
}
// TODO: change all return type for all getoffset
static int getoffset(RBinFile *arch, int type, int idx) {
struct r_bin_dex_obj_t *dex = arch->o->bin_obj;
switch (type) {
case 'm': // methods
// TODO: ADD CHECK
return offset_of_method_idx (arch, dex, idx);
case 'o': // objects
break;
case 's': // strings
if (dex->header.strings_size > idx) {
if (dex->strings) return dex->strings[idx];
}
break;
case 't': // type
return dex_get_type_offset (arch, idx);
case 'c': // class
return dex_get_type_offset (arch, idx);
//return sdb_num_get (cdb, sdb_fmt (0, "%d", idx), 0);
}
return -1;
}
static char *getname(RBinFile *arch, int type, int idx) {
struct r_bin_dex_obj_t *dex = arch->o->bin_obj;
switch (type) {
case 'm': // methods
return dex_method_fullname (dex, idx);
case 'c': // classes
return dex_class_name_byid (dex, idx);
case 'f': // fields
return dex_field_name (dex, idx);
}
return NULL;
}
static RList *sections(RBinFile *arch) {
struct r_bin_dex_obj_t *bin = arch->o->bin_obj;
RList *ml = methods (arch);
RBinSection *ptr = NULL;
int ns, fsymsz = 0;
RList *ret = NULL;
RListIter *iter;
RBinSymbol *m;
int fsym = 0;
r_list_foreach (ml, iter, m) {
if (!fsym || m->paddr < fsym) {
fsym = m->paddr;
}
ns = m->paddr + m->size;
if (ns > arch->buf->length) {
continue;
}
if (ns > fsymsz) {
fsymsz = ns;
}
}
if (!fsym) {
return NULL;
}
if (!(ret = r_list_new ())) {
return NULL;
}
ret->free = free;
if ((ptr = R_NEW0 (RBinSection))) {
strcpy (ptr->name, "header");
ptr->size = ptr->vsize = sizeof (struct dex_header_t);
ptr->paddr= ptr->vaddr = 0;
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP;
ptr->add = true;
r_list_append (ret, ptr);
}
if ((ptr = R_NEW0 (RBinSection))) {
strcpy (ptr->name, "constpool");
//ptr->size = ptr->vsize = fsym;
ptr->paddr= ptr->vaddr = sizeof (struct dex_header_t);
ptr->size = bin->code_from - ptr->vaddr; // fix size
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP;
ptr->add = true;
r_list_append (ret, ptr);
}
if ((ptr = R_NEW0 (RBinSection))) {
strcpy (ptr->name, "code");
ptr->vaddr = ptr->paddr = bin->code_from; //ptr->vaddr = fsym;
ptr->size = bin->code_to - ptr->paddr;
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_EXECUTABLE | R_BIN_SCN_MAP;
ptr->add = true;
r_list_append (ret, ptr);
}
if ((ptr = R_NEW0 (RBinSection))) {
//ut64 sz = arch ? r_buf_size (arch->buf): 0;
strcpy (ptr->name, "data");
ptr->paddr = ptr->vaddr = fsymsz+fsym;
if (ptr->vaddr > arch->buf->length) {
ptr->paddr = ptr->vaddr = bin->code_to;
ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr;
} else {
ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr;
// hacky workaround
//dprintf ("Hack\n");
//ptr->size = ptr->vsize = 1024;
}
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; //|2;
ptr->add = true;
r_list_append (ret, ptr);
}
return ret;
}
static void header(RBinFile *arch) {
struct r_bin_dex_obj_t *bin = arch->o->bin_obj;
struct r_bin_t *rbin = arch->rbin;
rbin->cb_printf ("DEX file header:\n");
rbin->cb_printf ("magic : 'dex\\n035\\0'\n");
rbin->cb_printf ("checksum : %x\n", bin->header.checksum);
rbin->cb_printf ("signature : %02x%02x...%02x%02x\n", bin->header.signature[0], bin->header.signature[1], bin->header.signature[18], bin->header.signature[19]);
rbin->cb_printf ("file_size : %d\n", bin->header.size);
rbin->cb_printf ("header_size : %d\n", bin->header.header_size);
rbin->cb_printf ("link_size : %d\n", bin->header.linksection_size);
rbin->cb_printf ("link_off : %d (0x%06x)\n", bin->header.linksection_offset, bin->header.linksection_offset);
rbin->cb_printf ("string_ids_size : %d\n", bin->header.strings_size);
rbin->cb_printf ("string_ids_off : %d (0x%06x)\n", bin->header.strings_offset, bin->header.strings_offset);
rbin->cb_printf ("type_ids_size : %d\n", bin->header.types_size);
rbin->cb_printf ("type_ids_off : %d (0x%06x)\n", bin->header.types_offset, bin->header.types_offset);
rbin->cb_printf ("proto_ids_size : %d\n", bin->header.prototypes_size);
rbin->cb_printf ("proto_ids_off : %d (0x%06x)\n", bin->header.prototypes_offset, bin->header.prototypes_offset);
rbin->cb_printf ("field_ids_size : %d\n", bin->header.fields_size);
rbin->cb_printf ("field_ids_off : %d (0x%06x)\n", bin->header.fields_offset, bin->header.fields_offset);
rbin->cb_printf ("method_ids_size : %d\n", bin->header.method_size);
rbin->cb_printf ("method_ids_off : %d (0x%06x)\n", bin->header.method_offset, bin->header.method_offset);
rbin->cb_printf ("class_defs_size : %d\n", bin->header.class_size);
rbin->cb_printf ("class_defs_off : %d (0x%06x)\n", bin->header.class_offset, bin->header.class_offset);
rbin->cb_printf ("data_size : %d\n", bin->header.data_size);
rbin->cb_printf ("data_off : %d (0x%06x)\n\n", bin->header.data_offset, bin->header.data_offset);
// TODO: print information stored in the RBIN not this ugly fix
dexdump = true;
bin->methods_list = NULL;
dex_loadcode (arch, bin);
dexdump = false;
}
static ut64 size(RBinFile *arch) {
int ret;
ut32 off = 0, len = 0;
ut8 u32s[sizeof (ut32)] = {0};
ret = r_buf_read_at (arch->buf, 108, u32s, 4);
if (ret != 4) {
return 0;
}
off = r_read_le32 (u32s);
ret = r_buf_read_at (arch->buf, 104, u32s, 4);
if (ret != 4) {
return 0;
}
len = r_read_le32 (u32s);
return off + len;
}
RBinPlugin r_bin_plugin_dex = {
.name = "dex",
.desc = "dex format bin plugin",
.license = "LGPL3",
.get_sdb = &get_sdb,
.load = &load,
.load_bytes = &load_bytes,
.check = &check,
.check_bytes = &check_bytes,
.baddr = &baddr,
.entries = entries,
.classes = classes,
.sections = sections,
.symbols = methods,
.imports = imports,
.strings = strings,
.info = &info,
.header = &header,
.size = &size,
.get_offset = &getoffset,
.get_name = &getname,
.dbginfo = &r_bin_dbginfo_dex,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_BIN,
.data = &r_bin_plugin_dex,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3173_0 |
crossvul-cpp_data_bad_339_5 | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Initially written by David Mattes <david.mattes@boeing.com> */
/* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "internal.h"
#include "pkcs15.h"
#define MANU_ID "Gemplus"
#define APPLET_NAME "GemSAFE V1"
#define DRIVER_SERIAL_NUMBER "v0.9"
#define GEMSAFE_APP_PATH "3F001600"
#define GEMSAFE_PATH "3F0016000004"
/* Apparently, the Applet max read "quanta" is 248 bytes
* Gemalto ClassicClient reads files in chunks of 238 bytes
*/
#define GEMSAFE_READ_QUANTUM 248
#define GEMSAFE_MAX_OBJLEN 28672
int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *);
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags);
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags);
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags);
typedef struct cdata_st {
char *label;
int authority;
const char *path;
size_t index;
size_t count;
const char *id;
int obj_flags;
} cdata;
const unsigned int gemsafe_cert_max = 12;
cdata gemsafe_cert[] = {
{"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE},
};
typedef struct pdata_st {
const u8 atr[SC_MAX_ATR_SIZE];
const size_t atr_len;
const char *id;
const char *label;
const char *path;
const int ref;
const int type;
const unsigned int maxlen;
const unsigned int minlen;
const int flags;
const int tries_left;
const char pad_char;
const int obj_flags;
} pindata;
const unsigned int gemsafe_pin_max = 2;
const pindata gemsafe_pin[] = {
/* ATR-specific PIN policies, first match found is used: */
{ {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65,
0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC,
8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE },
/* default PIN policy comes last: */
{ { 0 }, 0,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD,
16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }
};
typedef struct prdata_st {
const char *id;
char *label;
unsigned int modulus_len;
int usage;
const char *path;
int ref;
const char *auth_id;
int obj_flags;
} prdata;
#define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION
#define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP
#define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP | \
SC_PKCS15_PRKEY_USAGE_SIGN
prdata gemsafe_prkeys[] = {
{ "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE},
};
static int gemsafe_get_cert_len(sc_card_t *card)
{
int r;
u8 ibuf[GEMSAFE_MAX_OBJLEN];
u8 *iptr;
struct sc_path path;
struct sc_file *file;
size_t objlen, certlen;
unsigned int ind, i=0;
sc_format_path(GEMSAFE_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* Initial read */
r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0);
if (r < 0)
return SC_ERROR_INTERNAL;
/* Actual stored object size is encoded in first 2 bytes
* (allocated EF space is much greater!)
*/
objlen = (((size_t) ibuf[0]) << 8) | ibuf[1];
sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) {
sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
return SC_ERROR_INTERNAL;
}
/* It looks like the first thing in the block is a table of
* which keys are allocated. The table is small and is in the
* first 248 bytes. Example for a card with 10 key containers:
* 01 f0 00 03 03 b0 00 03 <= 1st key unallocated
* 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated
* 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated
* 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated
* 01 f0 00 07 03 b0 00 07 <= 5th key unallocated
* ...
* 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated
* For allocated keys, the fourth byte seems to indicate the
* default key and the fifth byte indicates the key_ref of
* the private key.
*/
ind = 2; /* skip length */
while (ibuf[ind] == 0x01) {
if (ibuf[ind+1] == 0xFE) {
gemsafe_prkeys[i].ref = ibuf[ind+4];
sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d",
i+1, gemsafe_prkeys[i].ref);
ind += 9;
}
else {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
sc_log(card->ctx, "Key container %d is unallocated", i+1);
ind += 8;
}
i++;
}
/* Delete additional key containers from the data structures if
* this card can't accommodate them.
*/
for (; i < gemsafe_cert_max; i++) {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
/* Read entire file, then dissect in memory.
* Gemalto ClassicClient seems to do it the same way.
*/
iptr = ibuf + GEMSAFE_READ_QUANTUM;
while ((size_t)(iptr - ibuf) < objlen) {
r = sc_read_binary(card, iptr - ibuf, iptr,
MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0);
if (r < 0) {
sc_log(card->ctx, "Could not read cert object");
return SC_ERROR_INTERNAL;
}
iptr += GEMSAFE_READ_QUANTUM;
}
/* Search buffer for certificates, they start with 0x3082. */
i = 0;
while (ind < objlen - 1) {
if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) {
/* Find next allocated key container */
while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL)
i++;
if (i == gemsafe_cert_max) {
sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind);
return SC_SUCCESS;
}
/* DER cert len is encoded this way */
if (ind+3 >= sizeof ibuf)
return SC_ERROR_INVALID_DATA;
certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4;
sc_log(card->ctx,
"Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u",
i+1, ind, certlen);
gemsafe_cert[i].index = ind;
gemsafe_cert[i].count = certlen;
ind += certlen;
i++;
} else
ind++;
}
/* Delete additional key containers from the data structures if
* they're missing on the card.
*/
for (; i < gemsafe_cert_max; i++) {
if (gemsafe_cert[i].label) {
sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1);
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
}
return SC_SUCCESS;
}
static int gemsafe_detect_card( sc_pkcs15_card_t *p15card)
{
if (strcmp(p15card->card->name, "GemSAFE V1"))
return SC_ERROR_WRONG_CARD;
return SC_SUCCESS;
}
static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card)
{
int r;
unsigned int i;
struct sc_path path;
struct sc_file *file = NULL;
struct sc_card *card = p15card->card;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_log(p15card->card->ctx, "Setting pkcs15 parameters");
if (p15card->tokeninfo->label)
free(p15card->tokeninfo->label);
p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1);
if (!p15card->tokeninfo->label)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->label, APPLET_NAME);
if (p15card->tokeninfo->serial_number)
free(p15card->tokeninfo->serial_number);
p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1);
if (!p15card->tokeninfo->serial_number)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER);
/* the GemSAFE applet version number */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
/* Manual says Le=0x05, but should be 0x08 to return full version number */
apdu.le = 0x08;
apdu.lc = 0;
apdu.datalen = 0;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return SC_ERROR_INTERNAL;
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* the manufacturer ID, in this case GemPlus */
if (p15card->tokeninfo->manufacturer_id)
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1);
if (!p15card->tokeninfo->manufacturer_id)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID);
/* determine allocated key containers and length of certificates */
r = gemsafe_get_cert_len(card);
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* set certs */
sc_log(p15card->card->ctx, "Setting certificates");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
if (gemsafe_cert[i].label == NULL)
continue;
sc_format_path(gemsafe_cert[i].path, &path);
sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id);
path.index = gemsafe_cert[i].index;
path.count = gemsafe_cert[i].count;
sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509,
gemsafe_cert[i].authority, &path, &p15Id,
gemsafe_cert[i].label, gemsafe_cert[i].obj_flags);
}
/* set gemsafe_pin */
sc_log(p15card->card->ctx, "Setting PIN");
for (i=0; i < gemsafe_pin_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id);
sc_format_path(gemsafe_pin[i].path, &path);
if (gemsafe_pin[i].atr_len == 0 ||
(gemsafe_pin[i].atr_len == p15card->card->atr.len &&
memcmp(p15card->card->atr.value, gemsafe_pin[i].atr,
p15card->card->atr.len) == 0)) {
sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label,
&path, gemsafe_pin[i].ref, gemsafe_pin[i].type,
gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen,
gemsafe_pin[i].flags, gemsafe_pin[i].tries_left,
gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags);
break;
}
};
/* set private keys */
sc_log(p15card->card->ctx, "Setting private keys");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id, authId, *pauthId;
struct sc_path path;
int key_ref = 0x03;
if (gemsafe_prkeys[i].label == NULL)
continue;
sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id);
if (gemsafe_prkeys[i].auth_id) {
sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId);
pauthId = &authId;
} else
pauthId = NULL;
sc_format_path(gemsafe_prkeys[i].path, &path);
/*
* The key ref may be different for different sites;
* by adding flags=n where the low order 4 bits can be
* the key ref we can force it.
*/
if ( p15card->card->flags & 0x0F) {
key_ref = p15card->card->flags & 0x0F;
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Overriding key_ref %d with %d\n",
gemsafe_prkeys[i].ref, key_ref);
} else
key_ref = gemsafe_prkeys[i].ref;
sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label,
SC_PKCS15_TYPE_PRKEY_RSA,
gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage,
&path, key_ref, pauthId,
gemsafe_prkeys[i].obj_flags);
}
/* select the application DF */
sc_log(p15card->card->ctx, "Selecting application DF");
sc_format_path(GEMSAFE_APP_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* set the application DF */
if (p15card->file_app)
free(p15card->file_app);
p15card->file_app = file;
return SC_SUCCESS;
}
int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)
return sc_pkcs15emu_gemsafeV1_init(p15card);
else {
int r = gemsafe_detect_card(p15card);
if (r)
return SC_ERROR_WRONG_CARD;
return sc_pkcs15emu_gemsafeV1_init(p15card);
}
}
static sc_pkcs15_df_t *
sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type)
{
sc_pkcs15_df_t *df;
sc_file_t *file;
int created = 0;
while (1) {
for (df = p15card->df_list; df; df = df->next) {
if (df->type == type) {
if (created)
df->enumerated = 1;
return df;
}
}
assert(created == 0);
file = sc_file_new();
if (!file)
return NULL;
sc_format_path("11001101", &file->path);
sc_pkcs15_add_df(p15card, type, &file->path);
sc_file_free(file);
created++;
}
}
static int
sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type,
const char *label, void *data,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_object_t *obj;
int df_type;
obj = calloc(1, sizeof(*obj));
obj->type = type;
obj->data = data;
if (label)
strncpy(obj->label, label, sizeof(obj->label)-1);
obj->flags = obj_flags;
if (auth_id)
obj->auth_id = *auth_id;
switch (type & SC_PKCS15_TYPE_CLASS_MASK) {
case SC_PKCS15_TYPE_AUTH:
df_type = SC_PKCS15_AODF;
break;
case SC_PKCS15_TYPE_PRKEY:
df_type = SC_PKCS15_PRKDF;
break;
case SC_PKCS15_TYPE_PUBKEY:
df_type = SC_PKCS15_PUKDF;
break;
case SC_PKCS15_TYPE_CERT:
df_type = SC_PKCS15_CDF;
break;
default:
sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type);
free(obj);
return SC_ERROR_INVALID_ARGUMENTS;
}
obj->df = sc_pkcs15emu_get_df(p15card, df_type);
sc_pkcs15_add_object(p15card, obj);
return 0;
}
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags)
{
sc_pkcs15_auth_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
info->auth_method = SC_AC_CHV;
info->auth_id = *id;
info->attrs.pin.min_length = min_length;
info->attrs.pin.max_length = max_length;
info->attrs.pin.stored_length = max_length;
info->attrs.pin.type = type;
info->attrs.pin.reference = ref;
info->attrs.pin.flags = flags;
info->attrs.pin.pad_char = pad_char;
info->tries_left = tries_left;
info->logged_in = SC_PIN_STATE_UNKNOWN;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags)
{
sc_pkcs15_cert_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->authority = authority;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_prkey_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->modulus_length = modulus_length;
info->usage = usage;
info->native = 1;
info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE
| SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE
| SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE
| SC_PKCS15_PRKEY_ACCESS_LOCAL;
info->key_reference = ref;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label,
info, auth_id, obj_flags);
}
/* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_339_5 |
crossvul-cpp_data_good_3407_2 | /* fshelp.c -- Filesystem helper functions */
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2004,2005,2006,2007,2008 Free Software Foundation, Inc.
*
* GRUB 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.
*
* GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <grub/err.h>
#include <grub/mm.h>
#include <grub/misc.h>
#include <grub/disk.h>
#include <grub/fshelp.h>
GRUB_EXPORT(grub_fshelp_view);
GRUB_EXPORT(grub_fshelp_find_file);
GRUB_EXPORT(grub_fshelp_log2blksize);
GRUB_EXPORT(grub_fshelp_read_file);
int grub_fshelp_view = 0;
struct grub_fshelp_find_file_closure
{
grub_fshelp_node_t rootnode;
int (*iterate_dir) (grub_fshelp_node_t dir,
int (*hook)
(const char *filename,
enum grub_fshelp_filetype filetype,
grub_fshelp_node_t node, void *closure),
void *closure);
void *closure;
char *(*read_symlink) (grub_fshelp_node_t node);
int symlinknest;
enum grub_fshelp_filetype foundtype;
grub_fshelp_node_t currroot;
};
static void
free_node (grub_fshelp_node_t node, struct grub_fshelp_find_file_closure *c)
{
if (node != c->rootnode && node != c->currroot)
grub_free (node);
}
struct find_file_closure
{
char *name;
enum grub_fshelp_filetype *type;
grub_fshelp_node_t *oldnode;
grub_fshelp_node_t *currnode;
};
static int
iterate (const char *filename,
enum grub_fshelp_filetype filetype,
grub_fshelp_node_t node,
void *closure)
{
struct find_file_closure *c = closure;
if (filetype == GRUB_FSHELP_UNKNOWN ||
(grub_strcmp (c->name, filename) &&
(! (filetype & GRUB_FSHELP_CASE_INSENSITIVE) ||
grub_strncasecmp (c->name, filename, GRUB_LONG_MAX))))
{
grub_free (node);
return 0;
}
/* The node is found, stop iterating over the nodes. */
*(c->type) = filetype & ~GRUB_FSHELP_CASE_INSENSITIVE;
*(c->oldnode) = *(c->currnode);
*(c->currnode) = node;
return 1;
}
static grub_err_t
find_file (const char *currpath, grub_fshelp_node_t currroot,
grub_fshelp_node_t *currfound,
struct grub_fshelp_find_file_closure *c)
{
char *fpath = grub_malloc (grub_strlen (currpath) + 1);
char *name = fpath;
char *next;
enum grub_fshelp_filetype type = GRUB_FSHELP_DIR;
grub_fshelp_node_t currnode = currroot;
grub_fshelp_node_t oldnode = currroot;
c->currroot = currroot;
grub_strncpy (fpath, currpath, grub_strlen (currpath) + 1);
/* Remove all leading slashes. */
while (*name == '/')
name++;
if (! *name)
{
*currfound = currnode;
free (fpath);
return 0;
}
for (;;)
{
int found;
struct find_file_closure cc;
/* Extract the actual part from the pathname. */
next = grub_strchr (name, '/');
if (next)
{
/* Remove all leading slashes. */
while (*next == '/')
*(next++) = '\0';
}
/* At this point it is expected that the current node is a
directory, check if this is true. */
if (type != GRUB_FSHELP_DIR)
{
free_node (currnode, c);
free (fpath);
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory");
}
cc.name = name;
cc.type = &type;
cc.oldnode = &oldnode;
cc.currnode = &currnode;
/* Iterate over the directory. */
found = c->iterate_dir (currnode, iterate, &cc);
if (! found)
{
if (grub_errno) {
free (fpath);
return grub_errno;
}
break;
}
/* Read in the symlink and follow it. */
if (type == GRUB_FSHELP_SYMLINK)
{
char *symlink;
/* Test if the symlink does not loop. */
if (++(c->symlinknest) == 8)
{
free_node (currnode, c);
free_node (oldnode, c);
free (fpath);
return grub_error (GRUB_ERR_SYMLINK_LOOP,
"too deep nesting of symlinks");
}
symlink = c->read_symlink (currnode);
free_node (currnode, c);
if (!symlink)
{
free_node (oldnode, c);
free (fpath);
return grub_errno;
}
/* The symlink is an absolute path, go back to the root inode. */
if (symlink[0] == '/')
{
free_node (oldnode, c);
oldnode = c->rootnode;
}
/* Lookup the node the symlink points to. */
find_file (symlink, oldnode, &currnode, c);
type = c->foundtype;
grub_free (symlink);
if (grub_errno)
{
free_node (oldnode, c);
free (fpath);
return grub_errno;
}
}
free_node (oldnode, c);
/* Found the node! */
if (! next || *next == '\0')
{
*currfound = currnode;
c->foundtype = type;
free (fpath);
return 0;
}
name = next;
}
free (fpath);
return grub_error (GRUB_ERR_FILE_NOT_FOUND, "file not found");
}
/* Lookup the node PATH. The node ROOTNODE describes the root of the
directory tree. The node found is returned in FOUNDNODE, which is
either a ROOTNODE or a new malloc'ed node. ITERATE_DIR is used to
iterate over all directory entries in the current node.
READ_SYMLINK is used to read the symlink if a node is a symlink.
EXPECTTYPE is the type node that is expected by the called, an
error is generated if the node is not of the expected type. Make
sure you use the NESTED_FUNC_ATTR macro for HOOK, this is required
because GCC has a nasty bug when using regparm=3. */
grub_err_t
grub_fshelp_find_file (const char *path, grub_fshelp_node_t rootnode,
grub_fshelp_node_t *foundnode,
int (*iterate_dir) (grub_fshelp_node_t dir,
int (*hook)
(const char *filename,
enum grub_fshelp_filetype filetype,
grub_fshelp_node_t node,
void *closure),
void *closure),
void *closure,
char *(*read_symlink) (grub_fshelp_node_t node),
enum grub_fshelp_filetype expecttype)
{
grub_err_t err;
struct grub_fshelp_find_file_closure c;
c.rootnode = rootnode;
c.iterate_dir = iterate_dir;
c.closure = closure;
c.read_symlink = read_symlink;
c.symlinknest = 0;
c.foundtype = GRUB_FSHELP_DIR;
if (!path || path[0] != '/')
{
grub_error (GRUB_ERR_BAD_FILENAME, "bad filename");
return grub_errno;
}
err = find_file (path, rootnode, foundnode, &c);
if (err)
return err;
/* Check if the node that was found was of the expected type. */
if (expecttype == GRUB_FSHELP_REG && c.foundtype != expecttype)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a regular file");
else if (expecttype == GRUB_FSHELP_DIR && c.foundtype != expecttype)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory");
return 0;
}
unsigned long long grub_hack_lastoff = 0;
/* Read LEN bytes from the file NODE on disk DISK into the buffer BUF,
beginning with the block POS. READ_HOOK should be set before
reading a block from the file. GET_BLOCK is used to translate file
blocks to disk blocks. The file is FILESIZE bytes big and the
blocks have a size of LOG2BLOCKSIZE (in log2). */
grub_ssize_t
grub_fshelp_read_file (grub_disk_t disk, grub_fshelp_node_t node,
void (*read_hook) (grub_disk_addr_t sector,
unsigned offset,
unsigned length,
void *closure),
void *closure, int flags,
grub_off_t pos, grub_size_t len, char *buf,
grub_disk_addr_t (*get_block) (grub_fshelp_node_t node,
grub_disk_addr_t block),
grub_off_t filesize, int log2blocksize)
{
grub_disk_addr_t i, blockcnt;
int blocksize = 1 << (log2blocksize + GRUB_DISK_SECTOR_BITS);
/* Adjust LEN so it we can't read past the end of the file. */
if (pos + len > filesize)
len = filesize - pos;
if (len < 1 || len == 0xffffffff) {
return -1;
}
blockcnt = ((len + pos) + blocksize - 1) >>
(log2blocksize + GRUB_DISK_SECTOR_BITS);
for (i = pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS); i < blockcnt; i++)
{
grub_disk_addr_t blknr;
int blockoff = pos & (blocksize - 1);
int blockend = blocksize;
int skipfirst = 0;
blknr = get_block (node, i);
if (grub_errno)
return -1;
blknr = blknr << log2blocksize;
/* Last block. */
if (i == blockcnt - 1)
{
blockend = (len + pos) & (blocksize - 1);
/* The last portion is exactly blocksize. */
if (! blockend)
blockend = blocksize;
}
/* First block. */
if (i == (pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS)))
{
skipfirst = blockoff;
blockend -= skipfirst;
}
/* If the block number is 0 this block is not stored on disk but
is zero filled instead. */
if (blknr)
{
disk->read_hook = read_hook;
disk->closure = closure;
//printf ("blknr: %d\n", blknr);
grub_hack_lastoff = blknr * 512;
grub_disk_read_ex (disk, blknr, skipfirst, blockend, buf, flags);
disk->read_hook = 0;
if (grub_errno)
return -1;
}
else if (buf)
grub_memset (buf, 0, blockend);
if (buf)
buf += blocksize - skipfirst;
}
return len;
}
unsigned int
grub_fshelp_log2blksize (unsigned int blksize, unsigned int *pow)
{
int mod;
*pow = 0;
while (blksize > 1)
{
mod = blksize - ((blksize >> 1) << 1);
blksize >>= 1;
/* Check if it really is a power of two. */
if (mod)
return grub_error (GRUB_ERR_BAD_NUMBER,
"the blocksize is not a power of two");
(*pow)++;
}
return GRUB_ERR_NONE;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3407_2 |
crossvul-cpp_data_bad_5079_0 | /*
* Packet matching code for ARP packets.
*
* Based heavily, if not almost entirely, upon ip_tables.c framework.
*
* Some ARP specific bits are:
*
* Copyright (C) 2002 David S. Miller (davem@redhat.com)
* Copyright (C) 2006-2009 Patrick McHardy <kaber@trash.net>
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/capability.h>
#include <linux/if_arp.h>
#include <linux/kmod.h>
#include <linux/vmalloc.h>
#include <linux/proc_fs.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <net/compat.h>
#include <net/sock.h>
#include <asm/uaccess.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_arp/arp_tables.h>
#include "../../netfilter/xt_repldata.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David S. Miller <davem@redhat.com>");
MODULE_DESCRIPTION("arptables core");
/*#define DEBUG_ARP_TABLES*/
/*#define DEBUG_ARP_TABLES_USER*/
#ifdef DEBUG_ARP_TABLES
#define dprintf(format, args...) pr_debug(format, ## args)
#else
#define dprintf(format, args...)
#endif
#ifdef DEBUG_ARP_TABLES_USER
#define duprintf(format, args...) pr_debug(format, ## args)
#else
#define duprintf(format, args...)
#endif
#ifdef CONFIG_NETFILTER_DEBUG
#define ARP_NF_ASSERT(x) WARN_ON(!(x))
#else
#define ARP_NF_ASSERT(x)
#endif
void *arpt_alloc_initial_table(const struct xt_table *info)
{
return xt_alloc_initial_table(arpt, ARPT);
}
EXPORT_SYMBOL_GPL(arpt_alloc_initial_table);
static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap,
const char *hdr_addr, int len)
{
int i, ret;
if (len > ARPT_DEV_ADDR_LEN_MAX)
len = ARPT_DEV_ADDR_LEN_MAX;
ret = 0;
for (i = 0; i < len; i++)
ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i];
return ret != 0;
}
/*
* Unfortunately, _b and _mask are not aligned to an int (or long int)
* Some arches dont care, unrolling the loop is a win on them.
* For other arches, we only have a 16bit alignement.
*/
static unsigned long ifname_compare(const char *_a, const char *_b, const char *_mask)
{
#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
unsigned long ret = ifname_compare_aligned(_a, _b, _mask);
#else
unsigned long ret = 0;
const u16 *a = (const u16 *)_a;
const u16 *b = (const u16 *)_b;
const u16 *mask = (const u16 *)_mask;
int i;
for (i = 0; i < IFNAMSIZ/sizeof(u16); i++)
ret |= (a[i] ^ b[i]) & mask[i];
#endif
return ret;
}
/* Returns whether packet matches rule or not. */
static inline int arp_packet_match(const struct arphdr *arphdr,
struct net_device *dev,
const char *indev,
const char *outdev,
const struct arpt_arp *arpinfo)
{
const char *arpptr = (char *)(arphdr + 1);
const char *src_devaddr, *tgt_devaddr;
__be32 src_ipaddr, tgt_ipaddr;
long ret;
#define FWINV(bool, invflg) ((bool) ^ !!(arpinfo->invflags & (invflg)))
if (FWINV((arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop,
ARPT_INV_ARPOP)) {
dprintf("ARP operation field mismatch.\n");
dprintf("ar_op: %04x info->arpop: %04x info->arpop_mask: %04x\n",
arphdr->ar_op, arpinfo->arpop, arpinfo->arpop_mask);
return 0;
}
if (FWINV((arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd,
ARPT_INV_ARPHRD)) {
dprintf("ARP hardware address format mismatch.\n");
dprintf("ar_hrd: %04x info->arhrd: %04x info->arhrd_mask: %04x\n",
arphdr->ar_hrd, arpinfo->arhrd, arpinfo->arhrd_mask);
return 0;
}
if (FWINV((arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro,
ARPT_INV_ARPPRO)) {
dprintf("ARP protocol address format mismatch.\n");
dprintf("ar_pro: %04x info->arpro: %04x info->arpro_mask: %04x\n",
arphdr->ar_pro, arpinfo->arpro, arpinfo->arpro_mask);
return 0;
}
if (FWINV((arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln,
ARPT_INV_ARPHLN)) {
dprintf("ARP hardware address length mismatch.\n");
dprintf("ar_hln: %02x info->arhln: %02x info->arhln_mask: %02x\n",
arphdr->ar_hln, arpinfo->arhln, arpinfo->arhln_mask);
return 0;
}
src_devaddr = arpptr;
arpptr += dev->addr_len;
memcpy(&src_ipaddr, arpptr, sizeof(u32));
arpptr += sizeof(u32);
tgt_devaddr = arpptr;
arpptr += dev->addr_len;
memcpy(&tgt_ipaddr, arpptr, sizeof(u32));
if (FWINV(arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr, dev->addr_len),
ARPT_INV_SRCDEVADDR) ||
FWINV(arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr, dev->addr_len),
ARPT_INV_TGTDEVADDR)) {
dprintf("Source or target device address mismatch.\n");
return 0;
}
if (FWINV((src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr,
ARPT_INV_SRCIP) ||
FWINV(((tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr),
ARPT_INV_TGTIP)) {
dprintf("Source or target IP address mismatch.\n");
dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n",
&src_ipaddr,
&arpinfo->smsk.s_addr,
&arpinfo->src.s_addr,
arpinfo->invflags & ARPT_INV_SRCIP ? " (INV)" : "");
dprintf("TGT: %pI4 Mask: %pI4 Target: %pI4.%s\n",
&tgt_ipaddr,
&arpinfo->tmsk.s_addr,
&arpinfo->tgt.s_addr,
arpinfo->invflags & ARPT_INV_TGTIP ? " (INV)" : "");
return 0;
}
/* Look for ifname matches. */
ret = ifname_compare(indev, arpinfo->iniface, arpinfo->iniface_mask);
if (FWINV(ret != 0, ARPT_INV_VIA_IN)) {
dprintf("VIA in mismatch (%s vs %s).%s\n",
indev, arpinfo->iniface,
arpinfo->invflags & ARPT_INV_VIA_IN ? " (INV)" : "");
return 0;
}
ret = ifname_compare(outdev, arpinfo->outiface, arpinfo->outiface_mask);
if (FWINV(ret != 0, ARPT_INV_VIA_OUT)) {
dprintf("VIA out mismatch (%s vs %s).%s\n",
outdev, arpinfo->outiface,
arpinfo->invflags & ARPT_INV_VIA_OUT ? " (INV)" : "");
return 0;
}
return 1;
#undef FWINV
}
static inline int arp_checkentry(const struct arpt_arp *arp)
{
if (arp->flags & ~ARPT_F_MASK) {
duprintf("Unknown flag bits set: %08X\n",
arp->flags & ~ARPT_F_MASK);
return 0;
}
if (arp->invflags & ~ARPT_INV_MASK) {
duprintf("Unknown invflag bits set: %08X\n",
arp->invflags & ~ARPT_INV_MASK);
return 0;
}
return 1;
}
static unsigned int
arpt_error(struct sk_buff *skb, const struct xt_action_param *par)
{
net_err_ratelimited("arp_tables: error: '%s'\n",
(const char *)par->targinfo);
return NF_DROP;
}
static inline const struct xt_entry_target *
arpt_get_target_c(const struct arpt_entry *e)
{
return arpt_get_target((struct arpt_entry *)e);
}
static inline struct arpt_entry *
get_entry(const void *base, unsigned int offset)
{
return (struct arpt_entry *)(base + offset);
}
static inline
struct arpt_entry *arpt_next_entry(const struct arpt_entry *entry)
{
return (void *)entry + entry->next_offset;
}
unsigned int arpt_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct xt_table *table)
{
unsigned int hook = state->hook;
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
unsigned int verdict = NF_DROP;
const struct arphdr *arp;
struct arpt_entry *e, **jumpstack;
const char *indev, *outdev;
const void *table_base;
unsigned int cpu, stackidx = 0;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
if (!pskb_may_pull(skb, arp_hdr_len(skb->dev)))
return NF_DROP;
indev = state->in ? state->in->name : nulldevname;
outdev = state->out ? state->out->name : nulldevname;
local_bh_disable();
addend = xt_write_recseq_begin();
private = table->private;
cpu = smp_processor_id();
/*
* Ensure we load private-> members after we've fetched the base
* pointer.
*/
smp_read_barrier_depends();
table_base = private->entries;
jumpstack = (struct arpt_entry **)private->jumpstack[cpu];
/* No TEE support for arptables, so no need to switch to alternate
* stack. All targets that reenter must return absolute verdicts.
*/
e = get_entry(table_base, private->hook_entry[hook]);
acpar.net = state->net;
acpar.in = state->in;
acpar.out = state->out;
acpar.hooknum = hook;
acpar.family = NFPROTO_ARP;
acpar.hotdrop = false;
arp = arp_hdr(skb);
do {
const struct xt_entry_target *t;
struct xt_counters *counter;
if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) {
e = arpt_next_entry(e);
continue;
}
counter = xt_get_this_cpu_counter(&e->counters);
ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1);
t = arpt_get_target_c(e);
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned int)(-v) - 1;
break;
}
if (stackidx == 0) {
e = get_entry(table_base,
private->underflow[hook]);
} else {
e = jumpstack[--stackidx];
e = arpt_next_entry(e);
}
continue;
}
if (table_base + v
!= arpt_next_entry(e)) {
jumpstack[stackidx++] = e;
}
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
/* Target might have changed stuff. */
arp = arp_hdr(skb);
if (verdict == XT_CONTINUE)
e = arpt_next_entry(e);
else
/* Verdict */
break;
} while (!acpar.hotdrop);
xt_write_recseq_end(addend);
local_bh_enable();
if (acpar.hotdrop)
return NF_DROP;
else
return verdict;
}
/* All zeroes == unconditional rule. */
static inline bool unconditional(const struct arpt_arp *arp)
{
static const struct arpt_arp uncond;
return memcmp(arp, &uncond, sizeof(uncond)) == 0;
}
/* Figures out from what hook each rule can be called: returns 0 if
* there are loops. Puts hook bitmask in comefrom.
*/
static int mark_source_chains(const struct xt_table_info *newinfo,
unsigned int valid_hooks, void *entry0)
{
unsigned int hook;
/* No recursion; use packet counter to save back ptrs (reset
* to 0 as we leave), and comefrom to save source hook bitmask.
*/
for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) {
unsigned int pos = newinfo->hook_entry[hook];
struct arpt_entry *e
= (struct arpt_entry *)(entry0 + pos);
if (!(valid_hooks & (1 << hook)))
continue;
/* Set initial back pointer. */
e->counters.pcnt = pos;
for (;;) {
const struct xt_standard_target *t
= (void *)arpt_get_target_c(e);
int visited = e->comefrom & (1 << hook);
if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) {
pr_notice("arptables: loop hook %u pos %u %08X.\n",
hook, pos, e->comefrom);
return 0;
}
e->comefrom
|= ((1 << hook) | (1 << NF_ARP_NUMHOOKS));
/* Unconditional return/END. */
if ((e->target_offset == sizeof(struct arpt_entry) &&
(strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < 0 && unconditional(&e->arp)) ||
visited) {
unsigned int oldpos, size;
if ((strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < -NF_MAX_VERDICT - 1) {
duprintf("mark_source_chains: bad "
"negative verdict (%i)\n",
t->verdict);
return 0;
}
/* Return: backtrack through the last
* big jump.
*/
do {
e->comefrom ^= (1<<NF_ARP_NUMHOOKS);
oldpos = pos;
pos = e->counters.pcnt;
e->counters.pcnt = 0;
/* We're at the start. */
if (pos == oldpos)
goto next;
e = (struct arpt_entry *)
(entry0 + pos);
} while (oldpos == pos + e->next_offset);
/* Move along one */
size = e->next_offset;
e = (struct arpt_entry *)
(entry0 + pos + size);
e->counters.pcnt = pos;
pos += size;
} else {
int newpos = t->verdict;
if (strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0 &&
newpos >= 0) {
if (newpos > newinfo->size -
sizeof(struct arpt_entry)) {
duprintf("mark_source_chains: "
"bad verdict (%i)\n",
newpos);
return 0;
}
/* This a jump; chase it. */
duprintf("Jump rule %u -> %u\n",
pos, newpos);
} else {
/* ... this is a fallthru */
newpos = pos + e->next_offset;
}
e = (struct arpt_entry *)
(entry0 + newpos);
e->counters.pcnt = pos;
pos = newpos;
}
}
next:
duprintf("Finished chain %u\n", hook);
}
return 1;
}
static inline int check_entry(const struct arpt_entry *e)
{
const struct xt_entry_target *t;
if (!arp_checkentry(&e->arp))
return -EINVAL;
if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset)
return -EINVAL;
t = arpt_get_target_c(e);
if (e->target_offset + t->u.target_size > e->next_offset)
return -EINVAL;
return 0;
}
static inline int check_target(struct arpt_entry *e, const char *name)
{
struct xt_entry_target *t = arpt_get_target(e);
int ret;
struct xt_tgchk_param par = {
.table = name,
.entryinfo = e,
.target = t->u.kernel.target,
.targinfo = t->data,
.hook_mask = e->comefrom,
.family = NFPROTO_ARP,
};
ret = xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false);
if (ret < 0) {
duprintf("arp_tables: check failed for `%s'.\n",
t->u.kernel.target->name);
return ret;
}
return 0;
}
static inline int
find_check_entry(struct arpt_entry *e, const char *name, unsigned int size)
{
struct xt_entry_target *t;
struct xt_target *target;
int ret;
e->counters.pcnt = xt_percpu_counter_alloc();
if (IS_ERR_VALUE(e->counters.pcnt))
return -ENOMEM;
t = arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("find_check_entry: `%s' not found\n", t->u.user.name);
ret = PTR_ERR(target);
goto out;
}
t->u.kernel.target = target;
ret = check_target(e, name);
if (ret)
goto err;
return 0;
err:
module_put(t->u.kernel.target->me);
out:
xt_percpu_counter_free(e->counters.pcnt);
return ret;
}
static bool check_underflow(const struct arpt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(&e->arp))
return false;
t = arpt_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
static inline int check_entry_size_and_hooks(struct arpt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct arpt_entry) >= limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
static inline void cleanup_entry(struct arpt_entry *e)
{
struct xt_tgdtor_param par;
struct xt_entry_target *t;
t = arpt_get_target(e);
par.target = t->u.kernel.target;
par.targinfo = t->data;
par.family = NFPROTO_ARP;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
xt_percpu_counter_free(e->counters.pcnt);
}
/* Checks and translates the user-supplied table segment (held in
* newinfo).
*/
static int translate_table(struct xt_table_info *newinfo, void *entry0,
const struct arpt_replace *repl)
{
struct arpt_entry *iter;
unsigned int i;
int ret = 0;
newinfo->size = repl->size;
newinfo->number = repl->num_entries;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
newinfo->hook_entry[i] = 0xFFFFFFFF;
newinfo->underflow[i] = 0xFFFFFFFF;
}
duprintf("translate_table: size %u\n", newinfo->size);
i = 0;
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = check_entry_size_and_hooks(iter, newinfo, entry0,
entry0 + repl->size,
repl->hook_entry,
repl->underflow,
repl->valid_hooks);
if (ret != 0)
break;
++i;
if (strcmp(arpt_get_target(iter)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret);
if (ret != 0)
return ret;
if (i != repl->num_entries) {
duprintf("translate_table: %u not %u entries\n",
i, repl->num_entries);
return -EINVAL;
}
/* Check hooks all assigned */
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
/* Only hooks which are valid */
if (!(repl->valid_hooks & (1 << i)))
continue;
if (newinfo->hook_entry[i] == 0xFFFFFFFF) {
duprintf("Invalid hook entry %u %u\n",
i, repl->hook_entry[i]);
return -EINVAL;
}
if (newinfo->underflow[i] == 0xFFFFFFFF) {
duprintf("Invalid underflow %u %u\n",
i, repl->underflow[i]);
return -EINVAL;
}
}
if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) {
duprintf("Looping hook\n");
return -ELOOP;
}
/* Finally, each sanity check must pass */
i = 0;
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = find_check_entry(iter, repl->name, repl->size);
if (ret != 0)
break;
++i;
}
if (ret != 0) {
xt_entry_foreach(iter, entry0, newinfo->size) {
if (i-- == 0)
break;
cleanup_entry(iter);
}
return ret;
}
return ret;
}
static void get_counters(const struct xt_table_info *t,
struct xt_counters counters[])
{
struct arpt_entry *iter;
unsigned int cpu;
unsigned int i;
for_each_possible_cpu(cpu) {
seqcount_t *s = &per_cpu(xt_recseq, cpu);
i = 0;
xt_entry_foreach(iter, t->entries, t->size) {
struct xt_counters *tmp;
u64 bcnt, pcnt;
unsigned int start;
tmp = xt_get_per_cpu_counter(&iter->counters, cpu);
do {
start = read_seqcount_begin(s);
bcnt = tmp->bcnt;
pcnt = tmp->pcnt;
} while (read_seqcount_retry(s, start));
ADD_COUNTER(counters[i], bcnt, pcnt);
++i;
}
}
}
static struct xt_counters *alloc_counters(const struct xt_table *table)
{
unsigned int countersize;
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
/* We need atomic snapshot of counters: rest doesn't change
* (other than comefrom, which userspace doesn't care
* about).
*/
countersize = sizeof(struct xt_counters) * private->number;
counters = vzalloc(countersize);
if (counters == NULL)
return ERR_PTR(-ENOMEM);
get_counters(private, counters);
return counters;
}
static int copy_entries_to_user(unsigned int total_size,
const struct xt_table *table,
void __user *userptr)
{
unsigned int off, num;
const struct arpt_entry *e;
struct xt_counters *counters;
struct xt_table_info *private = table->private;
int ret = 0;
void *loc_cpu_entry;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
loc_cpu_entry = private->entries;
/* ... then copy entire thing ... */
if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) {
ret = -EFAULT;
goto free_counters;
}
/* FIXME: use iterator macros --RR */
/* ... then go back and fix counters and names */
for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){
const struct xt_entry_target *t;
e = (struct arpt_entry *)(loc_cpu_entry + off);
if (copy_to_user(userptr + off
+ offsetof(struct arpt_entry, counters),
&counters[num],
sizeof(counters[num])) != 0) {
ret = -EFAULT;
goto free_counters;
}
t = arpt_get_target_c(e);
if (copy_to_user(userptr + off + e->target_offset
+ offsetof(struct xt_entry_target,
u.user.name),
t->u.kernel.target->name,
strlen(t->u.kernel.target->name)+1) != 0) {
ret = -EFAULT;
goto free_counters;
}
}
free_counters:
vfree(counters);
return ret;
}
#ifdef CONFIG_COMPAT
static void compat_standard_from_user(void *dst, const void *src)
{
int v = *(compat_int_t *)src;
if (v > 0)
v += xt_compat_calc_jump(NFPROTO_ARP, v);
memcpy(dst, &v, sizeof(v));
}
static int compat_standard_to_user(void __user *dst, const void *src)
{
compat_int_t cv = *(int *)src;
if (cv > 0)
cv -= xt_compat_calc_jump(NFPROTO_ARP, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
static int compat_calc_entry(const struct arpt_entry *e,
const struct xt_table_info *info,
const void *base, struct xt_table_info *newinfo)
{
const struct xt_entry_target *t;
unsigned int entry_offset;
int off, i, ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - base;
t = arpt_get_target_c(e);
off += xt_compat_target_offset(t->u.kernel.target);
newinfo->size -= off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
if (info->hook_entry[i] &&
(e < (struct arpt_entry *)(base + info->hook_entry[i])))
newinfo->hook_entry[i] -= off;
if (info->underflow[i] &&
(e < (struct arpt_entry *)(base + info->underflow[i])))
newinfo->underflow[i] -= off;
}
return 0;
}
static int compat_table_info(const struct xt_table_info *info,
struct xt_table_info *newinfo)
{
struct arpt_entry *iter;
const void *loc_cpu_entry;
int ret;
if (!newinfo || !info)
return -EINVAL;
/* we dont care about newinfo->entries */
memcpy(newinfo, info, offsetof(struct xt_table_info, entries));
newinfo->initial_entries = 0;
loc_cpu_entry = info->entries;
xt_compat_init_offsets(NFPROTO_ARP, info->number);
xt_entry_foreach(iter, loc_cpu_entry, info->size) {
ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo);
if (ret != 0)
return ret;
}
return 0;
}
#endif
static int get_info(struct net *net, void __user *user,
const int *len, int compat)
{
char name[XT_TABLE_MAXNAMELEN];
struct xt_table *t;
int ret;
if (*len != sizeof(struct arpt_getinfo)) {
duprintf("length %u != %Zu\n", *len,
sizeof(struct arpt_getinfo));
return -EINVAL;
}
if (copy_from_user(name, user, sizeof(name)) != 0)
return -EFAULT;
name[XT_TABLE_MAXNAMELEN-1] = '\0';
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_lock(NFPROTO_ARP);
#endif
t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name),
"arptable_%s", name);
if (!IS_ERR_OR_NULL(t)) {
struct arpt_getinfo info;
const struct xt_table_info *private = t->private;
#ifdef CONFIG_COMPAT
struct xt_table_info tmp;
if (compat) {
ret = compat_table_info(private, &tmp);
xt_compat_flush_offsets(NFPROTO_ARP);
private = &tmp;
}
#endif
memset(&info, 0, sizeof(info));
info.valid_hooks = t->valid_hooks;
memcpy(info.hook_entry, private->hook_entry,
sizeof(info.hook_entry));
memcpy(info.underflow, private->underflow,
sizeof(info.underflow));
info.num_entries = private->number;
info.size = private->size;
strcpy(info.name, name);
if (copy_to_user(user, &info, *len) != 0)
ret = -EFAULT;
else
ret = 0;
xt_table_unlock(t);
module_put(t->me);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_unlock(NFPROTO_ARP);
#endif
return ret;
}
static int get_entries(struct net *net, struct arpt_get_entries __user *uptr,
const int *len)
{
int ret;
struct arpt_get_entries get;
struct xt_table *t;
if (*len < sizeof(get)) {
duprintf("get_entries: %u < %Zu\n", *len, sizeof(get));
return -EINVAL;
}
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct arpt_get_entries) + get.size) {
duprintf("get_entries: %u != %Zu\n", *len,
sizeof(struct arpt_get_entries) + get.size);
return -EINVAL;
}
t = xt_find_table_lock(net, NFPROTO_ARP, get.name);
if (!IS_ERR_OR_NULL(t)) {
const struct xt_table_info *private = t->private;
duprintf("t->private->number = %u\n",
private->number);
if (get.size == private->size)
ret = copy_entries_to_user(private->size,
t, uptr->entrytable);
else {
duprintf("get_entries: I've got %u not %u!\n",
private->size, get.size);
ret = -EAGAIN;
}
module_put(t->me);
xt_table_unlock(t);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
return ret;
}
static int __do_replace(struct net *net, const char *name,
unsigned int valid_hooks,
struct xt_table_info *newinfo,
unsigned int num_counters,
void __user *counters_ptr)
{
int ret;
struct xt_table *t;
struct xt_table_info *oldinfo;
struct xt_counters *counters;
void *loc_cpu_old_entry;
struct arpt_entry *iter;
ret = 0;
counters = vzalloc(num_counters * sizeof(struct xt_counters));
if (!counters) {
ret = -ENOMEM;
goto out;
}
t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name),
"arptable_%s", name);
if (IS_ERR_OR_NULL(t)) {
ret = t ? PTR_ERR(t) : -ENOENT;
goto free_newinfo_counters_untrans;
}
/* You lied! */
if (valid_hooks != t->valid_hooks) {
duprintf("Valid hook crap: %08X vs %08X\n",
valid_hooks, t->valid_hooks);
ret = -EINVAL;
goto put_module;
}
oldinfo = xt_replace_table(t, num_counters, newinfo, &ret);
if (!oldinfo)
goto put_module;
/* Update module usage count based on number of rules */
duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n",
oldinfo->number, oldinfo->initial_entries, newinfo->number);
if ((oldinfo->number > oldinfo->initial_entries) ||
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
if ((oldinfo->number > oldinfo->initial_entries) &&
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
/* Get the old counters, and synchronize with replace */
get_counters(oldinfo, counters);
/* Decrease module usage counts and free resource */
loc_cpu_old_entry = oldinfo->entries;
xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size)
cleanup_entry(iter);
xt_free_table_info(oldinfo);
if (copy_to_user(counters_ptr, counters,
sizeof(struct xt_counters) * num_counters) != 0) {
/* Silent error, can't fail, new table is already in place */
net_warn_ratelimited("arptables: counters copy to user failed while replacing table\n");
}
vfree(counters);
xt_table_unlock(t);
return ret;
put_module:
module_put(t->me);
xt_table_unlock(t);
free_newinfo_counters_untrans:
vfree(counters);
out:
return ret;
}
static int do_replace(struct net *net, const void __user *user,
unsigned int len)
{
int ret;
struct arpt_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct arpt_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
if (tmp.num_counters == 0)
return -EINVAL;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_table(newinfo, loc_cpu_entry, &tmp);
if (ret != 0)
goto free_newinfo;
duprintf("arp_tables: Translated table\n");
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, tmp.counters);
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int do_add_counters(struct net *net, const void __user *user,
unsigned int len, int compat)
{
unsigned int i;
struct xt_counters_info tmp;
struct xt_counters *paddc;
unsigned int num_counters;
const char *name;
int size;
void *ptmp;
struct xt_table *t;
const struct xt_table_info *private;
int ret = 0;
struct arpt_entry *iter;
unsigned int addend;
#ifdef CONFIG_COMPAT
struct compat_xt_counters_info compat_tmp;
if (compat) {
ptmp = &compat_tmp;
size = sizeof(struct compat_xt_counters_info);
} else
#endif
{
ptmp = &tmp;
size = sizeof(struct xt_counters_info);
}
if (copy_from_user(ptmp, user, size) != 0)
return -EFAULT;
#ifdef CONFIG_COMPAT
if (compat) {
num_counters = compat_tmp.num_counters;
name = compat_tmp.name;
} else
#endif
{
num_counters = tmp.num_counters;
name = tmp.name;
}
if (len != size + num_counters * sizeof(struct xt_counters))
return -EINVAL;
paddc = vmalloc(len - size);
if (!paddc)
return -ENOMEM;
if (copy_from_user(paddc, user + size, len - size) != 0) {
ret = -EFAULT;
goto free;
}
t = xt_find_table_lock(net, NFPROTO_ARP, name);
if (IS_ERR_OR_NULL(t)) {
ret = t ? PTR_ERR(t) : -ENOENT;
goto free;
}
local_bh_disable();
private = t->private;
if (private->number != num_counters) {
ret = -EINVAL;
goto unlock_up_free;
}
i = 0;
addend = xt_write_recseq_begin();
xt_entry_foreach(iter, private->entries, private->size) {
struct xt_counters *tmp;
tmp = xt_get_this_cpu_counter(&iter->counters);
ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt);
++i;
}
xt_write_recseq_end(addend);
unlock_up_free:
local_bh_enable();
xt_table_unlock(t);
module_put(t->me);
free:
vfree(paddc);
return ret;
}
#ifdef CONFIG_COMPAT
static inline void compat_release_entry(struct compat_arpt_entry *e)
{
struct xt_entry_target *t;
t = compat_arpt_get_target(e);
module_put(t->u.kernel.target->me);
}
static inline int
check_compat_entry_size_and_hooks(struct compat_arpt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_arpt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct arpt_entry *)e);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
static int
compat_copy_entry_from_user(struct compat_arpt_entry *e, void **dstptr,
unsigned int *size, const char *name,
struct xt_table_info *newinfo, unsigned char *base)
{
struct xt_entry_target *t;
struct xt_target *target;
struct arpt_entry *de;
unsigned int origsize;
int ret, h;
ret = 0;
origsize = *size;
de = (struct arpt_entry *)*dstptr;
memcpy(de, e, sizeof(struct arpt_entry));
memcpy(&de->counters, &e->counters, sizeof(e->counters));
*dstptr += sizeof(struct arpt_entry);
*size += sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
de->target_offset = e->target_offset - (origsize - *size);
t = compat_arpt_get_target(e);
target = t->u.kernel.target;
xt_compat_target_from_user(t, dstptr, size);
de->next_offset = e->next_offset - (origsize - *size);
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if ((unsigned char *)de - base < newinfo->hook_entry[h])
newinfo->hook_entry[h] -= origsize - *size;
if ((unsigned char *)de - base < newinfo->underflow[h])
newinfo->underflow[h] -= origsize - *size;
}
return ret;
}
static int translate_compat_table(const char *name,
unsigned int valid_hooks,
struct xt_table_info **pinfo,
void **pentry0,
unsigned int total_size,
unsigned int number,
unsigned int *hook_entries,
unsigned int *underflows)
{
unsigned int i, j;
struct xt_table_info *newinfo, *info;
void *pos, *entry0, *entry1;
struct compat_arpt_entry *iter0;
struct arpt_entry *iter1;
unsigned int size;
int ret = 0;
info = *pinfo;
entry0 = *pentry0;
size = total_size;
info->number = number;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
info->hook_entry[i] = 0xFFFFFFFF;
info->underflow[i] = 0xFFFFFFFF;
}
duprintf("translate_compat_table: size %u\n", info->size);
j = 0;
xt_compat_lock(NFPROTO_ARP);
xt_compat_init_offsets(NFPROTO_ARP, number);
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter0, entry0, total_size) {
ret = check_compat_entry_size_and_hooks(iter0, info, &size,
entry0,
entry0 + total_size,
hook_entries,
underflows,
name);
if (ret != 0)
goto out_unlock;
++j;
}
ret = -EINVAL;
if (j != number) {
duprintf("translate_compat_table: %u not %u entries\n",
j, number);
goto out_unlock;
}
/* Check hooks all assigned */
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
/* Only hooks which are valid */
if (!(valid_hooks & (1 << i)))
continue;
if (info->hook_entry[i] == 0xFFFFFFFF) {
duprintf("Invalid hook entry %u %u\n",
i, hook_entries[i]);
goto out_unlock;
}
if (info->underflow[i] == 0xFFFFFFFF) {
duprintf("Invalid underflow %u %u\n",
i, underflows[i]);
goto out_unlock;
}
}
ret = -ENOMEM;
newinfo = xt_alloc_table_info(size);
if (!newinfo)
goto out_unlock;
newinfo->number = number;
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
newinfo->hook_entry[i] = info->hook_entry[i];
newinfo->underflow[i] = info->underflow[i];
}
entry1 = newinfo->entries;
pos = entry1;
size = total_size;
xt_entry_foreach(iter0, entry0, total_size) {
ret = compat_copy_entry_from_user(iter0, &pos, &size,
name, newinfo, entry1);
if (ret != 0)
break;
}
xt_compat_flush_offsets(NFPROTO_ARP);
xt_compat_unlock(NFPROTO_ARP);
if (ret)
goto free_newinfo;
ret = -ELOOP;
if (!mark_source_chains(newinfo, valid_hooks, entry1))
goto free_newinfo;
i = 0;
xt_entry_foreach(iter1, entry1, newinfo->size) {
iter1->counters.pcnt = xt_percpu_counter_alloc();
if (IS_ERR_VALUE(iter1->counters.pcnt)) {
ret = -ENOMEM;
break;
}
ret = check_target(iter1, name);
if (ret != 0) {
xt_percpu_counter_free(iter1->counters.pcnt);
break;
}
++i;
if (strcmp(arpt_get_target(iter1)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
if (ret) {
/*
* The first i matches need cleanup_entry (calls ->destroy)
* because they had called ->check already. The other j-i
* entries need only release.
*/
int skip = i;
j -= i;
xt_entry_foreach(iter0, entry0, newinfo->size) {
if (skip-- > 0)
continue;
if (j-- == 0)
break;
compat_release_entry(iter0);
}
xt_entry_foreach(iter1, entry1, newinfo->size) {
if (i-- == 0)
break;
cleanup_entry(iter1);
}
xt_free_table_info(newinfo);
return ret;
}
*pinfo = newinfo;
*pentry0 = entry1;
xt_free_table_info(info);
return 0;
free_newinfo:
xt_free_table_info(newinfo);
out:
xt_entry_foreach(iter0, entry0, total_size) {
if (j-- == 0)
break;
compat_release_entry(iter0);
}
return ret;
out_unlock:
xt_compat_flush_offsets(NFPROTO_ARP);
xt_compat_unlock(NFPROTO_ARP);
goto out;
}
struct compat_arpt_replace {
char name[XT_TABLE_MAXNAMELEN];
u32 valid_hooks;
u32 num_entries;
u32 size;
u32 hook_entry[NF_ARP_NUMHOOKS];
u32 underflow[NF_ARP_NUMHOOKS];
u32 num_counters;
compat_uptr_t counters;
struct compat_arpt_entry entries[0];
};
static int compat_do_replace(struct net *net, void __user *user,
unsigned int len)
{
int ret;
struct compat_arpt_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct arpt_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.size >= INT_MAX / num_possible_cpus())
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
if (tmp.num_counters == 0)
return -EINVAL;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_compat_table(tmp.name, tmp.valid_hooks,
&newinfo, &loc_cpu_entry, tmp.size,
tmp.num_entries, tmp.hook_entry,
tmp.underflow);
if (ret != 0)
goto free_newinfo;
duprintf("compat_do_replace: Translated table\n");
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, compat_ptr(tmp.counters));
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int compat_do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user,
unsigned int len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case ARPT_SO_SET_REPLACE:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case ARPT_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 1);
break;
default:
duprintf("do_arpt_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static int compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr,
compat_uint_t *size,
struct xt_counters *counters,
unsigned int i)
{
struct xt_entry_target *t;
struct compat_arpt_entry __user *ce;
u_int16_t target_offset, next_offset;
compat_uint_t origsize;
int ret;
origsize = *size;
ce = (struct compat_arpt_entry __user *)*dstptr;
if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 ||
copy_to_user(&ce->counters, &counters[i],
sizeof(counters[i])) != 0)
return -EFAULT;
*dstptr += sizeof(struct compat_arpt_entry);
*size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
target_offset = e->target_offset - (origsize - *size);
t = arpt_get_target(e);
ret = xt_compat_target_to_user(t, dstptr, size);
if (ret)
return ret;
next_offset = e->next_offset - (origsize - *size);
if (put_user(target_offset, &ce->target_offset) != 0 ||
put_user(next_offset, &ce->next_offset) != 0)
return -EFAULT;
return 0;
}
static int compat_copy_entries_to_user(unsigned int total_size,
struct xt_table *table,
void __user *userptr)
{
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
void __user *pos;
unsigned int size;
int ret = 0;
unsigned int i = 0;
struct arpt_entry *iter;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
pos = userptr;
size = total_size;
xt_entry_foreach(iter, private->entries, total_size) {
ret = compat_copy_entry_to_user(iter, &pos,
&size, counters, i++);
if (ret != 0)
break;
}
vfree(counters);
return ret;
}
struct compat_arpt_get_entries {
char name[XT_TABLE_MAXNAMELEN];
compat_uint_t size;
struct compat_arpt_entry entrytable[0];
};
static int compat_get_entries(struct net *net,
struct compat_arpt_get_entries __user *uptr,
int *len)
{
int ret;
struct compat_arpt_get_entries get;
struct xt_table *t;
if (*len < sizeof(get)) {
duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get));
return -EINVAL;
}
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct compat_arpt_get_entries) + get.size) {
duprintf("compat_get_entries: %u != %zu\n",
*len, sizeof(get) + get.size);
return -EINVAL;
}
xt_compat_lock(NFPROTO_ARP);
t = xt_find_table_lock(net, NFPROTO_ARP, get.name);
if (!IS_ERR_OR_NULL(t)) {
const struct xt_table_info *private = t->private;
struct xt_table_info info;
duprintf("t->private->number = %u\n", private->number);
ret = compat_table_info(private, &info);
if (!ret && get.size == info.size) {
ret = compat_copy_entries_to_user(private->size,
t, uptr->entrytable);
} else if (!ret) {
duprintf("compat_get_entries: I've got %u not %u!\n",
private->size, get.size);
ret = -EAGAIN;
}
xt_compat_flush_offsets(NFPROTO_ARP);
module_put(t->me);
xt_table_unlock(t);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
xt_compat_unlock(NFPROTO_ARP);
return ret;
}
static int do_arpt_get_ctl(struct sock *, int, void __user *, int *);
static int compat_do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user,
int *len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case ARPT_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 1);
break;
case ARPT_SO_GET_ENTRIES:
ret = compat_get_entries(sock_net(sk), user, len);
break;
default:
ret = do_arpt_get_ctl(sk, cmd, user, len);
}
return ret;
}
#endif
static int do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case ARPT_SO_SET_REPLACE:
ret = do_replace(sock_net(sk), user, len);
break;
case ARPT_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 0);
break;
default:
duprintf("do_arpt_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static int do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case ARPT_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 0);
break;
case ARPT_SO_GET_ENTRIES:
ret = get_entries(sock_net(sk), user, len);
break;
case ARPT_SO_GET_REVISION_TARGET: {
struct xt_get_revision rev;
if (*len != sizeof(rev)) {
ret = -EINVAL;
break;
}
if (copy_from_user(&rev, user, sizeof(rev)) != 0) {
ret = -EFAULT;
break;
}
rev.name[sizeof(rev.name)-1] = 0;
try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name,
rev.revision, 1, &ret),
"arpt_%s", rev.name);
break;
}
default:
duprintf("do_arpt_get_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static void __arpt_unregister_table(struct xt_table *table)
{
struct xt_table_info *private;
void *loc_cpu_entry;
struct module *table_owner = table->me;
struct arpt_entry *iter;
private = xt_unregister_table(table);
/* Decrease module usage counts and free resources */
loc_cpu_entry = private->entries;
xt_entry_foreach(iter, loc_cpu_entry, private->size)
cleanup_entry(iter);
if (private->number > private->initial_entries)
module_put(table_owner);
xt_free_table_info(private);
}
int arpt_register_table(struct net *net,
const struct xt_table *table,
const struct arpt_replace *repl,
const struct nf_hook_ops *ops,
struct xt_table **res)
{
int ret;
struct xt_table_info *newinfo;
struct xt_table_info bootstrap = {0};
void *loc_cpu_entry;
struct xt_table *new_table;
newinfo = xt_alloc_table_info(repl->size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
memcpy(loc_cpu_entry, repl->entries, repl->size);
ret = translate_table(newinfo, loc_cpu_entry, repl);
duprintf("arpt_register_table: translate table gives %d\n", ret);
if (ret != 0)
goto out_free;
new_table = xt_register_table(net, table, &bootstrap, newinfo);
if (IS_ERR(new_table)) {
ret = PTR_ERR(new_table);
goto out_free;
}
/* set res now, will see skbs right after nf_register_net_hooks */
WRITE_ONCE(*res, new_table);
ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks));
if (ret != 0) {
__arpt_unregister_table(new_table);
*res = NULL;
}
return ret;
out_free:
xt_free_table_info(newinfo);
return ret;
}
void arpt_unregister_table(struct net *net, struct xt_table *table,
const struct nf_hook_ops *ops)
{
nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks));
__arpt_unregister_table(table);
}
/* The built-in targets: standard (NULL) and error. */
static struct xt_target arpt_builtin_tg[] __read_mostly = {
{
.name = XT_STANDARD_TARGET,
.targetsize = sizeof(int),
.family = NFPROTO_ARP,
#ifdef CONFIG_COMPAT
.compatsize = sizeof(compat_int_t),
.compat_from_user = compat_standard_from_user,
.compat_to_user = compat_standard_to_user,
#endif
},
{
.name = XT_ERROR_TARGET,
.target = arpt_error,
.targetsize = XT_FUNCTION_MAXNAMELEN,
.family = NFPROTO_ARP,
},
};
static struct nf_sockopt_ops arpt_sockopts = {
.pf = PF_INET,
.set_optmin = ARPT_BASE_CTL,
.set_optmax = ARPT_SO_SET_MAX+1,
.set = do_arpt_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_arpt_set_ctl,
#endif
.get_optmin = ARPT_BASE_CTL,
.get_optmax = ARPT_SO_GET_MAX+1,
.get = do_arpt_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_arpt_get_ctl,
#endif
.owner = THIS_MODULE,
};
static int __net_init arp_tables_net_init(struct net *net)
{
return xt_proto_init(net, NFPROTO_ARP);
}
static void __net_exit arp_tables_net_exit(struct net *net)
{
xt_proto_fini(net, NFPROTO_ARP);
}
static struct pernet_operations arp_tables_net_ops = {
.init = arp_tables_net_init,
.exit = arp_tables_net_exit,
};
static int __init arp_tables_init(void)
{
int ret;
ret = register_pernet_subsys(&arp_tables_net_ops);
if (ret < 0)
goto err1;
/* No one else will be downing sem now, so we won't sleep */
ret = xt_register_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg));
if (ret < 0)
goto err2;
/* Register setsockopt */
ret = nf_register_sockopt(&arpt_sockopts);
if (ret < 0)
goto err4;
pr_info("arp_tables: (C) 2002 David S. Miller\n");
return 0;
err4:
xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg));
err2:
unregister_pernet_subsys(&arp_tables_net_ops);
err1:
return ret;
}
static void __exit arp_tables_fini(void)
{
nf_unregister_sockopt(&arpt_sockopts);
xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg));
unregister_pernet_subsys(&arp_tables_net_ops);
}
EXPORT_SYMBOL(arpt_register_table);
EXPORT_SYMBOL(arpt_unregister_table);
EXPORT_SYMBOL(arpt_do_table);
module_init(arp_tables_init);
module_exit(arp_tables_fini);
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5079_0 |
crossvul-cpp_data_good_5283_3 | /*
+----------------------------------------------------------------------+
| ZIP archive support for Phar |
+----------------------------------------------------------------------+
| Copyright (c) 2007-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Gregory Beaver <cellog@php.net> |
+----------------------------------------------------------------------+
*/
#include "phar_internal.h"
#define PHAR_GET_16(var) ((php_uint16)((((php_uint16)var[0]) & 0xff) | \
(((php_uint16)var[1]) & 0xff) << 8))
#define PHAR_GET_32(var) ((php_uint32)((((php_uint32)var[0]) & 0xff) | \
(((php_uint32)var[1]) & 0xff) << 8 | \
(((php_uint32)var[2]) & 0xff) << 16 | \
(((php_uint32)var[3]) & 0xff) << 24))
static inline void phar_write_32(char buffer[4], php_uint32 value)
{
buffer[3] = (unsigned char) ((value & 0xff000000) >> 24);
buffer[2] = (unsigned char) ((value & 0xff0000) >> 16);
buffer[1] = (unsigned char) ((value & 0xff00) >> 8);
buffer[0] = (unsigned char) (value & 0xff);
}
static inline void phar_write_16(char buffer[2], php_uint32 value)
{
buffer[1] = (unsigned char) ((value & 0xff00) >> 8);
buffer[0] = (unsigned char) (value & 0xff);
}
# define PHAR_SET_32(var, value) phar_write_32(var, (php_uint32) (value));
# define PHAR_SET_16(var, value) phar_write_16(var, (php_uint16) (value));
static int phar_zip_process_extra(php_stream *fp, phar_entry_info *entry, php_uint16 len) /* {{{ */
{
union {
phar_zip_extra_field_header header;
phar_zip_unix3 unix3;
} h;
int read;
do {
if (sizeof(h.header) != php_stream_read(fp, (char *) &h.header, sizeof(h.header))) {
return FAILURE;
}
if (h.header.tag[0] != 'n' || h.header.tag[1] != 'u') {
/* skip to next header */
php_stream_seek(fp, PHAR_GET_16(h.header.size), SEEK_CUR);
len -= PHAR_GET_16(h.header.size) + 4;
continue;
}
/* unix3 header found */
read = php_stream_read(fp, (char *) &(h.unix3.crc32), sizeof(h.unix3) - sizeof(h.header));
len -= read + 4;
if (sizeof(h.unix3) - sizeof(h.header) != read) {
return FAILURE;
}
if (PHAR_GET_16(h.unix3.size) > sizeof(h.unix3) - 4) {
/* skip symlink filename - we may add this support in later */
php_stream_seek(fp, PHAR_GET_16(h.unix3.size) - sizeof(h.unix3.size), SEEK_CUR);
}
/* set permissions */
entry->flags &= PHAR_ENT_COMPRESSION_MASK;
if (entry->is_dir) {
entry->flags |= PHAR_GET_16(h.unix3.perms) & PHAR_ENT_PERM_MASK;
} else {
entry->flags |= PHAR_GET_16(h.unix3.perms) & PHAR_ENT_PERM_MASK;
}
} while (len);
return SUCCESS;
}
/* }}} */
/*
extracted from libzip
zip_dirent.c -- read directory entry (local or central), clean dirent
Copyright (C) 1999, 2003, 2004, 2005 Dieter Baron and Thomas Klausner
This function is part of libzip, a library to manipulate ZIP archives.
The authors can be contacted at <nih@giga.or.at>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The names of the authors may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
static time_t phar_zip_d2u_time(char *cdtime, char *cddate) /* {{{ */
{
int dtime = PHAR_GET_16(cdtime), ddate = PHAR_GET_16(cddate);
struct tm *tm, tmbuf;
time_t now;
now = time(NULL);
tm = php_localtime_r(&now, &tmbuf);
tm->tm_year = ((ddate>>9)&127) + 1980 - 1900;
tm->tm_mon = ((ddate>>5)&15) - 1;
tm->tm_mday = ddate&31;
tm->tm_hour = (dtime>>11)&31;
tm->tm_min = (dtime>>5)&63;
tm->tm_sec = (dtime<<1)&62;
return mktime(tm);
}
/* }}} */
static void phar_zip_u2d_time(time_t time, char *dtime, char *ddate) /* {{{ */
{
php_uint16 ctime, cdate;
struct tm *tm, tmbuf;
tm = php_localtime_r(&time, &tmbuf);
cdate = ((tm->tm_year+1900-1980)<<9) + ((tm->tm_mon+1)<<5) + tm->tm_mday;
ctime = ((tm->tm_hour)<<11) + ((tm->tm_min)<<5) + ((tm->tm_sec)>>1);
PHAR_SET_16(dtime, ctime);
PHAR_SET_16(ddate, cdate);
}
/* }}} */
/**
* Does not check for a previously opened phar in the cache.
*
* Parse a new one and add it to the cache, returning either SUCCESS or
* FAILURE, and setting pphar to the pointer to the manifest entry
*
* This is used by phar_open_from_fp to process a zip-based phar, but can be called
* directly.
*/
int phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error) /* {{{ */
{
phar_zip_dir_end locator;
char buf[sizeof(locator) + 65536];
zend_long size;
php_uint16 i;
phar_archive_data *mydata = NULL;
phar_entry_info entry = {0};
char *p = buf, *ext, *actual_alias = NULL;
char *metadata = NULL;
size = php_stream_tell(fp);
if (size > sizeof(locator) + 65536) {
/* seek to max comment length + end of central directory record */
size = sizeof(locator) + 65536;
if (FAILURE == php_stream_seek(fp, -size, SEEK_END)) {
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: unable to search for end of central directory in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
} else {
php_stream_seek(fp, 0, SEEK_SET);
}
if (!php_stream_read(fp, buf, size)) {
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: unable to read in data to search for end of central directory in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
while ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) {
if ((p - buf) + sizeof(locator) <= size && !memcmp(p + 1, "K\5\6", 3)) {
memcpy((void *)&locator, (void *) p, sizeof(locator));
if (PHAR_GET_16(locator.centraldisk) != 0 || PHAR_GET_16(locator.disknumber) != 0) {
/* split archives not handled */
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: split archives spanning multiple zips cannot be processed in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
if (PHAR_GET_16(locator.counthere) != PHAR_GET_16(locator.count)) {
if (error) {
spprintf(error, 4096, "phar error: corrupt zip archive, conflicting file count in end of central directory record in zip-based phar \"%s\"", fname);
}
php_stream_close(fp);
return FAILURE;
}
mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));
mydata->is_persistent = PHAR_G(persist);
/* read in archive comment, if any */
if (PHAR_GET_16(locator.comment_len)) {
metadata = p + sizeof(locator);
if (PHAR_GET_16(locator.comment_len) != size - (metadata - buf)) {
if (error) {
spprintf(error, 4096, "phar error: corrupt zip archive, zip file comment truncated in zip-based phar \"%s\"", fname);
}
php_stream_close(fp);
pefree(mydata, mydata->is_persistent);
return FAILURE;
}
mydata->metadata_len = PHAR_GET_16(locator.comment_len);
if (phar_parse_metadata(&metadata, &mydata->metadata, PHAR_GET_16(locator.comment_len)) == FAILURE) {
mydata->metadata_len = 0;
/* if not valid serialized data, it is a regular string */
ZVAL_NEW_STR(&mydata->metadata, zend_string_init(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent));
}
} else {
ZVAL_UNDEF(&mydata->metadata);
}
goto foundit;
}
}
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: end of central directory not found in zip-based phar \"%s\"", fname);
}
return FAILURE;
foundit:
mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent);
#ifdef PHP_WIN32
phar_unixify_path_separators(mydata->fname, fname_len);
#endif
mydata->is_zip = 1;
mydata->fname_len = fname_len;
ext = strrchr(mydata->fname, '/');
if (ext) {
mydata->ext = memchr(ext, '.', (mydata->fname + fname_len) - ext);
if (mydata->ext == ext) {
mydata->ext = memchr(ext + 1, '.', (mydata->fname + fname_len) - ext - 1);
}
if (mydata->ext) {
mydata->ext_len = (mydata->fname + fname_len) - mydata->ext;
}
}
/* clean up on big-endian systems */
/* seek to central directory */
php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);
/* read in central directory */
zend_hash_init(&mydata->manifest, PHAR_GET_16(locator.count),
zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->mounted_dirs, 5,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->virtual_dirs, PHAR_GET_16(locator.count) * 2,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
entry.phar = mydata;
entry.is_zip = 1;
entry.fp_type = PHAR_FP;
entry.is_persistent = mydata->is_persistent;
#define PHAR_ZIP_FAIL_FREE(errmsg, save) \
zend_hash_destroy(&mydata->manifest); \
mydata->manifest.u.flags = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.u.flags = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.u.flags = 0; \
php_stream_close(fp); \
zval_dtor(&mydata->metadata); \
if (mydata->signature) { \
efree(mydata->signature); \
} \
if (error) { \
spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \
} \
pefree(mydata->fname, mydata->is_persistent); \
if (mydata->alias) { \
pefree(mydata->alias, mydata->is_persistent); \
} \
pefree(mydata, mydata->is_persistent); \
efree(save); \
return FAILURE;
#define PHAR_ZIP_FAIL(errmsg) \
zend_hash_destroy(&mydata->manifest); \
mydata->manifest.u.flags = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.u.flags = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.u.flags = 0; \
php_stream_close(fp); \
zval_dtor(&mydata->metadata); \
if (mydata->signature) { \
efree(mydata->signature); \
} \
if (error) { \
spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \
} \
pefree(mydata->fname, mydata->is_persistent); \
if (mydata->alias) { \
pefree(mydata->alias, mydata->is_persistent); \
} \
pefree(mydata, mydata->is_persistent); \
return FAILURE;
/* add each central directory item to the manifest */
for (i = 0; i < PHAR_GET_16(locator.count); ++i) {
phar_zip_central_dir_file zipentry;
zend_off_t beforeus = php_stream_tell(fp);
if (sizeof(zipentry) != php_stream_read(fp, (char *) &zipentry, sizeof(zipentry))) {
PHAR_ZIP_FAIL("unable to read central directory entry, truncated");
}
/* clean up for bigendian systems */
if (memcmp("PK\1\2", zipentry.signature, 4)) {
/* corrupted entry */
PHAR_ZIP_FAIL("corrupted central directory entry, no magic signature");
}
if (entry.is_persistent) {
entry.manifest_pos = i;
}
entry.compressed_filesize = PHAR_GET_32(zipentry.compsize);
entry.uncompressed_filesize = PHAR_GET_32(zipentry.uncompsize);
entry.crc32 = PHAR_GET_32(zipentry.crc32);
/* do not PHAR_GET_16 either on the next line */
entry.timestamp = phar_zip_d2u_time(zipentry.timestamp, zipentry.datestamp);
entry.flags = PHAR_ENT_PERM_DEF_FILE;
entry.header_offset = PHAR_GET_32(zipentry.offset);
entry.offset = entry.offset_abs = PHAR_GET_32(zipentry.offset) + sizeof(phar_zip_file_header) + PHAR_GET_16(zipentry.filename_len) +
PHAR_GET_16(zipentry.extra_len);
if (PHAR_GET_16(zipentry.flags) & PHAR_ZIP_FLAG_ENCRYPTED) {
PHAR_ZIP_FAIL("Cannot process encrypted zip files");
}
if (!PHAR_GET_16(zipentry.filename_len)) {
PHAR_ZIP_FAIL("Cannot process zips created from stdin (zero-length filename)");
}
entry.filename_len = PHAR_GET_16(zipentry.filename_len);
entry.filename = (char *) pemalloc(entry.filename_len + 1, entry.is_persistent);
if (entry.filename_len != php_stream_read(fp, entry.filename, entry.filename_len)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in filename from central directory, truncated");
}
entry.filename[entry.filename_len] = '\0';
if (entry.filename[entry.filename_len - 1] == '/') {
entry.is_dir = 1;
if(entry.filename_len > 1) {
entry.filename_len--;
}
entry.flags |= PHAR_ENT_PERM_DEF_DIR;
} else {
entry.is_dir = 0;
}
if (entry.filename_len == sizeof(".phar/signature.bin")-1 && !strncmp(entry.filename, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) {
size_t read;
php_stream *sigfile;
zend_off_t now;
char *sig;
now = php_stream_tell(fp);
pefree(entry.filename, entry.is_persistent);
sigfile = php_stream_fopen_tmpfile();
if (!sigfile) {
PHAR_ZIP_FAIL("couldn't open temporary file");
}
php_stream_seek(fp, 0, SEEK_SET);
/* copy file contents + local headers and zip comment, if any, to be hashed for signature */
php_stream_copy_to_stream_ex(fp, sigfile, entry.header_offset, NULL);
/* seek to central directory */
php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);
/* copy central directory header */
php_stream_copy_to_stream_ex(fp, sigfile, beforeus - PHAR_GET_32(locator.cdir_offset), NULL);
if (metadata) {
php_stream_write(sigfile, metadata, PHAR_GET_16(locator.comment_len));
}
php_stream_seek(fp, sizeof(phar_zip_file_header) + entry.header_offset + entry.filename_len + PHAR_GET_16(zipentry.extra_len), SEEK_SET);
sig = (char *) emalloc(entry.uncompressed_filesize);
read = php_stream_read(fp, sig, entry.uncompressed_filesize);
if (read != entry.uncompressed_filesize || read <= 8) {
php_stream_close(sigfile);
efree(sig);
PHAR_ZIP_FAIL("signature cannot be read");
}
mydata->sig_flags = PHAR_GET_32(sig);
if (FAILURE == phar_verify_signature(sigfile, php_stream_tell(sigfile), mydata->sig_flags, sig + 8, entry.uncompressed_filesize - 8, fname, &mydata->signature, &mydata->sig_len, error)) {
efree(sig);
if (error) {
char *save;
php_stream_close(sigfile);
spprintf(&save, 4096, "signature cannot be verified: %s", *error);
efree(*error);
PHAR_ZIP_FAIL_FREE(save, save);
} else {
php_stream_close(sigfile);
PHAR_ZIP_FAIL("signature cannot be verified");
}
}
php_stream_close(sigfile);
efree(sig);
/* signature checked out, let's ensure this is the last file in the phar */
if (i != PHAR_GET_16(locator.count) - 1) {
PHAR_ZIP_FAIL("entries exist after signature, invalid phar");
}
continue;
}
phar_add_virtual_dirs(mydata, entry.filename, entry.filename_len);
if (PHAR_GET_16(zipentry.extra_len)) {
zend_off_t loc = php_stream_tell(fp);
if (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("Unable to process extra field header for file in central directory");
}
php_stream_seek(fp, loc + PHAR_GET_16(zipentry.extra_len), SEEK_SET);
}
switch (PHAR_GET_16(zipentry.compressed)) {
case PHAR_ZIP_COMP_NONE :
/* compression flag already set */
break;
case PHAR_ZIP_COMP_DEFLATE :
entry.flags |= PHAR_ENT_COMPRESSED_GZ;
if (!PHAR_G(has_zlib)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("zlib extension is required");
}
break;
case PHAR_ZIP_COMP_BZIP2 :
entry.flags |= PHAR_ENT_COMPRESSED_BZ2;
if (!PHAR_G(has_bz2)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("bzip2 extension is required");
}
break;
case 1 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Shrunk) used in this zip");
case 2 :
case 3 :
case 4 :
case 5 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Reduce) used in this zip");
case 6 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Implode) used in this zip");
case 7 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Tokenize) used in this zip");
case 9 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Deflate64) used in this zip");
case 10 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (PKWare Implode/old IBM TERSE) used in this zip");
case 14 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (LZMA) used in this zip");
case 18 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (IBM TERSE) used in this zip");
case 19 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (IBM LZ77) used in this zip");
case 97 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (WavPack) used in this zip");
case 98 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (PPMd) used in this zip");
default :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (unknown) used in this zip");
}
/* get file metadata */
if (PHAR_GET_16(zipentry.comment_len)) {
if (PHAR_GET_16(zipentry.comment_len) != php_stream_read(fp, buf, PHAR_GET_16(zipentry.comment_len))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in file comment, truncated");
}
p = buf;
entry.metadata_len = PHAR_GET_16(zipentry.comment_len);
if (phar_parse_metadata(&p, &(entry.metadata), PHAR_GET_16(zipentry.comment_len)) == FAILURE) {
entry.metadata_len = 0;
/* if not valid serialized data, it is a regular string */
ZVAL_NEW_STR(&entry.metadata, zend_string_init(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent));
}
} else {
ZVAL_UNDEF(&entry.metadata);
}
if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
php_stream_filter *filter;
zend_off_t saveloc;
/* verify local file header */
phar_zip_file_header local;
/* archive alias found */
saveloc = php_stream_tell(fp);
php_stream_seek(fp, PHAR_GET_32(zipentry.offset), SEEK_SET);
if (sizeof(local) != php_stream_read(fp, (char *) &local, sizeof(local))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (cannot read local file header for alias)");
}
/* verify local header */
if (entry.filename_len != PHAR_GET_16(local.filename_len) || entry.crc32 != PHAR_GET_32(local.crc32) || entry.uncompressed_filesize != PHAR_GET_32(local.uncompsize) || entry.compressed_filesize != PHAR_GET_32(local.compsize)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (local header of alias does not match central directory)");
}
/* construct actual offset to file start - local extra_len can be different from central extra_len */
entry.offset = entry.offset_abs =
sizeof(local) + entry.header_offset + PHAR_GET_16(local.filename_len) + PHAR_GET_16(local.extra_len);
php_stream_seek(fp, entry.offset, SEEK_SET);
/* these next lines should be for php < 5.2.6 after 5.3 filters are fixed */
fp->writepos = 0;
fp->readpos = 0;
php_stream_seek(fp, entry.offset, SEEK_SET);
fp->writepos = 0;
fp->readpos = 0;
/* the above lines should be for php < 5.2.6 after 5.3 filters are fixed */
mydata->alias_len = entry.uncompressed_filesize;
if (entry.flags & PHAR_ENT_COMPRESSED_GZ) {
filter = php_stream_filter_create("zlib.inflate", NULL, php_stream_is_persistent(fp));
if (!filter) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to decompress alias, zlib filter creation failed");
}
php_stream_filter_append(&fp->readfilters, filter);
// TODO: refactor to avoid reallocation ???
//??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)
{
zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);
if (str) {
entry.uncompressed_filesize = ZSTR_LEN(str);
actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
} else {
actual_alias = NULL;
entry.uncompressed_filesize = 0;
}
}
if (!entry.uncompressed_filesize || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1);
} else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) {
filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp));
if (!filter) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, bzip2 filter creation failed");
}
php_stream_filter_append(&fp->readfilters, filter);
// TODO: refactor to avoid reallocation ???
//??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)
{
zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);
if (str) {
entry.uncompressed_filesize = ZSTR_LEN(str);
actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
} else {
actual_alias = NULL;
entry.uncompressed_filesize = 0;
}
}
if (!entry.uncompressed_filesize || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1);
} else {
// TODO: refactor to avoid reallocation ???
//??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)
{
zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);
if (str) {
entry.uncompressed_filesize = ZSTR_LEN(str);
actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
} else {
actual_alias = NULL;
entry.uncompressed_filesize = 0;
}
}
if (!entry.uncompressed_filesize || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
}
/* return to central directory parsing */
php_stream_seek(fp, saveloc, SEEK_SET);
}
phar_set_inode(&entry);
zend_hash_str_add_mem(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry, sizeof(phar_entry_info));
}
mydata->fp = fp;
if (zend_hash_str_exists(&(mydata->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
mydata->is_data = 0;
} else {
mydata->is_data = 1;
}
zend_hash_str_add_ptr(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len, mydata);
if (actual_alias) {
phar_archive_data *fd_ptr;
if (!phar_validate_alias(actual_alias, mydata->alias_len)) {
if (error) {
spprintf(error, 4096, "phar error: invalid alias \"%s\" in zip-based phar \"%s\"", actual_alias, fname);
}
efree(actual_alias);
zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);
return FAILURE;
}
mydata->is_temporary_alias = 0;
if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len))) {
if (SUCCESS != phar_free_alias(fd_ptr, actual_alias, mydata->alias_len)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with implicit alias, alias is already in use", fname);
}
efree(actual_alias);
zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);
return FAILURE;
}
}
mydata->alias = entry.is_persistent ? pestrndup(actual_alias, mydata->alias_len, 1) : actual_alias;
if (entry.is_persistent) {
efree(actual_alias);
}
zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata);
} else {
phar_archive_data *fd_ptr;
if (alias_len) {
if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) {
if (SUCCESS != phar_free_alias(fd_ptr, alias, alias_len)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with explicit alias, alias is already in use", fname);
}
zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);
return FAILURE;
}
}
zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata);
mydata->alias = pestrndup(alias, alias_len, mydata->is_persistent);
mydata->alias_len = alias_len;
} else {
mydata->alias = pestrndup(mydata->fname, fname_len, mydata->is_persistent);
mydata->alias_len = fname_len;
}
mydata->is_temporary_alias = 1;
}
if (pphar) {
*pphar = mydata;
}
return SUCCESS;
}
/* }}} */
/**
* Create or open a zip-based phar for writing
*/
int phar_open_or_create_zip(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error) /* {{{ */
{
phar_archive_data *phar;
int ret = phar_create_or_parse_filename(fname, fname_len, alias, alias_len, is_data, options, &phar, error);
if (FAILURE == ret) {
return FAILURE;
}
if (pphar) {
*pphar = phar;
}
phar->is_data = is_data;
if (phar->is_zip) {
return ret;
}
if (phar->is_brandnew) {
phar->internal_file_start = 0;
phar->is_zip = 1;
phar->is_tar = 0;
return SUCCESS;
}
/* we've reached here - the phar exists and is a regular phar */
if (error) {
spprintf(error, 4096, "phar zip error: phar \"%s\" already exists as a regular phar and must be deleted from disk prior to creating as a zip-based phar", fname);
}
return FAILURE;
}
/* }}} */
struct _phar_zip_pass {
php_stream *filefp;
php_stream *centralfp;
php_stream *old;
int free_fp;
int free_ufp;
char **error;
};
/* perform final modification of zip contents for each file in the manifest before saving */
static int phar_zip_changed_apply_int(phar_entry_info *entry, void *arg) /* {{{ */
{
phar_zip_file_header local;
phar_zip_unix3 perms;
phar_zip_central_dir_file central;
struct _phar_zip_pass *p;
php_uint32 newcrc32;
zend_off_t offset;
int not_really_modified = 0;
p = (struct _phar_zip_pass*) arg;
if (entry->is_mounted) {
return ZEND_HASH_APPLY_KEEP;
}
if (entry->is_deleted) {
if (entry->fp_refcount <= 0) {
return ZEND_HASH_APPLY_REMOVE;
} else {
/* we can't delete this in-memory until it is closed */
return ZEND_HASH_APPLY_KEEP;
}
}
phar_add_virtual_dirs(entry->phar, entry->filename, entry->filename_len);
memset(&local, 0, sizeof(local));
memset(¢ral, 0, sizeof(central));
memset(&perms, 0, sizeof(perms));
strncpy(local.signature, "PK\3\4", 4);
strncpy(central.signature, "PK\1\2", 4);
PHAR_SET_16(central.extra_len, sizeof(perms));
PHAR_SET_16(local.extra_len, sizeof(perms));
perms.tag[0] = 'n';
perms.tag[1] = 'u';
PHAR_SET_16(perms.size, sizeof(perms) - 4);
PHAR_SET_16(perms.perms, entry->flags & PHAR_ENT_PERM_MASK);
{
php_uint32 crc = (php_uint32) ~0;
CRC32(crc, perms.perms[0]);
CRC32(crc, perms.perms[1]);
PHAR_SET_32(perms.crc32, ~crc);
}
if (entry->flags & PHAR_ENT_COMPRESSED_GZ) {
PHAR_SET_16(central.compressed, PHAR_ZIP_COMP_DEFLATE);
PHAR_SET_16(local.compressed, PHAR_ZIP_COMP_DEFLATE);
}
if (entry->flags & PHAR_ENT_COMPRESSED_BZ2) {
PHAR_SET_16(central.compressed, PHAR_ZIP_COMP_BZIP2);
PHAR_SET_16(local.compressed, PHAR_ZIP_COMP_BZIP2);
}
/* do not use PHAR_GET_16 on either field of the next line */
phar_zip_u2d_time(entry->timestamp, local.timestamp, local.datestamp);
memcpy(central.timestamp, local.timestamp, sizeof(local.timestamp));
memcpy(central.datestamp, local.datestamp, sizeof(local.datestamp));
PHAR_SET_16(central.filename_len, entry->filename_len + (entry->is_dir ? 1 : 0));
PHAR_SET_16(local.filename_len, entry->filename_len + (entry->is_dir ? 1 : 0));
PHAR_SET_32(central.offset, php_stream_tell(p->filefp));
/* do extra field for perms later */
if (entry->is_modified) {
php_uint32 loc;
php_stream_filter *filter;
php_stream *efp;
if (entry->is_dir) {
entry->is_modified = 0;
if (entry->fp_type == PHAR_MOD && entry->fp != entry->phar->fp && entry->fp != entry->phar->ufp) {
php_stream_close(entry->fp);
entry->fp = NULL;
entry->fp_type = PHAR_FP;
}
goto continue_dir;
}
if (FAILURE == phar_open_entry_fp(entry, p->error, 0)) {
spprintf(p->error, 0, "unable to open file contents of file \"%s\" in zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
/* we can be modified and already be compressed, such as when chmod() is executed */
if (entry->flags & PHAR_ENT_COMPRESSION_MASK && (entry->old_flags == entry->flags || !entry->old_flags)) {
not_really_modified = 1;
goto is_compressed;
}
if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0)) {
spprintf(p->error, 0, "unable to seek to start of file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
efp = phar_get_efp(entry, 0);
newcrc32 = ~0;
for (loc = 0;loc < entry->uncompressed_filesize; ++loc) {
CRC32(newcrc32, php_stream_getc(efp));
}
entry->crc32 = ~newcrc32;
PHAR_SET_32(central.uncompsize, entry->uncompressed_filesize);
PHAR_SET_32(local.uncompsize, entry->uncompressed_filesize);
if (!(entry->flags & PHAR_ENT_COMPRESSION_MASK)) {
/* not compressed */
entry->compressed_filesize = entry->uncompressed_filesize;
PHAR_SET_32(central.compsize, entry->uncompressed_filesize);
PHAR_SET_32(local.compsize, entry->uncompressed_filesize);
goto not_compressed;
}
filter = php_stream_filter_create(phar_compress_filter(entry, 0), NULL, 0);
if (!filter) {
if (entry->flags & PHAR_ENT_COMPRESSED_GZ) {
spprintf(p->error, 0, "unable to gzip compress file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
} else {
spprintf(p->error, 0, "unable to bzip2 compress file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
}
return ZEND_HASH_APPLY_STOP;
}
/* create new file that holds the compressed version */
/* work around inability to specify freedom in write and strictness
in read count */
entry->cfp = php_stream_fopen_tmpfile();
if (!entry->cfp) {
spprintf(p->error, 0, "unable to create temporary file for file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
php_stream_flush(efp);
if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0)) {
spprintf(p->error, 0, "unable to seek to start of file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
php_stream_filter_append((&entry->cfp->writefilters), filter);
if (SUCCESS != php_stream_copy_to_stream_ex(efp, entry->cfp, entry->uncompressed_filesize, NULL)) {
spprintf(p->error, 0, "unable to copy compressed file contents of file \"%s\" while creating new phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
php_stream_filter_flush(filter, 1);
php_stream_flush(entry->cfp);
php_stream_filter_remove(filter, 1);
php_stream_seek(entry->cfp, 0, SEEK_END);
entry->compressed_filesize = (php_uint32) php_stream_tell(entry->cfp);
PHAR_SET_32(central.compsize, entry->compressed_filesize);
PHAR_SET_32(local.compsize, entry->compressed_filesize);
/* generate crc on compressed file */
php_stream_rewind(entry->cfp);
entry->old_flags = entry->flags;
entry->is_modified = 1;
} else {
is_compressed:
PHAR_SET_32(central.uncompsize, entry->uncompressed_filesize);
PHAR_SET_32(local.uncompsize, entry->uncompressed_filesize);
PHAR_SET_32(central.compsize, entry->compressed_filesize);
PHAR_SET_32(local.compsize, entry->compressed_filesize);
if (p->old) {
if (-1 == php_stream_seek(p->old, entry->offset_abs, SEEK_SET)) {
spprintf(p->error, 0, "unable to seek to start of file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
}
}
not_compressed:
PHAR_SET_32(central.crc32, entry->crc32);
PHAR_SET_32(local.crc32, entry->crc32);
continue_dir:
/* set file metadata */
if (Z_TYPE(entry->metadata) != IS_UNDEF) {
php_serialize_data_t metadata_hash;
if (entry->metadata_str.s) {
smart_str_free(&entry->metadata_str);
}
entry->metadata_str.s = NULL;
PHP_VAR_SERIALIZE_INIT(metadata_hash);
php_var_serialize(&entry->metadata_str, &entry->metadata, &metadata_hash);
PHP_VAR_SERIALIZE_DESTROY(metadata_hash);
PHAR_SET_16(central.comment_len, ZSTR_LEN(entry->metadata_str.s));
}
entry->header_offset = php_stream_tell(p->filefp);
offset = entry->header_offset + sizeof(local) + entry->filename_len + (entry->is_dir ? 1 : 0) + sizeof(perms);
if (sizeof(local) != php_stream_write(p->filefp, (char *)&local, sizeof(local))) {
spprintf(p->error, 0, "unable to write local file header of file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (sizeof(central) != php_stream_write(p->centralfp, (char *)¢ral, sizeof(central))) {
spprintf(p->error, 0, "unable to write central directory entry for file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (entry->is_dir) {
if (entry->filename_len != php_stream_write(p->filefp, entry->filename, entry->filename_len)) {
spprintf(p->error, 0, "unable to write filename to local directory entry for directory \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (1 != php_stream_write(p->filefp, "/", 1)) {
spprintf(p->error, 0, "unable to write filename to local directory entry for directory \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (entry->filename_len != php_stream_write(p->centralfp, entry->filename, entry->filename_len)) {
spprintf(p->error, 0, "unable to write filename to central directory entry for directory \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (1 != php_stream_write(p->centralfp, "/", 1)) {
spprintf(p->error, 0, "unable to write filename to central directory entry for directory \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
} else {
if (entry->filename_len != php_stream_write(p->filefp, entry->filename, entry->filename_len)) {
spprintf(p->error, 0, "unable to write filename to local directory entry for file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (entry->filename_len != php_stream_write(p->centralfp, entry->filename, entry->filename_len)) {
spprintf(p->error, 0, "unable to write filename to central directory entry for file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
}
if (sizeof(perms) != php_stream_write(p->filefp, (char *)&perms, sizeof(perms))) {
spprintf(p->error, 0, "unable to write local extra permissions file header of file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (sizeof(perms) != php_stream_write(p->centralfp, (char *)&perms, sizeof(perms))) {
spprintf(p->error, 0, "unable to write central extra permissions file header of file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (!not_really_modified && entry->is_modified) {
if (entry->cfp) {
if (SUCCESS != php_stream_copy_to_stream_ex(entry->cfp, p->filefp, entry->compressed_filesize, NULL)) {
spprintf(p->error, 0, "unable to write compressed contents of file \"%s\" in zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
php_stream_close(entry->cfp);
entry->cfp = NULL;
} else {
if (FAILURE == phar_open_entry_fp(entry, p->error, 0)) {
return ZEND_HASH_APPLY_STOP;
}
phar_seek_efp(entry, 0, SEEK_SET, 0, 0);
if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(entry, 0), p->filefp, entry->uncompressed_filesize, NULL)) {
spprintf(p->error, 0, "unable to write contents of file \"%s\" in zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
}
if (entry->fp_type == PHAR_MOD && entry->fp != entry->phar->fp && entry->fp != entry->phar->ufp && entry->fp_refcount == 0) {
php_stream_close(entry->fp);
}
entry->is_modified = 0;
} else {
entry->is_modified = 0;
if (entry->fp_refcount) {
/* open file pointers refer to this fp, do not free the stream */
switch (entry->fp_type) {
case PHAR_FP:
p->free_fp = 0;
break;
case PHAR_UFP:
p->free_ufp = 0;
default:
break;
}
}
if (!entry->is_dir && entry->compressed_filesize && SUCCESS != php_stream_copy_to_stream_ex(p->old, p->filefp, entry->compressed_filesize, NULL)) {
spprintf(p->error, 0, "unable to copy contents of file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
}
entry->fp = NULL;
entry->offset = entry->offset_abs = offset;
entry->fp_type = PHAR_FP;
if (entry->metadata_str.s) {
if (ZSTR_LEN(entry->metadata_str.s) != php_stream_write(p->centralfp, ZSTR_VAL(entry->metadata_str.s), ZSTR_LEN(entry->metadata_str.s))) {
spprintf(p->error, 0, "unable to write metadata as file comment for file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
smart_str_free(&entry->metadata_str);
return ZEND_HASH_APPLY_STOP;
}
smart_str_free(&entry->metadata_str);
}
return ZEND_HASH_APPLY_KEEP;
}
/* }}} */
static int phar_zip_changed_apply(zval *zv, void *arg) /* {{{ */
{
return phar_zip_changed_apply_int(Z_PTR_P(zv), arg);
}
/* }}} */
static int phar_zip_applysignature(phar_archive_data *phar, struct _phar_zip_pass *pass,
smart_str *metadata) /* {{{ */
{
/* add signature for executable tars or tars explicitly set with setSignatureAlgorithm */
if (!phar->is_data || phar->sig_flags) {
int signature_length;
char *signature, sigbuf[8];
phar_entry_info entry = {0};
php_stream *newfile;
zend_off_t tell, st;
newfile = php_stream_fopen_tmpfile();
if (newfile == NULL) {
spprintf(pass->error, 0, "phar error: unable to create temporary file for the signature file");
return FAILURE;
}
st = tell = php_stream_tell(pass->filefp);
/* copy the local files, central directory, and the zip comment to generate the hash */
php_stream_seek(pass->filefp, 0, SEEK_SET);
php_stream_copy_to_stream_ex(pass->filefp, newfile, tell, NULL);
tell = php_stream_tell(pass->centralfp);
php_stream_seek(pass->centralfp, 0, SEEK_SET);
php_stream_copy_to_stream_ex(pass->centralfp, newfile, tell, NULL);
if (metadata->s) {
php_stream_write(newfile, ZSTR_VAL(metadata->s), ZSTR_LEN(metadata->s));
}
if (FAILURE == phar_create_signature(phar, newfile, &signature, &signature_length, pass->error)) {
if (pass->error) {
char *save = *(pass->error);
spprintf(pass->error, 0, "phar error: unable to write signature to zip-based phar: %s", save);
efree(save);
}
php_stream_close(newfile);
return FAILURE;
}
entry.filename = ".phar/signature.bin";
entry.filename_len = sizeof(".phar/signature.bin")-1;
entry.fp = php_stream_fopen_tmpfile();
entry.fp_type = PHAR_MOD;
entry.is_modified = 1;
if (entry.fp == NULL) {
spprintf(pass->error, 0, "phar error: unable to create temporary file for signature");
return FAILURE;
}
PHAR_SET_32(sigbuf, phar->sig_flags);
PHAR_SET_32(sigbuf + 4, signature_length);
if (8 != (int)php_stream_write(entry.fp, sigbuf, 8) || signature_length != (int)php_stream_write(entry.fp, signature, signature_length)) {
efree(signature);
if (pass->error) {
spprintf(pass->error, 0, "phar error: unable to write signature to zip-based phar %s", phar->fname);
}
php_stream_close(newfile);
return FAILURE;
}
efree(signature);
entry.uncompressed_filesize = entry.compressed_filesize = signature_length + 8;
entry.phar = phar;
/* throw out return value and write the signature */
phar_zip_changed_apply_int(&entry, (void *)pass);
php_stream_close(newfile);
if (pass->error && *(pass->error)) {
/* error is set by writeheaders */
php_stream_close(newfile);
return FAILURE;
}
} /* signature */
return SUCCESS;
}
/* }}} */
int phar_zip_flush(phar_archive_data *phar, char *user_stub, zend_long len, int defaultstub, char **error) /* {{{ */
{
char *pos;
smart_str main_metadata_str = {0};
static const char newstub[] = "<?php // zip-based phar archive stub file\n__HALT_COMPILER();";
char halt_stub[] = "__HALT_COMPILER();";
char *tmp;
php_stream *stubfile, *oldfile;
php_serialize_data_t metadata_hash;
int free_user_stub, closeoldfile = 0;
phar_entry_info entry = {0};
char *temperr = NULL;
struct _phar_zip_pass pass;
phar_zip_dir_end eocd;
php_uint32 cdir_size, cdir_offset;
pass.error = &temperr;
entry.flags = PHAR_ENT_PERM_DEF_FILE;
entry.timestamp = time(NULL);
entry.is_modified = 1;
entry.is_zip = 1;
entry.phar = phar;
entry.fp_type = PHAR_MOD;
if (phar->is_persistent) {
if (error) {
spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
if (phar->is_data) {
goto nostub;
}
/* set alias */
if (!phar->is_temporary_alias && phar->alias_len) {
entry.fp = php_stream_fopen_tmpfile();
if (entry.fp == NULL) {
spprintf(error, 0, "phar error: unable to create temporary file");
return EOF;
}
if (phar->alias_len != (int)php_stream_write(entry.fp, phar->alias, phar->alias_len)) {
if (error) {
spprintf(error, 0, "unable to set alias in zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
entry.uncompressed_filesize = entry.compressed_filesize = phar->alias_len;
entry.filename = estrndup(".phar/alias.txt", sizeof(".phar/alias.txt")-1);
entry.filename_len = sizeof(".phar/alias.txt")-1;
if (NULL == zend_hash_str_update_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info))) {
if (error) {
spprintf(error, 0, "unable to set alias in zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
} else {
zend_hash_str_del(&phar->manifest, ".phar/alias.txt", sizeof(".phar/alias.txt")-1);
}
/* register alias */
if (phar->alias_len) {
if (FAILURE == phar_get_archive(&phar, phar->fname, phar->fname_len, phar->alias, phar->alias_len, error)) {
return EOF;
}
}
/* set stub */
if (user_stub && !defaultstub) {
if (len < 0) {
/* resource passed in */
if (!(php_stream_from_zval_no_verify(stubfile, (zval *)user_stub))) {
if (error) {
spprintf(error, 0, "unable to access resource to copy stub to new zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
if (len == -1) {
len = PHP_STREAM_COPY_ALL;
} else {
len = -len;
}
user_stub = 0;
// TODO: refactor to avoid reallocation ???
//??? len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)
{
zend_string *str = php_stream_copy_to_mem(stubfile, len, 0);
if (str) {
len = ZSTR_LEN(str);
user_stub = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
} else {
user_stub = NULL;
len = 0;
}
}
if (!len || !user_stub) {
if (error) {
spprintf(error, 0, "unable to read resource to copy stub to new zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
free_user_stub = 1;
} else {
free_user_stub = 0;
}
tmp = estrndup(user_stub, len);
if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) {
efree(tmp);
if (error) {
spprintf(error, 0, "illegal stub for zip-based phar \"%s\"", phar->fname);
}
if (free_user_stub) {
efree(user_stub);
}
return EOF;
}
pos = user_stub + (pos - tmp);
efree(tmp);
len = pos - user_stub + 18;
entry.fp = php_stream_fopen_tmpfile();
if (entry.fp == NULL) {
spprintf(error, 0, "phar error: unable to create temporary file");
return EOF;
}
entry.uncompressed_filesize = len + 5;
if ((size_t)len != php_stream_write(entry.fp, user_stub, len)
|| 5 != php_stream_write(entry.fp, " ?>\r\n", 5)) {
if (error) {
spprintf(error, 0, "unable to create stub from string in new zip-based phar \"%s\"", phar->fname);
}
if (free_user_stub) {
efree(user_stub);
}
php_stream_close(entry.fp);
return EOF;
}
entry.filename = estrndup(".phar/stub.php", sizeof(".phar/stub.php")-1);
entry.filename_len = sizeof(".phar/stub.php")-1;
if (NULL == zend_hash_str_update_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info))) {
if (free_user_stub) {
efree(user_stub);
}
if (error) {
spprintf(error, 0, "unable to set stub in zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
if (free_user_stub) {
efree(user_stub);
}
} else {
/* Either this is a brand new phar (add the stub), or the default stub is required (overwrite the stub) */
entry.fp = php_stream_fopen_tmpfile();
if (entry.fp == NULL) {
spprintf(error, 0, "phar error: unable to create temporary file");
return EOF;
}
if (sizeof(newstub)-1 != php_stream_write(entry.fp, newstub, sizeof(newstub)-1)) {
php_stream_close(entry.fp);
if (error) {
spprintf(error, 0, "unable to %s stub in%szip-based phar \"%s\", failed", user_stub ? "overwrite" : "create", user_stub ? " " : " new ", phar->fname);
}
return EOF;
}
entry.uncompressed_filesize = entry.compressed_filesize = sizeof(newstub) - 1;
entry.filename = estrndup(".phar/stub.php", sizeof(".phar/stub.php")-1);
entry.filename_len = sizeof(".phar/stub.php")-1;
if (!defaultstub) {
if (!zend_hash_str_exists(&phar->manifest, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
if (NULL == zend_hash_str_add_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info))) {
php_stream_close(entry.fp);
efree(entry.filename);
if (error) {
spprintf(error, 0, "unable to create stub in zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
} else {
php_stream_close(entry.fp);
efree(entry.filename);
}
} else {
if (NULL == zend_hash_str_update_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info))) {
php_stream_close(entry.fp);
efree(entry.filename);
if (error) {
spprintf(error, 0, "unable to overwrite stub in zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
}
}
nostub:
if (phar->fp && !phar->is_brandnew) {
oldfile = phar->fp;
closeoldfile = 0;
php_stream_rewind(oldfile);
} else {
oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL);
closeoldfile = oldfile != NULL;
}
/* save modified files to the zip */
pass.old = oldfile;
pass.filefp = php_stream_fopen_tmpfile();
if (!pass.filefp) {
fperror:
if (closeoldfile) {
php_stream_close(oldfile);
}
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to open temporary file", phar->fname);
}
return EOF;
}
pass.centralfp = php_stream_fopen_tmpfile();
if (!pass.centralfp) {
goto fperror;
}
pass.free_fp = pass.free_ufp = 1;
memset(&eocd, 0, sizeof(eocd));
strncpy(eocd.signature, "PK\5\6", 4);
if (!phar->is_data && !phar->sig_flags) {
phar->sig_flags = PHAR_SIG_SHA1;
}
if (phar->sig_flags) {
PHAR_SET_16(eocd.counthere, zend_hash_num_elements(&phar->manifest) + 1);
PHAR_SET_16(eocd.count, zend_hash_num_elements(&phar->manifest) + 1);
} else {
PHAR_SET_16(eocd.counthere, zend_hash_num_elements(&phar->manifest));
PHAR_SET_16(eocd.count, zend_hash_num_elements(&phar->manifest));
}
zend_hash_apply_with_argument(&phar->manifest, phar_zip_changed_apply, (void *) &pass);
if (Z_TYPE(phar->metadata) != IS_UNDEF) {
/* set phar metadata */
PHP_VAR_SERIALIZE_INIT(metadata_hash);
php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash);
PHP_VAR_SERIALIZE_DESTROY(metadata_hash);
}
if (temperr) {
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: %s", phar->fname, temperr);
}
efree(temperr);
temperror:
php_stream_close(pass.centralfp);
nocentralerror:
if (Z_TYPE(phar->metadata) != IS_UNDEF) {
smart_str_free(&main_metadata_str);
}
php_stream_close(pass.filefp);
if (closeoldfile) {
php_stream_close(oldfile);
}
return EOF;
}
if (FAILURE == phar_zip_applysignature(phar, &pass, &main_metadata_str)) {
goto temperror;
}
/* save zip */
cdir_size = php_stream_tell(pass.centralfp);
cdir_offset = php_stream_tell(pass.filefp);
PHAR_SET_32(eocd.cdir_size, cdir_size);
PHAR_SET_32(eocd.cdir_offset, cdir_offset);
php_stream_seek(pass.centralfp, 0, SEEK_SET);
{
size_t clen;
int ret = php_stream_copy_to_stream_ex(pass.centralfp, pass.filefp, PHP_STREAM_COPY_ALL, &clen);
if (SUCCESS != ret || clen != cdir_size) {
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write central-directory", phar->fname);
}
goto temperror;
}
}
php_stream_close(pass.centralfp);
if (Z_TYPE(phar->metadata) != IS_UNDEF) {
/* set phar metadata */
PHAR_SET_16(eocd.comment_len, ZSTR_LEN(main_metadata_str.s));
if (sizeof(eocd) != php_stream_write(pass.filefp, (char *)&eocd, sizeof(eocd))) {
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write end of central-directory", phar->fname);
}
goto nocentralerror;
}
if (ZSTR_LEN(main_metadata_str.s) != php_stream_write(pass.filefp, ZSTR_VAL(main_metadata_str.s), ZSTR_LEN(main_metadata_str.s))) {
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write metadata to zip comment", phar->fname);
}
goto nocentralerror;
}
smart_str_free(&main_metadata_str);
} else {
if (sizeof(eocd) != php_stream_write(pass.filefp, (char *)&eocd, sizeof(eocd))) {
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write end of central-directory", phar->fname);
}
goto nocentralerror;
}
}
if (phar->fp && pass.free_fp) {
php_stream_close(phar->fp);
}
if (phar->ufp) {
if (pass.free_ufp) {
php_stream_close(phar->ufp);
}
phar->ufp = NULL;
}
/* re-open */
phar->is_brandnew = 0;
if (phar->donotflush) {
/* deferred flush */
phar->fp = pass.filefp;
} else {
phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL);
if (!phar->fp) {
if (closeoldfile) {
php_stream_close(oldfile);
}
phar->fp = pass.filefp;
if (error) {
spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname);
}
return EOF;
}
php_stream_rewind(pass.filefp);
php_stream_copy_to_stream_ex(pass.filefp, phar->fp, PHP_STREAM_COPY_ALL, NULL);
/* we could also reopen the file in "rb" mode but there is no need for that */
php_stream_close(pass.filefp);
}
if (closeoldfile) {
php_stream_close(oldfile);
}
return EOF;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5283_3 |
crossvul-cpp_data_bad_3187_1 | /*
* Glue code for libmspack handling.
* Author: 웃 Sebastian Andrzej Siewior
* ✉ sebastian @ breakpoint ̣cc
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <mspack.h>
#include "clamav.h"
#include "fmap.h"
#include "scanners.h"
#include "others.h"
enum mspack_type {
FILETYPE_DUNNO,
FILETYPE_FMAP,
FILETYPE_FILENAME,
};
struct mspack_name {
fmap_t *fmap;
off_t org;
};
struct mspack_system_ex {
struct mspack_system ops;
off_t max_size;
};
struct mspack_handle {
enum mspack_type type;
fmap_t *fmap;
off_t org;
off_t offset;
FILE *f;
off_t max_size;
};
static struct mspack_file *mspack_fmap_open(struct mspack_system *self,
const char *filename, int mode)
{
struct mspack_name *mspack_name;
struct mspack_handle *mspack_handle;
struct mspack_system_ex *self_ex;
const char *fmode;
const struct mspack_system *mptr = self;
if (!filename) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
return NULL;
}
mspack_handle = malloc(sizeof(*mspack_handle));
if (!mspack_handle) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
return NULL;
}
switch (mode) {
case MSPACK_SYS_OPEN_READ:
mspack_handle->type = FILETYPE_FMAP;
mspack_name = (struct mspack_name *)filename;
mspack_handle->fmap = mspack_name->fmap;
mspack_handle->org = mspack_name->org;
mspack_handle->offset = 0;
return (struct mspack_file *)mspack_handle;
case MSPACK_SYS_OPEN_WRITE:
fmode = "wb";
break;
case MSPACK_SYS_OPEN_UPDATE:
fmode = "r+b";
break;
case MSPACK_SYS_OPEN_APPEND:
fmode = "ab";
break;
default:
cli_dbgmsg("%s() wrong mode\n", __func__);
goto out_err;
}
mspack_handle->type = FILETYPE_FILENAME;
mspack_handle->f = fopen(filename, fmode);
if (!mspack_handle->f) {
cli_dbgmsg("%s() failed %d\n", __func__, __LINE__);
goto out_err;
}
self_ex = (struct mspack_system_ex *)((char *)mptr - offsetof(struct mspack_system_ex,ops));
mspack_handle->max_size = self_ex->max_size;
return (struct mspack_file *)mspack_handle;
out_err:
free(mspack_handle);
return NULL;
}
static void mspack_fmap_close(struct mspack_file *file)
{
struct mspack_handle *mspack_handle = (struct mspack_handle *)file;
if (!mspack_handle)
return;
if (mspack_handle->type == FILETYPE_FILENAME)
fclose(mspack_handle->f);
free(mspack_handle);
}
static int mspack_fmap_read(struct mspack_file *file, void *buffer, int bytes)
{
struct mspack_handle *mspack_handle = (struct mspack_handle *)file;
off_t offset;
size_t count;
int ret;
if (bytes < 0) {
cli_dbgmsg("%s() %d\n", __func__, __LINE__);
return -1;
}
if (!mspack_handle) {
cli_dbgmsg("%s() %d\n", __func__, __LINE__);
return -1;
}
if (mspack_handle->type == FILETYPE_FMAP) {
offset = mspack_handle->offset + mspack_handle->org;
ret = fmap_readn(mspack_handle->fmap, buffer, offset, bytes);
if (ret != bytes) {
cli_dbgmsg("%s() %d %d, %d\n", __func__, __LINE__, bytes, ret);
return ret;
}
mspack_handle->offset += bytes;
return bytes;
}
count = fread(buffer, bytes, 1, mspack_handle->f);
if (count < 1) {
cli_dbgmsg("%s() %d %d, %zd\n", __func__, __LINE__, bytes, count);
return -1;
}
return bytes;
}
static int mspack_fmap_write(struct mspack_file *file, void *buffer, int bytes)
{
struct mspack_handle *mspack_handle = (struct mspack_handle *)file;
size_t count;
off_t max_size;
if (bytes < 0 || !mspack_handle) {
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
if (mspack_handle->type == FILETYPE_FMAP) {
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
if (!bytes)
return 0;
max_size = mspack_handle->max_size;
if (!max_size)
return bytes;
max_size = max_size < (off_t) bytes ? max_size : (off_t) bytes;
mspack_handle->max_size -= max_size;
count = fwrite(buffer, max_size, 1, mspack_handle->f);
if (count < 1) {
cli_dbgmsg("%s() err %m <%zd %d>\n", __func__, count, bytes);
return -1;
}
return bytes;
}
static int mspack_fmap_seek(struct mspack_file *file, off_t offset, int mode)
{
struct mspack_handle *mspack_handle = (struct mspack_handle *)file;
if (!mspack_handle) {
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
if (mspack_handle->type == FILETYPE_FMAP) {
off_t new_pos;
switch (mode) {
case MSPACK_SYS_SEEK_START:
new_pos = offset;
break;
case MSPACK_SYS_SEEK_CUR:
new_pos = mspack_handle->offset + offset;
break;
case MSPACK_SYS_SEEK_END:
new_pos = mspack_handle->fmap->len + offset;
break;
default:
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
if (new_pos < 0 || new_pos > mspack_handle->fmap->len) {
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
mspack_handle->offset = new_pos;
return 0;
}
switch (mode) {
case MSPACK_SYS_SEEK_START:
mode = SEEK_SET;
break;
case MSPACK_SYS_SEEK_CUR:
mode = SEEK_CUR;
break;
case MSPACK_SYS_SEEK_END:
mode = SEEK_END;
break;
default:
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
return fseek(mspack_handle->f, offset, mode);
}
static off_t mspack_fmap_tell(struct mspack_file *file)
{
struct mspack_handle *mspack_handle = (struct mspack_handle *)file;
if (!mspack_handle)
return -1;
if (mspack_handle->type == FILETYPE_FMAP)
return mspack_handle->offset;
return (off_t) ftell(mspack_handle->f);
}
static void mspack_fmap_message(struct mspack_file *file, const char *fmt, ...)
{
cli_dbgmsg("%s() %s\n", __func__, fmt);
}
static void *mspack_fmap_alloc(struct mspack_system *self, size_t num)
{
return malloc(num);
}
static void mspack_fmap_free(void *mem)
{
free(mem);
}
static void mspack_fmap_copy(void *src, void *dst, size_t num)
{
memcpy(dst, src, num);
}
static struct mspack_system mspack_sys_fmap_ops = {
.open = mspack_fmap_open,
.close = mspack_fmap_close,
.read = mspack_fmap_read,
.write = mspack_fmap_write,
.seek = mspack_fmap_seek,
.tell = mspack_fmap_tell,
.message = mspack_fmap_message,
.alloc = mspack_fmap_alloc,
.free = mspack_fmap_free,
.copy = mspack_fmap_copy,
};
static int cli_scanfile(const char *filename, cli_ctx *ctx)
{
int fd, ret;
/* internal version of cl_scanfile with arec/mrec preserved */
fd = safe_open(filename, O_RDONLY|O_BINARY);
if (fd < 0)
return CL_EOPEN;
ret = cli_magic_scandesc(fd, ctx);
close(fd);
return ret;
}
int cli_scanmscab(cli_ctx *ctx, off_t sfx_offset)
{
struct mscab_decompressor *cab_d;
struct mscabd_cabinet *cab_h;
struct mscabd_file *cab_f;
int ret;
int files;
int virus_num = 0;
struct mspack_name mspack_fmap = {
.fmap = *ctx->fmap,
.org = sfx_offset,
};
struct mspack_system_ex ops_ex;
memset(&ops_ex, 0, sizeof(struct mspack_system_ex));
ops_ex.ops = mspack_sys_fmap_ops;
MSPACK_SYS_SELFTEST(ret);
if (ret) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
return CL_EUNPACK;
}
cab_d = mspack_create_cab_decompressor(&ops_ex.ops);
if (!cab_d) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
return CL_EUNPACK;
}
cab_h = cab_d->open(cab_d, (char *)&mspack_fmap);
if (!cab_h) {
ret = CL_EFORMAT;
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
goto out_dest;
}
files = 0;
for (cab_f = cab_h->files; cab_f; cab_f = cab_f->next) {
off_t max_size;
char *tmp_fname;
ret = cli_matchmeta(ctx, cab_f->filename, 0, cab_f->length, 0,
files, 0, NULL);
if (ret) {
if (ret == CL_VIRUS) {
virus_num++;
if (!SCAN_ALL)
break;
}
goto out_close;
}
if (ctx->engine->maxscansize) {
if (ctx->scansize >= ctx->engine->maxscansize) {
ret = CL_CLEAN;
break;
}
}
if (ctx->engine->maxscansize &&
ctx->scansize + ctx->engine->maxfilesize >=
ctx->engine->maxscansize)
max_size = ctx->engine->maxscansize -
ctx->scansize;
else
max_size = ctx->engine->maxfilesize ?
ctx->engine->maxfilesize :
0xffffffff;
tmp_fname = cli_gentemp(ctx->engine->tmpdir);
if (!tmp_fname) {
ret = CL_EMEM;
break;
}
ops_ex.max_size = max_size;
/* scan */
ret = cab_d->extract(cab_d, cab_f, tmp_fname);
if (ret)
/* Failed to extract. Try to scan what is there */
cli_dbgmsg("%s() failed to extract %d\n", __func__, ret);
ret = cli_scanfile(tmp_fname, ctx);
if (ret == CL_VIRUS)
virus_num++;
if (!ctx->engine->keeptmp) {
if (!access(tmp_fname, R_OK) && cli_unlink(tmp_fname)) {
free(tmp_fname);
ret = CL_EUNLINK;
break;
}
}
free(tmp_fname);
files++;
if (ret == CL_VIRUS && SCAN_ALL)
continue;
if (ret)
break;
}
out_close:
cab_d->close(cab_d, cab_h);
out_dest:
mspack_destroy_cab_decompressor(cab_d);
if (virus_num)
return CL_VIRUS;
return ret;
}
int cli_scanmschm(cli_ctx *ctx)
{
struct mschm_decompressor *mschm_d;
struct mschmd_header *mschm_h;
struct mschmd_file *mschm_f;
int ret;
int files;
int virus_num = 0;
struct mspack_name mspack_fmap = {
.fmap = *ctx->fmap,
};
struct mspack_system_ex ops_ex;
memset(&ops_ex, 0, sizeof(struct mspack_system_ex));
ops_ex.ops = mspack_sys_fmap_ops;
MSPACK_SYS_SELFTEST(ret);
if (ret) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
return CL_EUNPACK;
}
mschm_d = mspack_create_chm_decompressor(&ops_ex.ops);
if (!mschm_d) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
return CL_EUNPACK;
}
mschm_h = mschm_d->open(mschm_d, (char *)&mspack_fmap);
if (!mschm_h) {
ret = CL_EFORMAT;
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
goto out_dest;
}
files = 0;
for (mschm_f = mschm_h->files; mschm_f; mschm_f = mschm_f->next) {
off_t max_size;
char *tmp_fname;
ret = cli_matchmeta(ctx, mschm_f->filename, 0, mschm_f->length,
0, files, 0, NULL);
if (ret) {
if (ret == CL_VIRUS) {
virus_num++;
if (!SCAN_ALL)
break;
}
goto out_close;
}
if (ctx->engine->maxscansize) {
if (ctx->scansize >= ctx->engine->maxscansize) {
ret = CL_CLEAN;
break;
}
}
if (ctx->engine->maxscansize &&
ctx->scansize + ctx->engine->maxfilesize >=
ctx->engine->maxscansize)
max_size = ctx->engine->maxscansize -
ctx->scansize;
else
max_size = ctx->engine->maxfilesize ?
ctx->engine->maxfilesize :
0xffffffff;
ops_ex.max_size = max_size;
tmp_fname = cli_gentemp(ctx->engine->tmpdir);
if (!tmp_fname) {
ret = CL_EMEM;
break;
}
/* scan */
ret = mschm_d->extract(mschm_d, mschm_f, tmp_fname);
if (ret)
/* Failed to extract. Try to scan what is there */
cli_dbgmsg("%s() failed to extract %d\n", __func__, ret);
ret = cli_scanfile(tmp_fname, ctx);
if (ret == CL_VIRUS)
virus_num++;
if (!ctx->engine->keeptmp) {
if (!access(tmp_fname, R_OK) && cli_unlink(tmp_fname)) {
free(tmp_fname);
ret = CL_EUNLINK;
break;
}
}
free(tmp_fname);
files++;
if (ret == CL_VIRUS && SCAN_ALL)
continue;
if (ret)
break;
}
out_close:
mschm_d->close(mschm_d, mschm_h);
out_dest:
mspack_destroy_chm_decompressor(mschm_d);
if (virus_num)
return CL_VIRUS;
return ret;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3187_1 |
crossvul-cpp_data_bad_3407_3 | /* radare - LGPL - Copyright 2011 pancake<nopcode.org> */
#include <r_io.h>
#include <r_fs.h>
#include "grubfs.h"
#include <stdio.h>
#include <string.h>
static RIOBind *bio = NULL;
static ut64 delta = 0;
static void* empty (int sz) {
void *p = malloc (sz);
if (p) memset (p, '\0', sz);
return p;
}
static grub_err_t read_foo (struct grub_disk *disk, grub_disk_addr_t sector, grub_size_t size, char *buf) {
if (disk != NULL) {
const int blocksize = 512; // unhardcode 512
int ret;
RIOBind *iob = disk->data;
if (bio) iob = bio;
//printf ("io %p\n", file->root->iob.io);
ret = iob->read_at (iob->io, delta+(blocksize*sector),
(ut8*)buf, size*blocksize);
if (ret == -1)
return 1;
//printf ("DISK PTR = %p\n", disk->data);
//printf ("\nBUF: %x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);
} else eprintf ("oops. no disk\n");
return 0; // 0 is ok
}
GrubFS *grubfs_new (struct grub_fs *myfs, void *data) {
struct grub_file *file;
GrubFS *gfs = empty (sizeof (GrubFS));
// hacky mallocs :D
gfs->file = file = empty (sizeof (struct grub_file));
file->device = empty (sizeof (struct grub_device)+1024);
file->device->disk = empty (sizeof (struct grub_disk));
file->device->disk->dev = (grub_disk_dev_t)file->device; // hack!
file->device->disk->dev->read = read_foo; // grub_disk_dev
file->device->disk->data = data;
//file->device->disk->read_hook = read_foo; //read_hook;
file->fs = myfs;
return gfs;
}
grub_disk_t grubfs_disk (void *data) {
struct grub_disk *disk = empty (sizeof (struct grub_disk));
disk->dev = empty (sizeof (struct grub_disk_dev));
disk->dev->read = read_foo; // grub_disk_dev
disk->data = data;
return disk;
}
void grubfs_free (GrubFS *gf) {
if (gf) {
if (gf->file && gf->file->device)
free (gf->file->device->disk);
//free (gf->file->device);
free (gf->file);
free (gf);
}
}
void grubfs_bind_io (RIOBind *iob, ut64 _delta) {
bio = iob;
delta = _delta;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3407_3 |
crossvul-cpp_data_bad_4985_0 | /*
* MOV demuxer
* Copyright (c) 2001 Fabrice Bellard
* Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <limits.h>
//#define DEBUG
//#define MOV_EXPORT_ALL_METADATA
#include "libavutil/audioconvert.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/intfloat.h"
#include "libavutil/mathematics.h"
#include "libavutil/avstring.h"
#include "libavutil/dict.h"
#include "libavutil/opt.h"
#include "libavutil/timecode.h"
#include "libavcodec/ac3tab.h"
#include "avformat.h"
#include "internal.h"
#include "avio_internal.h"
#include "riff.h"
#include "isom.h"
#include "libavcodec/get_bits.h"
#include "id3v1.h"
#include "mov_chan.h"
#if CONFIG_ZLIB
#include <zlib.h>
#endif
/*
* First version by Francois Revol revol@free.fr
* Seek function by Gael Chardon gael.dev@4now.net
*/
#include "qtpalette.h"
#undef NDEBUG
#include <assert.h>
/* those functions parse an atom */
/* links atom IDs to parse functions */
typedef struct MOVParseTableEntry {
uint32_t type;
int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
} MOVParseTableEntry;
static const MOVParseTableEntry mov_default_parse_table[];
static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
unsigned len, const char *key)
{
char buf[16];
short current, total = 0;
avio_rb16(pb); // unknown
current = avio_rb16(pb);
if (len >= 6)
total = avio_rb16(pb);
if (!total)
snprintf(buf, sizeof(buf), "%d", current);
else
snprintf(buf, sizeof(buf), "%d/%d", current, total);
av_dict_set(&c->fc->metadata, key, buf, 0);
return 0;
}
static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
unsigned len, const char *key)
{
char buf[16];
/* bypass padding bytes */
avio_r8(pb);
avio_r8(pb);
avio_r8(pb);
snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
av_dict_set(&c->fc->metadata, key, buf, 0);
return 0;
}
static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
unsigned len, const char *key)
{
char buf[16];
snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
av_dict_set(&c->fc->metadata, key, buf, 0);
return 0;
}
static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
unsigned len, const char *key)
{
short genre;
char buf[20];
avio_r8(pb); // unknown
genre = avio_r8(pb);
if (genre < 1 || genre > ID3v1_GENRE_MAX)
return 0;
snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
av_dict_set(&c->fc->metadata, key, buf, 0);
return 0;
}
static const uint32_t mac_to_unicode[128] = {
0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
};
static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
char *dst, int dstlen)
{
char *p = dst;
char *end = dst+dstlen-1;
int i;
for (i = 0; i < len; i++) {
uint8_t t, c = avio_r8(pb);
if (c < 0x80 && p < end)
*p++ = c;
else if (p < end)
PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
}
*p = 0;
return p - dst;
}
static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
#ifdef MOV_EXPORT_ALL_METADATA
char tmp_key[5];
#endif
char str[1024], key2[16], language[4] = {0};
const char *key = NULL;
uint16_t str_size, langcode = 0;
uint32_t data_type = 0;
int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
switch (atom.type) {
case MKTAG(0xa9,'n','a','m'): key = "title"; break;
case MKTAG(0xa9,'a','u','t'):
case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
case MKTAG( 'c','p','r','t'):
case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
case MKTAG(0xa9,'c','m','t'):
case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
case MKTAG(0xa9,'a','l','b'): key = "album"; break;
case MKTAG(0xa9,'d','a','y'): key = "date"; break;
case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
case MKTAG( 'g','n','r','e'): key = "genre";
parse = mov_metadata_gnre; break;
case MKTAG(0xa9,'t','o','o'):
case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
case MKTAG( 'd','e','s','c'): key = "description";break;
case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
case MKTAG( 't','v','s','h'): key = "show"; break;
case MKTAG( 't','v','e','n'): key = "episode_id";break;
case MKTAG( 't','v','n','n'): key = "network"; break;
case MKTAG( 't','r','k','n'): key = "track";
parse = mov_metadata_track_or_disc_number; break;
case MKTAG( 'd','i','s','k'): key = "disc";
parse = mov_metadata_track_or_disc_number; break;
case MKTAG( 't','v','e','s'): key = "episode_sort";
parse = mov_metadata_int8_bypass_padding; break;
case MKTAG( 't','v','s','n'): key = "season_number";
parse = mov_metadata_int8_bypass_padding; break;
case MKTAG( 's','t','i','k'): key = "media_type";
parse = mov_metadata_int8_no_padding; break;
case MKTAG( 'h','d','v','d'): key = "hd_video";
parse = mov_metadata_int8_no_padding; break;
case MKTAG( 'p','g','a','p'): key = "gapless_playback";
parse = mov_metadata_int8_no_padding; break;
}
if (c->itunes_metadata && atom.size > 8) {
int data_size = avio_rb32(pb);
int tag = avio_rl32(pb);
if (tag == MKTAG('d','a','t','a')) {
data_type = avio_rb32(pb); // type
avio_rb32(pb); // unknown
str_size = data_size - 16;
atom.size -= 16;
} else return 0;
} else if (atom.size > 4 && key && !c->itunes_metadata) {
str_size = avio_rb16(pb); // string length
langcode = avio_rb16(pb);
ff_mov_lang_to_iso639(langcode, language);
atom.size -= 4;
} else
str_size = atom.size;
#ifdef MOV_EXPORT_ALL_METADATA
if (!key) {
snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
key = tmp_key;
}
#endif
if (!key)
return 0;
if (atom.size < 0)
return AVERROR_INVALIDDATA;
str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
if (parse)
parse(c, pb, str_size, key);
else {
if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
mov_read_mac_string(c, pb, str_size, str, sizeof(str));
} else {
avio_read(pb, str, str_size);
str[str_size] = 0;
}
av_dict_set(&c->fc->metadata, key, str, 0);
if (*language && strcmp(language, "und")) {
snprintf(key2, sizeof(key2), "%s-%s", key, language);
av_dict_set(&c->fc->metadata, key2, str, 0);
}
}
av_dlog(c->fc, "lang \"%3s\" ", language);
av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
key, str, (char*)&atom.type, str_size, atom.size);
return 0;
}
static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
int64_t start;
int i, nb_chapters, str_len, version;
char str[256+1];
if ((atom.size -= 5) < 0)
return 0;
version = avio_r8(pb);
avio_rb24(pb);
if (version)
avio_rb32(pb); // ???
nb_chapters = avio_r8(pb);
for (i = 0; i < nb_chapters; i++) {
if (atom.size < 9)
return 0;
start = avio_rb64(pb);
str_len = avio_r8(pb);
if ((atom.size -= 9+str_len) < 0)
return 0;
avio_read(pb, str, str_len);
str[str_len] = 0;
avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
}
return 0;
}
static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
int64_t total_size = 0;
MOVAtom a;
int i;
if (atom.size < 0)
atom.size = INT64_MAX;
while (total_size + 8 <= atom.size && !url_feof(pb)) {
int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
a.size = atom.size;
a.type=0;
if (atom.size >= 8) {
a.size = avio_rb32(pb);
a.type = avio_rl32(pb);
if (atom.type != MKTAG('r','o','o','t') &&
atom.type != MKTAG('m','o','o','v'))
{
if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
{
av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
avio_skip(pb, -8);
return 0;
}
}
total_size += 8;
if (a.size == 1) { /* 64 bit extended size */
a.size = avio_rb64(pb) - 8;
total_size += 8;
}
}
av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
if (a.size == 0) {
a.size = atom.size - total_size + 8;
}
a.size -= 8;
if (a.size < 0)
break;
a.size = FFMIN(a.size, atom.size - total_size);
for (i = 0; mov_default_parse_table[i].type; i++)
if (mov_default_parse_table[i].type == a.type) {
parse = mov_default_parse_table[i].parse;
break;
}
// container is user data
if (!parse && (atom.type == MKTAG('u','d','t','a') ||
atom.type == MKTAG('i','l','s','t')))
parse = mov_read_udta_string;
if (!parse) { /* skip leaf atoms data */
avio_skip(pb, a.size);
} else {
int64_t start_pos = avio_tell(pb);
int64_t left;
int err = parse(c, pb, a);
if (err < 0)
return err;
if (c->found_moov && c->found_mdat &&
((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
start_pos + a.size == avio_size(pb))) {
if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
c->next_root_atom = start_pos + a.size;
return 0;
}
left = a.size - avio_tell(pb) + start_pos;
if (left > 0) /* skip garbage at atom end */
avio_skip(pb, left);
}
total_size += a.size;
}
if (total_size < atom.size && atom.size < 0x7ffff)
avio_skip(pb, atom.size - total_size);
return 0;
}
static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
int entries, i, j;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
avio_rb32(pb); // version + flags
entries = avio_rb32(pb);
if (entries >= UINT_MAX / sizeof(*sc->drefs))
return AVERROR_INVALIDDATA;
av_free(sc->drefs);
sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
if (!sc->drefs)
return AVERROR(ENOMEM);
sc->drefs_count = entries;
for (i = 0; i < sc->drefs_count; i++) {
MOVDref *dref = &sc->drefs[i];
uint32_t size = avio_rb32(pb);
int64_t next = avio_tell(pb) + size - 4;
if (size < 12)
return AVERROR_INVALIDDATA;
dref->type = avio_rl32(pb);
avio_rb32(pb); // version + flags
av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
if (dref->type == MKTAG('a','l','i','s') && size > 150) {
/* macintosh alias record */
uint16_t volume_len, len;
int16_t type;
avio_skip(pb, 10);
volume_len = avio_r8(pb);
volume_len = FFMIN(volume_len, 27);
avio_read(pb, dref->volume, 27);
dref->volume[volume_len] = 0;
av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
avio_skip(pb, 12);
len = avio_r8(pb);
len = FFMIN(len, 63);
avio_read(pb, dref->filename, 63);
dref->filename[len] = 0;
av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
avio_skip(pb, 16);
/* read next level up_from_alias/down_to_target */
dref->nlvl_from = avio_rb16(pb);
dref->nlvl_to = avio_rb16(pb);
av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
dref->nlvl_from, dref->nlvl_to);
avio_skip(pb, 16);
for (type = 0; type != -1 && avio_tell(pb) < next; ) {
if(url_feof(pb))
return AVERROR_EOF;
type = avio_rb16(pb);
len = avio_rb16(pb);
av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
if (len&1)
len += 1;
if (type == 2) { // absolute path
av_free(dref->path);
dref->path = av_mallocz(len+1);
if (!dref->path)
return AVERROR(ENOMEM);
avio_read(pb, dref->path, len);
if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
len -= volume_len;
memmove(dref->path, dref->path+volume_len, len);
dref->path[len] = 0;
}
for (j = 0; j < len; j++)
if (dref->path[j] == ':')
dref->path[j] = '/';
av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
} else if (type == 0) { // directory name
av_free(dref->dir);
dref->dir = av_malloc(len+1);
if (!dref->dir)
return AVERROR(ENOMEM);
avio_read(pb, dref->dir, len);
dref->dir[len] = 0;
for (j = 0; j < len; j++)
if (dref->dir[j] == ':')
dref->dir[j] = '/';
av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
} else
avio_skip(pb, len);
}
}
avio_seek(pb, next, SEEK_SET);
}
return 0;
}
static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
uint32_t type;
uint32_t av_unused ctype;
int title_size;
char *title_str;
if (c->fc->nb_streams < 1) // meta before first trak
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
/* component type */
ctype = avio_rl32(pb);
type = avio_rl32(pb); /* component subtype */
av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
if (type == MKTAG('v','i','d','e'))
st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
else if (type == MKTAG('s','o','u','n'))
st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
else if (type == MKTAG('m','1','a',' '))
st->codec->codec_id = CODEC_ID_MP2;
else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
avio_rb32(pb); /* component manufacture */
avio_rb32(pb); /* component flags */
avio_rb32(pb); /* component flags mask */
title_size = atom.size - 24;
if (title_size > 0) {
title_str = av_malloc(title_size + 1); /* Add null terminator */
if (!title_str)
return AVERROR(ENOMEM);
avio_read(pb, title_str, title_size);
title_str[title_size] = 0;
if (title_str[0])
av_dict_set(&st->metadata, "handler_name", title_str +
(!c->isom && title_str[0] == title_size - 1), 0);
av_freep(&title_str);
}
return 0;
}
int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
int tag;
if (fc->nb_streams < 1)
return 0;
st = fc->streams[fc->nb_streams-1];
avio_rb32(pb); /* version + flags */
ff_mp4_read_descr(fc, pb, &tag);
if (tag == MP4ESDescrTag) {
ff_mp4_parse_es_descr(pb, NULL);
} else
avio_rb16(pb); /* ID */
ff_mp4_read_descr(fc, pb, &tag);
if (tag == MP4DecConfigDescrTag)
ff_mp4_read_dec_config_descr(fc, st, pb);
return 0;
}
static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
return ff_mov_read_esds(c->fc, pb, atom);
}
static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
int ac3info, acmod, lfeon, bsmod;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
ac3info = avio_rb24(pb);
bsmod = (ac3info >> 14) & 0x7;
acmod = (ac3info >> 11) & 0x7;
lfeon = (ac3info >> 10) & 0x1;
st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
if (lfeon)
st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
st->codec->audio_service_type = bsmod;
if (st->codec->channels > 1 && bsmod == 0x7)
st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
return 0;
}
static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
uint8_t version;
uint32_t flags, layout_tag, bitmap, num_descr, label_mask;
int i;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
if (atom.size < 16)
return 0;
version = avio_r8(pb);
flags = avio_rb24(pb);
layout_tag = avio_rb32(pb);
bitmap = avio_rb32(pb);
num_descr = avio_rb32(pb);
if (atom.size < 16ULL + num_descr * 20ULL)
return 0;
av_dlog(c->fc, "chan: size=%" PRId64 " version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
atom.size, version, flags, layout_tag, bitmap, num_descr);
label_mask = 0;
for (i = 0; i < num_descr; i++) {
uint32_t av_unused label, cflags;
label = avio_rb32(pb); // mChannelLabel
cflags = avio_rb32(pb); // mChannelFlags
avio_rl32(pb); // mCoordinates[0]
avio_rl32(pb); // mCoordinates[1]
avio_rl32(pb); // mCoordinates[2]
if (layout_tag == 0) {
uint32_t mask_incr = ff_mov_get_channel_label(label);
if (mask_incr == 0) {
label_mask = 0;
break;
}
label_mask |= mask_incr;
}
}
if (layout_tag == 0)
st->codec->channel_layout = label_mask;
else
st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
return 0;
}
static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
ff_get_wav_header(pb, st->codec, atom.size);
return 0;
}
static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
const int num = avio_rb32(pb);
const int den = avio_rb32(pb);
AVStream *st;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
(den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
av_log(c->fc, AV_LOG_WARNING,
"sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
num, den);
} else if (den != 0) {
st->sample_aspect_ratio.num = num;
st->sample_aspect_ratio.den = den;
}
return 0;
}
/* this atom contains actual media data */
static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
if (atom.size == 0) /* wrong one (MP4) */
return 0;
c->found_mdat=1;
return 0; /* now go for moov */
}
/* read major brand, minor version and compatible brands and store them as metadata */
static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
uint32_t minor_ver;
int comp_brand_size;
char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
char* comp_brands_str;
uint8_t type[5] = {0};
avio_read(pb, type, 4);
if (strcmp(type, "qt "))
c->isom = 1;
av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
av_dict_set(&c->fc->metadata, "major_brand", type, 0);
minor_ver = avio_rb32(pb); /* minor version */
snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
comp_brand_size = atom.size - 8;
if (comp_brand_size < 0)
return AVERROR_INVALIDDATA;
comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
if (!comp_brands_str)
return AVERROR(ENOMEM);
avio_read(pb, comp_brands_str, comp_brand_size);
comp_brands_str[comp_brand_size] = 0;
av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
av_freep(&comp_brands_str);
return 0;
}
/* this atom should contain all header atoms */
static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
int ret;
if ((ret = mov_read_default(c, pb, atom)) < 0)
return ret;
/* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
/* so we don't parse the whole file if over a network */
c->found_moov=1;
return 0; /* now go for mdat */
}
static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
c->fragment.moof_offset = avio_tell(pb) - 8;
av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
return mov_read_default(c, pb, atom);
}
static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
{
char buffer[32];
if (time) {
struct tm *ptm;
time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
ptm = gmtime(&time);
if (!ptm) return;
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
av_dict_set(metadata, "creation_time", buffer, 0);
}
}
static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
int version;
char language[4] = {0};
unsigned lang;
time_t creation_time;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
version = avio_r8(pb);
if (version > 1) {
av_log_ask_for_sample(c, "unsupported version %d\n", version);
return AVERROR_PATCHWELCOME;
}
avio_rb24(pb); /* flags */
if (version == 1) {
creation_time = avio_rb64(pb);
avio_rb64(pb);
} else {
creation_time = avio_rb32(pb);
avio_rb32(pb); /* modification time */
}
mov_metadata_creation_time(&st->metadata, creation_time);
sc->time_scale = avio_rb32(pb);
st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
lang = avio_rb16(pb); /* language */
if (ff_mov_lang_to_iso639(lang, language))
av_dict_set(&st->metadata, "language", language, 0);
avio_rb16(pb); /* quality */
return 0;
}
static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
time_t creation_time;
int version = avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
if (version == 1) {
creation_time = avio_rb64(pb);
avio_rb64(pb);
} else {
creation_time = avio_rb32(pb);
avio_rb32(pb); /* modification time */
}
mov_metadata_creation_time(&c->fc->metadata, creation_time);
c->time_scale = avio_rb32(pb); /* time scale */
av_dlog(c->fc, "time scale = %i\n", c->time_scale);
c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
// set the AVCodecContext duration because the duration of individual tracks
// may be inaccurate
if (c->time_scale > 0)
c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
avio_rb32(pb); /* preferred scale */
avio_rb16(pb); /* preferred volume */
avio_skip(pb, 10); /* reserved */
avio_skip(pb, 36); /* display matrix */
avio_rb32(pb); /* preview time */
avio_rb32(pb); /* preview duration */
avio_rb32(pb); /* poster time */
avio_rb32(pb); /* selection time */
avio_rb32(pb); /* selection duration */
avio_rb32(pb); /* current time */
avio_rb32(pb); /* next track ID */
return 0;
}
static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
if ((uint64_t)atom.size > (1<<30))
return AVERROR_INVALIDDATA;
// currently SVQ3 decoder expect full STSD header - so let's fake it
// this should be fixed and just SMI header should be passed
av_free(st->codec->extradata);
st->codec->extradata_size = 0;
st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
if (!st->codec->extradata)
return AVERROR(ENOMEM);
st->codec->extradata_size = 0x5a + atom.size;
memcpy(st->codec->extradata, "SVQ3", 4); // fake
avio_read(pb, st->codec->extradata + 0x5a, atom.size);
av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
return 0;
}
static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
int little_endian;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
little_endian = avio_rb16(pb) & 0xFF;
av_dlog(c->fc, "enda %d\n", little_endian);
if (little_endian == 1) {
switch (st->codec->codec_id) {
case CODEC_ID_PCM_S24BE:
st->codec->codec_id = CODEC_ID_PCM_S24LE;
break;
case CODEC_ID_PCM_S32BE:
st->codec->codec_id = CODEC_ID_PCM_S32LE;
break;
case CODEC_ID_PCM_F32BE:
st->codec->codec_id = CODEC_ID_PCM_F32LE;
break;
case CODEC_ID_PCM_F64BE:
st->codec->codec_id = CODEC_ID_PCM_F64LE;
break;
default:
break;
}
}
return 0;
}
static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
unsigned mov_field_order;
enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
if (c->fc->nb_streams < 1) // will happen with jp2 files
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
if (atom.size < 2)
return AVERROR_INVALIDDATA;
mov_field_order = avio_rb16(pb);
if ((mov_field_order & 0xFF00) == 0x0100)
decoded_field_order = AV_FIELD_PROGRESSIVE;
else if ((mov_field_order & 0xFF00) == 0x0200) {
switch (mov_field_order & 0xFF) {
case 0x01: decoded_field_order = AV_FIELD_TT;
break;
case 0x06: decoded_field_order = AV_FIELD_BB;
break;
case 0x09: decoded_field_order = AV_FIELD_TB;
break;
case 0x0E: decoded_field_order = AV_FIELD_BT;
break;
}
}
if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
}
st->codec->field_order = decoded_field_order;
return 0;
}
/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
enum CodecID codec_id)
{
AVStream *st;
uint64_t size;
uint8_t *buf;
if (c->fc->nb_streams < 1) // will happen with jp2 files
return 0;
st= c->fc->streams[c->fc->nb_streams-1];
if (st->codec->codec_id != codec_id)
return 0; /* unexpected codec_id - don't mess with extradata */
size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
return AVERROR_INVALIDDATA;
buf= av_realloc(st->codec->extradata, size);
if (!buf)
return AVERROR(ENOMEM);
st->codec->extradata= buf;
buf+= st->codec->extradata_size;
st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
AV_WB32( buf , atom.size + 8);
AV_WL32( buf + 4, atom.type);
avio_read(pb, buf + 8, atom.size);
return 0;
}
/* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
return mov_read_extradata(c, pb, atom, CODEC_ID_ALAC);
}
static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
return mov_read_extradata(c, pb, atom, CODEC_ID_AVS);
}
static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
return mov_read_extradata(c, pb, atom, CODEC_ID_JPEG2000);
}
static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
if ((uint64_t)atom.size > (1<<30))
return AVERROR_INVALIDDATA;
if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
// pass all frma atom to codec, needed at least for QDMC and QDM2
av_free(st->codec->extradata);
st->codec->extradata_size = 0;
st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
if (!st->codec->extradata)
return AVERROR(ENOMEM);
st->codec->extradata_size = atom.size;
avio_read(pb, st->codec->extradata, atom.size);
} else if (atom.size > 8) { /* to read frma, esds atoms */
int ret;
if ((ret = mov_read_default(c, pb, atom)) < 0)
return ret;
} else
avio_skip(pb, atom.size);
return 0;
}
/**
* This function reads atom content and puts data in extradata without tag
* nor size unlike mov_read_extradata.
*/
static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
if ((uint64_t)atom.size > (1<<30))
return AVERROR_INVALIDDATA;
if (atom.size >= 10) {
// Broken files created by legacy versions of Libav and FFmpeg will
// wrap a whole fiel atom inside of a glbl atom.
unsigned size = avio_rb32(pb);
unsigned type = avio_rl32(pb);
avio_seek(pb, -8, SEEK_CUR);
if (type == MKTAG('f','i','e','l') && size == atom.size)
return mov_read_default(c, pb, atom);
}
av_free(st->codec->extradata);
st->codec->extradata_size = 0;
st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
if (!st->codec->extradata)
return AVERROR(ENOMEM);
st->codec->extradata_size = atom.size;
avio_read(pb, st->codec->extradata, atom.size);
return 0;
}
static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
uint8_t profile_level;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
if (atom.size >= (1<<28) || atom.size < 7)
return AVERROR_INVALIDDATA;
profile_level = avio_r8(pb);
if (profile_level & 0xf0 != 0xc0)
return 0;
av_free(st->codec->extradata);
st->codec->extradata_size = 0;
st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
if (!st->codec->extradata)
return AVERROR(ENOMEM);
st->codec->extradata_size = atom.size - 7;
avio_seek(pb, 6, SEEK_CUR);
avio_read(pb, st->codec->extradata, st->codec->extradata_size);
return 0;
}
/**
* An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
* but can have extradata appended at the end after the 40 bytes belonging
* to the struct.
*/
static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
if (c->fc->nb_streams < 1)
return 0;
if (atom.size <= 40)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
if ((uint64_t)atom.size > (1<<30))
return AVERROR_INVALIDDATA;
av_free(st->codec->extradata);
st->codec->extradata_size = 0;
st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
if (!st->codec->extradata)
return AVERROR(ENOMEM);
st->codec->extradata_size = atom.size - 40;
avio_skip(pb, 40);
avio_read(pb, st->codec->extradata, atom.size - 40);
return 0;
}
static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
unsigned int i, entries;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
entries = avio_rb32(pb);
if (!entries)
return 0;
if (entries >= UINT_MAX/sizeof(int64_t))
return AVERROR_INVALIDDATA;
sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
if (!sc->chunk_offsets)
return AVERROR(ENOMEM);
sc->chunk_count = entries;
if (atom.type == MKTAG('s','t','c','o'))
for (i=0; i<entries; i++)
sc->chunk_offsets[i] = avio_rb32(pb);
else if (atom.type == MKTAG('c','o','6','4'))
for (i=0; i<entries; i++)
sc->chunk_offsets[i] = avio_rb64(pb);
else
return AVERROR_INVALIDDATA;
return 0;
}
/**
* Compute codec id for 'lpcm' tag.
* See CoreAudioTypes and AudioStreamBasicDescription at Apple.
*/
enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
{
if (flags & 1) { // floating point
if (flags & 2) { // big endian
if (bps == 32) return CODEC_ID_PCM_F32BE;
else if (bps == 64) return CODEC_ID_PCM_F64BE;
} else {
if (bps == 32) return CODEC_ID_PCM_F32LE;
else if (bps == 64) return CODEC_ID_PCM_F64LE;
}
} else {
if (flags & 2) {
if (bps == 8)
// signed integer
if (flags & 4) return CODEC_ID_PCM_S8;
else return CODEC_ID_PCM_U8;
else if (bps == 16) return CODEC_ID_PCM_S16BE;
else if (bps == 24) return CODEC_ID_PCM_S24BE;
else if (bps == 32) return CODEC_ID_PCM_S32BE;
} else {
if (bps == 8)
if (flags & 4) return CODEC_ID_PCM_S8;
else return CODEC_ID_PCM_U8;
else if (bps == 16) return CODEC_ID_PCM_S16LE;
else if (bps == 24) return CODEC_ID_PCM_S24LE;
else if (bps == 32) return CODEC_ID_PCM_S32LE;
}
}
return CODEC_ID_NONE;
}
int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
{
AVStream *st;
MOVStreamContext *sc;
int j, pseudo_stream_id;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
//Parsing Sample description table
enum CodecID id;
int dref_id = 1;
MOVAtom a = { AV_RL32("stsd") };
int64_t start_pos = avio_tell(pb);
int size = avio_rb32(pb); /* size */
uint32_t format = avio_rl32(pb); /* data format */
if (size >= 16) {
avio_rb32(pb); /* reserved */
avio_rb16(pb); /* reserved */
dref_id = avio_rb16(pb);
}else if (size <= 0){
av_log(c->fc, AV_LOG_ERROR, "invalid size %d in stsd\n", size);
return -1;
}
if (st->codec->codec_tag &&
st->codec->codec_tag != format &&
(c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
: st->codec->codec_tag != MKTAG('j','p','e','g'))
){
/* Multiple fourcc, we skip JPEG. This is not correct, we should
* export it as a separate AVStream but this needs a few changes
* in the MOV demuxer, patch welcome. */
av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
avio_skip(pb, size - (avio_tell(pb) - start_pos));
continue;
}
/* we cannot demux concatenated h264 streams because of different extradata */
if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 might not play corrently.\n");
sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
sc->dref_id= dref_id;
st->codec->codec_tag = format;
id = ff_codec_get_id(ff_codec_movaudio_tags, format);
if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
} else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
id = ff_codec_get_id(ff_codec_movvideo_tags, format);
if (id <= 0)
id = ff_codec_get_id(ff_codec_bmp_tags, format);
if (id > 0)
st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
(st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
st->codec->codec_id == CODEC_ID_NONE)){
id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
if (id > 0)
st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
}
}
av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
(format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
(format >> 24) & 0xff, st->codec->codec_type);
if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
unsigned int color_depth, len;
int color_greyscale;
int color_table_id;
st->codec->codec_id = id;
avio_rb16(pb); /* version */
avio_rb16(pb); /* revision level */
avio_rb32(pb); /* vendor */
avio_rb32(pb); /* temporal quality */
avio_rb32(pb); /* spatial quality */
st->codec->width = avio_rb16(pb); /* width */
st->codec->height = avio_rb16(pb); /* height */
avio_rb32(pb); /* horiz resolution */
avio_rb32(pb); /* vert resolution */
avio_rb32(pb); /* data size, always 0 */
avio_rb16(pb); /* frames per samples */
len = avio_r8(pb); /* codec name, pascal string */
if (len > 31)
len = 31;
mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
if (len < 31)
avio_skip(pb, 31 - len);
/* codec_tag YV12 triggers an UV swap in rawdec.c */
if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
st->codec->codec_tag=MKTAG('I', '4', '2', '0');
st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
color_table_id = avio_rb16(pb); /* colortable id */
av_dlog(c->fc, "depth %d, ctab id %d\n",
st->codec->bits_per_coded_sample, color_table_id);
/* figure out the palette situation */
color_depth = st->codec->bits_per_coded_sample & 0x1F;
color_greyscale = st->codec->bits_per_coded_sample & 0x20;
/* if the depth is 2, 4, or 8 bpp, file is palettized */
if ((color_depth == 2) || (color_depth == 4) ||
(color_depth == 8)) {
/* for palette traversal */
unsigned int color_start, color_count, color_end;
unsigned char a, r, g, b;
if (color_greyscale) {
int color_index, color_dec;
/* compute the greyscale palette */
st->codec->bits_per_coded_sample = color_depth;
color_count = 1 << color_depth;
color_index = 255;
color_dec = 256 / (color_count - 1);
for (j = 0; j < color_count; j++) {
if (id == CODEC_ID_CINEPAK){
r = g = b = color_count - 1 - color_index;
}else
r = g = b = color_index;
sc->palette[j] =
(0xFFU << 24) | (r << 16) | (g << 8) | (b);
color_index -= color_dec;
if (color_index < 0)
color_index = 0;
}
} else if (color_table_id) {
const uint8_t *color_table;
/* if flag bit 3 is set, use the default palette */
color_count = 1 << color_depth;
if (color_depth == 2)
color_table = ff_qt_default_palette_4;
else if (color_depth == 4)
color_table = ff_qt_default_palette_16;
else
color_table = ff_qt_default_palette_256;
for (j = 0; j < color_count; j++) {
r = color_table[j * 3 + 0];
g = color_table[j * 3 + 1];
b = color_table[j * 3 + 2];
sc->palette[j] =
(0xFFU << 24) | (r << 16) | (g << 8) | (b);
}
} else {
/* load the palette from the file */
color_start = avio_rb32(pb);
color_count = avio_rb16(pb);
color_end = avio_rb16(pb);
if ((color_start <= 255) &&
(color_end <= 255)) {
for (j = color_start; j <= color_end; j++) {
/* each A, R, G, or B component is 16 bits;
* only use the top 8 bits */
a = avio_r8(pb);
avio_r8(pb);
r = avio_r8(pb);
avio_r8(pb);
g = avio_r8(pb);
avio_r8(pb);
b = avio_r8(pb);
avio_r8(pb);
sc->palette[j] =
(a << 24 ) | (r << 16) | (g << 8) | (b);
}
}
}
sc->has_palette = 1;
}
} else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
int bits_per_sample, flags;
uint16_t version = avio_rb16(pb);
st->codec->codec_id = id;
avio_rb16(pb); /* revision level */
avio_rb32(pb); /* vendor */
st->codec->channels = avio_rb16(pb); /* channel count */
av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
sc->audio_cid = avio_rb16(pb);
avio_rb16(pb); /* packet size = 0 */
st->codec->sample_rate = ((avio_rb32(pb) >> 16));
//Read QT version 1 fields. In version 0 these do not exist.
av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
if (!c->isom) {
if (version==1) {
sc->samples_per_frame = avio_rb32(pb);
avio_rb32(pb); /* bytes per packet */
sc->bytes_per_frame = avio_rb32(pb);
avio_rb32(pb); /* bytes per sample */
} else if (version==2) {
avio_rb32(pb); /* sizeof struct only */
st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
st->codec->channels = avio_rb32(pb);
avio_rb32(pb); /* always 0x7F000000 */
st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
flags = avio_rb32(pb); /* lpcm format specific flag */
sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
if (format == MKTAG('l','p','c','m'))
st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
}
}
switch (st->codec->codec_id) {
case CODEC_ID_PCM_S8:
case CODEC_ID_PCM_U8:
if (st->codec->bits_per_coded_sample == 16)
st->codec->codec_id = CODEC_ID_PCM_S16BE;
break;
case CODEC_ID_PCM_S16LE:
case CODEC_ID_PCM_S16BE:
if (st->codec->bits_per_coded_sample == 8)
st->codec->codec_id = CODEC_ID_PCM_S8;
else if (st->codec->bits_per_coded_sample == 24)
st->codec->codec_id =
st->codec->codec_id == CODEC_ID_PCM_S16BE ?
CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
break;
/* set values for old format before stsd version 1 appeared */
case CODEC_ID_MACE3:
sc->samples_per_frame = 6;
sc->bytes_per_frame = 2*st->codec->channels;
break;
case CODEC_ID_MACE6:
sc->samples_per_frame = 6;
sc->bytes_per_frame = 1*st->codec->channels;
break;
case CODEC_ID_ADPCM_IMA_QT:
sc->samples_per_frame = 64;
sc->bytes_per_frame = 34*st->codec->channels;
break;
case CODEC_ID_GSM:
sc->samples_per_frame = 160;
sc->bytes_per_frame = 33;
break;
default:
break;
}
bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
if (bits_per_sample) {
st->codec->bits_per_coded_sample = bits_per_sample;
sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
}
} else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
// ttxt stsd contains display flags, justification, background
// color, fonts, and default styles, so fake an atom to read it
MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
mov_read_glbl(c, pb, fake_atom);
st->codec->codec_id= id;
st->codec->width = sc->width;
st->codec->height = sc->height;
} else {
if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
MOVStreamContext *tmcd_ctx = st->priv_data;
int val;
avio_rb32(pb); /* reserved */
val = avio_rb32(pb); /* flags */
tmcd_ctx->tmcd_flags = val;
if (val & 1)
st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
avio_rb32(pb); /* time scale */
avio_rb32(pb); /* frame duration */
st->codec->time_base.den = avio_r8(pb); /* number of frame */
st->codec->time_base.num = 1;
}
/* other codec type, just skip (rtp, mp4s, ...) */
avio_skip(pb, size - (avio_tell(pb) - start_pos));
}
/* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
a.size = size - (avio_tell(pb) - start_pos);
if (a.size > 8) {
int ret;
if ((ret = mov_read_default(c, pb, a)) < 0)
return ret;
} else if (a.size > 0)
avio_skip(pb, a.size);
}
if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
st->codec->sample_rate= sc->time_scale;
/* special codec parameters handling */
switch (st->codec->codec_id) {
#if CONFIG_DV_DEMUXER
case CODEC_ID_DVAUDIO:
c->dv_fctx = avformat_alloc_context();
c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
if (!c->dv_demux) {
av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
return AVERROR(ENOMEM);
}
sc->dv_audio_container = 1;
st->codec->codec_id = CODEC_ID_PCM_S16LE;
break;
#endif
/* no ifdef since parameters are always those */
case CODEC_ID_QCELP:
// force sample rate for qcelp when not stored in mov
if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
st->codec->sample_rate = 8000;
st->codec->channels= 1; /* really needed */
break;
case CODEC_ID_AMR_NB:
st->codec->channels= 1; /* really needed */
/* force sample rate for amr, stsd in 3gp does not store sample rate */
st->codec->sample_rate = 8000;
break;
case CODEC_ID_AMR_WB:
st->codec->channels = 1;
st->codec->sample_rate = 16000;
break;
case CODEC_ID_MP2:
case CODEC_ID_MP3:
st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
st->need_parsing = AVSTREAM_PARSE_FULL;
break;
case CODEC_ID_GSM:
case CODEC_ID_ADPCM_MS:
case CODEC_ID_ADPCM_IMA_WAV:
st->codec->block_align = sc->bytes_per_frame;
break;
case CODEC_ID_ALAC:
if (st->codec->extradata_size == 36) {
st->codec->channels = AV_RB8 (st->codec->extradata+21);
st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
}
break;
case CODEC_ID_AC3:
st->need_parsing = AVSTREAM_PARSE_FULL;
break;
case CODEC_ID_MPEG1VIDEO:
st->need_parsing = AVSTREAM_PARSE_FULL;
break;
default:
break;
}
return 0;
}
static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
int entries;
avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
entries = avio_rb32(pb);
return ff_mov_read_stsd_entries(c, pb, entries);
}
static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
unsigned int i, entries;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
entries = avio_rb32(pb);
av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
if (!entries)
return 0;
if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
return AVERROR_INVALIDDATA;
sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
if (!sc->stsc_data)
return AVERROR(ENOMEM);
sc->stsc_count = entries;
for (i=0; i<entries; i++) {
sc->stsc_data[i].first = avio_rb32(pb);
sc->stsc_data[i].count = avio_rb32(pb);
sc->stsc_data[i].id = avio_rb32(pb);
}
return 0;
}
static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
unsigned i, entries;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
avio_rb32(pb); // version + flags
entries = avio_rb32(pb);
if (entries >= UINT_MAX / sizeof(*sc->stps_data))
return AVERROR_INVALIDDATA;
sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
if (!sc->stps_data)
return AVERROR(ENOMEM);
sc->stps_count = entries;
for (i = 0; i < entries; i++) {
sc->stps_data[i] = avio_rb32(pb);
//av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
}
return 0;
}
static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
unsigned int i, entries;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
entries = avio_rb32(pb);
av_dlog(c->fc, "keyframe_count = %d\n", entries);
if (!entries)
{
sc->keyframe_absent = 1;
return 0;
}
if (entries >= UINT_MAX / sizeof(int))
return AVERROR_INVALIDDATA;
sc->keyframes = av_malloc(entries * sizeof(int));
if (!sc->keyframes)
return AVERROR(ENOMEM);
sc->keyframe_count = entries;
for (i=0; i<entries; i++) {
sc->keyframes[i] = avio_rb32(pb);
//av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
}
return 0;
}
static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
unsigned int i, entries, sample_size, field_size, num_bytes;
GetBitContext gb;
unsigned char* buf;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
if (atom.type == MKTAG('s','t','s','z')) {
sample_size = avio_rb32(pb);
if (!sc->sample_size) /* do not overwrite value computed in stsd */
sc->sample_size = sample_size;
sc->alt_sample_size = sample_size;
field_size = 32;
} else {
sample_size = 0;
avio_rb24(pb); /* reserved */
field_size = avio_r8(pb);
}
entries = avio_rb32(pb);
av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
sc->sample_count = entries;
if (sample_size)
return 0;
if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
return AVERROR_INVALIDDATA;
}
if (!entries)
return 0;
if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
return AVERROR_INVALIDDATA;
sc->sample_sizes = av_malloc(entries * sizeof(int));
if (!sc->sample_sizes)
return AVERROR(ENOMEM);
num_bytes = (entries*field_size+4)>>3;
buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
if (!buf) {
av_freep(&sc->sample_sizes);
return AVERROR(ENOMEM);
}
if (avio_read(pb, buf, num_bytes) < num_bytes) {
av_freep(&sc->sample_sizes);
av_free(buf);
return AVERROR_INVALIDDATA;
}
init_get_bits(&gb, buf, 8*num_bytes);
for (i = 0; i < entries; i++) {
sc->sample_sizes[i] = get_bits_long(&gb, field_size);
sc->data_size += sc->sample_sizes[i];
}
av_free(buf);
return 0;
}
static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
unsigned int i, entries;
int64_t duration=0;
int64_t total_sample_count=0;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
entries = avio_rb32(pb);
av_dlog(c->fc, "track[%i].stts.entries = %i\n",
c->fc->nb_streams-1, entries);
if (entries >= UINT_MAX / sizeof(*sc->stts_data))
return -1;
sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
if (!sc->stts_data)
return AVERROR(ENOMEM);
sc->stts_count = entries;
for (i=0; i<entries; i++) {
int sample_duration;
int sample_count;
sample_count=avio_rb32(pb);
sample_duration = avio_rb32(pb);
/* sample_duration < 0 is invalid based on the spec */
if (sample_duration < 0) {
av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
sample_duration = 1;
}
sc->stts_data[i].count= sample_count;
sc->stts_data[i].duration= sample_duration;
av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
sample_count, sample_duration);
duration+=(int64_t)sample_duration*sample_count;
total_sample_count+=sample_count;
}
st->nb_frames= total_sample_count;
if (duration)
st->duration= duration;
sc->track_end = duration;
return 0;
}
static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
unsigned int i, entries;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
entries = avio_rb32(pb);
av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
if (!entries)
return 0;
if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
return AVERROR_INVALIDDATA;
sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
if (!sc->ctts_data)
return AVERROR(ENOMEM);
sc->ctts_count = entries;
for (i=0; i<entries; i++) {
int count =avio_rb32(pb);
int duration =avio_rb32(pb);
sc->ctts_data[i].count = count;
sc->ctts_data[i].duration= duration;
if (FFABS(duration) > (1<<28) && i+2<entries) {
av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
av_freep(&sc->ctts_data);
sc->ctts_count = 0;
return 0;
}
if (duration < 0 && i+2<entries)
sc->dts_shift = FFMAX(sc->dts_shift, -duration);
}
av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
return 0;
}
static void mov_build_index(MOVContext *mov, AVStream *st)
{
MOVStreamContext *sc = st->priv_data;
int64_t current_offset;
int64_t current_dts = 0;
unsigned int stts_index = 0;
unsigned int stsc_index = 0;
unsigned int stss_index = 0;
unsigned int stps_index = 0;
unsigned int i, j;
uint64_t stream_size = 0;
AVIndexEntry *mem;
/* adjust first dts according to edit list */
if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
if (sc->empty_duration)
sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
sc->time_offset = sc->start_time - sc->empty_duration;
current_dts = -sc->time_offset;
if (sc->ctts_data && sc->stts_data &&
sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
/* more than 16 frames delay, dts are likely wrong
this happens with files created by iMovie */
sc->wrong_dts = 1;
st->codec->has_b_frames = 1;
}
}
/* only use old uncompressed audio chunk demuxing when stts specifies it */
if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
unsigned int current_sample = 0;
unsigned int stts_sample = 0;
unsigned int sample_size;
unsigned int distance = 0;
int key_off = sc->keyframe_count && sc->keyframes[0] == 1;
current_dts -= sc->dts_shift;
if (!sc->sample_count || st->nb_index_entries)
return;
if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
return;
mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
if (!mem)
return;
st->index_entries = mem;
st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
for (i = 0; i < sc->chunk_count; i++) {
current_offset = sc->chunk_offsets[i];
while (stsc_index + 1 < sc->stsc_count &&
i + 1 == sc->stsc_data[stsc_index + 1].first)
stsc_index++;
for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
int keyframe = 0;
if (current_sample >= sc->sample_count) {
av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
return;
}
if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
keyframe = 1;
if (stss_index + 1 < sc->keyframe_count)
stss_index++;
} else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
keyframe = 1;
if (stps_index + 1 < sc->stps_count)
stps_index++;
}
if (keyframe)
distance = 0;
sample_size = sc->alt_sample_size > 0 ? sc->alt_sample_size : sc->sample_sizes[current_sample];
if (sc->pseudo_stream_id == -1 ||
sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
e->pos = current_offset;
e->timestamp = current_dts;
e->size = sample_size;
e->min_distance = distance;
e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
"size %d, distance %d, keyframe %d\n", st->index, current_sample,
current_offset, current_dts, sample_size, distance, keyframe);
}
current_offset += sample_size;
stream_size += sample_size;
current_dts += sc->stts_data[stts_index].duration;
distance++;
stts_sample++;
current_sample++;
if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
stts_sample = 0;
stts_index++;
}
}
}
if (st->duration > 0)
st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
} else {
unsigned chunk_samples, total = 0;
// compute total chunk count
for (i = 0; i < sc->stsc_count; i++) {
unsigned count, chunk_count;
chunk_samples = sc->stsc_data[i].count;
if (i != sc->stsc_count - 1 &&
sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
return;
}
if (sc->samples_per_frame >= 160) { // gsm
count = chunk_samples / sc->samples_per_frame;
} else if (sc->samples_per_frame > 1) {
unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
count = (chunk_samples+samples-1) / samples;
} else {
count = (chunk_samples+1023) / 1024;
}
if (i < sc->stsc_count - 1)
chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
else
chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
total += chunk_count * count;
}
av_dlog(mov->fc, "chunk count %d\n", total);
if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
return;
mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
if (!mem)
return;
st->index_entries = mem;
st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
// populate index
for (i = 0; i < sc->chunk_count; i++) {
current_offset = sc->chunk_offsets[i];
if (stsc_index + 1 < sc->stsc_count &&
i + 1 == sc->stsc_data[stsc_index + 1].first)
stsc_index++;
chunk_samples = sc->stsc_data[stsc_index].count;
while (chunk_samples > 0) {
AVIndexEntry *e;
unsigned size, samples;
if (sc->samples_per_frame >= 160) { // gsm
samples = sc->samples_per_frame;
size = sc->bytes_per_frame;
} else {
if (sc->samples_per_frame > 1) {
samples = FFMIN((1024 / sc->samples_per_frame)*
sc->samples_per_frame, chunk_samples);
size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
} else {
samples = FFMIN(1024, chunk_samples);
size = samples * sc->sample_size;
}
}
if (st->nb_index_entries >= total) {
av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
return;
}
e = &st->index_entries[st->nb_index_entries++];
e->pos = current_offset;
e->timestamp = current_dts;
e->size = size;
e->min_distance = 0;
e->flags = AVINDEX_KEYFRAME;
av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
"size %d, duration %d\n", st->index, i, current_offset, current_dts,
size, samples);
current_offset += size;
current_dts += samples;
chunk_samples -= samples;
}
}
}
}
static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
{
/* try relative path, we do not try the absolute because it can leak information about our
system to an attacker */
if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
char filename[1024];
const char *src_path;
int i, l;
/* find a source dir */
src_path = strrchr(src, '/');
if (src_path)
src_path++;
else
src_path = src;
/* find a next level down to target */
for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
if (ref->path[l] == '/') {
if (i == ref->nlvl_to - 1)
break;
else
i++;
}
/* compose filename if next level down to target was found */
if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
memcpy(filename, src, src_path - src);
filename[src_path - src] = 0;
for (i = 1; i < ref->nlvl_from; i++)
av_strlcat(filename, "../", 1024);
av_strlcat(filename, ref->path + l + 1, 1024);
if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
return 0;
}
} else if (use_absolute_path) {
av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
"this is a possible security issue\n");
if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
return 0;
}
return AVERROR(ENOENT);
}
static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
int ret;
st = avformat_new_stream(c->fc, NULL);
if (!st) return AVERROR(ENOMEM);
st->id = c->fc->nb_streams;
sc = av_mallocz(sizeof(MOVStreamContext));
if (!sc) return AVERROR(ENOMEM);
st->priv_data = sc;
st->codec->codec_type = AVMEDIA_TYPE_DATA;
sc->ffindex = st->index;
if ((ret = mov_read_default(c, pb, atom)) < 0)
return ret;
/* sanity checks */
if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
(!sc->sample_size && !sc->sample_count))) {
av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
st->index);
return 0;
}
if (sc->time_scale <= 0) {
av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
sc->time_scale = c->time_scale;
if (sc->time_scale <= 0)
sc->time_scale = 1;
}
avpriv_set_pts_info(st, 64, 1, sc->time_scale);
mov_build_index(c, st);
if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
MOVDref *dref = &sc->drefs[sc->dref_id - 1];
if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
c->use_absolute_path, c->fc) < 0)
av_log(c->fc, AV_LOG_ERROR,
"stream %d, error opening alias: path='%s', dir='%s', "
"filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
st->index, dref->path, dref->dir, dref->filename,
dref->volume, dref->nlvl_from, dref->nlvl_to);
} else
sc->pb = c->fc->pb;
if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
if (!st->sample_aspect_ratio.num &&
(st->codec->width != sc->width || st->codec->height != sc->height)) {
st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
((double)st->codec->width * sc->height), INT_MAX);
}
av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
sc->time_scale*st->nb_frames, st->duration, INT_MAX);
if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
sc->time_scale, sc->stts_data[0].duration, INT_MAX);
}
switch (st->codec->codec_id) {
#if CONFIG_H261_DECODER
case CODEC_ID_H261:
#endif
#if CONFIG_H263_DECODER
case CODEC_ID_H263:
#endif
#if CONFIG_H264_DECODER
case CODEC_ID_H264:
#endif
#if CONFIG_MPEG4_DECODER
case CODEC_ID_MPEG4:
#endif
st->codec->width = 0; /* let decoder init width/height */
st->codec->height= 0;
break;
}
/* Do not need those anymore. */
av_freep(&sc->chunk_offsets);
av_freep(&sc->stsc_data);
av_freep(&sc->sample_sizes);
av_freep(&sc->keyframes);
av_freep(&sc->stts_data);
av_freep(&sc->stps_data);
return 0;
}
static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
int ret;
c->itunes_metadata = 1;
ret = mov_read_default(c, pb, atom);
c->itunes_metadata = 0;
return ret;
}
static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
while (atom.size > 8) {
uint32_t tag = avio_rl32(pb);
atom.size -= 4;
if (tag == MKTAG('h','d','l','r')) {
avio_seek(pb, -8, SEEK_CUR);
atom.size += 8;
return mov_read_default(c, pb, atom);
}
}
return 0;
}
static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
int i;
int width;
int height;
int64_t disp_transform[2];
int display_matrix[3][2];
AVStream *st;
MOVStreamContext *sc;
int version;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
version = avio_r8(pb);
avio_rb24(pb); /* flags */
/*
MOV_TRACK_ENABLED 0x0001
MOV_TRACK_IN_MOVIE 0x0002
MOV_TRACK_IN_PREVIEW 0x0004
MOV_TRACK_IN_POSTER 0x0008
*/
if (version == 1) {
avio_rb64(pb);
avio_rb64(pb);
} else {
avio_rb32(pb); /* creation time */
avio_rb32(pb); /* modification time */
}
st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
avio_rb32(pb); /* reserved */
/* highlevel (considering edits) duration in movie timebase */
(version == 1) ? avio_rb64(pb) : avio_rb32(pb);
avio_rb32(pb); /* reserved */
avio_rb32(pb); /* reserved */
avio_rb16(pb); /* layer */
avio_rb16(pb); /* alternate group */
avio_rb16(pb); /* volume */
avio_rb16(pb); /* reserved */
//read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
// they're kept in fixed point format through all calculations
// ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
for (i = 0; i < 3; i++) {
display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
avio_rb32(pb); // 2.30 fixed point (not used)
}
width = avio_rb32(pb); // 16.16 fixed point track width
height = avio_rb32(pb); // 16.16 fixed point track height
sc->width = width >> 16;
sc->height = height >> 16;
//Assign clockwise rotate values based on transform matrix so that
//we can compensate for iPhone orientation during capture.
if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
av_dict_set(&st->metadata, "rotate", "90", 0);
}
if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
av_dict_set(&st->metadata, "rotate", "180", 0);
}
if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
av_dict_set(&st->metadata, "rotate", "270", 0);
}
// transform the display width/height according to the matrix
// skip this if the display matrix is the default identity matrix
// or if it is rotating the picture, ex iPhone 3GS
// to keep the same scale, use [width height 1<<16]
if (width && height &&
((display_matrix[0][0] != 65536 ||
display_matrix[1][1] != 65536) &&
!display_matrix[0][1] &&
!display_matrix[1][0] &&
!display_matrix[2][0] && !display_matrix[2][1])) {
for (i = 0; i < 2; i++)
disp_transform[i] =
(int64_t) width * display_matrix[0][i] +
(int64_t) height * display_matrix[1][i] +
((int64_t) display_matrix[2][i] << 16);
//sample aspect ratio is new width/height divided by old width/height
st->sample_aspect_ratio = av_d2q(
((double) disp_transform[0] * height) /
((double) disp_transform[1] * width), INT_MAX);
}
return 0;
}
static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
MOVFragment *frag = &c->fragment;
MOVTrackExt *trex = NULL;
int flags, track_id, i;
avio_r8(pb); /* version */
flags = avio_rb24(pb);
track_id = avio_rb32(pb);
if (!track_id)
return AVERROR_INVALIDDATA;
frag->track_id = track_id;
for (i = 0; i < c->trex_count; i++)
if (c->trex_data[i].track_id == frag->track_id) {
trex = &c->trex_data[i];
break;
}
if (!trex) {
av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
return AVERROR_INVALIDDATA;
}
frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
avio_rb64(pb) : frag->moof_offset;
frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
avio_rb32(pb) : trex->duration;
frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
avio_rb32(pb) : trex->size;
frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
avio_rb32(pb) : trex->flags;
av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
return 0;
}
static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
c->chapter_track = avio_rb32(pb);
return 0;
}
static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
MOVTrackExt *trex;
if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
return AVERROR_INVALIDDATA;
trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
if (!trex)
return AVERROR(ENOMEM);
c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
c->trex_data = trex;
trex = &c->trex_data[c->trex_count++];
avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
trex->track_id = avio_rb32(pb);
trex->stsd_id = avio_rb32(pb);
trex->duration = avio_rb32(pb);
trex->size = avio_rb32(pb);
trex->flags = avio_rb32(pb);
return 0;
}
static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
MOVFragment *frag = &c->fragment;
AVStream *st = NULL;
MOVStreamContext *sc;
MOVStts *ctts_data;
uint64_t offset;
int64_t dts;
int data_offset = 0;
unsigned entries, first_sample_flags = frag->flags;
int flags, distance, i, found_keyframe = 0;
for (i = 0; i < c->fc->nb_streams; i++) {
if (c->fc->streams[i]->id == frag->track_id) {
st = c->fc->streams[i];
break;
}
}
if (!st) {
av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
return AVERROR_INVALIDDATA;
}
sc = st->priv_data;
if (sc->pseudo_stream_id+1 != frag->stsd_id)
return 0;
avio_r8(pb); /* version */
flags = avio_rb24(pb);
entries = avio_rb32(pb);
av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
/* Always assume the presence of composition time offsets.
* Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
* 1) in the initial movie, there are no samples.
* 2) in the first movie fragment, there is only one sample without composition time offset.
* 3) in the subsequent movie fragments, there are samples with composition time offset. */
if (!sc->ctts_count && sc->sample_count)
{
/* Complement ctts table if moov atom doesn't have ctts atom. */
ctts_data = av_malloc(sizeof(*sc->ctts_data));
if (!ctts_data)
return AVERROR(ENOMEM);
sc->ctts_data = ctts_data;
sc->ctts_data[sc->ctts_count].count = sc->sample_count;
sc->ctts_data[sc->ctts_count].duration = 0;
sc->ctts_count++;
}
if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
return AVERROR_INVALIDDATA;
ctts_data = av_realloc(sc->ctts_data,
(entries+sc->ctts_count)*sizeof(*sc->ctts_data));
if (!ctts_data)
return AVERROR(ENOMEM);
sc->ctts_data = ctts_data;
if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
dts = sc->track_end - sc->time_offset;
offset = frag->base_data_offset + data_offset;
distance = 0;
av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
for (i = 0; i < entries; i++) {
unsigned sample_size = frag->size;
int sample_flags = i ? frag->flags : first_sample_flags;
unsigned sample_duration = frag->duration;
int keyframe = 0;
if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
sc->ctts_data[sc->ctts_count].count = 1;
sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
avio_rb32(pb) : 0;
sc->ctts_count++;
if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
keyframe = 1;
else if (!found_keyframe)
keyframe = found_keyframe =
!(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
if (keyframe)
distance = 0;
av_add_index_entry(st, offset, dts, sample_size, distance,
keyframe ? AVINDEX_KEYFRAME : 0);
av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
"size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
offset, dts, sample_size, distance, keyframe);
distance++;
dts += sample_duration;
offset += sample_size;
sc->data_size += sample_size;
}
frag->moof_offset = offset;
st->duration = sc->track_end = dts + sc->time_offset;
return 0;
}
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
/* like the files created with Adobe Premiere 5.0, for samples see */
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
int err;
if (atom.size < 8)
return 0; /* continue */
if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
avio_skip(pb, atom.size - 4);
return 0;
}
atom.type = avio_rl32(pb);
atom.size -= 8;
if (atom.type != MKTAG('m','d','a','t')) {
avio_skip(pb, atom.size);
return 0;
}
err = mov_read_mdat(c, pb, atom);
return err;
}
static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
#if CONFIG_ZLIB
AVIOContext ctx;
uint8_t *cmov_data;
uint8_t *moov_data; /* uncompressed data */
long cmov_len, moov_len;
int ret = -1;
avio_rb32(pb); /* dcom atom */
if (avio_rl32(pb) != MKTAG('d','c','o','m'))
return AVERROR_INVALIDDATA;
if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
return AVERROR_INVALIDDATA;
}
avio_rb32(pb); /* cmvd atom */
if (avio_rl32(pb) != MKTAG('c','m','v','d'))
return AVERROR_INVALIDDATA;
moov_len = avio_rb32(pb); /* uncompressed size */
cmov_len = atom.size - 6 * 4;
cmov_data = av_malloc(cmov_len);
if (!cmov_data)
return AVERROR(ENOMEM);
moov_data = av_malloc(moov_len);
if (!moov_data) {
av_free(cmov_data);
return AVERROR(ENOMEM);
}
avio_read(pb, cmov_data, cmov_len);
if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
goto free_and_return;
if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
goto free_and_return;
atom.type = MKTAG('m','o','o','v');
atom.size = moov_len;
ret = mov_read_default(c, &ctx, atom);
free_and_return:
av_free(moov_data);
av_free(cmov_data);
return ret;
#else
av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
return AVERROR(ENOSYS);
#endif
}
/* edit list atom */
static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
MOVStreamContext *sc;
int i, edit_count, version, edit_start_index = 0;
if (c->fc->nb_streams < 1)
return 0;
sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
version = avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
edit_count = avio_rb32(pb); /* entries */
if ((uint64_t)edit_count*12+8 > atom.size)
return AVERROR_INVALIDDATA;
for (i=0; i<edit_count; i++){
int64_t time;
int64_t duration;
if (version == 1) {
duration = avio_rb64(pb);
time = avio_rb64(pb);
} else {
duration = avio_rb32(pb); /* segment duration */
time = (int32_t)avio_rb32(pb); /* media time */
}
avio_rb32(pb); /* Media rate */
if (i == 0 && time == -1) {
sc->empty_duration = duration;
edit_start_index = 1;
} else if (i == edit_start_index && time >= 0)
sc->start_time = time;
}
if (edit_count > 1)
av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
"a/v desync might occur, patch welcome\n");
av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
return 0;
}
static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
if (atom.size < 16)
return 0;
avio_skip(pb, 4);
ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
return 0;
}
static const MOVParseTableEntry mov_default_parse_table[] = {
{ MKTAG('a','v','s','s'), mov_read_avss },
{ MKTAG('c','h','p','l'), mov_read_chpl },
{ MKTAG('c','o','6','4'), mov_read_stco },
{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
{ MKTAG('d','i','n','f'), mov_read_default },
{ MKTAG('d','r','e','f'), mov_read_dref },
{ MKTAG('e','d','t','s'), mov_read_default },
{ MKTAG('e','l','s','t'), mov_read_elst },
{ MKTAG('e','n','d','a'), mov_read_enda },
{ MKTAG('f','i','e','l'), mov_read_fiel },
{ MKTAG('f','t','y','p'), mov_read_ftyp },
{ MKTAG('g','l','b','l'), mov_read_glbl },
{ MKTAG('h','d','l','r'), mov_read_hdlr },
{ MKTAG('i','l','s','t'), mov_read_ilst },
{ MKTAG('j','p','2','h'), mov_read_jp2h },
{ MKTAG('m','d','a','t'), mov_read_mdat },
{ MKTAG('m','d','h','d'), mov_read_mdhd },
{ MKTAG('m','d','i','a'), mov_read_default },
{ MKTAG('m','e','t','a'), mov_read_meta },
{ MKTAG('m','i','n','f'), mov_read_default },
{ MKTAG('m','o','o','f'), mov_read_moof },
{ MKTAG('m','o','o','v'), mov_read_moov },
{ MKTAG('m','v','e','x'), mov_read_default },
{ MKTAG('m','v','h','d'), mov_read_mvhd },
{ MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
{ MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
{ MKTAG('a','v','c','C'), mov_read_glbl },
{ MKTAG('p','a','s','p'), mov_read_pasp },
{ MKTAG('s','t','b','l'), mov_read_default },
{ MKTAG('s','t','c','o'), mov_read_stco },
{ MKTAG('s','t','p','s'), mov_read_stps },
{ MKTAG('s','t','r','f'), mov_read_strf },
{ MKTAG('s','t','s','c'), mov_read_stsc },
{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
{ MKTAG('s','t','t','s'), mov_read_stts },
{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
{ MKTAG('t','r','a','k'), mov_read_trak },
{ MKTAG('t','r','a','f'), mov_read_default },
{ MKTAG('t','r','e','f'), mov_read_default },
{ MKTAG('c','h','a','p'), mov_read_chap },
{ MKTAG('t','r','e','x'), mov_read_trex },
{ MKTAG('t','r','u','n'), mov_read_trun },
{ MKTAG('u','d','t','a'), mov_read_default },
{ MKTAG('w','a','v','e'), mov_read_wave },
{ MKTAG('e','s','d','s'), mov_read_esds },
{ MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
{ MKTAG('w','f','e','x'), mov_read_wfex },
{ MKTAG('c','m','o','v'), mov_read_cmov },
{ MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
{ MKTAG('d','v','c','1'), mov_read_dvc1 },
{ 0, NULL }
};
static int mov_probe(AVProbeData *p)
{
unsigned int offset;
uint32_t tag;
int score = 0;
/* check file header */
offset = 0;
for (;;) {
/* ignore invalid offset */
if ((offset + 8) > (unsigned int)p->buf_size)
return score;
tag = AV_RL32(p->buf + offset + 4);
switch(tag) {
/* check for obvious tags */
case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
case MKTAG('m','o','o','v'):
case MKTAG('m','d','a','t'):
case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
case MKTAG('f','t','y','p'):
return AVPROBE_SCORE_MAX;
/* those are more common words, so rate then a bit less */
case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
case MKTAG('w','i','d','e'):
case MKTAG('f','r','e','e'):
case MKTAG('j','u','n','k'):
case MKTAG('p','i','c','t'):
return AVPROBE_SCORE_MAX - 5;
case MKTAG(0x82,0x82,0x7f,0x7d):
case MKTAG('s','k','i','p'):
case MKTAG('u','u','i','d'):
case MKTAG('p','r','f','l'):
offset = AV_RB32(p->buf+offset) + offset;
/* if we only find those cause probedata is too small at least rate them */
score = AVPROBE_SCORE_MAX - 50;
break;
default:
/* unrecognized tag */
return score;
}
}
}
// must be done after parsing all trak because there's no order requirement
static void mov_read_chapters(AVFormatContext *s)
{
MOVContext *mov = s->priv_data;
AVStream *st = NULL;
MOVStreamContext *sc;
int64_t cur_pos;
int i;
for (i = 0; i < s->nb_streams; i++)
if (s->streams[i]->id == mov->chapter_track) {
st = s->streams[i];
break;
}
if (!st) {
av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
return;
}
st->discard = AVDISCARD_ALL;
sc = st->priv_data;
cur_pos = avio_tell(sc->pb);
for (i = 0; i < st->nb_index_entries; i++) {
AVIndexEntry *sample = &st->index_entries[i];
int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
uint8_t *title;
uint16_t ch;
int len, title_len;
if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
goto finish;
}
// the first two bytes are the length of the title
len = avio_rb16(sc->pb);
if (len > sample->size-2)
continue;
title_len = 2*len + 1;
if (!(title = av_mallocz(title_len)))
goto finish;
// The samples could theoretically be in any encoding if there's an encd
// atom following, but in practice are only utf-8 or utf-16, distinguished
// instead by the presence of a BOM
if (!len) {
title[0] = 0;
} else {
ch = avio_rb16(sc->pb);
if (ch == 0xfeff)
avio_get_str16be(sc->pb, len, title, title_len);
else if (ch == 0xfffe)
avio_get_str16le(sc->pb, len, title, title_len);
else {
AV_WB16(title, ch);
if (len == 1 || len == 2)
title[len] = 0;
else
avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
}
}
avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
av_freep(&title);
}
finish:
avio_seek(sc->pb, cur_pos, SEEK_SET);
}
static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
uint32_t value, int flags)
{
AVTimecode tc;
char buf[AV_TIMECODE_STR_SIZE];
AVRational rate = {st->codec->time_base.den,
st->codec->time_base.num};
int ret = av_timecode_init(&tc, rate, flags, 0, s);
if (ret < 0)
return ret;
av_dict_set(&st->metadata, "timecode",
av_timecode_make_string(&tc, buf, value), 0);
return 0;
}
static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
{
MOVStreamContext *sc = st->priv_data;
int flags = 0;
int64_t cur_pos = avio_tell(sc->pb);
uint32_t value;
if (!st->nb_index_entries)
return -1;
avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
value = avio_rb32(s->pb);
if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
/* Assume Counter flag is set to 1 in tmcd track (even though it is likely
* not the case) and thus assume "frame number format" instead of QT one.
* No sample with tmcd track can be found with a QT timecode at the moment,
* despite what the tmcd track "suggests" (Counter flag set to 0 means QT
* format). */
parse_timecode_in_framenum_format(s, st, value, flags);
avio_seek(sc->pb, cur_pos, SEEK_SET);
return 0;
}
static int mov_read_close(AVFormatContext *s)
{
MOVContext *mov = s->priv_data;
int i, j;
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
MOVStreamContext *sc = st->priv_data;
av_freep(&sc->ctts_data);
for (j = 0; j < sc->drefs_count; j++) {
av_freep(&sc->drefs[j].path);
av_freep(&sc->drefs[j].dir);
}
av_freep(&sc->drefs);
if (sc->pb && sc->pb != s->pb)
avio_close(sc->pb);
sc->pb = NULL;
av_freep(&sc->chunk_offsets);
av_freep(&sc->keyframes);
av_freep(&sc->sample_sizes);
av_freep(&sc->stps_data);
av_freep(&sc->stsc_data);
av_freep(&sc->stts_data);
}
if (mov->dv_demux) {
for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
av_freep(&mov->dv_fctx->streams[i]->codec);
av_freep(&mov->dv_fctx->streams[i]);
}
av_freep(&mov->dv_fctx);
av_freep(&mov->dv_demux);
}
av_freep(&mov->trex_data);
return 0;
}
static int mov_read_header(AVFormatContext *s)
{
MOVContext *mov = s->priv_data;
AVIOContext *pb = s->pb;
int err;
MOVAtom atom = { AV_RL32("root") };
mov->fc = s;
/* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
if (pb->seekable)
atom.size = avio_size(pb);
else
atom.size = INT64_MAX;
/* check MOV header */
if ((err = mov_read_default(mov, pb, atom)) < 0) {
av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
mov_read_close(s);
return err;
}
if (!mov->found_moov) {
av_log(s, AV_LOG_ERROR, "moov atom not found\n");
mov_read_close(s);
return AVERROR_INVALIDDATA;
}
av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
if (pb->seekable) {
int i;
if (mov->chapter_track > 0)
mov_read_chapters(s);
for (i = 0; i < s->nb_streams; i++)
if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
mov_read_timecode_track(s, s->streams[i]);
}
if (mov->trex_data) {
int i;
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
MOVStreamContext *sc = st->priv_data;
if (st->duration)
st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
}
}
return 0;
}
static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
{
AVIndexEntry *sample = NULL;
int64_t best_dts = INT64_MAX;
int i;
for (i = 0; i < s->nb_streams; i++) {
AVStream *avst = s->streams[i];
MOVStreamContext *msc = avst->priv_data;
if (msc->pb && msc->current_sample < avst->nb_index_entries) {
AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
(s->pb->seekable &&
((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
(FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
sample = current_sample;
best_dts = dts;
*st = avst;
}
}
}
return sample;
}
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
{
MOVContext *mov = s->priv_data;
MOVStreamContext *sc;
AVIndexEntry *sample;
AVStream *st = NULL;
int ret;
mov->fc = s;
retry:
sample = mov_find_next_sample(s, &st);
if (!sample) {
mov->found_mdat = 0;
if (!mov->next_root_atom)
return AVERROR_EOF;
avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
mov->next_root_atom = 0;
if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
url_feof(s->pb))
return AVERROR_EOF;
av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
goto retry;
}
sc = st->priv_data;
/* must be done just before reading, to avoid infinite loop on sample */
sc->current_sample++;
if (st->discard != AVDISCARD_ALL) {
if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
sc->ffindex, sample->pos);
return AVERROR_INVALIDDATA;
}
ret = av_get_packet(sc->pb, pkt, sample->size);
if (ret < 0)
return ret;
if (sc->has_palette) {
uint8_t *pal;
pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
if (!pal) {
av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
} else {
memcpy(pal, sc->palette, AVPALETTE_SIZE);
sc->has_palette = 0;
}
}
#if CONFIG_DV_DEMUXER
if (mov->dv_demux && sc->dv_audio_container) {
avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
av_free(pkt->data);
pkt->size = 0;
ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
if (ret < 0)
return ret;
}
#endif
}
pkt->stream_index = sc->ffindex;
pkt->dts = sample->timestamp;
if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
/* update ctts context */
sc->ctts_sample++;
if (sc->ctts_index < sc->ctts_count &&
sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
sc->ctts_index++;
sc->ctts_sample = 0;
}
if (sc->wrong_dts)
pkt->dts = AV_NOPTS_VALUE;
} else {
int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
st->index_entries[sc->current_sample].timestamp : st->duration;
pkt->duration = next_dts - pkt->dts;
pkt->pts = pkt->dts;
}
if (st->discard == AVDISCARD_ALL)
goto retry;
pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
pkt->pos = sample->pos;
av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
return 0;
}
static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
{
MOVStreamContext *sc = st->priv_data;
int sample, time_sample;
int i;
sample = av_index_search_timestamp(st, timestamp, flags);
av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
sample = 0;
if (sample < 0) /* not sure what to do */
return AVERROR_INVALIDDATA;
sc->current_sample = sample;
av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
/* adjust ctts index */
if (sc->ctts_data) {
time_sample = 0;
for (i = 0; i < sc->ctts_count; i++) {
int next = time_sample + sc->ctts_data[i].count;
if (next > sc->current_sample) {
sc->ctts_index = i;
sc->ctts_sample = sc->current_sample - time_sample;
break;
}
time_sample = next;
}
}
return sample;
}
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
{
AVStream *st;
int64_t seek_timestamp, timestamp;
int sample;
int i;
if (stream_index >= s->nb_streams)
return AVERROR_INVALIDDATA;
if (sample_time < 0)
sample_time = 0;
st = s->streams[stream_index];
sample = mov_seek_stream(s, st, sample_time, flags);
if (sample < 0)
return sample;
/* adjust seek timestamp to found sample timestamp */
seek_timestamp = st->index_entries[sample].timestamp;
for (i = 0; i < s->nb_streams; i++) {
st = s->streams[i];
if (stream_index == i)
continue;
timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
mov_seek_stream(s, st, timestamp, flags);
}
return 0;
}
static const AVOption options[] = {
{"use_absolute_path",
"allow using absolute path when opening alias, this is a possible security issue",
offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.dbl = 0},
0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
{NULL}
};
static const AVClass class = {"mov,mp4,m4a,3gp,3g2,mj2", av_default_item_name, options, LIBAVUTIL_VERSION_INT};
AVInputFormat ff_mov_demuxer = {
.name = "mov,mp4,m4a,3gp,3g2,mj2",
.long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
.priv_data_size = sizeof(MOVContext),
.read_probe = mov_probe,
.read_header = mov_read_header,
.read_packet = mov_read_packet,
.read_close = mov_read_close,
.read_seek = mov_read_seek,
.priv_class = &class,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4985_0 |
crossvul-cpp_data_good_2540_1 | /* $Id: upnpreplyparse.c,v 1.19 2015/07/15 10:29:11 nanard Exp $ */
/* vim: tabstop=4 shiftwidth=4 noexpandtab
* MiniUPnP project
* http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
* (c) 2006-2017 Thomas Bernard
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "upnpreplyparse.h"
#include "minixml.h"
static void
NameValueParserStartElt(void * d, const char * name, int l)
{
struct NameValueParserData * data = (struct NameValueParserData *)d;
data->topelt = 1;
if(l>63)
l = 63;
memcpy(data->curelt, name, l);
data->curelt[l] = '\0';
data->cdata = NULL;
data->cdatalen = 0;
}
static void
NameValueParserEndElt(void * d, const char * name, int l)
{
struct NameValueParserData * data = (struct NameValueParserData *)d;
struct NameValue * nv;
(void)name;
(void)l;
if(!data->topelt)
return;
if(strcmp(data->curelt, "NewPortListing") != 0)
{
int l;
/* standard case. Limited to n chars strings */
l = data->cdatalen;
nv = malloc(sizeof(struct NameValue));
if(nv == NULL)
{
/* malloc error */
#ifdef DEBUG
fprintf(stderr, "%s: error allocating memory",
"NameValueParserEndElt");
#endif /* DEBUG */
return;
}
if(l>=(int)sizeof(nv->value))
l = sizeof(nv->value) - 1;
strncpy(nv->name, data->curelt, 64);
nv->name[63] = '\0';
if(data->cdata != NULL)
{
memcpy(nv->value, data->cdata, l);
nv->value[l] = '\0';
}
else
{
nv->value[0] = '\0';
}
nv->l_next = data->l_head; /* insert in list */
data->l_head = nv;
}
data->cdata = NULL;
data->cdatalen = 0;
data->topelt = 0;
}
static void
NameValueParserGetData(void * d, const char * datas, int l)
{
struct NameValueParserData * data = (struct NameValueParserData *)d;
if(strcmp(data->curelt, "NewPortListing") == 0)
{
/* specific case for NewPortListing which is a XML Document */
data->portListing = malloc(l + 1);
if(!data->portListing)
{
/* malloc error */
#ifdef DEBUG
fprintf(stderr, "%s: error allocating memory",
"NameValueParserGetData");
#endif /* DEBUG */
return;
}
memcpy(data->portListing, datas, l);
data->portListing[l] = '\0';
data->portListingLength = l;
}
else
{
/* standard case. */
data->cdata = datas;
data->cdatalen = l;
}
}
void
ParseNameValue(const char * buffer, int bufsize,
struct NameValueParserData * data)
{
struct xmlparser parser;
memset(data, 0, sizeof(struct NameValueParserData));
/* init xmlparser object */
parser.xmlstart = buffer;
parser.xmlsize = bufsize;
parser.data = data;
parser.starteltfunc = NameValueParserStartElt;
parser.endeltfunc = NameValueParserEndElt;
parser.datafunc = NameValueParserGetData;
parser.attfunc = 0;
parsexml(&parser);
}
void
ClearNameValueList(struct NameValueParserData * pdata)
{
struct NameValue * nv;
if(pdata->portListing)
{
free(pdata->portListing);
pdata->portListing = NULL;
pdata->portListingLength = 0;
}
while((nv = pdata->l_head) != NULL)
{
pdata->l_head = nv->l_next;
free(nv);
}
}
char *
GetValueFromNameValueList(struct NameValueParserData * pdata,
const char * Name)
{
struct NameValue * nv;
char * p = NULL;
for(nv = pdata->l_head;
(nv != NULL) && (p == NULL);
nv = nv->l_next)
{
if(strcmp(nv->name, Name) == 0)
p = nv->value;
}
return p;
}
#if 0
/* useless now that minixml ignores namespaces by itself */
char *
GetValueFromNameValueListIgnoreNS(struct NameValueParserData * pdata,
const char * Name)
{
struct NameValue * nv;
char * p = NULL;
char * pname;
for(nv = pdata->head.lh_first;
(nv != NULL) && (p == NULL);
nv = nv->entries.le_next)
{
pname = strrchr(nv->name, ':');
if(pname)
pname++;
else
pname = nv->name;
if(strcmp(pname, Name)==0)
p = nv->value;
}
return p;
}
#endif
/* debug all-in-one function
* do parsing then display to stdout */
#ifdef DEBUG
void
DisplayNameValueList(char * buffer, int bufsize)
{
struct NameValueParserData pdata;
struct NameValue * nv;
ParseNameValue(buffer, bufsize, &pdata);
for(nv = pdata.l_head;
nv != NULL;
nv = nv->l_next)
{
printf("%s = %s\n", nv->name, nv->value);
}
ClearNameValueList(&pdata);
}
#endif /* DEBUG */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2540_1 |
crossvul-cpp_data_bad_614_0 | #include <uwsgi.h>
extern struct uwsgi_server uwsgi;
#ifdef __BIG_ENDIAN__
uint16_t uwsgi_swap16(uint16_t x) {
return (uint16_t) ((x & 0xff) << 8 | (x & 0xff00) >> 8);
}
uint32_t uwsgi_swap32(uint32_t x) {
x = ((x << 8) & 0xFF00FF00) | ((x >> 8) & 0x00FF00FF);
return (x >> 16) | (x << 16);
}
// thanks to ffmpeg project for this idea :P
uint64_t uwsgi_swap64(uint64_t x) {
union {
uint64_t ll;
uint32_t l[2];
} w, r;
w.ll = x;
r.l[0] = uwsgi_swap32(w.l[1]);
r.l[1] = uwsgi_swap32(w.l[0]);
return r.ll;
}
#endif
// check if a string is a valid hex number
int check_hex(char *str, int len) {
int i;
for (i = 0; i < len; i++) {
if ((str[i] < '0' && str[i] > '9') && (str[i] < 'a' && str[i] > 'f') && (str[i] < 'A' && str[i] > 'F')
) {
return 0;
}
}
return 1;
}
// increase worker harakiri
void inc_harakiri(struct wsgi_request *wsgi_req, int sec) {
if (uwsgi.master_process) {
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].harakiri += sec;
}
else {
alarm(uwsgi.harakiri_options.workers + sec);
}
}
// set worker harakiri
void set_harakiri(struct wsgi_request *wsgi_req, int sec) {
if (!wsgi_req) return;
if (sec == 0) {
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].harakiri = 0;
}
else {
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].harakiri = uwsgi_now() + sec;
}
if (!uwsgi.master_process) {
alarm(sec);
}
}
// set user harakiri
void set_user_harakiri(struct wsgi_request *wsgi_req, int sec) {
if (!uwsgi.master_process) {
uwsgi_log("!!! unable to set user harakiri without the master process !!!\n");
return;
}
// a 0 seconds value, reset the timer
time_t timeout = sec == 0 ? 0 : uwsgi_now() + sec;
if (uwsgi.muleid > 0) {
uwsgi.mules[uwsgi.muleid - 1].user_harakiri = timeout;
}
else if (uwsgi.i_am_a_spooler) {
struct uwsgi_spooler *uspool = uwsgi.i_am_a_spooler;
uspool->user_harakiri = timeout;
}
else if (wsgi_req) {
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].user_harakiri = timeout;
}
}
// set mule harakiri
void set_mule_harakiri(int sec) {
if (sec == 0) {
uwsgi.mules[uwsgi.muleid - 1].harakiri = 0;
}
else {
uwsgi.mules[uwsgi.muleid - 1].harakiri = uwsgi_now() + sec;
}
if (!uwsgi.master_process) {
alarm(sec);
}
}
// set spooler harakiri
void set_spooler_harakiri(int sec) {
if (sec == 0) {
uwsgi.i_am_a_spooler->harakiri = 0;
}
else {
uwsgi.i_am_a_spooler->harakiri = uwsgi_now() + sec;
}
if (!uwsgi.master_process) {
alarm(sec);
}
}
// daemonize to the specified logfile
void daemonize(char *logfile) {
pid_t pid;
// do not daemonize under emperor
if (uwsgi.has_emperor) {
logto(logfile);
return;
}
pid = fork();
if (pid < 0) {
uwsgi_error("fork()");
exit(1);
}
if (pid != 0) {
_exit(0);
}
if (setsid() < 0) {
uwsgi_error("setsid()");
exit(1);
}
/* refork... */
pid = fork();
if (pid < 0) {
uwsgi_error("fork()");
exit(1);
}
if (pid != 0) {
_exit(0);
}
if (!uwsgi.do_not_change_umask) {
umask(0);
}
/*if (chdir("/") != 0) {
uwsgi_error("chdir()");
exit(1);
} */
uwsgi_remap_fd(0, "/dev/null");
logto(logfile);
}
// get current working directory
char *uwsgi_get_cwd() {
#if defined(__GLIBC__)
return getcwd(NULL, 0);
#else
// set this to static to avoid useless reallocations in stats mode
static size_t newsize = 256;
char *cwd = uwsgi_malloc(newsize);
if (getcwd(cwd, newsize) == NULL && errno == ERANGE) {
newsize += 256;
uwsgi_log("need a bigger buffer (%lu bytes) for getcwd(). doing reallocation.\n", (unsigned long) newsize);
free(cwd);
cwd = uwsgi_malloc(newsize);
if (getcwd(cwd, newsize) == NULL) {
uwsgi_error("getcwd()");
exit(1);
}
}
return cwd;
#endif
}
#ifdef __linux__
void uwsgi_set_cgroup() {
char *cgroup_taskfile;
FILE *cgroup;
char *cgroup_opt;
struct uwsgi_string_list *usl, *uslo;
if (!uwsgi.cgroup)
return;
if (getuid())
return;
usl = uwsgi.cgroup;
while (usl) {
int mode = strtol(uwsgi.cgroup_dir_mode, 0, 8);
if (mkdir(usl->value, mode)) {
if (errno != EEXIST) {
uwsgi_error("uwsgi_set_cgroup()/mkdir()");
exit(1);
}
if (chmod(usl->value, mode)) {
uwsgi_error("uwsgi_set_cgroup()/chmod()");
exit(1);
}
uwsgi_log("using Linux cgroup %s with mode %o\n", usl->value, mode);
}
else {
uwsgi_log("created Linux cgroup %s with mode %o\n", usl->value, mode);
}
cgroup_taskfile = uwsgi_concat2(usl->value, "/tasks");
cgroup = fopen(cgroup_taskfile, "w");
if (!cgroup) {
uwsgi_error_open(cgroup_taskfile);
exit(1);
}
if (fprintf(cgroup, "%d\n", (int) getpid()) <= 0 || ferror(cgroup) || fclose(cgroup)) {
uwsgi_error("could not set cgroup");
exit(1);
}
uwsgi_log("assigned process %d to cgroup %s\n", (int) getpid(), cgroup_taskfile);
free(cgroup_taskfile);
uslo = uwsgi.cgroup_opt;
while (uslo) {
cgroup_opt = strchr(uslo->value, '=');
if (!cgroup_opt) {
cgroup_opt = strchr(uslo->value, ':');
if (!cgroup_opt) {
uwsgi_log("invalid cgroup-opt syntax\n");
exit(1);
}
}
cgroup_opt[0] = 0;
cgroup_opt++;
cgroup_taskfile = uwsgi_concat3(usl->value, "/", uslo->value);
cgroup = fopen(cgroup_taskfile, "w");
if (cgroup) {
if (fprintf(cgroup, "%s\n", cgroup_opt) <= 0 || ferror(cgroup) || fclose(cgroup)) {
uwsgi_log("could not set cgroup option %s to %s\n", uslo->value, cgroup_opt);
exit(1);
}
uwsgi_log("set %s to %s\n", cgroup_opt, cgroup_taskfile);
}
free(cgroup_taskfile);
cgroup_opt[-1] = '=';
uslo = uslo->next;
}
usl = usl->next;
}
}
#endif
#ifdef UWSGI_CAP
void uwsgi_apply_cap(cap_value_t * cap, int caps_count) {
cap_value_t minimal_cap_values[] = { CAP_SYS_CHROOT, CAP_SETUID, CAP_SETGID, CAP_SETPCAP };
cap_t caps = cap_init();
if (!caps) {
uwsgi_error("cap_init()");
exit(1);
}
cap_clear(caps);
cap_set_flag(caps, CAP_EFFECTIVE, 4, minimal_cap_values, CAP_SET);
cap_set_flag(caps, CAP_PERMITTED, 4, minimal_cap_values, CAP_SET);
cap_set_flag(caps, CAP_PERMITTED, caps_count, cap, CAP_SET);
cap_set_flag(caps, CAP_INHERITABLE, caps_count, cap, CAP_SET);
if (cap_set_proc(caps) < 0) {
uwsgi_error("cap_set_proc()");
exit(1);
}
cap_free(caps);
#ifdef __linux__
#ifdef SECBIT_KEEP_CAPS
if (prctl(SECBIT_KEEP_CAPS, 1, 0, 0, 0) < 0) {
uwsgi_error("prctl()");
exit(1);
}
#else
if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0) {
uwsgi_error("prctl()");
exit(1);
}
#endif
#endif
}
#endif
// drop privileges (as root)
/*
here we manage jails/namespaces too
it is a pretty huge function... refactory is needed
*/
void uwsgi_as_root() {
if (getuid() > 0)
goto nonroot;
#ifndef __RUMP__
if (!uwsgi.master_as_root && !uwsgi.uidname) {
uwsgi_log_initial("uWSGI running as root, you can use --uid/--gid/--chroot options\n");
}
#endif
int in_jail = 0;
#if defined(__linux__) && !defined(OBSOLETE_LINUX_KERNEL)
if (uwsgi.unshare && !uwsgi.reloads) {
if (unshare(uwsgi.unshare)) {
uwsgi_error("unshare()");
exit(1);
}
else {
uwsgi_log("[linux-namespace] applied unshare() mask: %d\n", uwsgi.unshare);
}
#ifdef CLONE_NEWUSER
if (uwsgi.unshare & CLONE_NEWUSER) {
if (setuid(0)) {
uwsgi_error("uwsgi_as_root()/setuid(0)");
exit(1);
}
}
#endif
in_jail = 1;
}
#endif
#ifdef UWSGI_CAP
if (uwsgi.cap && uwsgi.cap_count > 0 && !uwsgi.reloads) {
uwsgi_apply_cap(uwsgi.cap, uwsgi.cap_count);
}
#endif
#if defined(__FreeBSD__) || defined(__GNU_kFreeBSD__)
if (uwsgi.jail && !uwsgi.reloads) {
struct jail ujail;
char *jarg = uwsgi_str(uwsgi.jail);
char *j_hostname = NULL;
char *j_name = NULL;
char *space = strchr(jarg, ' ');
if (space) {
*space = 0;
j_hostname = space + 1;
space = strchr(j_hostname, ' ');
if (space) {
*space = 0;
j_name = space + 1;
}
}
ujail.version = JAIL_API_VERSION;
ujail.path = jarg;
ujail.hostname = j_hostname ? j_hostname : "";
ujail.jailname = j_name;
ujail.ip4s = 0;
ujail.ip6s = 0;
struct uwsgi_string_list *usl = NULL;
uwsgi_foreach(usl, uwsgi.jail_ip4) {
ujail.ip4s++;
}
struct in_addr *saddr = uwsgi_calloc(sizeof(struct in_addr) * ujail.ip4s);
int i = 0;
uwsgi_foreach(usl, uwsgi.jail_ip4) {
if (!inet_pton(AF_INET, usl->value, &saddr[i].s_addr)) {
uwsgi_error("jail()/inet_pton()");
exit(1);
}
i++;
}
ujail.ip4 = saddr;
#ifdef AF_INET6
uwsgi_foreach(usl, uwsgi.jail_ip6) {
ujail.ip6s++;
}
struct in6_addr *saddr6 = uwsgi_calloc(sizeof(struct in6_addr) * ujail.ip6s);
i = 0;
uwsgi_foreach(usl, uwsgi.jail_ip6) {
if (!inet_pton(AF_INET6, usl->value, &saddr6[i].s6_addr)) {
uwsgi_error("jail()/inet_pton()");
exit(1);
}
i++;
}
ujail.ip6 = saddr6;
#endif
int jail_id = jail(&ujail);
if (jail_id < 0) {
uwsgi_error("jail()");
exit(1);
}
if (uwsgi.jidfile) {
if (uwsgi_write_intfile(uwsgi.jidfile, jail_id)) {
uwsgi_log("unable to write jidfile\n");
exit(1);
}
}
uwsgi_log("--- running in FreeBSD jail %d ---\n", jail_id);
in_jail = 1;
}
#ifdef UWSGI_HAS_FREEBSD_LIBJAIL
if (uwsgi.jail_attach && !uwsgi.reloads) {
struct jailparam jparam;
uwsgi_log("attaching to FreeBSD jail %s ...\n", uwsgi.jail_attach);
if (!is_a_number(uwsgi.jail_attach)) {
if (jailparam_init(&jparam, "name")) {
uwsgi_error("jailparam_init()");
exit(1);
}
}
else {
if (jailparam_init(&jparam, "jid")) {
uwsgi_error("jailparam_init()");
exit(1);
}
}
jailparam_import(&jparam, uwsgi.jail_attach);
int jail_id = jailparam_set(&jparam, 1, JAIL_UPDATE | JAIL_ATTACH);
if (jail_id < 0) {
uwsgi_error("jailparam_set()");
exit(1);
}
jailparam_free(&jparam, 1);
uwsgi_log("--- running in FreeBSD jail %d ---\n", jail_id);
in_jail = 1;
}
if (uwsgi.jail2 && !uwsgi.reloads) {
struct uwsgi_string_list *usl = NULL;
unsigned nparams = 0;
uwsgi_foreach(usl, uwsgi.jail2) {
nparams++;
}
struct jailparam *params = uwsgi_malloc(sizeof(struct jailparam) * nparams);
int i = 0;
uwsgi_foreach(usl, uwsgi.jail2) {
uwsgi_log("FreeBSD libjail applying %s\n", usl->value);
char *equal = strchr(usl->value, '=');
if (equal) {
*equal = 0;
}
if (jailparam_init(¶ms[i], usl->value)) {
uwsgi_error("jailparam_init()");
exit(1);
}
if (equal) {
jailparam_import(¶ms[i], equal + 1);
*equal = '=';
}
else {
jailparam_import(¶ms[i], "1");
}
i++;
}
int jail_id = jailparam_set(params, nparams, JAIL_CREATE | JAIL_ATTACH);
if (jail_id < 0) {
uwsgi_error("jailparam_set()");
exit(1);
}
jailparam_free(params, nparams);
if (uwsgi.jidfile) {
if (uwsgi_write_intfile(uwsgi.jidfile, jail_id)) {
uwsgi_log("unable to write jidfile\n");
exit(1);
}
}
uwsgi_log("--- running in FreeBSD jail %d ---\n", jail_id);
in_jail = 1;
}
#endif
#endif
if (in_jail || uwsgi.jailed) {
uwsgi_hooks_run(uwsgi.hook_post_jail, "post-jail", 1);
struct uwsgi_string_list *usl = NULL;
uwsgi_foreach(usl, uwsgi.mount_post_jail) {
uwsgi_log("mounting \"%s\" (post-jail)...\n", usl->value);
if (uwsgi_mount_hook(usl->value)) {
exit(1);
}
}
uwsgi_foreach(usl, uwsgi.umount_post_jail) {
uwsgi_log("un-mounting \"%s\" (post-jail)...\n", usl->value);
if (uwsgi_umount_hook(usl->value)) {
exit(1);
}
}
uwsgi_foreach(usl, uwsgi.exec_post_jail) {
uwsgi_log("running \"%s\" (post-jail)...\n", usl->value);
int ret = uwsgi_run_command_and_wait(NULL, usl->value);
if (ret != 0) {
uwsgi_log("command \"%s\" exited with non-zero code: %d\n", usl->value, ret);
exit(1);
}
}
uwsgi_foreach(usl, uwsgi.call_post_jail) {
if (uwsgi_call_symbol(usl->value)) {
uwsgi_log("unable to call function \"%s\"\n", usl->value);
exit(1);
}
}
if (uwsgi.refork_post_jail) {
uwsgi_log("re-fork()ing...\n");
pid_t pid = fork();
if (pid < 0) {
uwsgi_error("fork()");
exit(1);
}
if (pid > 0) {
// block all signals
sigset_t smask;
sigfillset(&smask);
sigprocmask(SIG_BLOCK, &smask, NULL);
int status;
if (waitpid(pid, &status, 0) < 0) {
uwsgi_error("waitpid()");
}
_exit(0);
}
}
int i;
for (i = 0; i < uwsgi.gp_cnt; i++) {
if (uwsgi.gp[i]->post_jail) {
uwsgi.gp[i]->post_jail();
}
}
}
if (uwsgi.chroot && !uwsgi.reloads) {
if (!uwsgi.master_as_root)
uwsgi_log("chroot() to %s\n", uwsgi.chroot);
if (chroot(uwsgi.chroot)) {
uwsgi_error("chroot()");
exit(1);
}
#ifdef __linux__
if (uwsgi.logging_options.memory_report) {
uwsgi_log("*** Warning, on linux system you have to bind-mount the /proc fs in your chroot to get memory debug/report.\n");
}
#endif
}
#ifdef __linux__
if (uwsgi.pivot_root && !uwsgi.reloads) {
char *arg = uwsgi_str(uwsgi.pivot_root);
char *space = strchr(arg, ' ');
if (!space) {
uwsgi_log("invalid pivot_root syntax, new_root and put_old must be separated by a space\n");
exit(1);
}
*space = 0;
#if defined(MS_REC) && defined(MS_PRIVATE)
if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL)) {
uwsgi_error("mount()");
exit(1);
}
#endif
if (chdir(arg)) {
uwsgi_error("pivot_root()/chdir()");
exit(1);
}
space += 1 + strlen(arg);
if (space[0] == '/')
space++;
if (pivot_root(".", space)) {
uwsgi_error("pivot_root()");
exit(1);
}
if (uwsgi.logging_options.memory_report) {
uwsgi_log("*** Warning, on linux system you have to bind-mount the /proc fs in your chroot to get memory debug/report.\n");
}
free(arg);
if (chdir("/")) {
uwsgi_error("chdir()");
exit(1);
}
}
#endif
#if defined(__linux__) && !defined(OBSOLETE_LINUX_KERNEL)
if (uwsgi.unshare2 && !uwsgi.reloads) {
if (unshare(uwsgi.unshare2)) {
uwsgi_error("unshare()");
exit(1);
}
else {
uwsgi_log("[linux-namespace] applied unshare() mask: %d\n", uwsgi.unshare2);
}
#ifdef CLONE_NEWUSER
if (uwsgi.unshare2 & CLONE_NEWUSER) {
if (setuid(0)) {
uwsgi_error("uwsgi_as_root()/setuid(0)");
exit(1);
}
}
#endif
in_jail = 1;
}
#endif
if (uwsgi.refork_as_root) {
uwsgi_log("re-fork()ing...\n");
pid_t pid = fork();
if (pid < 0) {
uwsgi_error("fork()");
exit(1);
}
if (pid > 0) {
// block all signals
sigset_t smask;
sigfillset(&smask);
sigprocmask(SIG_BLOCK, &smask, NULL);
int status;
if (waitpid(pid, &status, 0) < 0) {
uwsgi_error("waitpid()");
}
_exit(0);
}
}
struct uwsgi_string_list *usl;
uwsgi_foreach(usl, uwsgi.wait_for_interface) {
if (!uwsgi.wait_for_interface_timeout) {
uwsgi.wait_for_interface_timeout = 60;
}
uwsgi_log("waiting for interface %s (max %d seconds) ...\n", usl->value, uwsgi.wait_for_interface_timeout);
int counter = 0;
for (;;) {
if (counter > uwsgi.wait_for_interface_timeout) {
uwsgi_log("interface %s unavailable after %d seconds\n", usl->value, counter);
exit(1);
}
unsigned int index = if_nametoindex(usl->value);
if (index > 0) {
uwsgi_log("interface %s found with index %u\n", usl->value, index);
break;
}
else {
sleep(1);
counter++;
}
}
}
uwsgi_foreach(usl, uwsgi.wait_for_fs) {
if (uwsgi_wait_for_fs(usl->value, 0)) exit(1);
}
uwsgi_foreach(usl, uwsgi.wait_for_file) {
if (uwsgi_wait_for_fs(usl->value, 1)) exit(1);
}
uwsgi_foreach(usl, uwsgi.wait_for_dir) {
if (uwsgi_wait_for_fs(usl->value, 2)) exit(1);
}
uwsgi_foreach(usl, uwsgi.wait_for_mountpoint) {
if (uwsgi_wait_for_mountpoint(usl->value)) exit(1);
}
uwsgi_hooks_run(uwsgi.hook_as_root, "as root", 1);
uwsgi_foreach(usl, uwsgi.mount_as_root) {
uwsgi_log("mounting \"%s\" (as root)...\n", usl->value);
if (uwsgi_mount_hook(usl->value)) {
exit(1);
}
}
uwsgi_foreach(usl, uwsgi.umount_as_root) {
uwsgi_log("un-mounting \"%s\" (as root)...\n", usl->value);
if (uwsgi_umount_hook(usl->value)) {
exit(1);
}
}
// now run the scripts needed by root
uwsgi_foreach(usl, uwsgi.exec_as_root) {
uwsgi_log("running \"%s\" (as root)...\n", usl->value);
int ret = uwsgi_run_command_and_wait(NULL, usl->value);
if (ret != 0) {
uwsgi_log("command \"%s\" exited with non-zero code: %d\n", usl->value, ret);
exit(1);
}
}
uwsgi_foreach(usl, uwsgi.call_as_root) {
if (uwsgi_call_symbol(usl->value)) {
uwsgi_log("unable to call function \"%s\"\n", usl->value);
}
}
if (uwsgi.gidname) {
struct group *ugroup = getgrnam(uwsgi.gidname);
if (ugroup) {
uwsgi.gid = ugroup->gr_gid;
}
else {
uwsgi_log("group %s not found.\n", uwsgi.gidname);
exit(1);
}
}
if (uwsgi.uidname) {
struct passwd *upasswd = getpwnam(uwsgi.uidname);
if (upasswd) {
uwsgi.uid = upasswd->pw_uid;
}
else {
uwsgi_log("user %s not found.\n", uwsgi.uidname);
exit(1);
}
}
if (uwsgi.logfile_chown) {
int log_fd = 2;
if (uwsgi.log_master && uwsgi.original_log_fd > -1) {
log_fd = uwsgi.original_log_fd;
}
if (fchown(log_fd, uwsgi.uid, uwsgi.gid)) {
uwsgi_error("fchown()");
exit(1);
}
}
// fix ipcsem owner
if (uwsgi.lock_ops.lock_init == uwsgi_lock_ipcsem_init) {
struct uwsgi_lock_item *uli = uwsgi.registered_locks;
while (uli) {
union semun {
int val;
struct semid_ds *buf;
ushort *array;
} semu;
struct semid_ds sds;
memset(&sds, 0, sizeof(sds));
semu.buf = &sds;
int semid = 0;
memcpy(&semid, uli->lock_ptr, sizeof(int));
if (semctl(semid, 0, IPC_STAT, semu)) {
uwsgi_error("semctl()");
exit(1);
}
semu.buf->sem_perm.uid = uwsgi.uid;
semu.buf->sem_perm.gid = uwsgi.gid;
if (semctl(semid, 0, IPC_SET, semu)) {
uwsgi_error("semctl()");
exit(1);
}
uli = uli->next;
}
}
// ok try to call some special hook before finally dropping privileges
int i;
for (i = 0; i < uwsgi.gp_cnt; i++) {
if (uwsgi.gp[i]->before_privileges_drop) {
uwsgi.gp[i]->before_privileges_drop();
}
}
if (uwsgi.gid) {
if (!uwsgi.master_as_root)
uwsgi_log("setgid() to %d\n", uwsgi.gid);
if (setgid(uwsgi.gid)) {
uwsgi_error("setgid()");
exit(1);
}
if (uwsgi.no_initgroups || !uwsgi.uid) {
if (setgroups(0, NULL)) {
uwsgi_error("setgroups()");
exit(1);
}
}
else {
char *uidname = uwsgi.uidname;
if (!uidname) {
struct passwd *pw = getpwuid(uwsgi.uid);
if (pw)
uidname = pw->pw_name;
}
if (!uidname)
uidname = uwsgi_num2str(uwsgi.uid);
if (initgroups(uidname, uwsgi.gid)) {
uwsgi_error("setgroups()");
exit(1);
}
}
struct uwsgi_string_list *usl;
size_t ags = 0;
uwsgi_foreach(usl, uwsgi.additional_gids) ags++;
if (ags > 0) {
gid_t *ags_list = uwsgi_calloc(sizeof(gid_t) * ags);
size_t g_pos = 0;
uwsgi_foreach(usl, uwsgi.additional_gids) {
ags_list[g_pos] = atoi(usl->value);
if (!ags_list[g_pos]) {
struct group *g = getgrnam(usl->value);
if (g) {
ags_list[g_pos] = g->gr_gid;
}
else {
uwsgi_log("unable to find group %s\n", usl->value);
exit(1);
}
}
g_pos++;
}
if (setgroups(ags, ags_list)) {
uwsgi_error("setgroups()");
exit(1);
}
}
int additional_groups = getgroups(0, NULL);
if (additional_groups > 0) {
gid_t *gids = uwsgi_calloc(sizeof(gid_t) * additional_groups);
if (getgroups(additional_groups, gids) > 0) {
int i;
for (i = 0; i < additional_groups; i++) {
if (gids[i] == uwsgi.gid)
continue;
struct group *gr = getgrgid(gids[i]);
if (gr) {
uwsgi_log("set additional group %d (%s)\n", gids[i], gr->gr_name);
}
else {
uwsgi_log("set additional group %d\n", gids[i]);
}
}
}
free(gids);
}
}
if (uwsgi.uid) {
if (!uwsgi.master_as_root)
uwsgi_log("setuid() to %d\n", uwsgi.uid);
if (setuid(uwsgi.uid)) {
uwsgi_error("setuid()");
exit(1);
}
}
#ifndef __RUMP__
if (!getuid()) {
uwsgi_log_initial("*** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** \n");
}
#endif
#ifdef UWSGI_CAP
if (uwsgi.cap && uwsgi.cap_count > 0 && !uwsgi.reloads) {
cap_t caps = cap_init();
if (!caps) {
uwsgi_error("cap_init()");
exit(1);
}
cap_clear(caps);
cap_set_flag(caps, CAP_EFFECTIVE, uwsgi.cap_count, uwsgi.cap, CAP_SET);
cap_set_flag(caps, CAP_PERMITTED, uwsgi.cap_count, uwsgi.cap, CAP_SET);
cap_set_flag(caps, CAP_INHERITABLE, uwsgi.cap_count, uwsgi.cap, CAP_SET);
if (cap_set_proc(caps) < 0) {
uwsgi_error("cap_set_proc()");
exit(1);
}
cap_free(caps);
}
#endif
if (uwsgi.refork) {
uwsgi_log("re-fork()ing...\n");
pid_t pid = fork();
if (pid < 0) {
uwsgi_error("fork()");
exit(1);
}
if (pid > 0) {
// block all signals
sigset_t smask;
sigfillset(&smask);
sigprocmask(SIG_BLOCK, &smask, NULL);
int status;
if (waitpid(pid, &status, 0) < 0) {
uwsgi_error("waitpid()");
}
_exit(0);
}
}
uwsgi_hooks_run(uwsgi.hook_as_user, "as user", 1);
// now run the scripts needed by the user
uwsgi_foreach(usl, uwsgi.exec_as_user) {
uwsgi_log("running \"%s\" (as uid: %d gid: %d) ...\n", usl->value, (int) getuid(), (int) getgid());
int ret = uwsgi_run_command_and_wait(NULL, usl->value);
if (ret != 0) {
uwsgi_log("command \"%s\" exited with non-zero code: %d\n", usl->value, ret);
exit(1);
}
}
uwsgi_foreach(usl, uwsgi.call_as_user) {
if (uwsgi_call_symbol(usl->value)) {
uwsgi_log("unable to call function \"%s\"\n", usl->value);
exit(1);
}
}
// we could now patch the binary
if (uwsgi.unprivileged_binary_patch) {
uwsgi.argv[0] = uwsgi.unprivileged_binary_patch;
execvp(uwsgi.unprivileged_binary_patch, uwsgi.argv);
uwsgi_error("execvp()");
exit(1);
}
if (uwsgi.unprivileged_binary_patch_arg) {
uwsgi_exec_command_with_args(uwsgi.unprivileged_binary_patch_arg);
}
return;
nonroot:
if (uwsgi.chroot && !uwsgi.is_a_reload) {
uwsgi_log("cannot chroot() as non-root user\n");
exit(1);
}
if (uwsgi.gid && getgid() != uwsgi.gid) {
uwsgi_log("cannot setgid() as non-root user\n");
exit(1);
}
if (uwsgi.uid && getuid() != uwsgi.uid) {
uwsgi_log("cannot setuid() as non-root user\n");
exit(1);
}
}
static void close_and_free_request(struct wsgi_request *wsgi_req) {
// close the connection with the client
if (!wsgi_req->fd_closed) {
// NOTE, if we close the socket before receiving eventually sent data, socket layer will send a RST
wsgi_req->socket->proto_close(wsgi_req);
}
if (wsgi_req->post_file) {
fclose(wsgi_req->post_file);
}
if (wsgi_req->post_read_buf) {
free(wsgi_req->post_read_buf);
}
if (wsgi_req->post_readline_buf) {
free(wsgi_req->post_readline_buf);
}
if (wsgi_req->proto_parser_buf) {
free(wsgi_req->proto_parser_buf);
}
}
// destroy a request
void uwsgi_destroy_request(struct wsgi_request *wsgi_req) {
close_and_free_request(wsgi_req);
int foo;
if (uwsgi.threads > 1) {
// now the thread can die...
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &foo);
}
// reset for avoiding following requests to fail on non-uwsgi protocols
// thanks Marko Tiikkaja for catching it
wsgi_req->uh->_pktsize = 0;
// some plugins expected async_id to be defined before setup
int tmp_id = wsgi_req->async_id;
memset(wsgi_req, 0, sizeof(struct wsgi_request));
wsgi_req->async_id = tmp_id;
}
// finalize/close/free a request
void uwsgi_close_request(struct wsgi_request *wsgi_req) {
int waitpid_status;
int tmp_id;
uint64_t tmp_rt, rss = 0, vsz = 0;
#ifdef __linux__
uint64_t uss = 0, pss = 0;
#endif
// apply transformations
if (wsgi_req->transformations) {
if (uwsgi_apply_final_transformations(wsgi_req) == 0) {
if (wsgi_req->transformed_chunk && wsgi_req->transformed_chunk_len > 0) {
uwsgi_response_write_body_do(wsgi_req, wsgi_req->transformed_chunk, wsgi_req->transformed_chunk_len);
}
}
uwsgi_free_transformations(wsgi_req);
}
// check if headers should be sent
if (wsgi_req->headers) {
if (!wsgi_req->headers_sent && !wsgi_req->headers_size && !wsgi_req->response_size) {
uwsgi_response_write_headers_do(wsgi_req);
}
uwsgi_buffer_destroy(wsgi_req->headers);
}
uint64_t end_of_request = uwsgi_micros();
wsgi_req->end_of_request = end_of_request;
if (!wsgi_req->do_not_account_avg_rt) {
tmp_rt = wsgi_req->end_of_request - wsgi_req->start_of_request;
uwsgi.workers[uwsgi.mywid].running_time += tmp_rt;
uwsgi.workers[uwsgi.mywid].avg_response_time = (uwsgi.workers[uwsgi.mywid].avg_response_time + tmp_rt) / 2;
}
// get memory usage
if (uwsgi.logging_options.memory_report || uwsgi.force_get_memusage) {
get_memusage(&rss, &vsz);
uwsgi.workers[uwsgi.mywid].vsz_size = vsz;
uwsgi.workers[uwsgi.mywid].rss_size = rss;
}
#ifdef __linux__
if (uwsgi.logging_options.memory_report || uwsgi.reload_on_uss || uwsgi.reload_on_pss) {
get_memusage_extra(&uss, &pss);
uwsgi.workers[uwsgi.mywid].uss_size = uss;
uwsgi.workers[uwsgi.mywid].pss_size = pss;
}
#endif
if (!wsgi_req->do_not_account) {
uwsgi.workers[0].requests++;
uwsgi.workers[uwsgi.mywid].requests++;
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].requests++;
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].write_errors += wsgi_req->write_errors;
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].read_errors += wsgi_req->read_errors;
// this is used for MAX_REQUESTS
uwsgi.workers[uwsgi.mywid].delta_requests++;
}
#ifdef UWSGI_ROUTING
// apply final routes after accounting
uwsgi_apply_final_routes(wsgi_req);
#endif
// close socket and free parsers-allocated memory
close_and_free_request(wsgi_req);
// after_request hook
if (!wsgi_req->is_raw && uwsgi.p[wsgi_req->uh->modifier1]->after_request)
uwsgi.p[wsgi_req->uh->modifier1]->after_request(wsgi_req);
// after_request custom hooks
struct uwsgi_string_list *usl = NULL;
uwsgi_foreach(usl, uwsgi.after_request_hooks) {
void (*func) (struct wsgi_request *) = (void (*)(struct wsgi_request *)) usl->custom_ptr;
func(wsgi_req);
}
if (uwsgi.threads > 1) {
// now the thread can die...
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &tmp_id);
}
// leave harakiri mode
if (uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].harakiri > 0) {
set_harakiri(wsgi_req, 0);
}
// leave user harakiri mode
if (uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].user_harakiri > 0) {
set_user_harakiri(wsgi_req, 0);
}
if (!wsgi_req->do_not_account) {
// this is racy in multithread mode
if (wsgi_req->response_size > 0) {
uwsgi.workers[uwsgi.mywid].tx += wsgi_req->response_size;
}
if (wsgi_req->headers_size > 0) {
uwsgi.workers[uwsgi.mywid].tx += wsgi_req->headers_size;
}
}
// defunct process reaper
if (uwsgi.reaper == 1) {
while (waitpid(WAIT_ANY, &waitpid_status, WNOHANG) > 0);
}
// free logvars
struct uwsgi_logvar *lv = wsgi_req->logvars;
while (lv) {
struct uwsgi_logvar *ptr = lv;
lv = lv->next;
free(ptr);
}
// free additional headers
struct uwsgi_string_list *ah = wsgi_req->additional_headers;
while (ah) {
struct uwsgi_string_list *ptr = ah;
ah = ah->next;
free(ptr->value);
free(ptr);
}
// free remove headers
ah = wsgi_req->remove_headers;
while (ah) {
struct uwsgi_string_list *ptr = ah;
ah = ah->next;
free(ptr->value);
free(ptr);
}
// free chunked input
if (wsgi_req->chunked_input_buf) {
uwsgi_buffer_destroy(wsgi_req->chunked_input_buf);
}
if (wsgi_req->body_chunked_buf) {
uwsgi_buffer_destroy(wsgi_req->body_chunked_buf);
}
// free websocket engine
if (wsgi_req->websocket_buf) {
uwsgi_buffer_destroy(wsgi_req->websocket_buf);
}
if (wsgi_req->websocket_send_buf) {
uwsgi_buffer_destroy(wsgi_req->websocket_send_buf);
}
// reset request
wsgi_req->uh->_pktsize = 0;
tmp_id = wsgi_req->async_id;
memset(wsgi_req, 0, sizeof(struct wsgi_request));
// some plugins expected async_id to be defined before setup
wsgi_req->async_id = tmp_id;
// yes, this is pretty useless but we cannot ensure all of the plugin have the same behaviour
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 0;
if (uwsgi.max_requests > 0 && uwsgi.workers[uwsgi.mywid].delta_requests >= (uwsgi.max_requests + ((uwsgi.mywid-1) * uwsgi.max_requests_delta))
&& (end_of_request - (uwsgi.workers[uwsgi.mywid].last_spawn * 1000000) >= uwsgi.min_worker_lifetime * 1000000)) {
goodbye_cruel_world("max requests reached (%llu >= %llu)",
(unsigned long long) uwsgi.workers[uwsgi.mywid].delta_requests,
(unsigned long long) (uwsgi.max_requests + ((uwsgi.mywid-1) * uwsgi.max_requests_delta))
);
}
if (uwsgi.reload_on_as && (rlim_t) vsz >= uwsgi.reload_on_as && (end_of_request - (uwsgi.workers[uwsgi.mywid].last_spawn * 1000000) >= uwsgi.min_worker_lifetime * 1000000)) {
goodbye_cruel_world("reload-on-as limit reached (%llu >= %llu)",
(unsigned long long) (rlim_t) vsz,
(unsigned long long) uwsgi.reload_on_as
);
}
if (uwsgi.reload_on_rss && (rlim_t) rss >= uwsgi.reload_on_rss && (end_of_request - (uwsgi.workers[uwsgi.mywid].last_spawn * 1000000) >= uwsgi.min_worker_lifetime * 1000000)) {
goodbye_cruel_world("reload-on-rss limit reached (%llu >= %llu)",
(unsigned long long) (rlim_t) rss,
(unsigned long long) uwsgi.reload_on_rss
);
}
#ifdef __linux__
if (uwsgi.reload_on_uss && (rlim_t) uss >= uwsgi.reload_on_uss && (end_of_request - (uwsgi.workers[uwsgi.mywid].last_spawn * 1000000) >= uwsgi.min_worker_lifetime * 1000000)) {
goodbye_cruel_world("reload-on-uss limit reached (%llu >= %llu)",
(unsigned long long) (rlim_t) uss,
(unsigned long long) uwsgi.reload_on_uss
);
}
if (uwsgi.reload_on_pss && (rlim_t) pss >= uwsgi.reload_on_pss && (end_of_request - (uwsgi.workers[uwsgi.mywid].last_spawn * 1000000) >= uwsgi.min_worker_lifetime * 1000000)) {
goodbye_cruel_world("reload-on-pss limit reached (%llu >= %llu)",
(unsigned long long) (rlim_t) pss,
(unsigned long long) uwsgi.reload_on_pss
);
}
#endif
// after the first request, if i am a vassal, signal Emperor about my loyalty
if (uwsgi.has_emperor && !uwsgi.loyal) {
uwsgi_log("announcing my loyalty to the Emperor...\n");
char byte = 17;
if (write(uwsgi.emperor_fd, &byte, 1) != 1) {
uwsgi_error("write()");
}
uwsgi.loyal = 1;
}
#ifdef __linux__
#ifdef MADV_MERGEABLE
// run the ksm mapper
if (uwsgi.linux_ksm > 0 && (uwsgi.workers[uwsgi.mywid].requests % uwsgi.linux_ksm) == 0) {
uwsgi_linux_ksm_map();
}
#endif
#endif
}
#ifdef __linux__
#ifdef MADV_MERGEABLE
void uwsgi_linux_ksm_map(void) {
int dirty = 0;
size_t i;
unsigned long long start = 0, end = 0;
int errors = 0;
int lines = 0;
int fd = open("/proc/self/maps", O_RDONLY);
if (fd < 0) {
uwsgi_error_open("[uwsgi-KSM] /proc/self/maps");
return;
}
// allocate memory if not available;
if (uwsgi.ksm_mappings_current == NULL) {
if (!uwsgi.ksm_buffer_size)
uwsgi.ksm_buffer_size = 32768;
uwsgi.ksm_mappings_current = uwsgi_malloc(uwsgi.ksm_buffer_size);
uwsgi.ksm_mappings_current_size = 0;
}
if (uwsgi.ksm_mappings_last == NULL) {
if (!uwsgi.ksm_buffer_size)
uwsgi.ksm_buffer_size = 32768;
uwsgi.ksm_mappings_last = uwsgi_malloc(uwsgi.ksm_buffer_size);
uwsgi.ksm_mappings_last_size = 0;
}
uwsgi.ksm_mappings_current_size = read(fd, uwsgi.ksm_mappings_current, uwsgi.ksm_buffer_size);
close(fd);
if (uwsgi.ksm_mappings_current_size <= 0) {
uwsgi_log("[uwsgi-KSM] unable to read /proc/self/maps data\n");
return;
}
// we now have areas
if (uwsgi.ksm_mappings_last_size == 0 || uwsgi.ksm_mappings_current_size != uwsgi.ksm_mappings_last_size) {
dirty = 1;
}
else {
if (memcmp(uwsgi.ksm_mappings_current, uwsgi.ksm_mappings_last, uwsgi.ksm_mappings_current_size) != 0) {
dirty = 1;
}
}
// it is dirty, swap addresses and parse it
if (dirty) {
char *tmp = uwsgi.ksm_mappings_last;
uwsgi.ksm_mappings_last = uwsgi.ksm_mappings_current;
uwsgi.ksm_mappings_current = tmp;
size_t tmp_size = uwsgi.ksm_mappings_last_size;
uwsgi.ksm_mappings_last_size = uwsgi.ksm_mappings_current_size;
uwsgi.ksm_mappings_current_size = tmp_size;
// scan each line and call madvise on it
char *ptr = uwsgi.ksm_mappings_last;
for (i = 0; i < uwsgi.ksm_mappings_last_size; i++) {
if (uwsgi.ksm_mappings_last[i] == '\n') {
lines++;
uwsgi.ksm_mappings_last[i] = 0;
if (sscanf(ptr, "%llx-%llx %*s", &start, &end) == 2) {
if (madvise((void *) (long) start, (size_t) (end - start), MADV_MERGEABLE)) {
errors++;
}
}
uwsgi.ksm_mappings_last[i] = '\n';
ptr = uwsgi.ksm_mappings_last + i + 1;
}
}
if (errors >= lines) {
uwsgi_error("[uwsgi-KSM] unable to share pages");
}
}
}
#endif
#endif
#ifdef __linux__
long uwsgi_num_from_file(char *filename, int quiet) {
char buf[16];
ssize_t len;
int fd = open(filename, O_RDONLY);
if (fd < 0) {
if (!quiet)
uwsgi_error_open(filename);
return -1L;
}
len = read(fd, buf, sizeof(buf));
if (len == 0) {
if (!quiet)
uwsgi_log("read error %s\n", filename);
close(fd);
return -1L;
}
close(fd);
return strtol(buf, (char **) NULL, 10);
}
#endif
// setup for a new request
void wsgi_req_setup(struct wsgi_request *wsgi_req, int async_id, struct uwsgi_socket *uwsgi_sock) {
wsgi_req->app_id = -1;
wsgi_req->async_id = async_id;
wsgi_req->sendfile_fd = -1;
wsgi_req->hvec = uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].hvec;
// skip the first 4 bytes;
wsgi_req->uh = (struct uwsgi_header *) uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].buffer;
wsgi_req->buffer = uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].buffer + 4;
if (uwsgi.post_buffering > 0) {
wsgi_req->post_buffering_buf = uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].post_buf;
}
if (uwsgi_sock) {
wsgi_req->socket = uwsgi_sock;
}
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 0;
// now check for suspend request
if (uwsgi.workers[uwsgi.mywid].suspended == 1) {
uwsgi_log_verbose("*** worker %d suspended ***\n", uwsgi.mywid);
cycle:
// wait for some signal (normally SIGTSTP) or 10 seconds (as fallback)
(void) poll(NULL, 0, 10 * 1000);
if (uwsgi.workers[uwsgi.mywid].suspended == 1)
goto cycle;
uwsgi_log_verbose("*** worker %d resumed ***\n", uwsgi.mywid);
}
}
int wsgi_req_async_recv(struct wsgi_request *wsgi_req) {
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 1;
wsgi_req->start_of_request = uwsgi_micros();
wsgi_req->start_of_request_in_sec = wsgi_req->start_of_request / 1000000;
if (!wsgi_req->do_not_add_to_async_queue) {
if (event_queue_add_fd_read(uwsgi.async_queue, wsgi_req->fd) < 0)
return -1;
async_add_timeout(wsgi_req, uwsgi.socket_timeout);
uwsgi.async_proto_fd_table[wsgi_req->fd] = wsgi_req;
}
// enter harakiri mode
if (uwsgi.harakiri_options.workers > 0) {
set_harakiri(wsgi_req, uwsgi.harakiri_options.workers);
}
return 0;
}
// receive a new request
int wsgi_req_recv(int queue, struct wsgi_request *wsgi_req) {
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 1;
wsgi_req->start_of_request = uwsgi_micros();
wsgi_req->start_of_request_in_sec = wsgi_req->start_of_request / 1000000;
// edge triggered sockets get the whole request during accept() phase
if (!wsgi_req->socket->edge_trigger) {
for (;;) {
int ret = wsgi_req->socket->proto(wsgi_req);
if (ret == UWSGI_OK)
break;
if (ret == UWSGI_AGAIN) {
ret = uwsgi_wait_read_req(wsgi_req);
if (ret <= 0)
return -1;
continue;
}
return -1;
}
}
// enter harakiri mode
if (uwsgi.harakiri_options.workers > 0) {
set_harakiri(wsgi_req, uwsgi.harakiri_options.workers);
}
#ifdef UWSGI_ROUTING
if (uwsgi_apply_routes(wsgi_req) == UWSGI_ROUTE_BREAK)
return 0;
#endif
wsgi_req->async_status = uwsgi.p[wsgi_req->uh->modifier1]->request(wsgi_req);
return 0;
}
void uwsgi_post_accept(struct wsgi_request *wsgi_req) {
// set close on exec (if not a new socket)
if (!wsgi_req->socket->edge_trigger && uwsgi.close_on_exec) {
if (fcntl(wsgi_req->fd, F_SETFD, FD_CLOEXEC) < 0) {
uwsgi_error("fcntl()");
}
}
// enable TCP_NODELAY ?
if (uwsgi.tcp_nodelay) {
uwsgi_tcp_nodelay(wsgi_req->fd);
}
}
// accept a new request
int wsgi_req_simple_accept(struct wsgi_request *wsgi_req, int fd) {
wsgi_req->fd = wsgi_req->socket->proto_accept(wsgi_req, fd);
if (wsgi_req->fd < 0) {
return -1;
}
uwsgi_post_accept(wsgi_req);
return 0;
}
// send heartbeat to the emperor
void uwsgi_heartbeat() {
if (!uwsgi.has_emperor)
return;
time_t now = uwsgi_now();
if (uwsgi.next_heartbeat <= now) {
char byte = 26;
if (write(uwsgi.emperor_fd, &byte, 1) != 1) {
uwsgi_error("write()");
}
uwsgi.next_heartbeat = now + uwsgi.heartbeat;
}
}
// accept a request
int wsgi_req_accept(int queue, struct wsgi_request *wsgi_req) {
int ret;
int interesting_fd = -1;
struct uwsgi_socket *uwsgi_sock = uwsgi.sockets;
int timeout = -1;
thunder_lock;
// Recheck the manage_next_request before going forward.
// This is because the worker might get cheaped while it's
// blocking on the thunder_lock, because thunder_lock is
// not interruptable, it'll slow down the cheaping process
// (the worker will handle the next request before shuts down).
if (!uwsgi.workers[uwsgi.mywid].manage_next_request) {
thunder_unlock;
return -1;
}
// heartbeat
// in multithreaded mode we are now locked
if (uwsgi.has_emperor && uwsgi.heartbeat) {
time_t now = uwsgi_now();
// overengineering ... (reduce skew problems)
timeout = uwsgi.heartbeat;
if (!uwsgi.next_heartbeat) {
uwsgi.next_heartbeat = now;
}
if (uwsgi.next_heartbeat >= now) {
timeout = uwsgi.next_heartbeat - now;
}
}
// need edge trigger ?
if (uwsgi.is_et) {
while (uwsgi_sock) {
if (uwsgi_sock->retry && uwsgi_sock->retry[wsgi_req->async_id]) {
timeout = 0;
break;
}
uwsgi_sock = uwsgi_sock->next;
}
// reset pointer
uwsgi_sock = uwsgi.sockets;
}
ret = event_queue_wait(queue, timeout, &interesting_fd);
if (ret < 0) {
thunder_unlock;
return -1;
}
// check for heartbeat
if (uwsgi.has_emperor && uwsgi.heartbeat) {
uwsgi_heartbeat();
// no need to continue if timed-out
if (ret == 0) {
thunder_unlock;
return -1;
}
}
// kill the thread after the request completion
if (uwsgi.threads > 1)
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &ret);
if (uwsgi.signal_socket > -1 && (interesting_fd == uwsgi.signal_socket || interesting_fd == uwsgi.my_signal_socket)) {
thunder_unlock;
uwsgi_receive_signal(wsgi_req, interesting_fd, "worker", uwsgi.mywid);
if (uwsgi.threads > 1)
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &ret);
return -1;
}
while (uwsgi_sock) {
if (interesting_fd == uwsgi_sock->fd || (uwsgi_sock->retry && uwsgi_sock->retry[wsgi_req->async_id]) || (uwsgi_sock->fd_threads && interesting_fd == uwsgi_sock->fd_threads[wsgi_req->async_id])) {
wsgi_req->socket = uwsgi_sock;
wsgi_req->fd = wsgi_req->socket->proto_accept(wsgi_req, interesting_fd);
thunder_unlock;
if (wsgi_req->fd < 0) {
if (uwsgi.threads > 1)
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &ret);
return -1;
}
if (!uwsgi_sock->edge_trigger) {
uwsgi_post_accept(wsgi_req);
}
return 0;
}
uwsgi_sock = uwsgi_sock->next;
}
thunder_unlock;
if (uwsgi.threads > 1)
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &ret);
return -1;
}
// translate a OS env to a uWSGI option
void env_to_arg(char *src, char *dst) {
int i;
int val = 0;
for (i = 0; i < (int) strlen(src); i++) {
if (src[i] == '=') {
val = 1;
}
if (val) {
dst[i] = src[i];
}
else {
dst[i] = tolower((int) src[i]);
if (dst[i] == '_') {
dst[i] = '-';
}
}
}
dst[strlen(src)] = 0;
}
// parse OS envs
void parse_sys_envs(char **envs) {
char **uenvs = envs;
char *earg, *eq_pos;
while (*uenvs) {
if (!strncmp(*uenvs, "UWSGI_", 6) && strncmp(*uenvs, "UWSGI_RELOADS=", 14) && strncmp(*uenvs, "UWSGI_VASSALS_DIR=", 18) && strncmp(*uenvs, "UWSGI_EMPEROR_FD=", 17) && strncmp(*uenvs, "UWSGI_BROODLORD_NUM=", 20) && strncmp(*uenvs, "UWSGI_EMPEROR_FD_CONFIG=", 24) && strncmp(*uenvs, "UWSGI_EMPEROR_PROXY=", 20) && strncmp(*uenvs, "UWSGI_JAIL_PID=", 15) && strncmp(*uenvs, "UWSGI_ORIGINAL_PROC_NAME=", 25)) {
earg = uwsgi_malloc(strlen(*uenvs + 6) + 1);
env_to_arg(*uenvs + 6, earg);
eq_pos = strchr(earg, '=');
if (!eq_pos) {
break;
}
eq_pos[0] = 0;
add_exported_option(earg, eq_pos + 1, 0);
}
uenvs++;
}
}
// get the application id
int uwsgi_get_app_id(struct wsgi_request *wsgi_req, char *key, uint16_t key_len, int modifier1) {
int i;
struct stat st;
int found;
char *app_name = key;
uint16_t app_name_len = key_len;
if (app_name_len == 0 && wsgi_req) {
app_name = wsgi_req->appid;
app_name_len = wsgi_req->appid_len;
if (app_name_len == 0) {
if (!uwsgi.ignore_script_name) {
app_name = wsgi_req->script_name;
app_name_len = wsgi_req->script_name_len;
}
if (uwsgi.vhost) {
char *vhost_name = uwsgi_concat3n(wsgi_req->host, wsgi_req->host_len, "|", 1, wsgi_req->script_name, wsgi_req->script_name_len);
app_name_len = wsgi_req->host_len + 1 + wsgi_req->script_name_len;
app_name = uwsgi_req_append(wsgi_req, "UWSGI_APPID", 11, vhost_name, app_name_len);
free(vhost_name);
if (!app_name) {
uwsgi_log("unable to add UWSGI_APPID to the uwsgi buffer, consider increasing it\n");
return -1;
}
#ifdef UWSGI_DEBUG
uwsgi_debug("VirtualHost KEY=%.*s\n", app_name_len, app_name);
#endif
}
wsgi_req->appid = app_name;
wsgi_req->appid_len = app_name_len;
}
}
for (i = 0; i < uwsgi_apps_cnt; i++) {
// reset check
found = 0;
#ifdef UWSGI_DEBUG
uwsgi_log("searching for %.*s in %.*s %p\n", app_name_len, app_name, uwsgi_apps[i].mountpoint_len, uwsgi_apps[i].mountpoint, uwsgi_apps[i].callable);
#endif
if (!uwsgi_apps[i].callable) {
continue;
}
if (!uwsgi_strncmp(uwsgi_apps[i].mountpoint, uwsgi_apps[i].mountpoint_len, app_name, app_name_len)) {
found = 1;
}
if (found) {
if (uwsgi_apps[i].touch_reload[0]) {
if (!stat(uwsgi_apps[i].touch_reload, &st)) {
if (st.st_mtime != uwsgi_apps[i].touch_reload_mtime) {
// serve the new request and reload
uwsgi.workers[uwsgi.mywid].manage_next_request = 0;
if (uwsgi.threads > 1) {
uwsgi.workers[uwsgi.mywid].destroy = 1;
}
#ifdef UWSGI_DEBUG
uwsgi_log("mtime %d %d\n", st.st_mtime, uwsgi_apps[i].touch_reload_mtime);
#endif
}
}
}
if (modifier1 == -1)
return i;
if (modifier1 == uwsgi_apps[i].modifier1)
return i;
}
}
return -1;
}
char *uwsgi_substitute(char *src, char *what, char *with) {
int count = 0;
if (!with)
return src;
size_t len = strlen(src);
size_t wlen = strlen(what);
size_t with_len = strlen(with);
char *p = strstr(src, what);
if (!p) {
return src;
}
while (p) {
count++;
p = strstr(p + wlen, what);
}
len += (count * with_len) + 1;
char *dst = uwsgi_calloc(len);
char *ptr = src;
p = strstr(ptr, what);
while (p) {
strncat(dst, ptr, (p - ptr));
strncat(dst, with, with_len);
ptr = p + wlen;
p = strstr(ptr, what);
}
strncat(dst, ptr, strlen(ptr));
return dst;
}
int uwsgi_is_file(char *filename) {
struct stat st;
if (stat(filename, &st)) {
return 0;
}
if (S_ISREG(st.st_mode))
return 1;
return 0;
}
int uwsgi_is_file2(char *filename, struct stat *st) {
if (stat(filename, st)) {
return 0;
}
if (S_ISREG(st->st_mode))
return 1;
return 0;
}
int uwsgi_is_dir(char *filename) {
struct stat st;
if (stat(filename, &st)) {
return 0;
}
if (S_ISDIR(st.st_mode))
return 1;
return 0;
}
int uwsgi_is_link(char *filename) {
struct stat st;
if (lstat(filename, &st)) {
return 0;
}
if (S_ISLNK(st.st_mode))
return 1;
return 0;
}
void *uwsgi_malloc(size_t size) {
char *ptr = malloc(size);
if (ptr == NULL) {
uwsgi_error("malloc()");
uwsgi_log("!!! tried memory allocation of %llu bytes !!!\n", (unsigned long long) size);
uwsgi_backtrace(uwsgi.backtrace_depth);
exit(1);
}
return ptr;
}
void *uwsgi_calloc(size_t size) {
// thanks Mathieu Dupuy for pointing out that calloc is faster
// than malloc + memset
char *ptr = calloc(1, size);
if (ptr == NULL) {
uwsgi_error("calloc()");
uwsgi_log("!!! tried memory allocation of %llu bytes !!!\n", (unsigned long long) size);
uwsgi_backtrace(uwsgi.backtrace_depth);
exit(1);
}
return ptr;
}
#ifdef AF_INET6
#define ADDR_AF_INET_FAMILY(addrtype) (addrtype == AF_INET || addrtype == AF_INET6)
#else
#define ADDR_AF_INET_FAMILY(addrtype) (addrtype == AF_INET)
#endif
char *uwsgi_resolve_ip(char *domain) {
struct hostent *he;
he = gethostbyname(domain);
if (!he || !*he->h_addr_list || !ADDR_AF_INET_FAMILY(he->h_addrtype)) {
return NULL;
}
return inet_ntoa(*(struct in_addr *) he->h_addr_list[0]);
}
int uwsgi_file_exists(char *filename) {
// TODO check for http url or stdin
return !access(filename, R_OK);
}
int uwsgi_file_executable(char *filename) {
// TODO check for http url or stdin
return !access(filename, R_OK | X_OK);
}
char *magic_sub(char *buffer, size_t len, size_t * size, char *magic_table[]) {
size_t i;
size_t magic_len = 0;
char *magic_buf = uwsgi_malloc(len);
char *magic_ptr = magic_buf;
char *old_magic_buf;
for (i = 0; i < len; i++) {
if (buffer[i] == '%' && (i + 1) < len && magic_table[(unsigned char) buffer[i + 1]]) {
old_magic_buf = magic_buf;
magic_buf = uwsgi_concat3n(old_magic_buf, magic_len, magic_table[(unsigned char) buffer[i + 1]], strlen(magic_table[(unsigned char) buffer[i + 1]]), buffer + i + 2, len - i - 2);
free(old_magic_buf);
magic_len += strlen(magic_table[(unsigned char) buffer[i + 1]]);
magic_ptr = magic_buf + magic_len;
i++;
}
else {
*magic_ptr = buffer[i];
magic_ptr++;
magic_len++;
}
}
*size = magic_len;
return magic_buf;
}
void init_magic_table(char *magic_table[]) {
int i;
for (i = 0; i <= 0xff; i++) {
magic_table[i] = "";
}
magic_table['%'] = "%";
magic_table['('] = "%(";
}
char *uwsgi_num2str(int num) {
char *str = uwsgi_malloc(11);
snprintf(str, 11, "%d", num);
return str;
}
char *uwsgi_64bit2str(int64_t num) {
char *str = uwsgi_malloc(sizeof(MAX64_STR) + 1);
snprintf(str, sizeof(MAX64_STR) + 1, "%lld", (long long) num);
return str;
}
int uwsgi_num2str2(int num, char *ptr) {
return snprintf(ptr, 11, "%d", num);
}
int uwsgi_num2str2n(int num, char *ptr, int size) {
return snprintf(ptr, size, "%d", num);
}
int uwsgi_long2str2n(unsigned long long num, char *ptr, int size) {
int ret = snprintf(ptr, size, "%llu", num);
if (ret <= 0 || ret > size)
return 0;
return ret;
}
int is_unix(char *socket_name, int len) {
return !memchr(socket_name, ':', len);
}
int is_a_number(char *what) {
int i;
for (i = 0; i < (int) strlen(what); i++) {
if (!isdigit((int) what[i]))
return 0;
}
return 1;
}
void uwsgi_unix_signal(int signum, void (*func) (int)) {
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = func;
sigemptyset(&sa.sa_mask);
if (sigaction(signum, &sa, NULL) < 0) {
uwsgi_error("sigaction()");
}
}
int uwsgi_list_has_num(char *list, int num) {
char *list2 = uwsgi_concat2(list, "");
char *p, *ctx = NULL;
uwsgi_foreach_token(list2, ",", p, ctx) {
if (atoi(p) == num) {
free(list2);
return 1;
}
}
free(list2);
return 0;
}
int uwsgi_list_has_str(char *list, char *str) {
char *list2 = uwsgi_str(list);
char *p, *ctx = NULL;
uwsgi_foreach_token(list2, " ", p, ctx) {
if (!strcasecmp(p, str)) {
free(list2);
return 1;
}
}
free(list2);
return 0;
}
static char hex2num(char *str) {
char val = 0;
val <<= 4;
if (str[0] >= '0' && str[0] <= '9') {
val += str[0] & 0x0F;
}
else if (str[0] >= 'A' && str[0] <= 'F') {
val += (str[0] & 0x0F) + 9;
}
else if (str[0] >= 'a' && str[0] <= 'f') {
val += (str[0] & 0x0F) + 9;
}
else {
return 0;
}
val <<= 4;
if (str[1] >= '0' && str[1] <= '9') {
val += str[1] & 0x0F;
}
else if (str[1] >= 'A' && str[1] <= 'F') {
val += (str[1] & 0x0F) + 9;
}
else if (str[1] >= 'a' && str[1] <= 'f') {
val += (str[1] & 0x0F) + 9;
}
else {
return 0;
}
return val;
}
int uwsgi_str2_num(char *str) {
int num = 0;
num = 10 * (str[0] - 48);
num += str[1] - 48;
return num;
}
int uwsgi_str3_num(char *str) {
int num = 0;
num = 100 * (str[0] - 48);
num += 10 * (str[1] - 48);
num += str[2] - 48;
return num;
}
int uwsgi_str4_num(char *str) {
int num = 0;
num = 1000 * (str[0] - 48);
num += 100 * (str[1] - 48);
num += 10 * (str[2] - 48);
num += str[3] - 48;
return num;
}
uint64_t uwsgi_str_num(char *str, int len) {
int i;
uint64_t num = 0;
uint64_t delta = pow(10, len);
for (i = 0; i < len; i++) {
delta = delta / 10;
num += delta * (str[i] - 48);
}
return num;
}
char *uwsgi_split3(char *buf, size_t len, char sep, char **part1, size_t * part1_len, char **part2, size_t * part2_len, char **part3, size_t * part3_len) {
size_t i;
int status = 0;
*part1 = NULL;
*part2 = NULL;
*part3 = NULL;
for (i = 0; i < len; i++) {
if (buf[i] == sep) {
// get part1
if (status == 0) {
*part1 = buf;
*part1_len = i;
status = 1;
}
// get part2
else if (status == 1) {
*part2 = *part1 + *part1_len + 1;
*part2_len = (buf + i) - *part2;
break;
}
}
}
if (*part1 && *part2) {
if (*part2 + *part2_len + 1 > buf + len) {
return NULL;
}
*part3 = *part2 + *part2_len + 1;
*part3_len = (buf + len) - *part3;
return buf + len;
}
return NULL;
}
char *uwsgi_split4(char *buf, size_t len, char sep, char **part1, size_t * part1_len, char **part2, size_t * part2_len, char **part3, size_t * part3_len, char **part4, size_t * part4_len) {
size_t i;
int status = 0;
*part1 = NULL;
*part2 = NULL;
*part3 = NULL;
*part4 = NULL;
for (i = 0; i < len; i++) {
if (buf[i] == sep) {
// get part1
if (status == 0) {
*part1 = buf;
*part1_len = i;
status = 1;
}
// get part2
else if (status == 1) {
*part2 = *part1 + *part1_len + 1;
*part2_len = (buf + i) - *part2;
status = 2;
}
// get part3
else if (status == 2) {
*part3 = *part2 + *part2_len + 1;
*part3_len = (buf + i) - *part3;
break;
}
}
}
if (*part1 && *part2 && *part3) {
if (*part3 + *part3_len + 1 > buf + len) {
return NULL;
}
*part4 = *part3 + *part3_len + 1;
*part4_len = (buf + len) - *part4;
return buf + len;
}
return NULL;
}
char *uwsgi_netstring(char *buf, size_t len, char **netstring, size_t * netstring_len) {
char *ptr = buf;
char *watermark = buf + len;
*netstring_len = 0;
while (ptr < watermark) {
// end of string size ?
if (*ptr == ':') {
*netstring_len = uwsgi_str_num(buf, ptr - buf);
if (ptr + *netstring_len + 2 > watermark) {
return NULL;
}
*netstring = ptr + 1;
return ptr + *netstring_len + 2;
}
ptr++;
}
return NULL;
}
struct uwsgi_dyn_dict *uwsgi_dyn_dict_new(struct uwsgi_dyn_dict **dd, char *key, int keylen, char *val, int vallen) {
struct uwsgi_dyn_dict *uwsgi_dd = *dd, *old_dd;
if (!uwsgi_dd) {
*dd = uwsgi_malloc(sizeof(struct uwsgi_dyn_dict));
uwsgi_dd = *dd;
uwsgi_dd->prev = NULL;
}
else {
while (uwsgi_dd) {
old_dd = uwsgi_dd;
uwsgi_dd = uwsgi_dd->next;
}
uwsgi_dd = uwsgi_malloc(sizeof(struct uwsgi_dyn_dict));
old_dd->next = uwsgi_dd;
uwsgi_dd->prev = old_dd;
}
uwsgi_dd->key = key;
uwsgi_dd->keylen = keylen;
uwsgi_dd->value = val;
uwsgi_dd->vallen = vallen;
uwsgi_dd->hits = 0;
uwsgi_dd->status = 0;
uwsgi_dd->next = NULL;
return uwsgi_dd;
}
void uwsgi_dyn_dict_del(struct uwsgi_dyn_dict *item) {
struct uwsgi_dyn_dict *prev = item->prev;
struct uwsgi_dyn_dict *next = item->next;
if (prev) {
prev->next = next;
}
if (next) {
next->prev = prev;
}
free(item);
}
void uwsgi_dyn_dict_free(struct uwsgi_dyn_dict **dd) {
struct uwsgi_dyn_dict *attr = *dd;
while(attr) {
struct uwsgi_dyn_dict *tmp = attr;
attr = attr->next;
if (tmp->value) free(tmp->value);
free(tmp);
}
*dd = NULL;
}
void *uwsgi_malloc_shared(size_t size) {
void *addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
if (addr == MAP_FAILED) {
uwsgi_log("unable to allocate %llu bytes (%lluMB)\n", (unsigned long long) size, (unsigned long long) (size / (1024 * 1024)));
uwsgi_error("mmap()");
exit(1);
}
return addr;
}
void *uwsgi_calloc_shared(size_t size) {
void *ptr = uwsgi_malloc_shared(size);
// NOTE by Mathieu Dupuy:
// OSes guarantee mmap MAP_ANON memory area to be zero-filled (see man pages)
// we should trust it, but history has taught us it is better to be paranoid.
// Lucky enough this function is called ony in startup phases, so performance
// tips/tricks are irrelevant (So, le'ts call memset...)
memset(ptr, 0, size);
return ptr;
}
struct uwsgi_string_list *uwsgi_string_new_list(struct uwsgi_string_list **list, char *value) {
struct uwsgi_string_list *uwsgi_string = *list, *old_uwsgi_string;
if (!uwsgi_string) {
*list = uwsgi_malloc(sizeof(struct uwsgi_string_list));
uwsgi_string = *list;
}
else {
while (uwsgi_string) {
old_uwsgi_string = uwsgi_string;
uwsgi_string = uwsgi_string->next;
}
uwsgi_string = uwsgi_malloc(sizeof(struct uwsgi_string_list));
old_uwsgi_string->next = uwsgi_string;
}
uwsgi_string->value = value;
uwsgi_string->len = 0;
if (value) {
uwsgi_string->len = strlen(value);
}
uwsgi_string->next = NULL;
uwsgi_string->custom = 0;
uwsgi_string->custom2 = 0;
uwsgi_string->custom_ptr = NULL;
return uwsgi_string;
}
#ifdef UWSGI_PCRE
struct uwsgi_regexp_list *uwsgi_regexp_custom_new_list(struct uwsgi_regexp_list **list, char *value, char *custom) {
struct uwsgi_regexp_list *url = *list, *old_url;
if (!url) {
*list = uwsgi_malloc(sizeof(struct uwsgi_regexp_list));
url = *list;
}
else {
while (url) {
old_url = url;
url = url->next;
}
url = uwsgi_malloc(sizeof(struct uwsgi_regexp_list));
old_url->next = url;
}
if (uwsgi_regexp_build(value, &url->pattern, &url->pattern_extra)) {
exit(1);
}
url->next = NULL;
url->custom = 0;
url->custom_ptr = NULL;
url->custom_str = custom;
return url;
}
int uwsgi_regexp_match_pattern(char *pattern, char *str) {
pcre *regexp;
pcre_extra *regexp_extra;
if (uwsgi_regexp_build(pattern, ®exp, ®exp_extra))
return 1;
return !uwsgi_regexp_match(regexp, regexp_extra, str, strlen(str));
}
#endif
char *uwsgi_string_get_list(struct uwsgi_string_list **list, int pos, size_t * len) {
struct uwsgi_string_list *uwsgi_string = *list;
int counter = 0;
while (uwsgi_string) {
if (counter == pos) {
*len = uwsgi_string->len;
return uwsgi_string->value;
}
uwsgi_string = uwsgi_string->next;
counter++;
}
*len = 0;
return NULL;
}
void uwsgi_string_del_list(struct uwsgi_string_list **list, struct uwsgi_string_list *item) {
struct uwsgi_string_list *uwsgi_string = *list, *old_uwsgi_string = NULL;
while (uwsgi_string) {
if (uwsgi_string == item) {
// parent instance ?
if (old_uwsgi_string == NULL) {
*list = uwsgi_string->next;
}
else {
old_uwsgi_string->next = uwsgi_string->next;
}
free(uwsgi_string);
return;
}
old_uwsgi_string = uwsgi_string;
uwsgi_string = uwsgi_string->next;
}
}
void uwsgi_sig_pause() {
sigset_t mask;
sigemptyset(&mask);
sigsuspend(&mask);
}
char *uwsgi_binsh() {
struct uwsgi_string_list *usl = NULL;
uwsgi_foreach(usl, uwsgi.binsh) {
if (uwsgi_file_executable(usl->value)) {
return usl->value;
}
}
return "/bin/sh";
}
void uwsgi_exec_command_with_args(char *cmdline) {
char *argv[4];
argv[0] = uwsgi_binsh();
argv[1] = "-c";
argv[2] = cmdline;
argv[3] = NULL;
execvp(argv[0], argv);
uwsgi_error("execvp()");
exit(1);
}
static int uwsgi_run_command_do(char *command, char *arg) {
char *argv[4];
#ifdef __linux__
if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) {
uwsgi_error("prctl()");
}
#endif
if (command == NULL) {
argv[0] = uwsgi_binsh();
argv[1] = "-c";
argv[2] = arg;
argv[3] = NULL;
execvp(argv[0], argv);
}
else {
argv[0] = command;
argv[1] = arg;
argv[2] = NULL;
execvp(command, argv);
}
uwsgi_error("execvp()");
//never here
exit(1);
}
int uwsgi_run_command_and_wait(char *command, char *arg) {
int waitpid_status = 0;
pid_t pid = fork();
if (pid < 0) {
return -1;
}
if (pid > 0) {
if (waitpid(pid, &waitpid_status, 0) < 0) {
uwsgi_error("uwsgi_run_command_and_wait()/waitpid()");
return -1;
}
return WEXITSTATUS(waitpid_status);
}
return uwsgi_run_command_do(command, arg);
}
int uwsgi_run_command_putenv_and_wait(char *command, char *arg, char **envs, unsigned int nenvs) {
int waitpid_status = 0;
pid_t pid = fork();
if (pid < 0) {
return -1;
}
if (pid > 0) {
if (waitpid(pid, &waitpid_status, 0) < 0) {
uwsgi_error("uwsgi_run_command_and_wait()/waitpid()");
return -1;
}
return WEXITSTATUS(waitpid_status);
}
unsigned int i;
for (i = 0; i < nenvs; i++) {
if (putenv(envs[i])) {
uwsgi_error("uwsgi_run_command_putenv_and_wait()/putenv()");
exit(1);
}
}
return uwsgi_run_command_do(command, arg);
}
pid_t uwsgi_run_command(char *command, int *stdin_fd, int stdout_fd) {
char *argv[4];
int waitpid_status = 0;
pid_t pid = fork();
if (pid < 0) {
return -1;
}
if (pid > 0) {
if (stdin_fd && stdin_fd[0] > -1) {
close(stdin_fd[0]);
}
if (stdout_fd > -1) {
close(stdout_fd);
}
if (waitpid(pid, &waitpid_status, WNOHANG) < 0) {
uwsgi_error("waitpid()");
return -1;
}
return pid;
}
uwsgi_close_all_sockets();
//uwsgi_close_all_fds();
int i;
for (i = 3; i < (int) uwsgi.max_fd; i++) {
if (stdin_fd) {
if (i == stdin_fd[0] || i == stdin_fd[1]) {
continue;
}
}
if (stdout_fd > -1) {
if (i == stdout_fd) {
continue;
}
}
#ifdef __APPLE__
fcntl(i, F_SETFD, FD_CLOEXEC);
#else
close(i);
#endif
}
if (stdin_fd) {
close(stdin_fd[1]);
}
else {
if (!uwsgi_valid_fd(0)) {
int in_fd = open("/dev/null", O_RDONLY);
if (in_fd < 0) {
uwsgi_error_open("/dev/null");
}
else {
if (in_fd != 0) {
if (dup2(in_fd, 0) < 0) {
uwsgi_error("dup2()");
}
}
}
}
}
if (stdout_fd > -1 && stdout_fd != 1) {
if (dup2(stdout_fd, 1) < 0) {
uwsgi_error("dup2()");
exit(1);
}
}
if (stdin_fd && stdin_fd[0] > -1 && stdin_fd[0] != 0) {
if (dup2(stdin_fd[0], 0) < 0) {
uwsgi_error("dup2()");
exit(1);
}
}
if (setsid() < 0) {
uwsgi_error("setsid()");
exit(1);
}
argv[0] = uwsgi_binsh();
argv[1] = "-c";
argv[2] = command;
argv[3] = NULL;
execvp(uwsgi_binsh(), argv);
uwsgi_error("execvp()");
//never here
exit(1);
}
int uwsgi_endswith(char *str1, char *str2) {
size_t i;
size_t str1len = strlen(str1);
size_t str2len = strlen(str2);
char *ptr;
if (str2len > str1len)
return 0;
ptr = (str1 + str1len) - str2len;
for (i = 0; i < str2len; i++) {
if (*ptr != str2[i])
return 0;
ptr++;
}
return 1;
}
void uwsgi_chown(char *filename, char *owner) {
uid_t new_uid = -1;
uid_t new_gid = -1;
struct group *new_group = NULL;
struct passwd *new_user = NULL;
char *colon = strchr(owner, ':');
if (colon) {
colon[0] = 0;
}
if (is_a_number(owner)) {
new_uid = atoi(owner);
}
else {
new_user = getpwnam(owner);
if (!new_user) {
uwsgi_log("unable to find user %s\n", owner);
exit(1);
}
new_uid = new_user->pw_uid;
}
if (colon) {
colon[0] = ':';
if (is_a_number(colon + 1)) {
new_gid = atoi(colon + 1);
}
else {
new_group = getgrnam(colon + 1);
if (!new_group) {
uwsgi_log("unable to find group %s\n", colon + 1);
exit(1);
}
new_gid = new_group->gr_gid;
}
}
if (chown(filename, new_uid, new_gid)) {
uwsgi_error("chown()");
exit(1);
}
}
char *uwsgi_get_binary_path(char *argvzero) {
#if defined(__linux__) || defined(__CYGWIN__)
char *buf = uwsgi_calloc(PATH_MAX + 1);
ssize_t len = readlink("/proc/self/exe", buf, PATH_MAX);
if (len > 0) {
return buf;
}
free(buf);
#elif defined(_WIN32)
char *buf = uwsgi_calloc(PATH_MAX + 1);
if (GetModuleFileName(NULL, buf, PATH_MAX) > 0) {
return buf;
}
free(buf);
#elif defined(__NetBSD__)
char *buf = uwsgi_calloc(PATH_MAX + 1);
ssize_t len = readlink("/proc/curproc/exe", buf, PATH_MAX);
if (len > 0) {
return buf;
}
if (realpath(argvzero, buf)) {
return buf;
}
free(buf);
#elif defined(__APPLE__)
char *buf = uwsgi_malloc(uwsgi.page_size);
uint32_t len = uwsgi.page_size;
if (_NSGetExecutablePath(buf, &len) == 0) {
// return only absolute path
#ifndef OLD_REALPATH
char *newbuf = realpath(buf, NULL);
if (newbuf) {
free(buf);
return newbuf;
}
#endif
}
free(buf);
#elif defined(__sun__)
// do not free this value !!!
char *buf = (char *) getexecname();
if (buf) {
// return only absolute path
if (buf[0] == '/') {
return buf;
}
char *newbuf = uwsgi_malloc(PATH_MAX + 1);
if (realpath(buf, newbuf)) {
return newbuf;
}
}
#elif defined(__FreeBSD__) || defined(__GNU_kFreeBSD__)
char *buf = uwsgi_malloc(uwsgi.page_size);
size_t len = uwsgi.page_size;
int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
if (sysctl(mib, 4, buf, &len, NULL, 0) == 0) {
return buf;
}
free(buf);
#endif
return argvzero;
}
char *uwsgi_get_line(char *ptr, char *watermark, int *size) {
char *p = ptr;
int count = 0;
while (p < watermark) {
if (*p == '\n') {
*size = count;
return ptr + count;
}
count++;
p++;
}
return NULL;
}
void uwsgi_build_mime_dict(char *filename) {
size_t size = 0;
char *buf = uwsgi_open_and_read(filename, &size, 1, NULL);
char *watermark = buf + size;
int linesize = 0;
char *line = buf;
int i;
int type_size = 0;
int ext_start = 0;
int found;
int entries = 0;
uwsgi_log("building mime-types dictionary from file %s...", filename);
while (uwsgi_get_line(line, watermark, &linesize) != NULL) {
found = 0;
if (isalnum((int) line[0])) {
// get the type size
for (i = 0; i < linesize; i++) {
if (isblank((int) line[i])) {
type_size = i;
found = 1;
break;
}
}
if (!found) {
line += linesize + 1;
continue;
}
found = 0;
for (i = type_size; i < linesize; i++) {
if (!isblank((int) line[i])) {
ext_start = i;
found = 1;
break;
}
}
if (!found) {
line += linesize + 1;
continue;
}
char *current = line + ext_start;
int ext_size = 0;
for (i = ext_start; i < linesize; i++) {
if (isblank((int) line[i])) {
#ifdef UWSGI_DEBUG
uwsgi_log("%.*s %.*s\n", ext_size, current, type_size, line);
#endif
uwsgi_dyn_dict_new(&uwsgi.mimetypes, current, ext_size, line, type_size);
entries++;
ext_size = 0;
current = NULL;
continue;
}
else if (current == NULL) {
current = line + i;
}
ext_size++;
}
if (current && ext_size > 1) {
#ifdef UWSGI_DEBUG
uwsgi_log("%.*s %.*s\n", ext_size, current, type_size, line);
#endif
uwsgi_dyn_dict_new(&uwsgi.mimetypes, current, ext_size, line, type_size);
entries++;
}
}
line += linesize + 1;
}
uwsgi_log("%d entry found\n", entries);
}
#ifdef __linux__
struct uwsgi_unshare_id {
char *name;
int value;
};
static struct uwsgi_unshare_id uwsgi_unshare_list[] = {
#ifdef CLONE_FILES
{"files", CLONE_FILES},
#endif
#ifdef CLONE_NEWIPC
{"ipc", CLONE_NEWIPC},
#endif
#ifdef CLONE_NEWNET
{"net", CLONE_NEWNET},
#endif
#ifdef CLONE_IO
{"io", CLONE_IO},
#endif
#ifdef CLONE_PARENT
{"parent", CLONE_PARENT},
#endif
#ifdef CLONE_NEWPID
{"pid", CLONE_NEWPID},
#endif
#ifdef CLONE_NEWNS
{"ns", CLONE_NEWNS},
{"fs", CLONE_NEWNS},
{"mount", CLONE_NEWNS},
{"mnt", CLONE_NEWNS},
#endif
#ifdef CLONE_SYSVSEM
{"sysvsem", CLONE_SYSVSEM},
#endif
#ifdef CLONE_NEWUTS
{"uts", CLONE_NEWUTS},
#endif
#ifdef CLONE_NEWUSER
{"user", CLONE_NEWUSER},
#endif
{NULL, -1}
};
static int uwsgi_get_unshare_id(char *name) {
struct uwsgi_unshare_id *uui = uwsgi_unshare_list;
while (uui->name) {
if (!strcmp(uui->name, name))
return uui->value;
uui++;
}
return -1;
}
void uwsgi_build_unshare(char *what, int *mask) {
char *list = uwsgi_str(what);
char *p, *ctx = NULL;
uwsgi_foreach_token(list, ",", p, ctx) {
int u_id = uwsgi_get_unshare_id(p);
if (u_id != -1) {
*mask |= u_id;
}
else {
uwsgi_log("unknown namespace subsystem: %s\n", p);
exit(1);
}
}
free(list);
}
#endif
#ifdef UWSGI_CAP
struct uwsgi_cap {
char *name;
cap_value_t value;
};
static struct uwsgi_cap uwsgi_cap_list[] = {
{"chown", CAP_CHOWN},
{"dac_override", CAP_DAC_OVERRIDE},
{"dac_read_search", CAP_DAC_READ_SEARCH},
{"fowner", CAP_FOWNER},
{"fsetid", CAP_FSETID},
{"kill", CAP_KILL},
{"setgid", CAP_SETGID},
{"setuid", CAP_SETUID},
{"setpcap", CAP_SETPCAP},
{"linux_immutable", CAP_LINUX_IMMUTABLE},
{"net_bind_service", CAP_NET_BIND_SERVICE},
{"net_broadcast", CAP_NET_BROADCAST},
{"net_admin", CAP_NET_ADMIN},
{"net_raw", CAP_NET_RAW},
{"ipc_lock", CAP_IPC_LOCK},
{"ipc_owner", CAP_IPC_OWNER},
{"sys_module", CAP_SYS_MODULE},
{"sys_rawio", CAP_SYS_RAWIO},
{"sys_chroot", CAP_SYS_CHROOT},
{"sys_ptrace", CAP_SYS_PTRACE},
{"sys_pacct", CAP_SYS_PACCT},
{"sys_admin", CAP_SYS_ADMIN},
{"sys_boot", CAP_SYS_BOOT},
{"sys_nice", CAP_SYS_NICE},
{"sys_resource", CAP_SYS_RESOURCE},
{"sys_time", CAP_SYS_TIME},
{"sys_tty_config", CAP_SYS_TTY_CONFIG},
{"mknod", CAP_MKNOD},
#ifdef CAP_LEASE
{"lease", CAP_LEASE},
#endif
#ifdef CAP_AUDIT_WRITE
{"audit_write", CAP_AUDIT_WRITE},
#endif
#ifdef CAP_AUDIT_CONTROL
{"audit_control", CAP_AUDIT_CONTROL},
#endif
#ifdef CAP_SETFCAP
{"setfcap", CAP_SETFCAP},
#endif
#ifdef CAP_MAC_OVERRIDE
{"mac_override", CAP_MAC_OVERRIDE},
#endif
#ifdef CAP_MAC_ADMIN
{"mac_admin", CAP_MAC_ADMIN},
#endif
#ifdef CAP_SYSLOG
{"syslog", CAP_SYSLOG},
#endif
#ifdef CAP_WAKE_ALARM
{"wake_alarm", CAP_WAKE_ALARM},
#endif
{NULL, -1}
};
static int uwsgi_get_cap_id(char *name) {
struct uwsgi_cap *ucl = uwsgi_cap_list;
while (ucl->name) {
if (!strcmp(ucl->name, name))
return ucl->value;
ucl++;
}
return -1;
}
int uwsgi_build_cap(char *what, cap_value_t ** cap) {
int cap_id;
char *caps = uwsgi_str(what);
int pos = 0;
int count = 0;
char *p, *ctx = NULL;
uwsgi_foreach_token(caps, ",", p, ctx) {
if (is_a_number(p)) {
count++;
}
else {
cap_id = uwsgi_get_cap_id(p);
if (cap_id != -1) {
count++;
}
else {
uwsgi_log("[security] unknown capability: %s\n", p);
}
}
}
free(caps);
*cap = uwsgi_malloc(sizeof(cap_value_t) * count);
caps = uwsgi_str(what);
ctx = NULL;
uwsgi_foreach_token(caps, ",", p, ctx) {
if (is_a_number(p)) {
cap_id = atoi(p);
}
else {
cap_id = uwsgi_get_cap_id(p);
}
if (cap_id != -1) {
(*cap)[pos] = cap_id;
uwsgi_log("setting capability %s [%d]\n", p, cap_id);
pos++;
}
else {
uwsgi_log("[security] unknown capability: %s\n", p);
}
}
free(caps);
return count;
}
#endif
void uwsgi_apply_config_pass(char symbol, char *(*hook) (char *)) {
int i, j;
for (i = 0; i < uwsgi.exported_opts_cnt; i++) {
int has_symbol = 0;
int depth = 0;
char *magic_key = NULL;
char *magic_val = NULL;
if (uwsgi.exported_opts[i]->value && !uwsgi.exported_opts[i]->configured) {
for (j = 0; j < (int) strlen(uwsgi.exported_opts[i]->value); j++) {
if (uwsgi.exported_opts[i]->value[j] == symbol) {
has_symbol = 1;
}
else if (uwsgi.exported_opts[i]->value[j] == '(' && has_symbol == 1) {
has_symbol = 2;
depth = 0;
magic_key = uwsgi.exported_opts[i]->value + j + 1;
}
else if (has_symbol > 1) {
if (uwsgi.exported_opts[i]->value[j] == '(') {
has_symbol++;
depth++;
}
else if (uwsgi.exported_opts[i]->value[j] == ')') {
if (depth > 0) {
has_symbol++;
depth--;
continue;
}
if (has_symbol <= 2) {
magic_key = NULL;
has_symbol = 0;
continue;
}
#ifdef UWSGI_DEBUG
uwsgi_log("need to interpret the %.*s tag\n", has_symbol - 2, magic_key);
#endif
char *tmp_magic_key = uwsgi_concat2n(magic_key, has_symbol - 2, "", 0);
magic_val = hook(tmp_magic_key);
free(tmp_magic_key);
if (!magic_val) {
magic_key = NULL;
has_symbol = 0;
continue;
}
uwsgi.exported_opts[i]->value = uwsgi_concat4n(uwsgi.exported_opts[i]->value, (magic_key - 2) - uwsgi.exported_opts[i]->value, magic_val, strlen(magic_val), magic_key + (has_symbol - 1), strlen(magic_key + (has_symbol - 1)), "", 0);
#ifdef UWSGI_DEBUG
uwsgi_log("computed new value = %s\n", uwsgi.exported_opts[i]->value);
#endif
magic_key = NULL;
has_symbol = 0;
j = 0;
}
else {
has_symbol++;
}
}
else {
has_symbol = 0;
}
}
}
}
}
void uwsgi_set_processname(char *name) {
#if defined(__linux__) || defined(__sun__)
size_t amount = 0;
size_t max_procname = uwsgi.argv_len + uwsgi.environ_len;
// prepare for strncat
*uwsgi.orig_argv[0] = 0;
if (uwsgi.procname_prefix) {
amount += strlen(uwsgi.procname_prefix);
if (amount >= max_procname)
return;
strncat(uwsgi.orig_argv[0], uwsgi.procname_prefix, max_procname - (amount + 1));
}
amount += strlen(name);
if (amount >= max_procname)
return;
strncat(uwsgi.orig_argv[0], name, max_procname - (amount + 1));
if (uwsgi.procname_append) {
amount += strlen(uwsgi.procname_append);
if (amount >= max_procname)
return;
strncat(uwsgi.orig_argv[0], uwsgi.procname_append, max_procname - (amount + 1));
}
// if we fit into argv, only fill argv with spaces, otherwise use environ as well
if (amount < uwsgi.argv_len) {
max_procname = uwsgi.argv_len;
}
// fill with spaces...
memset(uwsgi.orig_argv[0] + amount + 1, ' ', max_procname - (amount + 1));
#elif defined(__FreeBSD__) || defined(__GNU_kFreeBSD__) || defined(__NetBSD__)
if (uwsgi.procname_prefix) {
if (!uwsgi.procname_append) {
setproctitle("-%s%s", uwsgi.procname_prefix, name);
}
else {
setproctitle("-%s%s%s", uwsgi.procname_prefix, name, uwsgi.procname_append);
}
}
else if (uwsgi.procname_append) {
if (!uwsgi.procname_prefix) {
setproctitle("-%s%s", name, uwsgi.procname_append);
}
else {
setproctitle("-%s%s%s", uwsgi.procname_prefix, name, uwsgi.procname_append);
}
}
else {
setproctitle("-%s", name);
}
#endif
}
// this is a wrapper for fork restoring original argv
pid_t uwsgi_fork(char *name) {
pid_t pid = fork();
if (pid == 0) {
#ifndef __CYGWIN__
if (uwsgi.never_swap) {
if (mlockall(MCL_CURRENT | MCL_FUTURE)) {
uwsgi_error("mlockall()");
}
}
#endif
#if defined(__linux__) || defined(__sun__)
int i;
for (i = 0; i < uwsgi.argc; i++) {
// stop fixing original argv if the new one is bigger
if (!uwsgi.orig_argv[i]) break;
strcpy(uwsgi.orig_argv[i], uwsgi.argv[i]);
}
#endif
if (uwsgi.auto_procname && name) {
if (uwsgi.procname) {
uwsgi_set_processname(uwsgi.procname);
}
else {
uwsgi_set_processname(name);
}
}
}
return pid;
}
void escape_shell_arg(char *src, size_t len, char *dst) {
size_t i;
char *ptr = dst;
for (i = 0; i < len; i++) {
if (strchr("&;`'\"|*?~<>^()[]{}$\\\n", src[i])) {
*ptr++ = '\\';
}
*ptr++ = src[i];
}
*ptr++ = 0;
}
void escape_json(char *src, size_t len, char *dst) {
size_t i;
char *ptr = dst;
for (i = 0; i < len; i++) {
if (src[i] == '\t') {
*ptr++ = '\\';
*ptr++ = 't';
}
else if (src[i] == '\n') {
*ptr++ = '\\';
*ptr++ = 'n';
}
else if (src[i] == '\r') {
*ptr++ = '\\';
*ptr++ = 'r';
}
else if (src[i] == '"') {
*ptr++ = '\\';
*ptr++ = '"';
}
else if (src[i] == '\\') {
*ptr++ = '\\';
*ptr++ = '\\';
}
else {
*ptr++ = src[i];
}
}
*ptr++ = 0;
}
/*
build PATH_INFO from raw_uri
it manages:
percent encoding
dot_segments removal
stop at the first #
*/
void http_url_decode4(char *buf, uint16_t * len, char *dst, int no_slash_decode) {
enum {
zero = 0,
percent1,
percent2,
slash,
dot,
dotdot
} status;
uint16_t i, current_new_len, new_len = 0;
char value[2];
char *ptr = dst;
value[0] = '0';
value[1] = '0';
status = zero;
int no_slash = 0;
if (*len > 0 && buf[0] != '/') {
status = slash;
no_slash = 1;
}
for (i = 0; i < *len; i++) {
char c = buf[i];
if (c == '#')
break;
switch (status) {
case zero:
if (c == '%') {
status = percent1;
break;
}
if (c == '/') {
status = slash;
break;
}
*ptr++ = c;
new_len++;
break;
case percent1:
if (c == '%') {
*ptr++ = '%';
new_len++;
status = zero;
break;
}
value[0] = c;
status = percent2;
break;
case percent2:
value[1] = c;
if (no_slash_decode && value[0] == '2' && (value[1] == 'F' || value[1] == 'f')) {
*ptr++ = '%';
*ptr++ = value[0];
*ptr++ = value[1];
new_len += 3;
} else {
*ptr++ = hex2num(value);
new_len++;
}
status = zero;
break;
case slash:
if (c == '.') {
status = dot;
break;
}
// we could be at the first round (in non slash)
if (i > 0 || !no_slash) {
*ptr++ = '/';
new_len++;
}
if (c == '%') {
status = percent1;
break;
}
if (c == '/') {
status = slash;
break;
}
*ptr++ = c;
new_len++;
status = zero;
break;
case dot:
if (c == '.') {
status = dotdot;
break;
}
if (c == '/') {
status = slash;
break;
}
if (i > 1) {
*ptr++ = '/';
new_len++;
}
*ptr++ = '.';
new_len++;
if (c == '%') {
status = percent1;
break;
}
*ptr++ = c;
new_len++;
status = zero;
break;
case dotdot:
// here we need to remove a segment
if (c == '/') {
current_new_len = new_len;
while (current_new_len) {
current_new_len--;
ptr--;
if (dst[current_new_len] == '/') {
break;
}
}
new_len = current_new_len;
status = slash;
break;
}
if (i > 2) {
*ptr++ = '/';
new_len++;
}
*ptr++ = '.';
new_len++;
*ptr++ = '.';
new_len++;
if (c == '%') {
status = percent1;
break;
}
*ptr++ = c;
new_len++;
status = zero;
break;
// over engineering
default:
*ptr++ = c;
new_len++;
break;
}
}
switch (status) {
case slash:
case dot:
*ptr++ = '/';
new_len++;
break;
case dotdot:
current_new_len = new_len;
while (current_new_len) {
if (dst[current_new_len - 1] == '/') {
break;
}
current_new_len--;
}
new_len = current_new_len;
break;
default:
break;
}
*len = new_len;
}
/*
we scan the table in reverse, as updated values are at the end
*/
char *uwsgi_get_var(struct wsgi_request *wsgi_req, char *key, uint16_t keylen, uint16_t * len) {
int i;
for (i = wsgi_req->var_cnt - 1; i > 0; i -= 2) {
if (!uwsgi_strncmp(key, keylen, wsgi_req->hvec[i - 1].iov_base, wsgi_req->hvec[i - 1].iov_len)) {
*len = wsgi_req->hvec[i].iov_len;
return wsgi_req->hvec[i].iov_base;
}
}
return NULL;
}
struct uwsgi_app *uwsgi_add_app(int id, uint8_t modifier1, char *mountpoint, int mountpoint_len, void *interpreter, void *callable) {
if (id > uwsgi.max_apps) {
uwsgi_log("FATAL ERROR: you cannot load more than %d apps in a worker\n", uwsgi.max_apps);
exit(1);
}
struct uwsgi_app *wi = &uwsgi_apps[id];
memset(wi, 0, sizeof(struct uwsgi_app));
wi->modifier1 = modifier1;
wi->mountpoint_len = mountpoint_len < 0xff ? mountpoint_len : (0xff - 1);
strncpy(wi->mountpoint, mountpoint, wi->mountpoint_len);
wi->interpreter = interpreter;
wi->callable = callable;
uwsgi_apps_cnt++;
// check if we need to emulate fork() COW
int i;
if (uwsgi.mywid == 0) {
for (i = 1; i <= uwsgi.numproc; i++) {
memcpy(&uwsgi.workers[i].apps[id], &uwsgi.workers[0].apps[id], sizeof(struct uwsgi_app));
uwsgi.workers[i].apps_cnt = uwsgi_apps_cnt;
}
}
if (!uwsgi.no_default_app) {
if ((mountpoint_len == 0 || (mountpoint_len == 1 && mountpoint[0] == '/')) && uwsgi.default_app == -1) {
uwsgi.default_app = id;
}
}
return wi;
}
char *uwsgi_check_touches(struct uwsgi_string_list *touch_list) {
// touch->value - file path
// touch->custom - file timestamp
// touch->custom2 - 0 if file exists, 1 if it does not exists
struct uwsgi_string_list *touch = touch_list;
while (touch) {
struct stat tr_st;
if (stat(touch->value, &tr_st)) {
if (touch->custom && !touch->custom2) {
#ifdef UWSGI_DEBUG
uwsgi_log("[uwsgi-check-touches] File %s was removed\n", touch->value);
#endif
touch->custom2 = 1;
return touch->custom_ptr ? touch->custom_ptr : touch->value;
}
else if (!touch->custom && !touch->custom2) {
uwsgi_log("unable to stat() %s, events will be triggered as soon as the file is created\n", touch->value);
touch->custom2 = 1;
}
touch->custom = 0;
}
else {
if (!touch->custom && touch->custom2) {
#ifdef UWSGI_DEBUG
uwsgi_log("[uwsgi-check-touches] File was created: %s\n", touch->value);
#endif
touch->custom = (uint64_t) tr_st.st_mtime;
touch->custom2 = 0;
return touch->custom_ptr ? touch->custom_ptr : touch->value;
}
else if (touch->custom && (uint64_t) tr_st.st_mtime > touch->custom) {
#ifdef UWSGI_DEBUG
uwsgi_log("[uwsgi-check-touches] modification detected on %s: %llu -> %llu\n", touch->value, (unsigned long long) touch->custom, (unsigned long long) tr_st.st_mtime);
#endif
touch->custom = (uint64_t) tr_st.st_mtime;
return touch->custom_ptr ? touch->custom_ptr : touch->value;
}
touch->custom = (uint64_t) tr_st.st_mtime;
}
touch = touch->next;
}
return NULL;
}
char *uwsgi_chomp(char *str) {
ssize_t slen = (ssize_t) strlen(str), i;
if (!slen)
return str;
slen--;
for (i = slen; i >= 0; i--) {
if (str[i] == '\r' || str[i] == '\n') {
str[i] = 0;
}
else {
return str;
}
}
return str;
}
char *uwsgi_chomp2(char *str) {
ssize_t slen = (ssize_t) strlen(str), i;
if (!slen)
return str;
slen--;
for (i = slen; i >= 0; i--) {
if (str[i] == '\r' || str[i] == '\n' || str[i] == '\t' || str[i] == ' ') {
str[i] = 0;
}
else {
return str;
}
}
return str;
}
int uwsgi_tmpfd() {
int fd = -1;
char *tmpdir = getenv("TMPDIR");
if (!tmpdir) {
tmpdir = "/tmp";
}
#ifdef O_TMPFILE
fd = open(tmpdir, O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);
if (fd >= 0) {
return fd;
}
// fallback to old style
#endif
char *template = uwsgi_concat2(tmpdir, "/uwsgiXXXXXX");
fd = mkstemp(template);
unlink(template);
free(template);
return fd;
}
FILE *uwsgi_tmpfile() {
int fd = uwsgi_tmpfd();
if (fd < 0)
return NULL;
return fdopen(fd, "w+");
}
int uwsgi_file_to_string_list(char *filename, struct uwsgi_string_list **list) {
char line[1024];
FILE *fh = fopen(filename, "r");
if (fh) {
while (fgets(line, 1024, fh)) {
uwsgi_string_new_list(list, uwsgi_chomp(uwsgi_str(line)));
}
fclose(fh);
return 1;
}
uwsgi_error_open(filename);
return 0;
}
void uwsgi_setup_post_buffering() {
if (!uwsgi.post_buffering_bufsize)
uwsgi.post_buffering_bufsize = 8192;
if (uwsgi.post_buffering_bufsize < uwsgi.post_buffering) {
uwsgi.post_buffering_bufsize = uwsgi.post_buffering;
uwsgi_log("setting request body buffering size to %lu bytes\n", (unsigned long) uwsgi.post_buffering_bufsize);
}
}
void uwsgi_emulate_cow_for_apps(int id) {
int i;
// check if we need to emulate fork() COW
if (uwsgi.mywid == 0) {
for (i = 1; i <= uwsgi.numproc; i++) {
memcpy(&uwsgi.workers[i].apps[id], &uwsgi.workers[0].apps[id], sizeof(struct uwsgi_app));
uwsgi.workers[i].apps_cnt = uwsgi_apps_cnt;
}
}
}
int uwsgi_write_intfile(char *filename, int n) {
FILE *pidfile = fopen(filename, "w");
if (!pidfile) {
uwsgi_error_open(filename);
exit(1);
}
if (fprintf(pidfile, "%d\n", n) <= 0 || ferror(pidfile)) {
fclose(pidfile);
return -1;
}
if (fclose(pidfile)) {
return -1;
}
return 0;
}
void uwsgi_write_pidfile(char *pidfile_name) {
uwsgi_log("writing pidfile to %s\n", pidfile_name);
if (uwsgi_write_intfile(pidfile_name, (int) getpid())) {
uwsgi_log("could not write pidfile.\n");
}
}
void uwsgi_write_pidfile_explicit(char *pidfile_name, pid_t pid) {
uwsgi_log("writing pidfile to %s\n", pidfile_name);
if (uwsgi_write_intfile(pidfile_name, (int) pid)) {
uwsgi_log("could not write pidfile.\n");
}
}
char *uwsgi_expand_path(char *dir, int dir_len, char *ptr) {
char src[PATH_MAX + 1];
memcpy(src, dir, dir_len);
src[dir_len] = 0;
char *dst = ptr;
if (!dst)
dst = uwsgi_malloc(PATH_MAX + 1);
if (!realpath(src, dst)) {
uwsgi_error_realpath(src);
if (!ptr)
free(dst);
return NULL;
}
return dst;
}
void uwsgi_set_cpu_affinity() {
char buf[4096];
int ret;
int pos = 0;
if (uwsgi.cpu_affinity) {
int base_cpu = (uwsgi.mywid - 1) * uwsgi.cpu_affinity;
if (base_cpu >= uwsgi.cpus) {
base_cpu = base_cpu % uwsgi.cpus;
}
ret = snprintf(buf, 4096, "mapping worker %d to CPUs:", uwsgi.mywid);
if (ret < 25 || ret >= 4096) {
uwsgi_log("unable to initialize cpu affinity !!!\n");
exit(1);
}
pos += ret;
#if defined(__linux__) || defined(__GNU_kFreeBSD__)
cpu_set_t cpuset;
#elif defined(__FreeBSD__)
cpuset_t cpuset;
#endif
#if defined(__linux__) || defined(__FreeBSD__) || defined(__GNU_kFreeBSD__)
CPU_ZERO(&cpuset);
int i;
for (i = 0; i < uwsgi.cpu_affinity; i++) {
if (base_cpu >= uwsgi.cpus)
base_cpu = 0;
CPU_SET(base_cpu, &cpuset);
ret = snprintf(buf + pos, 4096 - pos, " %d", base_cpu);
if (ret < 2 || ret >= 4096) {
uwsgi_log("unable to initialize cpu affinity !!!\n");
exit(1);
}
pos += ret;
base_cpu++;
}
#endif
#if defined(__linux__) || defined(__GNU_kFreeBSD__)
if (sched_setaffinity(0, sizeof(cpu_set_t), &cpuset)) {
uwsgi_error("sched_setaffinity()");
}
#elif defined(__FreeBSD__)
if (cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(cpuset), &cpuset)) {
uwsgi_error("cpuset_setaffinity");
}
#endif
uwsgi_log("%s\n", buf);
}
}
#ifdef UWSGI_ELF
#if defined(__linux__)
#include <elf.h>
#endif
char *uwsgi_elf_section(char *filename, char *s, size_t * len) {
struct stat st;
char *output = NULL;
int fd = open(filename, O_RDONLY);
if (fd < 0) {
uwsgi_error_open(filename);
return NULL;
}
if (fstat(fd, &st)) {
uwsgi_error("stat()");
close(fd);
return NULL;
}
if (st.st_size < EI_NIDENT) {
uwsgi_log("invalid elf file: %s\n", filename);
close(fd);
return NULL;
}
char *addr = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (addr == MAP_FAILED) {
uwsgi_error("mmap()");
close(fd);
return NULL;
}
if (addr[0] != ELFMAG0)
goto clear;
if (addr[1] != ELFMAG1)
goto clear;
if (addr[2] != ELFMAG2)
goto clear;
if (addr[3] != ELFMAG3)
goto clear;
if (addr[4] == ELFCLASS32) {
// elf header
Elf32_Ehdr *elfh = (Elf32_Ehdr *) addr;
// first section
Elf32_Shdr *sections = ((Elf32_Shdr *) (addr + elfh->e_shoff));
// number of sections
int ns = elfh->e_shnum;
// the names table
Elf32_Shdr *table = §ions[elfh->e_shstrndx];
// string table session pointer
char *names = addr + table->sh_offset;
Elf32_Shdr *ss = NULL;
int i;
for (i = 0; i < ns; i++) {
char *name = names + sections[i].sh_name;
if (!strcmp(name, s)) {
ss = §ions[i];
break;
}
}
if (ss) {
*len = ss->sh_size;
output = uwsgi_concat2n(addr + ss->sh_offset, ss->sh_size, "", 0);
}
}
else if (addr[4] == ELFCLASS64) {
// elf header
Elf64_Ehdr *elfh = (Elf64_Ehdr *) addr;
// first section
Elf64_Shdr *sections = ((Elf64_Shdr *) (addr + elfh->e_shoff));
// number of sections
int ns = elfh->e_shnum;
// the names table
Elf64_Shdr *table = §ions[elfh->e_shstrndx];
// string table session pointer
char *names = addr + table->sh_offset;
Elf64_Shdr *ss = NULL;
int i;
for (i = 0; i < ns; i++) {
char *name = names + sections[i].sh_name;
if (!strcmp(name, s)) {
ss = §ions[i];
break;
}
}
if (ss) {
*len = ss->sh_size;
output = uwsgi_concat2n(addr + ss->sh_offset, ss->sh_size, "", 0);
}
}
clear:
close(fd);
munmap(addr, st.st_size);
return output;
}
#endif
static void *uwsgi_thread_run(void *arg) {
struct uwsgi_thread *ut = (struct uwsgi_thread *) arg;
// block all signals
sigset_t smask;
sigfillset(&smask);
pthread_sigmask(SIG_BLOCK, &smask, NULL);
ut->queue = event_queue_init();
event_queue_add_fd_read(ut->queue, ut->pipe[1]);
ut->func(ut);
return NULL;
}
struct uwsgi_thread *uwsgi_thread_new_with_data(void (*func) (struct uwsgi_thread *), void *data) {
struct uwsgi_thread *ut = uwsgi_calloc(sizeof(struct uwsgi_thread));
#if defined(SOCK_SEQPACKET) && defined(__linux__)
if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, ut->pipe)) {
#else
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, ut->pipe)) {
#endif
free(ut);
return NULL;
}
uwsgi_socket_nb(ut->pipe[0]);
uwsgi_socket_nb(ut->pipe[1]);
ut->func = func;
ut->data = data;
pthread_attr_init(&ut->tattr);
pthread_attr_setdetachstate(&ut->tattr, PTHREAD_CREATE_DETACHED);
// 512K should be enough...
pthread_attr_setstacksize(&ut->tattr, 512 * 1024);
if (pthread_create(&ut->tid, &ut->tattr, uwsgi_thread_run, ut)) {
uwsgi_error("pthread_create()");
goto error;
}
return ut;
error:
close(ut->pipe[0]);
close(ut->pipe[1]);
free(ut);
return NULL;
}
struct uwsgi_thread *uwsgi_thread_new(void (*func) (struct uwsgi_thread *)) {
return uwsgi_thread_new_with_data(func, NULL);
}
int uwsgi_kvlist_parse(char *src, size_t len, char list_separator, int kv_separator, ...) {
size_t i;
va_list ap;
struct uwsgi_string_list *itemlist = NULL;
char *buf = uwsgi_calloc(len + 1);
// ok let's start splitting the string
int escaped = 0;
char *base = buf;
char *ptr = buf;
for (i = 0; i < len; i++) {
if (src[i] == list_separator && !escaped) {
*ptr++ = 0;
uwsgi_string_new_list(&itemlist, base);
base = ptr;
}
else if (src[i] == '\\' && !escaped) {
escaped = 1;
}
else if (escaped) {
*ptr++ = src[i];
escaped = 0;
}
else {
*ptr++ = src[i];
}
}
if (ptr > base) {
uwsgi_string_new_list(&itemlist, base);
}
struct uwsgi_string_list *usl = itemlist;
while (usl) {
len = strlen(usl->value);
char *item_buf = uwsgi_calloc(len + 1);
base = item_buf;
ptr = item_buf;
escaped = 0;
for (i = 0; i < len; i++) {
if (usl->value[i] == kv_separator && !escaped) {
*ptr++ = 0;
va_start(ap, kv_separator);
for (;;) {
char *p = va_arg(ap, char *);
if (!p)
break;
char **pp = va_arg(ap, char **);
if (!pp)
break;
if (!strcmp(p, base)) {
*pp = uwsgi_str(usl->value + i + 1);
}
}
va_end(ap);
break;
}
else if (usl->value[i] == '\\' && !escaped) {
escaped = 1;
}
else if (escaped) {
escaped = 0;
}
else {
*ptr++ = usl->value[i];
}
}
free(item_buf);
usl = usl->next;
}
// destroy the list (no need to destroy the value as it is a pointer to buf)
usl = itemlist;
while (usl) {
struct uwsgi_string_list *tmp_usl = usl;
usl = usl->next;
free(tmp_usl);
}
free(buf);
return 0;
}
int uwsgi_send_http_stats(int fd) {
char buf[4096];
int ret = uwsgi_waitfd(fd, uwsgi.socket_timeout);
if (ret <= 0)
return -1;
if (read(fd, buf, 4096) <= 0)
return -1;
struct uwsgi_buffer *ub = uwsgi_buffer_new(uwsgi.page_size);
if (!ub)
return -1;
if (uwsgi_buffer_append(ub, "HTTP/1.0 200 OK\r\n", 17))
goto error;
if (uwsgi_buffer_append(ub, "Connection: close\r\n", 19))
goto error;
if (uwsgi_buffer_append(ub, "Access-Control-Allow-Origin: *\r\n", 32))
goto error;
if (uwsgi_buffer_append(ub, "Content-Type: application/json\r\n", 32))
goto error;
if (uwsgi_buffer_append(ub, "\r\n", 2))
goto error;
if (uwsgi_buffer_send(ub, fd))
goto error;
uwsgi_buffer_destroy(ub);
return 0;
error:
uwsgi_buffer_destroy(ub);
return -1;
}
int uwsgi_call_symbol(char *symbol) {
void (*func) (void) = dlsym(RTLD_DEFAULT, symbol);
if (!func)
return -1;
func();
return 0;
}
int uwsgi_plugin_modifier1(char *plugin) {
int ret = -1;
char *symbol_name = uwsgi_concat2(plugin, "_plugin");
struct uwsgi_plugin *up = dlsym(RTLD_DEFAULT, symbol_name);
if (!up)
goto end;
ret = up->modifier1;
end:
free(symbol_name);
return ret;
}
char *uwsgi_strip(char *src) {
char *dst = src;
size_t len = strlen(src);
int i;
for (i = 0; i < (ssize_t) len; i++) {
if (src[i] == ' ' || src[i] == '\t') {
dst++;
}
}
len -= (dst - src);
for (i = len; i >= 0; i--) {
if (dst[i] == ' ' || dst[i] == '\t') {
dst[i] = 0;
}
else {
break;
}
}
return dst;
}
void uwsgi_uuid(char *buf) {
#ifdef UWSGI_UUID
uuid_t uuid_value;
uuid_generate(uuid_value);
uuid_unparse(uuid_value, buf);
#else
int i, r[11];
if (!uwsgi_file_exists("/dev/urandom"))
goto fallback;
int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0)
goto fallback;
for (i = 0; i < 11; i++) {
if (read(fd, &r[i], 4) != 4) {
close(fd);
goto fallback;
}
}
close(fd);
goto done;
fallback:
for (i = 0; i < 11; i++) {
r[i] = rand();
}
done:
snprintf(buf, 37, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10]);
#endif
}
int uwsgi_uuid_cmp(char *x, char *y) {
int i;
for (i = 0; i < 36; i++) {
if (x[i] != y[i]) {
if (x[i] > y[i]) {
return 1;
}
return 0;
}
}
return 0;
}
void uwsgi_additional_header_add(struct wsgi_request *wsgi_req, char *hh, uint16_t hh_len) {
// will be freed on request's end
char *header = uwsgi_concat2n(hh, hh_len, "", 0);
uwsgi_string_new_list(&wsgi_req->additional_headers, header);
}
void uwsgi_remove_header(struct wsgi_request *wsgi_req, char *hh, uint16_t hh_len) {
char *header = uwsgi_concat2n(hh, hh_len, "", 0);
uwsgi_string_new_list(&wsgi_req->remove_headers, header);
}
// based on nginx implementation
static uint8_t b64_table64[] = {
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 62, 77, 77, 77, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 77, 77, 77, 77, 77, 77,
77, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 77, 77, 77, 77, 77,
77, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77
};
static char b64_table64_2[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char *uwsgi_base64_decode(char *buf, size_t len, size_t * d_len) {
// find the real size and check for invalid values
size_t i;
for (i = 0; i < len; i++) {
if (buf[i] == '=')
break;
// check for invalid content
if (b64_table64[(uint8_t) buf[i]] == 77) {
return NULL;
}
}
// check for invalid size
if (i % 4 == 1)
return NULL;
// compute the new size
*d_len = (((len + 3) / 4) * 3);
char *dst = uwsgi_malloc(*d_len + 1);
char *ptr = dst;
uint8_t *src = (uint8_t *) buf;
while (i > 3) {
*ptr++ = (char) (b64_table64[src[0]] << 2 | b64_table64[src[1]] >> 4);
*ptr++ = (char) (b64_table64[src[1]] << 4 | b64_table64[src[2]] >> 2);
*ptr++ = (char) (b64_table64[src[2]] << 6 | b64_table64[src[3]]);
src += 4;
i -= 4;
}
if (i > 1) {
*ptr++ = (char) (b64_table64[src[0]] << 2 | b64_table64[src[1]] >> 4);
}
if (i > 2) {
*ptr++ = (char) (b64_table64[src[1]] << 4 | b64_table64[src[2]] >> 2);
}
*d_len = (ptr - dst);
*ptr++ = 0;
return dst;
}
char *uwsgi_base64_encode(char *buf, size_t len, size_t * d_len) {
*d_len = ((len * 4) / 3) + 5;
uint8_t *src = (uint8_t *) buf;
char *dst = uwsgi_malloc(*d_len);
char *ptr = dst;
while (len >= 3) {
*ptr++ = b64_table64_2[src[0] >> 2];
*ptr++ = b64_table64_2[((src[0] << 4) & 0x30) | (src[1] >> 4)];
*ptr++ = b64_table64_2[((src[1] << 2) & 0x3C) | (src[2] >> 6)];
*ptr++ = b64_table64_2[src[2] & 0x3F];
src += 3;
len -= 3;
}
if (len > 0) {
*ptr++ = b64_table64_2[src[0] >> 2];
uint8_t tmp = (src[0] << 4) & 0x30;
if (len > 1)
tmp |= src[1] >> 4;
*ptr++ = b64_table64_2[tmp];
if (len < 2) {
*ptr++ = '=';
}
else {
*ptr++ = b64_table64_2[(src[1] << 2) & 0x3C];
}
*ptr++ = '=';
}
*ptr = 0;
*d_len = ((char *) ptr - dst);
return dst;
}
uint16_t uwsgi_be16(char *buf) {
uint16_t *src = (uint16_t *) buf;
uint16_t ret = 0;
uint8_t *ptr = (uint8_t *) & ret;
ptr[0] = (uint8_t) ((*src >> 8) & 0xff);
ptr[1] = (uint8_t) (*src & 0xff);
return ret;
}
uint32_t uwsgi_be32(char *buf) {
uint32_t *src = (uint32_t *) buf;
uint32_t ret = 0;
uint8_t *ptr = (uint8_t *) & ret;
ptr[0] = (uint8_t) ((*src >> 24) & 0xff);
ptr[1] = (uint8_t) ((*src >> 16) & 0xff);
ptr[2] = (uint8_t) ((*src >> 8) & 0xff);
ptr[3] = (uint8_t) (*src & 0xff);
return ret;
}
uint64_t uwsgi_be64(char *buf) {
uint64_t *src = (uint64_t *) buf;
uint64_t ret = 0;
uint8_t *ptr = (uint8_t *) & ret;
ptr[0] = (uint8_t) ((*src >> 56) & 0xff);
ptr[1] = (uint8_t) ((*src >> 48) & 0xff);
ptr[2] = (uint8_t) ((*src >> 40) & 0xff);
ptr[3] = (uint8_t) ((*src >> 32) & 0xff);
ptr[4] = (uint8_t) ((*src >> 24) & 0xff);
ptr[5] = (uint8_t) ((*src >> 16) & 0xff);
ptr[6] = (uint8_t) ((*src >> 8) & 0xff);
ptr[7] = (uint8_t) (*src & 0xff);
return ret;
}
char *uwsgi_get_header(struct wsgi_request *wsgi_req, char *hh, uint16_t len, uint16_t * rlen) {
char *key = uwsgi_malloc(len + 6);
uint16_t key_len = len;
char *ptr = key;
*rlen = 0;
if (uwsgi_strncmp(hh, len, "Content-Length", 14) && uwsgi_strncmp(hh, len, "Content-Type", 12)) {
memcpy(ptr, "HTTP_", 5);
ptr += 5;
key_len += 5;
}
uint16_t i;
for (i = 0; i < len; i++) {
if (hh[i] == '-') {
*ptr++ = '_';
}
else {
*ptr++ = toupper((int) hh[i]);
}
}
char *value = uwsgi_get_var(wsgi_req, key, key_len, rlen);
free(key);
return value;
}
static char *uwsgi_hex_table[] = {
"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
"30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
"40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
"50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
"60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
"70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
"80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
"90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
"A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
"B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
"C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
"D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
"E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
"F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF",
};
char *uwsgi_str_to_hex(char *src, size_t slen) {
char *dst = uwsgi_malloc(slen * 2);
char *ptr = dst;
size_t i;
for (i = 0; i < slen; i++) {
uint8_t pos = (uint8_t) src[i];
memcpy(ptr, uwsgi_hex_table[pos], 2);
ptr += 2;
}
return dst;
}
// dst has to be 3 times buf size (USE IT ONLY FOR PATH_INFO !!!)
void http_url_encode(char *buf, uint16_t * len, char *dst) {
uint16_t i;
char *ptr = dst;
for (i = 0; i < *len; i++) {
if ((buf[i] >= 'A' && buf[i] <= 'Z') || (buf[i] >= 'a' && buf[i] <= 'z') || (buf[i] >= '0' && buf[i] <= '9') || buf[i] == '-' || buf[i] == '_' || buf[i] == '.' || buf[i] == '~' || buf[i] == '/') {
*ptr++ = buf[i];
}
else {
char *h = uwsgi_hex_table[(int) buf[i]];
*ptr++ = '%';
*ptr++ = h[0];
*ptr++ = h[1];
}
}
*len = ptr - dst;
}
void uwsgi_takeover() {
if (uwsgi.i_am_a_spooler) {
uwsgi_spooler_run();
}
else if (uwsgi.muleid) {
uwsgi_mule_run();
}
else {
uwsgi_worker_run();
}
}
// create a message pipe
void create_msg_pipe(int *fd, int bufsize) {
#if defined(SOCK_SEQPACKET) && defined(__linux__)
if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fd)) {
#else
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, fd)) {
#endif
uwsgi_error("create_msg_pipe()/socketpair()");
exit(1);
}
uwsgi_socket_nb(fd[0]);
uwsgi_socket_nb(fd[1]);
if (bufsize) {
if (setsockopt(fd[0], SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(int))) {
uwsgi_error("create_msg_pipe()/setsockopt()");
}
if (setsockopt(fd[0], SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(int))) {
uwsgi_error("create_msg_pipe()/setsockopt()");
}
if (setsockopt(fd[1], SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(int))) {
uwsgi_error("create_msg_pipe()/setsockopt()");
}
if (setsockopt(fd[1], SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(int))) {
uwsgi_error("create_msg_pipe()/setsockopt()");
}
}
}
char *uwsgi_binary_path() {
return uwsgi.binary_path ? uwsgi.binary_path : "uwsgi";
}
void uwsgi_envdir(char *edir) {
DIR *d = opendir(edir);
if (!d) {
uwsgi_error("[uwsgi-envdir] opendir()");
exit(1);
}
struct dirent *de;
while ((de = readdir(d)) != NULL) {
// skip hidden files
if (de->d_name[0] == '.')
continue;
struct stat st;
char *filename = uwsgi_concat3(edir, "/", de->d_name);
if (stat(filename, &st)) {
uwsgi_log("[uwsgi-envdir] error stating %s\n", filename);
uwsgi_error("[uwsgi-envdir] stat()");
exit(1);
}
if (!S_ISREG(st.st_mode)) {
free(filename);
continue;
}
// unsetenv
if (st.st_size == 0) {
#ifdef UNSETENV_VOID
unsetenv(de->d_name);
#else
if (unsetenv(de->d_name)) {
uwsgi_log("[uwsgi-envdir] unable to unset %s\n", de->d_name);
uwsgi_error("[uwsgi-envdir] unsetenv");
exit(1);
}
#endif
free(filename);
continue;
}
// read the content of the file
size_t size = 0;
char *content = uwsgi_open_and_read(filename, &size, 1, NULL);
if (!content) {
uwsgi_log("[uwsgi-envdir] unable to open %s\n", filename);
uwsgi_error_open(filename);
exit(1);
}
free(filename);
// HACK, envdir states we only need to strip the end of the string ....
uwsgi_chomp2(content);
// ... and substitute 0 with \n
size_t slen = strlen(content);
size_t i;
for (i = 0; i < slen; i++) {
if (content[i] == 0) {
content[i] = '\n';
}
}
if (setenv(de->d_name, content, 1)) {
uwsgi_log("[uwsgi-envdir] unable to set %s\n", de->d_name);
uwsgi_error("[uwsgi-envdir] setenv");
exit(1);
}
free(content);
}
closedir(d);
}
void uwsgi_envdirs(struct uwsgi_string_list *envdirs) {
struct uwsgi_string_list *usl = envdirs;
while (usl) {
uwsgi_envdir(usl->value);
usl = usl->next;
}
}
void uwsgi_opt_envdir(char *opt, char *value, void *foobar) {
uwsgi_envdir(value);
}
void uwsgi_exit(int status) {
uwsgi.last_exit_code = status;
// disable macro expansion
(exit) (status);
}
int uwsgi_base128(struct uwsgi_buffer *ub, uint64_t l, int first) {
if (l > 127) {
if (uwsgi_base128(ub, l / 128, 0))
return -1;
}
l %= 128;
if (first) {
if (uwsgi_buffer_u8(ub, (uint8_t) l))
return -1;
}
else {
if (uwsgi_buffer_u8(ub, 0x80 | (uint8_t) l))
return -1;
}
return 0;
}
#ifdef __linux__
void uwsgi_setns(char *path) {
int (*u_setns) (int, int) = (int (*)(int, int)) dlsym(RTLD_DEFAULT, "setns");
if (!u_setns) {
uwsgi_log("your system misses setns() syscall !!!\n");
exit(1);
}
// count be overwritten
int count = 64;
uwsgi_log("joining namespaces from %s ...\n", path);
for (;;) {
int ns_fd = uwsgi_connect(path, 30, 0);
if (ns_fd < 0) {
uwsgi_error("uwsgi_setns()/uwsgi_connect()");
sleep(1);
continue;
}
int *fds = uwsgi_attach_fd(ns_fd, &count, "uwsgi-setns", 11);
if (fds && count > 0) {
int i;
for (i = 0; i < count; i++) {
if (fds[i] > -1) {
if (u_setns(fds[i], 0) < 0) {
uwsgi_error("uwsgi_setns()/setns()");
exit(1);
}
close(fds[i]);
}
}
free(fds);
close(ns_fd);
break;
}
if (fds)
free(fds);
close(ns_fd);
sleep(1);
}
}
#endif
mode_t uwsgi_mode_t(char *value, int *error) {
mode_t mode = 0;
*error = 0;
if (strlen(value) < 3) {
*error = 1;
return mode;
}
if (strlen(value) == 3) {
mode = (mode << 3) + (value[0] - '0');
mode = (mode << 3) + (value[1] - '0');
mode = (mode << 3) + (value[2] - '0');
}
else {
mode = (mode << 3) + (value[1] - '0');
mode = (mode << 3) + (value[2] - '0');
mode = (mode << 3) + (value[3] - '0');
}
return mode;
}
int uwsgi_wait_for_socket(char *socket_name) {
if (!uwsgi.wait_for_socket_timeout) {
uwsgi.wait_for_socket_timeout = 60;
}
uwsgi_log("waiting for %s (max %d seconds) ...\n", socket_name, uwsgi.wait_for_socket_timeout);
int counter = 0;
for (;;) {
if (counter > uwsgi.wait_for_socket_timeout) {
uwsgi_log("%s unavailable after %d seconds\n", socket_name, counter);
return -1;
}
// wait for 1 second to respect uwsgi.wait_for_fs_timeout
int fd = uwsgi_connect(socket_name, 1, 0);
if (fd < 0) goto retry;
close(fd);
uwsgi_log_verbose("%s ready\n", socket_name);
return 0;
retry:
sleep(1);
counter++;
}
return -1;
}
int uwsgi_wait_for_mountpoint(char *mountpoint) {
if (!uwsgi.wait_for_fs_timeout) {
uwsgi.wait_for_fs_timeout = 60;
}
uwsgi_log("waiting for %s (max %d seconds) ...\n", mountpoint, uwsgi.wait_for_fs_timeout);
int counter = 0;
for (;;) {
if (counter > uwsgi.wait_for_fs_timeout) {
uwsgi_log("%s unavailable after %d seconds\n", mountpoint, counter);
return -1;
}
struct stat st0;
struct stat st1;
if (stat(mountpoint, &st0)) goto retry;
if (!S_ISDIR(st0.st_mode)) goto retry;
char *relative = uwsgi_concat2(mountpoint, "/../");
if (stat(relative, &st1)) {
free(relative);
goto retry;
}
free(relative);
// useless :P
if (!S_ISDIR(st1.st_mode)) goto retry;
if (st0.st_dev == st1.st_dev) goto retry;
uwsgi_log_verbose("%s mounted\n", mountpoint);
return 0;
retry:
sleep(1);
counter++;
}
return -1;
}
// type -> 1 file, 2 dir, 0 both
int uwsgi_wait_for_fs(char *filename, int type) {
if (!uwsgi.wait_for_fs_timeout) {
uwsgi.wait_for_fs_timeout = 60;
}
uwsgi_log("waiting for %s (max %d seconds) ...\n", filename, uwsgi.wait_for_fs_timeout);
int counter = 0;
for (;;) {
if (counter > uwsgi.wait_for_fs_timeout) {
uwsgi_log("%s unavailable after %d seconds\n", filename, counter);
return -1;
}
struct stat st;
if (stat(filename, &st)) goto retry;
if (type == 1 && !S_ISREG(st.st_mode)) goto retry;
if (type == 2 && !S_ISDIR(st.st_mode)) goto retry;
uwsgi_log_verbose("%s found\n", filename);
return 0;
retry:
sleep(1);
counter++;
}
return -1;
}
#if !defined(_GNU_SOURCE) && !defined(__UCLIBC__)
int uwsgi_versionsort(const struct dirent **da, const struct dirent **db) {
const char *a = (*da)->d_name;
const char *b = (*db)->d_name;
long la, lb;
char *endptr;
// Check if a and b are valid numbers.
la = strtol(a, &endptr, 10);
if (strcmp(endptr, "\0") || endptr == a) {
a = NULL;
}
lb = strtol(b, &endptr, 10);
if (strcmp(endptr, "\0") || endptr == b) {
b = NULL;
}
if (a && b) {
return (la < lb ? -1 : la > lb);
} else if (a) {
return -1;
} else if (b) {
return 1;
} else {
return strcmp((*da)->d_name, (*db)->d_name);
}
}
#endif
void uwsgi_fix_range_for_size(enum uwsgi_range* parsed, int64_t* from, int64_t* to, int64_t size) {
if (*parsed != UWSGI_RANGE_PARSED) {
return;
}
if (*from < 0) {
*from = size + *from;
}
if (*to > size-1) {
*to = size-1;
}
if (*from == 0 && *to == size-1) {
/* we have a right to reset to 200 OK answer */
*parsed = UWSGI_RANGE_NOT_PARSED;
}
else if (*to >= *from) {
*parsed = UWSGI_RANGE_VALID;
}
else { /* case *from > size-1 is also handled here */
*parsed = UWSGI_RANGE_INVALID;
*from = 0;
*to = 0;
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_614_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.